Skip to contentSkip to conversation

mm/swap: fix swap_cache_get_folio() returning a folio that left the swap cache

PATCH Applied Jiayuan Chen 3 participants 10 messages Oct 15 – Oct 30

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 mm/swap: fix swap_cache_get_folio() returning a folio that left the swap cache

From: Jiayuan Chen <[email protected]>

swap_cache_get_folio() reads the folio from the swap table and takes a reference with folio_try_get(), without any lock. If the folio is removed from the swap cache and freed in between, and its memory gets reused, folio_try_get() still succeeds and we return a page that has nothing to do with the swap entry:

CPU 0 CPU 1
do_swap_page()
swap_cache_get_folio()
swp_tb = swap_table_get()
folio = swp_tb_to_folio(swp_tb)
madvise(MADV_DONTNEED)
zap_nonpresent_ptes()
swap_put_entries_direct()
swap_put_entries_cluster()
__try_to_reclaim_swap()
swap_cache_del_folio()
folio_put() <- freed
page reused, e.g. as an anon folio of another task
folio_try_get(folio) <- succeeds
return folio
swap_update_readahead() <- may clear PG_readahead on it
folio_lock_or_retry() <- locks it
folio_matches_swap_entry() fails, unlock and put

filemap_get_entry() does the same lockless lookup for the page cache, and after folio_try_get() it rechecks the xarray, because the folio may have been freed and reused in between. swap_cache_get_folio() lost that recheck when the swap cache moved to the swap table.

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.

Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")
Cc Jiayuan Chen <[email protected]>

---
https://sashiko.dev/#/patchset/[email protected]

---
 mm/swap_state.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
mm/swap_state.c +13 -3
index ebef568cd62e..d9e36c505398 100644
@@ -92,17 +92,27 @@ void show_swap_cache_info(void)
  */
 struct folio *swap_cache_get_folio(swp_entry_t entry)
 {
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(entry);
+	unsigned int ci_off = swp_cluster_offset(entry);
 	unsigned long swp_tb;
 	struct folio *folio;
 
 	for (;;) {
-		swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-					swp_cluster_offset(entry));
+		swp_tb = swap_table_get(ci, ci_off);
 		if (!swp_tb_is_folio(swp_tb))
 			return NULL;
 		folio = swp_tb_to_folio(swp_tb);
-		if (likely(folio_try_get(folio)))
+		if (!folio_try_get(folio))
+			continue;
+		/*
+		 * The folio may have been freed and its memory reused before
+		 * we got the reference. Make sure it is still in the slot.
+		 */
+		swp_tb = swap_table_get(ci, ci_off);
+		if (likely(swp_tb_is_folio(swp_tb) &&
+			   swp_tb_to_folio(swp_tb) == folio))
 			return folio;
+		folio_put(folio);
 	}
 
 	return NULL;
Signature · 1 line
2.43.0
maintainer
#1 lore raw
Quoted 33 lines · On Thu, 15 Oct 2026 14:05:27 +0800 Jiayuan Chen <[email protected]> wrote:

From: Jiayuan Chen <[email protected]>

swap_cache_get_folio() reads the folio from the swap table and takes a reference with folio_try_get(), without any lock. If the folio is removed from the swap cache and freed in between, and its memory gets reused, folio_try_get() still succeeds and we return a page that has nothing to do with the swap entry:

CPU 0 CPU 1
do_swap_page()
swap_cache_get_folio()
swp_tb = swap_table_get()
folio = swp_tb_to_folio(swp_tb)
madvise(MADV_DONTNEED)
zap_nonpresent_ptes()
swap_put_entries_direct()
swap_put_entries_cluster()
__try_to_reclaim_swap()
swap_cache_del_folio()
folio_put() <- freed
page reused, e.g. as an anon folio of another task
folio_try_get(folio) <- succeeds
return folio
swap_update_readahead() <- may clear PG_readahead on it
folio_lock_or_retry() <- locks it
folio_matches_swap_entry() fails, unlock and put

filemap_get_entry() does the same lockless lookup for the page cache, and after folio_try_get() it rechecks the xarray, because the folio may have been freed and reused in between. swap_cache_get_folio() lost that recheck when the swap cache moved to the swap table.

Quoted 6 lines

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.

Thanks.

As always, when fixing a bug please fully describe the worst-case userspace-visible runtime effects of that bug.

