[PATCH] mm/shmem: don't drop a folio whose swap write failed

From: Mani Tofigh via B4 Relay

Date: Mon Nov 23 2026 - 12:21:45 EST


From: Mani Tofigh <mt4022@xxxxxxxxxxxx>

shmem_swapin_folio() drops a large folio that does not fit the mapping
from the swap cache if the folio is neither dirty nor under writeback.
The folio can belong to another file and be under swap writeback, when
the swap entry was freed and reused before the swap cache lookup.

Swap write completion does not take the folio lock. On a failed write,
swap_write_end() marks the folio dirty and then ends writeback. Since
dirty is tested first, the folio can look clean and written:

CPU0 (swapin of file Y) CPU1 (swapout of file X)
----------------------- ------------------------
shmem_swapin_folio()
folio_test_dirty() == false
swap_write_end(), failed write
folio_mark_dirty()
folio_end_writeback()
folio_test_writeback() == false
swap_cache_del_folio()
/* X's data is lost */

The next swapin of X reads the slot whose write failed.

Test writeback first. Both flags are in folio->flags. If the
writeback test sees the write ended, the dirty test then sees the dirty
bit set before it.

With the fix, a folio whose swap write failed stays in the swap cache.

Fixes: fc2c19648d68 ("mm/shmem: fix swapin livelock on a mismatched large swap cache folio")
Suggested-by: Chris Mason <mason@xxxxxxxxxx>
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Mani Tofigh <mt4022@xxxxxxxxxxxx>
---
Managed to hit this by forcing the order in a VM, and it's gone with the fix.
---
mm/shmem.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/mm/shmem.c b/mm/shmem.c
index e351cd425d69..867f43315af1 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -2664,10 +2664,12 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
* A large folio that does not fit the mapping, e.g. because its swap
* entries were freed and reused, would be found again on every retry.
* Drop it from the swap cache so the retry can swap in a fitting one.
+ * A failed swap write sets dirty and then ends writeback without the
+ * folio lock, so test writeback before dirty.
*/
if (error == -EEXIST && folio && folio_test_large(folio) &&
- !folio_test_anon(folio) && !folio_test_dirty(folio) &&
- !folio_test_writeback(folio))
+ !folio_test_anon(folio) && !folio_test_writeback(folio) &&
+ !folio_test_dirty(folio))
swap_cache_del_folio(folio);
unlock:
if (folio)

---
base-commit: b6a9fa34ce4187cb69d3c588a4bbffc31ce5db8f
change-id: 20261123-shmem-swap-write-failed-bced285e8526

Best regards,
--
Mani Tofigh <mt4022@xxxxxxxxxxxx>