I asked $LLM for this and was told

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls, impaired reclaim or writeback, and potentially : system hangs. The subsequent swap-entry validation normally prevents : the wrong folio from being mapped into the faulting process, and : neither data corruption nor a kernel crash has been demonstrated.

Do you agree with this? OK with me adding this to your changelog?

Quoted 1 line
Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")

Given the above, I suggest adding cc:stable.

Do you and maintainers agree?

#2 lore raw

Hi Andrew,

Quoted 2 lines · Andrew Morton

On Thu, 15 Oct 2026 14:05:27 +0800 Jiayuan Chen <[email protected]> wrote:

[...]

Quoted 14 lines

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.
Thanks.

As always, when fixing a bug please fully describe the worst-case userspace-visible runtime effects of that bug.

I asked $LLM for this and was told

Quoted 9 lines

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls, impaired reclaim or writeback, and potentially : system hangs. The subsequent swap-entry validation normally prevents

I don't see a way to a system hang: the folio lock waiter is woken when the real owner unlocks, so the worst case is a stall. I suggest dropping "and potentially system hangs".

Writeback itself is not affected, only the PG_reclaim hint on where to put the folio after writeback. So "impaired reclaim or writeback" -> "impaired reclaim".

So I'd suggest:

  : When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process.  The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
  : These operations can interfere with unrelated workloads and may cause : unexpected stalls and impaired reclaim.  The subsequent swap-entry : validation normally prevents the wrong folio from being mapped into : the faulting process, and neither data corruption nor a kernel crash : has been demonstrated.

Quoted 9 lines

: the wrong folio from being mapped into the faulting process, and : neither data corruption nor a kernel crash has been demonstrated.

Do you agree with this? OK with me adding this to your changelog?

Quoted 1 line
Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")

Given the above, I suggest adding cc:stable.

Do you and maintainers agree?

Agreed for me.

#3 lore raw
Quoted 7 lines · Jiayuan Chen

Hi Andrew,

Quoted 2 lines · Andrew Morton

On Thu, 15 Oct 2026 14:05:27 +0800 Jiayuan Chen <[email protected]> wrote:

[...]

Hi all,

Quoted 36 lines
Quoted 14 lines

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.
Thanks.

As always, when fixing a bug please fully describe the worst-case userspace-visible runtime effects of that bug.

I asked $LLM for this and was told

Quoted 9 lines

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls, impaired reclaim or writeback, and potentially : system hangs. The subsequent swap-entry validation normally prevents

I don't see a way to a system hang: the folio lock waiter is woken when the real owner unlocks, so the worst case is a stall. I suggest dropping "and potentially system hangs".

Writeback itself is not affected, only the PG_reclaim hint on where to put the folio after writeback. So "impaired reclaim or writeback" -> "impaired reclaim".

So I'd suggest:

Quoted 9 lines

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls and impaired reclaim. The subsequent swap-entry : validation normally prevents the wrong folio from being mapped into

It's documented that caller always double checks the folio so this part is harmless from the aspect of data corruption or crash.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line
Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")

Given the above, I suggest adding cc:stable.

Do you and maintainers agree?

Agreed for me.

This is more like a optimization than a bug fix, but it's clean and easy to follow, Cc'ing stable is fine to me.

maintainer
#4 lore raw
Quoted 39 lines · On Fri, 16 Oct 2026 10:22:20 +0800 Kairui Song <[email protected]> wrote:
Quoted 7 lines · Jiayuan Chen

Hi Andrew,

Quoted 2 lines · Andrew Morton

On Thu, 15 Oct 2026 14:05:27 +0800 Jiayuan Chen <[email protected]> wrote:

[...]

Hi all,

Quoted 28 lines
Quoted 14 lines

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.
Thanks.

As always, when fixing a bug please fully describe the worst-case userspace-visible runtime effects of that bug.

I asked $LLM for this and was told

Quoted 9 lines

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls, impaired reclaim or writeback, and potentially : system hangs. The subsequent swap-entry validation normally prevents

I don't see a way to a system hang: the folio lock waiter is woken when the real owner unlocks, so the worst case is a stall. I suggest dropping "and potentially system hangs".

Yes, I think it's assuming the other-owned folio never gets unlocked.

Quoted 17 lines
Quoted 7 lines

Writeback itself is not affected, only the PG_reclaim hint on where to put the folio after writeback. So "impaired reclaim or writeback" -> "impaired reclaim".

So I'd suggest:

Quoted 9 lines

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls and impaired reclaim. The subsequent swap-entry : validation normally prevents the wrong folio from being mapped into

Quoted 2 lines

It's documented that caller always double checks the folio so this part is harmless from the aspect of data corruption or crash.

OK, thanks, adjustment made.

Quoted 10 lines
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")

Given the above, I suggest adding cc:stable.

Do you and maintainers agree?

Agreed for me.

This is more like a optimization than a bug fix, but it's clean and easy to follow, Cc'ing stable is fine to me.

Was that an ack ;)

Here's what I now have:

: swap_cache_get_folio() reads the folio from the swap table and takes a : reference with folio_try_get(), without any lock. If the folio is removed : from the swap cache and freed in between, and its memory gets reused, : folio_try_get() still succeeds and we return a page that has nothing to do : with the swap entry:
:
: CPU 0 CPU 1
: do_swap_page()
: swap_cache_get_folio()
: swp_tb = swap_table_get()
: folio = swp_tb_to_folio(swp_tb)
: madvise(MADV_DONTNEED)
: zap_nonpresent_ptes()
: swap_put_entries_direct()
: swap_put_entries_cluster()
: __try_to_reclaim_swap()
: swap_cache_del_folio()
: folio_put() <- freed

:                                          page reused, e.g. as an anon
:                                          folio of another task
:       folio_try_get(folio)               <- succeeds
:       return folio
:     swap_update_readahead()              <- may clear PG_readahead on it
:     folio_lock_or_retry()                <- locks it
:     folio_matches_swap_entry() fails, unlock and put

:
: filemap_get_entry() does the same lockless lookup for the page cache, and : after folio_try_get() it rechecks the xarray, because the folio may have : been freed and reused in between. swap_cache_get_folio() lost that : recheck when the swap cache moved to the swap table.
:
: So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and : takes the folio lock of someone else's page, before
: folio_matches_swap_entry() finds out the folio is not ours.
:
: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls and impaired reclaim. The subsequent swap-entry : validation normally prevents the wrong folio from being mapped into the : faulting process.
:
: It's documented that caller always double checks the folio so this part : is harmless from the aspect of data corruption or crash.
:
: Recheck the slot after folio_try_get() and retry if it no longer holds : this folio.

Reviewed-by
#5 lore raw
Quoted 72 lines · Andrew Morton
Quoted 39 lines · On Fri, 16 Oct 2026 10:22:20 +0800 Kairui Song <[email protected]> wrote:
Quoted 7 lines · Jiayuan Chen

Hi Andrew,

Quoted 2 lines · Andrew Morton

On Thu, 15 Oct 2026 14:05:27 +0800 Jiayuan Chen <[email protected]> wrote:

[...]

Hi all,

Quoted 28 lines
Quoted 14 lines

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.
Thanks.

As always, when fixing a bug please fully describe the worst-case userspace-visible runtime effects of that bug.

I asked $LLM for this and was told

Quoted 9 lines

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls, impaired reclaim or writeback, and potentially : system hangs. The subsequent swap-entry validation normally prevents

I don't see a way to a system hang: the folio lock waiter is woken when the real owner unlocks, so the worst case is a stall. I suggest dropping "and potentially system hangs".

Yes, I think it's assuming the other-owned folio never gets unlocked.

Quoted 17 lines
Quoted 7 lines

Writeback itself is not affected, only the PG_reclaim hint on where to put the folio after writeback. So "impaired reclaim or writeback" -> "impaired reclaim".

So I'd suggest:

Quoted 9 lines

: When the race occurs, a swap fault can acquire a reference to a : physical page that has been freed and reused for an unrelated purpose, : potentially by another process. The fault handler may then clear that : page's PG_readahead/PG_reclaim flag, wait on or acquire its folio lock, : and potentially attempt to remove it from an unrelated swap cache. :
: These operations can interfere with unrelated workloads and may cause : unexpected stalls and impaired reclaim. The subsequent swap-entry : validation normally prevents the wrong folio from being mapped into

Quoted 2 lines

It's documented that caller always double checks the folio so this part is harmless from the aspect of data corruption or crash.

OK, thanks, adjustment made.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 1 line
Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")

Given the above, I suggest adding cc:stable.

Do you and maintainers agree?

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Agreed for me.

This is more like a optimization than a bug fix, but it's clean and easy to follow, Cc'ing stable is fine to me.

Was that an ack ;)

Right it looks good to me :D

maintainer
#6 lore raw
In reply to Jiayuan Chen
Quoted 33 lines · On Thu, 15 Oct 2026 14:05:27 +0800 Jiayuan Chen <[email protected]> wrote:

From: Jiayuan Chen <[email protected]>

swap_cache_get_folio() reads the folio from the swap table and takes a reference with folio_try_get(), without any lock. If the folio is removed from the swap cache and freed in between, and its memory gets reused, folio_try_get() still succeeds and we return a page that has nothing to do with the swap entry:

CPU 0 CPU 1
do_swap_page()
swap_cache_get_folio()
swp_tb = swap_table_get()
folio = swp_tb_to_folio(swp_tb)
madvise(MADV_DONTNEED)
zap_nonpresent_ptes()
swap_put_entries_direct()
swap_put_entries_cluster()
__try_to_reclaim_swap()
swap_cache_del_folio()
folio_put() <- freed
page reused, e.g. as an anon folio of another task
folio_try_get(folio) <- succeeds
return folio
swap_update_readahead() <- may clear PG_readahead on it
folio_lock_or_retry() <- locks it
folio_matches_swap_entry() fails, unlock and put

filemap_get_entry() does the same lockless lookup for the page cache, and after folio_try_get() it rechecks the xarray, because the folio may have been freed and reused in between. swap_cache_get_folio() lost that recheck when the swap cache moved to the swap table.

Quoted 6 lines

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.

LLM says to me:

: The original folio could conceivably be freed, its physical page : reused, and the same PFN inserted into the same swap-table slot before : the second lookup. That would pass the check. However, the returned : reference would then belong to the newly inserted folio, and the later : swap-entry validation would still be required. I don't see that as : invalidating this fix.

Quoted 23 lines
mm/swap_state.c +7 -3
@@ -92,17 +92,27 @@ void show_swap_cache_info(void)
  */
 struct folio *swap_cache_get_folio(swp_entry_t entry)
 {
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(entry);
+	unsigned int ci_off = swp_cluster_offset(entry);
 	unsigned long swp_tb;
 	struct folio *folio;
 
 	for (;;) {
-		swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-					swp_cluster_offset(entry));
+		swp_tb = swap_table_get(ci, ci_off);
 		if (!swp_tb_is_folio(swp_tb))
 			return NULL;
 		folio = swp_tb_to_folio(swp_tb);
-		if (likely(folio_try_get(folio)))
+		if (!folio_try_get(folio))
+			continue;
+		/*
+		 * The folio may have been freed and its memory reused before

mm/swap_state.c void show_swap_cache_info(void) · line 118

Quoted 10 lines
mm/swap_state.c +6 -0
+		 * we got the reference. Make sure it is still in the slot.
+		 */
+		swp_tb = swap_table_get(ci, ci_off);
+		if (likely(swp_tb_is_folio(swp_tb) &&
+			   swp_tb_to_folio(swp_tb) == folio))
 			return folio;
+		folio_put(folio);
 	}
 
 	return NULL;

This return is now unreachable...

#7 lore raw

Hi Andrew,

Quoted 41 lines · Andrew Morton
Quoted 33 lines · On Thu, 15 Oct 2026 14:05:27 +0800 Jiayuan Chen <[email protected]> wrote:

From: Jiayuan Chen <[email protected]>

swap_cache_get_folio() reads the folio from the swap table and takes a reference with folio_try_get(), without any lock. If the folio is removed from the swap cache and freed in between, and its memory gets reused, folio_try_get() still succeeds and we return a page that has nothing to do with the swap entry:

CPU 0 CPU 1
do_swap_page()
swap_cache_get_folio()
swp_tb = swap_table_get()
folio = swp_tb_to_folio(swp_tb)
madvise(MADV_DONTNEED)
zap_nonpresent_ptes()
swap_put_entries_direct()
swap_put_entries_cluster()
__try_to_reclaim_swap()
swap_cache_del_folio()
folio_put() <- freed
page reused, e.g. as an anon folio of another task
folio_try_get(folio) <- succeeds
return folio
swap_update_readahead() <- may clear PG_readahead on it
folio_lock_or_retry() <- locks it
folio_matches_swap_entry() fails, unlock and put

filemap_get_entry() does the same lockless lookup for the page cache, and after folio_try_get() it rechecks the xarray, because the folio may have been freed and reused in between. swap_cache_get_folio() lost that recheck when the swap cache moved to the swap table.

Quoted 6 lines

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.

Quoted 8 lines

LLM says to me:

: The original folio could conceivably be freed, its physical page : reused, and the same PFN inserted into the same swap-table slot before : the second lookup. That would pass the check. However, the returned : reference would then belong to the newly inserted folio, and the later : swap-entry validation would still be required. I don't see that as : invalidating this fix.

I had the same worry at first, data corruption or something worse, but after thinking it through I agree. Passing the check there is fine:
the folio we return is the one currently in the slot, which is what
the function promises, and callers still check folio_matches_swap_entry() under the folio lock before using it. That's why I didn't mention it in the changelog.

Quoted 32 lines
Quoted 32 lines
mm/swap_state.c +13 -3
@@ -92,17 +92,27 @@ void show_swap_cache_info(void)
   */
  struct folio *swap_cache_get_folio(swp_entry_t entry)
  {
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(entry);
+	unsigned int ci_off = swp_cluster_offset(entry);
  	unsigned long swp_tb;
  	struct folio *folio;
 
  	for (;;) {
-		swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-					swp_cluster_offset(entry));
+		swp_tb = swap_table_get(ci, ci_off);
  		if (!swp_tb_is_folio(swp_tb))
  			return NULL;
  		folio = swp_tb_to_folio(swp_tb);
-		if (likely(folio_try_get(folio)))
+		if (!folio_try_get(folio))
+			continue;
+		/*
+		 * The folio may have been freed and its memory reused before
+		 * we got the reference. Make sure it is still in the slot.
+		 */
+		swp_tb = swap_table_get(ci, ci_off);
+		if (likely(swp_tb_is_folio(swp_tb) &&
+			   swp_tb_to_folio(swp_tb) == folio))
  			return folio;
+		folio_put(folio);
  	}
 
Quoted 2 lines

mm/swap_state.c void show_swap_cache_info(void) · line 118

Quoted 1 line
mm/swap_state.c +0 -0
  	return NULL;

This return is now unreachable...

Right, and it never was reachable, the loop has no break. It should have been dropped earlier...

#8 lore raw
In reply to Jiayuan Chen
Quoted 74 lines · Jiayuan Chen

From: Jiayuan Chen <[email protected]>

swap_cache_get_folio() reads the folio from the swap table and takes a reference with folio_try_get(), without any lock. If the folio is removed from the swap cache and freed in between, and its memory gets reused, folio_try_get() still succeeds and we return a page that has nothing to do with the swap entry:

CPU 0 CPU 1
do_swap_page()
swap_cache_get_folio()
swp_tb = swap_table_get()
folio = swp_tb_to_folio(swp_tb)
madvise(MADV_DONTNEED)
zap_nonpresent_ptes()
swap_put_entries_direct()
swap_put_entries_cluster()
__try_to_reclaim_swap()
swap_cache_del_folio()
folio_put() <- freed
page reused, e.g. as an anon folio of another task
folio_try_get(folio) <- succeeds
return folio
swap_update_readahead() <- may clear PG_readahead on it
folio_lock_or_retry() <- locks it
folio_matches_swap_entry() fails, unlock and put

filemap_get_entry() does the same lockless lookup for the page cache, and after folio_try_get() it rechecks the xarray, because the folio may have been freed and reused in between. swap_cache_get_folio() lost that recheck when the swap cache moved to the swap table.

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.

Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")
Cc Jiayuan Chen <[email protected]>

---
https://sashiko.dev/#/patchset/[email protected]

---
  mm/swap_state.c | 16 +++++++++++++---
  1 file changed, 13 insertions(+), 3 deletions(-)
mm/swap_state.c +7 -3
index ebef568cd62e..d9e36c505398 100644
@@ -92,17 +92,27 @@ void show_swap_cache_info(void)
   */
  struct folio *swap_cache_get_folio(swp_entry_t entry)
  {
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(entry);
+	unsigned int ci_off = swp_cluster_offset(entry);
  	unsigned long swp_tb;
  	struct folio *folio;
 
  	for (;;) {
-		swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-					swp_cluster_offset(entry));
+		swp_tb = swap_table_get(ci, ci_off);
  		if (!swp_tb_is_folio(swp_tb))
  			return NULL;
  		folio = swp_tb_to_folio(swp_tb);
-		if (likely(folio_try_get(folio)))
+		if (!folio_try_get(folio))
+			continue;
+		/*
+		 * The folio may have been freed and its memory reused before

mm/swap_state.c void show_swap_cache_info(void) · line 118

Quoted 10 lines
mm/swap_state.c +6 -0
+		 * we got the reference. Make sure it is still in the slot.
+		 */
+		swp_tb = swap_table_get(ci, ci_off);
+		if (likely(swp_tb_is_folio(swp_tb) &&
+			   swp_tb_to_folio(swp_tb) == folio))
  			return folio;
+		folio_put(folio);
  	}
 
  	return NULL;

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.

4 is the one I'd pick if nobody objects. Thoughts?

#9 lore raw
Quoted 115 lines · Jiayuan Chen
Quoted 73 lines · Jiayuan Chen

From: Jiayuan Chen <[email protected]>

swap_cache_get_folio() reads the folio from the swap table and takes a reference with folio_try_get(), without any lock. If the folio is removed from the swap cache and freed in between, and its memory gets reused, folio_try_get() still succeeds and we return a page that has nothing to do with the swap entry:

   CPU 0                                  CPU 1 do_swap_page()
     swap_cache_get_folio()
       swp_tb = swap_table_get()
       folio = swp_tb_to_folio(swp_tb)
                                          madvise(MADV_DONTNEED) zap_nonpresent_ptes()
swap_put_entries_direct()
swap_put_entries_cluster()
__try_to_reclaim_swap()
swap_cache_del_folio()
folio_put()   <- freed
                                          page reused, e.g. as an anon folio of another task folio_try_get(folio)               <- succeeds
       return folio
     swap_update_readahead()              <- may clear PG_readahead on it folio_lock_or_retry()                <- locks it folio_matches_swap_entry() fails, unlock and put

filemap_get_entry() does the same lockless lookup for the page cache, and after folio_try_get() it rechecks the xarray, because the folio may have been freed and reused in between. swap_cache_get_folio() lost that recheck when the swap cache moved to the swap table.

So CPU 0 writes to a folio it doesn't own: it may clear PG_readahead and takes the folio lock of someone else's page, before folio_matches_swap_entry() finds out the folio is not ours.

Recheck the slot after folio_try_get() and retry if it no longer holds this folio.

Fixes 8578e0c00dcf ("mm, swap: use the swap table for the swap cache and switch API")
Cc Jiayuan Chen <[email protected]>

---
https://sashiko.dev/#/patchset/[email protected]

---
  mm/swap_state.c | 16 +++++++++++++---

  1 file changed, 13 insertions(+), 3 deletions(-)
mm/swap_state.c +6 -3
index ebef568cd62e..d9e36c505398 100644
@@ -92,17 +92,27 @@ void show_swap_cache_info(void)
    */
   struct folio *swap_cache_get_folio(swp_entry_t entry)
   {
+    struct swap_cluster_info *ci = __swap_entry_to_cluster(entry);
+    unsigned int ci_off = swp_cluster_offset(entry);
       unsigned long swp_tb;
       struct folio *folio;
         for (;;) {
-        swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-                    swp_cluster_offset(entry));
+        swp_tb = swap_table_get(ci, ci_off);
           if (!swp_tb_is_folio(swp_tb))
               return NULL;
           folio = swp_tb_to_folio(swp_tb);
-        if (likely(folio_try_get(folio)))
+        if (!folio_try_get(folio))
+            continue;
+        /*

mm/swap_state.c void show_swap_cache_info(void) · line 116

Quoted 10 lines
mm/swap_state.c +7 -0
+         * The folio may have been freed and its memory reused before
+         * we got the reference. Make sure it is still in the slot.
+         */
+        swp_tb = swap_table_get(ci, ci_off);
+        if (likely(swp_tb_is_folio(swp_tb) &&
+               swp_tb_to_folio(swp_tb) == folio))
               return folio;
+        folio_put(folio);
       }
         return NULL;

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.

Quoted 5 lines

  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.

4 is the one I'd pick if nobody objects. Thoughts?

Plesase ignore his. I reply the wrong thread......