Linux-mm Archive on lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV)
@ 2026-12-03 18:12 Baoquan He
  2026-12-03 18:12 ` [PATCH v2 01/32] mm, swap: prepare the swap IO path for xswap backends Baoquan He
                   ` (31 more replies)
  0 siblings, 32 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

This is the second part of the xswap series. Phase I, posted
separately, added the file-less swap device: a sparse swap address
space that grows on demand, with the data stored in zswap. This part
gives the device a physical backend, accounts the swap that really
reaches a device, and unifies the per-slot backend records. It applies
on top of the phase I series.

Phase II (patches 1-17): a physical backend for xswap slots
-----------------------------------------------------------
A zswap-only slot has one copy: when zswap evicts or refuses the page,
the data is gone. A slot can now be written to a contiguous range of
physical swap slots on a real swap device. The xswap slot stays the
identity, and the physical slots are tagged with their owning xswap
entry, so writeback, readback and rebuild can find each other.

zswap eviction now has a destination, and a refused store falls back to
a real device instead of leaving the page resident. A cache-only entry
releases its physical range early. A large xswap folio is accepted only
when a contiguous physical range can back it, and is read back with one
I/O; otherwise reclaim is asked to split the folio. THP swapin is
enabled for entries whose whole range is contiguous on one device.
A backend that requires NOFS is skipped when the caller may not enter
the filesystem.

This partially refers to Nhat's vswap-v4 series: patch 1 is consistent
with his patch 3, patch 18/19/20/21 are from his patch 8. Tagging a swap
table entry with its owning xswap entry, releasing the physical range of
a cache-only entry, and enabling THP swapin, the principle is similar,
but the implementation is not, because the underlying data structures
differ, add Nhat's Co-developed-by.


Phase III (patches 18-26): swap accounting
------------------------------------------
An xswap entry is recorded with its owner at allocation, but the swap
charge is taken only when the entry gets a physical backend slot, and
given back with it. memory.swap.current therefore matches the backend
device's Used page for page. A zswap-only entry is not charged: the
compressed pool is already charged as memory, and charging it as swap
would count it twice. memory.swap.max=0 still permits swapout through
zswap. cgroup v1 keeps memsw on the slot, so xswap must not touch memsw
when it uncharges the backing.

Phase IV (patches 27-32): per-slot backend records
--------------------------------------------------
Every swap device keeps a per-cluster backend table, allocated on
demand: 512 words, one per slot. A word is either a zswap entry pointer
(low bit 1) or a physical backend entry (low bit 0); zero means no
record. zswap entries are indexed here instead of a per-type xarray,
so a lookup is O(1) by cluster. Reads take no cluster lock; the table
is allocated before the first record is published. A folio's slots or
a cluster's free batch are released with one range walk. The xswap
specific hooks run only on xswap devices.

Design notes
------------

An xswap slot is still a swap entry: the physical backend is a range of
slots on the real device, not a separate address space. The reverse map
is kept on the physical slot, so the physical device's reclaim scanner
can find the owner without walking the xswap cluster array. The owner
is published before the reverse map, and a stale range is dropped before
it is reused.

Testing
-------

QEMU KVM guest, 8G RAM, booted with xswap.max=10G. The complete
46-patch queue was built and booted on 1a7610248a38:

  - functional matrix: 30 checks passed, 0 failed; the overcommit case
    was run separately with vm.overcommit_memory=2 (8.15G RAM,
    overcommit_ratio 50, CommitLimit 14.56G, Committed_AS 4.65G, a
    10.49G device) and passed
  - swapoff xswap and swapoff -a, including destroying with 1,075,128 kB
    of live pages
  - 2000 create/destroy cycles: no per-cluster state is leaked (largest
    slab growth 196 objects)
  - a cgroup that cannot zswap gets no xswap slot
  - the vmallocinfo-reader stress with the grow test is clean
  - dmesg is clean except for the memcg OOM kill that the cgroup gate
    test asks for

The backend-specific tests were run on the previous base; the rebase to
1a7610248a38 is patch-identical (range-diff reports no change), so the
results carry over:

  - backend readback: every byte still holds the pattern (1.57M pages)
  - writeback + destroy: 3 cycles, the backend returns to 0 every time
  - THP swapin: 570,880 pages read back
  - shmem and split fallback: PASS
  - memcg charge P1-P6: ALL PASS
  - limit and race tests: PASS

Performance
-----------

The phase II backend is about capacity, not pageout speed. With the
complete queue on an earlier mm-new snapshot:

  - 128 GiB MADV_PAGEOUT, 144 threads, interleaved NUMA: 87,540 vs
    87,015 instructions per swapped page (-0.6%), 3,296 vs 3,304 MB/s,
    about 40 seconds of pageout on both. The difference is within the
    run-to-run spread.
  - usemem 64G in a 48G cgroup: with both kernels keeping the data in
    zswap, the median was 151.8 s (base) vs 145.2 s (xswap). That 4.3%
    difference is smaller than the run-to-run spread.
  - kbench, 1G memcg, 40 jobs, THP off, no writeback: median 225.58 s
    vs 225.21 s, total CPU 5657.9 s vs 5580.8 s, peak RSS 867 vs 863
    MiB, zswap peak 193 vs 227 MiB. This run measures the slot array
    and the zswap frontend; the backend is not used with writeback off.

Limitations
-----------

A large folio needs a contiguous physical range. If the range cannot be
allocated, the folio is split; a zswap-backed or mixed large folio is
read back at a smaller order. THP swapin is only used when the whole
range is contiguous on one device. Writeback needs a real swap device;
xswap-only capacity is still the zswap pool.

xswap.max=max reserves a large vmalloc range for the cluster_info
array. The per-type zswap tree of phase I is gone in this series: zswap
entries are indexed in the per-cluster backend table (phase IV). The
overcommit semantics for the swap address space are still open, as
described in the phase I posting. Runtime shrink is phase V and is not
part of this series.

This series depends on the phase I series ([PATCH v8 00/14]); apply
phase I first. The base is 1a7610248a38 (mm-new, 7.4.0-rc4); the phase
I tip is 779bedee9865 and this series ends at 3722b1e2daa3.

History:
======
[PATCH 00/12] mm, swap: give xswap a physical backend (xswap phase II)
https://lore.kernel.org/all/20261003005900.909710-1-hebaoquan@kylinos.cn/T/#u

[PATCH 0/6] mm, swap: charge xswap for physical backing (xswap phase III)
https://lore.kernel.org/all/20261003011111.1003090-1-hebaoquan@kylinos.cn/T/#u

The entire xswap code can be found here:
====
https://github.com/baoquan-he/linux.git xswap-v8

Baoquan He (27):
  mm, swap: tag a swap table entry with its owning xswap entry
  mm, swap: prepare the folio-less allocation path for xswap
  mm, swap: add a physical backend for xswap slots
  mm, swap: support swapoff of an xswap physical backend
  mm, swap: use the xswap physical backend
  mm, swap: fall back to disk when zswap refuses an xswap page
  mm, swap: reclaim physical slots backing cache-only xswap entries
  mm, swap: drop swap_folio_sector()
  mm, swap: drop a stale xswap physical slot range before reallocating
  mm, swap: publish the xswap backend owner before its reverse map
  mm, swap: skip a NOFS backend for xswap physical writeback
  mm, swap: pass the folio order through the swap slot allocator
  mm, swap: allocate a multi-slot range without a folio
  mm, swap: pass the folio order to the xswap physical backend
  mm, swap: enable large xswap folios with a contiguous physical slot
    range
  mm, swap: enable THP swapin for xswap entries
  mm, swap: do not retake the cluster lock when uncharging an xswap slot
  mm, swap: uncharge an xswap backend where its record is cleared
  mm, swap: account xswap backends for cgroup v1
  mm, swap: drop a refused xswap backend slot range directly
  mm, swap: route xswap by the zswap eligibility without flushing
  mm, swap: keep a per-cluster backend record for every swap device
  mm, swap: encode the per-slot backend record
  mm, swap: add accessors for the backend record
  mm, zswap: index entries in the swap device's backend table
  mm, swap: release a range of backend handles at once
  mm, swap: only run the xswap backend hooks on xswap devices

Nhat Pham (5):
  mm, swap: prepare the swap IO path for xswap backends
  mm, swap: split the swap memcg charge helpers
  mm, swap: do not charge zswap-backed xswap entries
  mm, swap: charge an xswap entry when it gets physical backing
  mm, swap: don't gate xswap on the physical swap free count

 .../admin-guide/cgroup-v1/memcg_test.rst      |    2 +-
 Documentation/admin-guide/mm/zswap.rst        |   12 +
 include/linux/memcontrol.h                    |    6 +
 include/linux/swap.h                          |   74 +-
 include/linux/swap_ops.h                      |   11 +-
 include/linux/zswap.h                         |   15 +-
 mm/memcontrol-v1.c                            |    3 +-
 mm/memcontrol.c                               |  170 +-
 mm/memory.c                                   |   25 +-
 mm/page_io.c                                  |  119 +-
 mm/shmem.c                                    |    2 +-
 mm/swap.h                                     |   52 +-
 mm/swap_state.c                               |    9 +
 mm/swap_table.h                               |   92 +-
 mm/swapfile.c                                 | 1567 ++++++++++++++---
 mm/vmscan.c                                   |   48 +-
 mm/zswap.c                                    |  258 ++-
 17 files changed, 2008 insertions(+), 457 deletions(-)

-- 
2.54.0



^ permalink raw reply	[flat|nested] 33+ messages in thread

* [PATCH v2 01/32] mm, swap: prepare the swap IO path for xswap backends
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 02/32] mm, swap: tag a swap table entry with its owning xswap entry Baoquan He
                   ` (30 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Nhat Pham <nphamcs@gmail.com>

An xswap folio is written to a physical device, but stays in the swap
cache of its own xswap entry, so folio->swap no longer says where the IO
goes.

The batched swap IO path takes the bio sector from folio->swap, which for
such a folio resolves the xswap device. That device has no bdev and no
extents, so the IO is set up wrong.

Pass the entry explicitly instead: __swap_writeout(), swap_add_folio()
and swap_ops->can_merge() take it as a parameter, and swap_iocb records
the first entry of each batch. The merge check, the bio sector and the
completion path all use it.

Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/swap.h     |  1 +
 include/linux/swap_ops.h |  9 +++---
 mm/page_io.c             | 59 ++++++++++++++++++++--------------------
 mm/swap.h                |  3 +-
 mm/swapfile.c            | 13 +++++++++
 mm/zswap.c               |  2 +-
 6 files changed, 51 insertions(+), 36 deletions(-)

diff --git a/include/linux/swap.h b/include/linux/swap.h
index 7979b56e5224..0c13f2c620e7 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -415,6 +415,7 @@ extern bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry);
 extern int swp_swapcount(swp_entry_t entry);
 extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
 sector_t swap_folio_sector(struct folio *folio);
+sector_t swap_entry_sector(swp_entry_t entry);
 
 /*
  * If there is an existing swap slot reference (swap entry) and the caller
diff --git a/include/linux/swap_ops.h b/include/linux/swap_ops.h
index d57b95931cd9..58100dfac056 100644
--- a/include/linux/swap_ops.h
+++ b/include/linux/swap_ops.h
@@ -10,6 +10,7 @@ struct swap_iocb {
 		struct bio	bio;
 	};
 	struct bio_vec		bvecs[SWAP_CLUSTER_MAX];
+	swp_entry_t		entry;	/* First entry of the batch */
 	int			nr_bvecs;
 	int			len;
 };
@@ -40,15 +41,15 @@ struct swap_io_ctx {
 struct swap_ops {
 	unsigned int		flags;
 
-	bool (*can_merge)(struct folio *folio, struct folio *prev_folio,
-			size_t prev_folio_size, int rw);
+	bool (*can_merge)(struct folio *folio, swp_entry_t entry,
+			  struct swap_iocb *sio, int rw);
 	void (*submit_write)(struct swap_io_ctx *ctx);
 	void (*submit_read)(struct swap_io_ctx *ctx);
 };
 
 void swap_fs_prepare_rw(struct swap_io_ctx *ctx, int rw, struct iov_iter *iter);
-bool swap_fs_can_merge(struct folio *folio, struct folio *prev_folio,
-		size_t prev_folio_size, int rw);
+bool swap_fs_can_merge(struct folio *folio, swp_entry_t entry,
+		       struct swap_iocb *sio, int rw);
 int swap_fs_activate(struct swap_info_struct *sis, const struct swap_ops *ops);
 
 #endif /* _MM_SWAP_OPS_H */
diff --git a/mm/page_io.c b/mm/page_io.c
index 54bdeab13641..2bc3b46e5529 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -265,7 +265,7 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 		return AOP_WRITEPAGE_ACTIVATE;
 	}
 
-	__swap_writeout(ctx, folio);
+	__swap_writeout(ctx, folio, folio->swap);
 	return 0;
 out_unlock:
 	folio_unlock(folio);
@@ -340,34 +340,33 @@ int sio_pool_init(void)
 }
 
 static bool swap_can_merge(struct swap_io_ctx *ctx, struct folio *folio,
-		int rw)
+		swp_entry_t entry, int rw)
 {
-	struct swap_info_struct *sis = __swap_entry_to_info(folio->swap);
-	struct bio_vec *last_bv = &ctx->sio->bvecs[ctx->sio->nr_bvecs - 1];
-	struct folio *prev_folio = bvec_folio(last_bv);
-	size_t prev_folio_size = folio_size(prev_folio);
+	struct swap_info_struct *sis = __swap_entry_to_info(entry);
 
 	if (ctx->sis != sis)
 		return false;
-	return sis->ops->can_merge(folio, prev_folio, prev_folio_size, rw);
+	return sis->ops->can_merge(folio, entry, ctx->sio, rw);
 }
 
-static void swap_add_folio(struct swap_io_ctx *ctx, struct folio *folio, int rw)
+static void swap_add_folio(struct swap_io_ctx *ctx, struct folio *folio,
+			   swp_entry_t entry, int rw)
 {
-	struct swap_info_struct *sis = __swap_entry_to_info(folio->swap);
+	struct swap_info_struct *sis = __swap_entry_to_info(entry);
 	struct swap_iocb *sio = ctx->sio;
 
 	/*
 	 * Callers flush a batch this folio can't join before adding it,
 	 * see swap_read_folio() and __swap_writeout().
 	 */
-	VM_WARN_ON_ONCE(sio && !swap_can_merge(ctx, folio, rw));
+	VM_WARN_ON_ONCE(sio && !swap_can_merge(ctx, folio, entry, rw));
 
 	if (!sio) {
 		ctx->sis = sis;
 		ctx->sio = sio = mempool_alloc(sio_pool, GFP_NOIO);
 		sio->nr_bvecs = 0;
 		sio->len = 0;
+		sio->entry = entry;
 	}
 	bvec_set_folio(&sio->bvecs[sio->nr_bvecs], folio, folio_size(folio), 0);
 	sio->len += folio_size(folio);
@@ -388,7 +387,8 @@ static void swap_add_folio(struct swap_io_ctx *ctx, struct folio *folio, int rw)
 	}
 }
 
-void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
+void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio,
+		     swp_entry_t entry)
 {
 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
 
@@ -410,9 +410,9 @@ void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	 * swap_read_folio(). But the write path opens no pressure window,
 	 * so there is nothing to order this against.
 	 */
-	if (ctx->sio && !swap_can_merge(ctx, folio, WRITE))
+	if (ctx->sio && !swap_can_merge(ctx, folio, entry, WRITE))
 		swap_write_submit(ctx);
-	swap_add_folio(ctx, folio, WRITE);
+	swap_add_folio(ctx, folio, entry, WRITE);
 }
 
 /*
@@ -493,7 +493,7 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	 * window opens, so that each batch is billed for its own read
 	 * rather than for the next folio's lookup and decompression.
 	 */
-	if (ctx->sio && !swap_can_merge(ctx, folio, READ))
+	if (ctx->sio && !swap_can_merge(ctx, folio, folio->swap, READ))
 		swap_read_submit(ctx);
 
 	/*
@@ -531,7 +531,7 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
-	swap_add_folio(ctx, folio, READ);
+	swap_add_folio(ctx, folio, folio->swap, READ);
 
 	/*
 	 * Synchronous devices do the whole read at submission time, submit
@@ -563,8 +563,6 @@ static void swap_fs_write_complete(struct kiocb *iocb, long ret)
 	bool failed = ret != sio->len;
 
 	if (failed) {
-		struct folio *folio = bvec_folio(&sio->bvecs[0]);
-
 		/*
 		 * In the case of swap-over-nfs, this can be a temporary failure
 		 * if the system has limited memory for allocating transmit
@@ -572,7 +570,7 @@ static void swap_fs_write_complete(struct kiocb *iocb, long ret)
 		 * folio_rotate_reclaimable but rate-limit the messages.
 		 */
 		pr_err_ratelimited("Write error %ld on dio swapfile (%llu)\n",
-				   ret, swap_dev_pos(folio->swap));
+				   ret, swap_dev_pos(sio->entry));
 	}
 
 	swap_write_end(sio, failed);
@@ -644,7 +642,7 @@ static void swap_bdev_submit_write(struct swap_io_ctx *ctx)
 	bio_init(bio, ctx->sis->bdev, sio->bvecs, ARRAY_SIZE(sio->bvecs),
 			REQ_OP_WRITE | REQ_SWAP);
 	bio->bi_iter.bi_size = sio->len;
-	bio->bi_iter.bi_sector = swap_folio_sector(bio_first_folio_all(bio));
+	bio->bi_iter.bi_sector = swap_entry_sector(sio->entry);
 	bio_associate_blkg_from_folio(bio, bio_first_folio_all(bio));
 
 	if (ctx->sis->flags & SWP_SYNCHRONOUS_IO) {
@@ -673,7 +671,7 @@ static void swap_bdev_submit_read(struct swap_io_ctx *ctx)
 	bio_init(bio, ctx->sis->bdev, sio->bvecs, ARRAY_SIZE(sio->bvecs),
 			REQ_OP_READ);
 	bio->bi_iter.bi_size = sio->len;
-	bio->bi_iter.bi_sector = swap_folio_sector(bio_first_folio_all(bio));
+	bio->bi_iter.bi_sector = swap_entry_sector(sio->entry);
 
 	if (ctx->sis->flags & SWP_SYNCHRONOUS_IO) {
 		/*
@@ -691,13 +689,15 @@ static void swap_bdev_submit_read(struct swap_io_ctx *ctx)
 	}
 }
 
-static bool swap_bdev_can_merge(struct folio *folio, struct folio *prev_folio,
-		size_t prev_folio_size, int rw)
+static bool swap_bdev_can_merge(struct folio *folio, swp_entry_t entry,
+				struct swap_iocb *sio, int rw)
 {
-	if (swap_folio_sector(folio) !=
-	    swap_folio_sector(prev_folio) + (prev_folio_size >> SECTOR_SHIFT))
+	if (swap_entry_sector(entry) !=
+	    swap_entry_sector(sio->entry) + (sio->len >> SECTOR_SHIFT))
 		return false;
-	if (rw == WRITE && !folio_blkg_can_merge(folio, prev_folio))
+	if (rw == WRITE &&
+	    !folio_blkg_can_merge(folio,
+				  bvec_folio(&sio->bvecs[sio->nr_bvecs - 1])))
 		return false;
 	return true;
 }
@@ -713,7 +713,7 @@ void swap_fs_prepare_rw(struct swap_io_ctx *ctx, int rw, struct iov_iter *iter)
 	struct swap_iocb *sio = ctx->sio;
 
 	init_sync_kiocb(&sio->iocb, ctx->sis->swap_file);
-	sio->iocb.ki_pos = swap_dev_pos(bvec_folio(&sio->bvecs[0])->swap);
+	sio->iocb.ki_pos = swap_dev_pos(sio->entry);
 	if (rw == WRITE)
 		sio->iocb.ki_complete = swap_fs_write_complete;
 	else
@@ -724,11 +724,10 @@ void swap_fs_prepare_rw(struct swap_io_ctx *ctx, int rw, struct iov_iter *iter)
 }
 EXPORT_SYMBOL_GPL(swap_fs_prepare_rw);
 
-bool swap_fs_can_merge(struct folio *folio, struct folio *prev_folio,
-		size_t prev_folio_size, int rw)
+bool swap_fs_can_merge(struct folio *folio, swp_entry_t entry,
+		       struct swap_iocb *sio, int rw)
 {
-	return swap_dev_pos(folio->swap) ==
-		swap_dev_pos(prev_folio->swap) + prev_folio_size;
+	return swap_dev_pos(entry) == swap_dev_pos(sio->entry) + sio->len;
 }
 EXPORT_SYMBOL_GPL(swap_fs_can_merge);
 
diff --git a/mm/swap.h b/mm/swap.h
index d488a69c2809..8979e8a7eb42 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -259,7 +259,8 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio);
 void swap_read_submit(struct swap_io_ctx *ctx);
 void swap_write_submit(struct swap_io_ctx *ctx);
 int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio);
-void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio);
+void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio,
+		     swp_entry_t entry);
 
 /* linux/mm/swap_state.c */
 extern struct address_space swap_space __read_mostly;
diff --git a/mm/swapfile.c b/mm/swapfile.c
index c66b4bbc3af7..e15b20274dfb 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -504,6 +504,19 @@ sector_t swap_folio_sector(struct folio *folio)
 	return sector << (PAGE_SHIFT - 9);
 }
 
+sector_t swap_entry_sector(swp_entry_t entry)
+{
+	struct swap_info_struct *sis = __swap_entry_to_info(entry);
+	struct swap_extent *se;
+	sector_t sector;
+	pgoff_t offset;
+
+	offset = swp_offset(entry);
+	se = offset_to_swap_extent(sis, offset);
+	sector = se->start_block + (offset - se->start_page);
+	return sector << (PAGE_SHIFT - 9);
+}
+
 /*
  * swap allocation tell device that a cluster of swap can now be discarded,
  * to allow the swap device to optimize its wear-levelling.
diff --git a/mm/zswap.c b/mm/zswap.c
index 52f350b2c452..b6a328ab787a 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1167,7 +1167,7 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	folio_put(folio);
 
 	/* start writeback */
-	__swap_writeout(ctx, folio);
+	__swap_writeout(ctx, folio, folio->swap);
 
 	return 0;
 
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 02/32] mm, swap: tag a swap table entry with its owning xswap entry
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
  2026-12-03 18:12 ` [PATCH v2 01/32] mm, swap: prepare the swap IO path for xswap backends Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 03/32] mm, swap: prepare the folio-less allocation path for xswap Baoquan He
                   ` (29 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

An xswap folio can be written out to a physical device. The data then
lives in a slot on that device, with no folio in the swap cache. Store
the xswap entry in that slot's swap table entry, so the owner of a
physical slot can be found again.

The low three bits of a swap table entry tell its type; 0b100 is free.
Use it to mark an entry that points at its owner, with the xswap type and
offset in the bits above.

Two paths hand out or cache a slot and know only the other two types.
Make them skip a pointer entry: cluster_scan_range() must not hand it out
as free, and __swap_cache_add_check() must not put a folio over it.
Otherwise readahead on a physical device can walk into it.

Co-developed-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swap_state.c |  3 +++
 mm/swap_table.h | 61 +++++++++++++++++++++++++++++++++++++++++++++----
 mm/swapfile.c   |  3 +++
 3 files changed, 63 insertions(+), 4 deletions(-)

diff --git a/mm/swap_state.c b/mm/swap_state.c
index 90cd99c25dfe..7298a9894737 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -189,6 +189,9 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 		return -ENOENT;
 	ci_off = swp_cluster_offset(targ_entry);
 	old_tb = __swap_table_get(ci, ci_off);
+	/* Readahead of a physical device can hit an xswap-backing slot. */
+	if (swp_tb_is_pointer(old_tb))
+		return -ENOENT;
 	if (swp_tb_is_folio(old_tb))
 		return -EEXIST;
 	/*
diff --git a/mm/swap_table.h b/mm/swap_table.h
index 072625d60d54..eadd0547d2ad 100644
--- a/mm/swap_table.h
+++ b/mm/swap_table.h
@@ -28,7 +28,7 @@ struct swap_memcg_table {
  * NULL:     |---------------- 0 ---------------| - Free slot
  * Shadow:   |SWAP_COUNT|Z|---- SHADOW_VAL ---|1| - Swapped out slot
  * PFN:      |SWAP_COUNT|Z|------ PFN -------|10| - Cached slot
- * Pointer:  |----------- Pointer ----------|100| - (Unused)
+ * Pointer:  |C|-- xswap type/offset --|100| - Backend slot
  * Bad:      |------------- 1 -------------|1000| - Bad slot
  * HIB:      |    0     |------- 1 -------|10000| - Hibernation slot
  *
@@ -50,9 +50,9 @@ struct swap_memcg_table {
  * - PFN: Swap slot is in use, and cached. Memcg info is recorded on the page
  *   struct.
  *
- * - Pointer: Unused yet. `0b100` is reserved for potential pointer usage
- *   because only the lower three bits can be used as a marker for 8 bytes
- *   aligned pointers.
+ * - Pointer: A physical swap slot backed by an xswap entry. `0b100` marks it
+ *   and the xswap type and offset go above it; C is SWP_RMAP_CACHE_ONLY. See
+ *   the layout in the CONFIG_XSWAP block below.
  *
  * - Bad: Swap slot is reserved, protects swap header or holes on swap devices.
  *
@@ -90,6 +90,59 @@ struct swap_memcg_table {
 /* Hibernation slot: ends with 0b10000, no count, rests of bits are all 1 */
 #define SWP_TB_HIB		(((~0UL) << 4) & ~SWP_TB_COUNT_MASK)
 
+#ifdef CONFIG_XSWAP
+/*
+ * Pointer-tagged swap table entry: the reverse map from a physical slot to
+ * the xswap entry it backs. Layout:
+ *
+ *   Pointer:  | xswap_type(8) | xswap_offset(53) |100|
+ *
+ * The low three bits identify the entry: 0b000 is a free, bad or hibernation
+ * slot, a shadow entry ends in 0b01 and a cached folio in 0b10, which leaves
+ * 0b100 as the only marker still free.
+ */
+#define SWP_TB_PTR_MARK			0b100UL
+#define SWP_TB_PTR_OFF_BITS		53
+#define SWP_TB_PTR_TYPE_BITS		8
+#define SWP_TB_PTR_OFF_SHIFT		3
+#define SWP_TB_PTR_TYPE_SHIFT		(SWP_TB_PTR_OFF_SHIFT + \
+					 SWP_TB_PTR_OFF_BITS)
+#define SWP_TB_PTR_OFF_MASK		((1UL << SWP_TB_PTR_OFF_BITS) - 1)
+#define SWP_TB_PTR_TYPE_MASK		((1UL << SWP_TB_PTR_TYPE_BITS) - 1)
+
+static inline bool swp_tb_is_pointer(unsigned long swp_tb)
+{
+	return (swp_tb & (BIT(3) - 1)) == SWP_TB_PTR_MARK;
+}
+
+static inline unsigned long xswap_entry_to_rmap(swp_entry_t entry)
+{
+	unsigned long type = swp_type(entry);
+	unsigned long off = swp_offset(entry);
+
+	VM_WARN_ON_ONCE(type > SWP_TB_PTR_TYPE_MASK);
+	VM_WARN_ON_ONCE(off > SWP_TB_PTR_OFF_MASK);
+	return (type << SWP_TB_PTR_TYPE_SHIFT) |
+	       (off << SWP_TB_PTR_OFF_SHIFT) |
+	       SWP_TB_PTR_MARK;
+}
+
+static inline swp_entry_t xswap_rmap_to_entry(unsigned long swp_tb)
+{
+	unsigned long type = (swp_tb >> SWP_TB_PTR_TYPE_SHIFT) &
+			     SWP_TB_PTR_TYPE_MASK;
+	unsigned long off = (swp_tb >> SWP_TB_PTR_OFF_SHIFT) &
+			    SWP_TB_PTR_OFF_MASK;
+
+	return swp_entry(type, off);
+}
+#else /* !CONFIG_XSWAP */
+static inline bool swp_tb_is_pointer(unsigned long swp_tb)
+{
+	return false;
+}
+#endif /* CONFIG_XSWAP */
+
 /* Macro for shadow offset calculation */
 #define SWAP_COUNT_SHIFT	SWP_TB_FLAGS_BITS
 
diff --git a/mm/swapfile.c b/mm/swapfile.c
index e15b20274dfb..7b6c7e9614b5 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -1133,6 +1133,9 @@ static bool cluster_scan_range(struct swap_info_struct *si,
 		swp_tb = __swap_table_get(ci, ci_off);
 		if (swp_tb_is_null(swp_tb))
 			continue;
+		/* Backs an xswap entry: the slot is not allocatable. */
+		if (swp_tb_is_pointer(swp_tb))
+			return false;
 		if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb)) {
 			if (!vm_swap_full())
 				return false;
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 03/32] mm, swap: prepare the folio-less allocation path for xswap
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
  2026-12-03 18:12 ` [PATCH v2 01/32] mm, swap: prepare the swap IO path for xswap backends Baoquan He
  2026-12-03 18:12 ` [PATCH v2 02/32] mm, swap: tag a swap table entry with its owning xswap entry Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 04/32] mm, swap: add a physical backend for xswap slots Baoquan He
                   ` (28 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

The xswap backend writes data to a slot on a real swap device. That slot
has no folio of its own, a case only hibernation used before, so the NULL
folio path is no longer limited to hibernation.

A folio-less slot packs into a cluster already in use instead of taking a
free cluster. Only a free cluster can serve a large order, so the free
ones are kept for large folios.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 23 +++++++++++------------
 1 file changed, 11 insertions(+), 12 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 7b6c7e9614b5..b164a6c50c29 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -1169,8 +1169,10 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 	 * Such swap slots starts with count == 0 and will be increased
 	 * upon folio unmap.
 	 *
-	 * Else, it's a exclusive order 0 allocation for hibernation.
-	 * The slot carries no swap count and is freed by offset.
+	 * Else, it's an exclusive order 0 allocation for a slot that has
+	 * no folio of its own: hibernation, and the physical slot that
+	 * backs an xswap entry.  The slot carries no swap count and is
+	 * freed by its owner.
 	 */
 	if (likely(folio)) {
 		order = folio_order(folio);
@@ -1178,16 +1180,12 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 		swap_cluster_assert_empty(ci, ci_off, nr_pages, false);
 		__swap_cache_add_folio(ci, folio, swp_entry(si->type,
 							    ci_off + cluster_offset(si, ci)));
-	} else if (IS_ENABLED(CONFIG_HIBERNATION)) {
+	} else {
 		order = 0;
 		nr_pages = 1;
 		swap_cluster_assert_empty(ci, ci_off, 1, false);
-		/* Exclusively owned by hibernation, must never enter the swap cache */
+		/* Owned by hibernation or the xswap backend; never cached. */
 		__swap_table_set(ci, ci_off, SWP_TB_HIB);
-	} else {
-		/* Allocation without folio is only possible with hibernation */
-		WARN_ON_ONCE(1);
-		return false;
 	}
 
 	/*
@@ -1402,11 +1400,12 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 
 new_cluster:
 	/*
-	 * A no_cache allocation cannot keep a per-CPU cluster, so pack it
-	 * into a cluster already in use and leave the free ones to
-	 * allocations that can use a whole one.
+	 * A slot with no folio packs into a cluster already in use: a free
+	 * cluster is the only thing a large order can allocate from.
+	 * nonfull_clusters is not pulled forward: free vs nonfull is
+	 * swap_prefer_free_cluster()'s choice for every allocation.
 	 */
-	if (no_cache && order < PMD_ORDER) {
+	if ((!folio || no_cache) && order < PMD_ORDER) {
 		found = alloc_swap_scan_list(si, &si->frag_clusters[order],
 					     folio, false, no_cache);
 		if (found)
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 04/32] mm, swap: add a physical backend for xswap slots
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (2 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 03/32] mm, swap: prepare the folio-less allocation path for xswap Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 05/32] mm, swap: support swapoff of an xswap physical backend Baoquan He
                   ` (27 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

An xswap slot holds its data only in the zswap pool. There is no
second copy anywhere, so once the pool drops the entry the data is
gone. Give xswap slots a physical backend they can be written out to:
a slot on the highest-priority real swap device.

The backend takes its slots from a lower-priority device. The cluster it
fills must not go into this CPU's swapout cache: swap_alloc_fast() reuses
that cache without checking the device, so one backend allocation would
send every later swapout there and xswap would never be picked again.

The backend is recorded per slot in ci->xs_table[], an array of
SWAPFILE_CLUSTER unsigned longs that is allocated on first use. If a
cluster only ever holds zswap-only slots, xs_table[] is never
allocated. Zero means "no backend".

Freeing an xswap slot releases its physical slot. The release checks
that the physical slot still belongs to this xswap entry. If it belongs
to another one, the record is stale: that slot was freed and handed out
again, and may by then belong to another entry, whose data must not be
dropped. A stale record can also name a slot on a device that has been
swapped off or reused, or a cluster whose table is already gone, so the
release pins the device, rejects a device reused as xswap, and checks
the offset and the table before touching either.

The target device is revalidated after it is pinned, so a swap_info
reused as an xswap device is not picked as its own backend.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swap.h     |  24 ++++
 mm/swapfile.c | 339 +++++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 361 insertions(+), 2 deletions(-)

diff --git a/mm/swap.h b/mm/swap.h
index 8979e8a7eb42..73aadd0f2bc8 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -58,6 +58,9 @@ struct swap_cluster_info {
 	u8 order;
 	atomic_long_t __rcu *table;	/* Swap table entries, see mm/swap_table.h */
 	unsigned int *extend_table;	/* For large swap count, protected by ci->lock */
+#ifdef CONFIG_XSWAP
+	unsigned long *xs_table;	/* Physical backend per slot, lazily allocated */
+#endif
 #ifdef CONFIG_MEMCG
 	struct swap_memcg_table *memcg_table;	/* Swap table entries' cgroup record */
 #endif
@@ -505,4 +508,25 @@ extern const struct swap_ops swap_bdev_ops;
 int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 		struct list_head *folio_list);
 
+#ifdef CONFIG_XSWAP
+swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot);
+swp_entry_t xswap_backend_alloc(swp_entry_t entry);
+void xswap_backend_free(swp_entry_t entry, swp_entry_t phys);
+#else
+static inline swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci,
+					     unsigned int slot)
+{
+	return (swp_entry_t){};
+}
+
+static inline swp_entry_t xswap_backend_alloc(swp_entry_t entry)
+{
+	return (swp_entry_t){};
+}
+
+static inline void xswap_backend_free(swp_entry_t entry, swp_entry_t phys)
+{
+}
+#endif /* CONFIG_XSWAP */
+
 #endif /* _MM_SWAP_H */
diff --git a/mm/swapfile.c b/mm/swapfile.c
index b164a6c50c29..9eb4284e9bc0 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -87,6 +87,13 @@ static void xswap_debugfs_del(struct swap_info_struct *si);
 static int xswap_map_clusters(struct swap_info_struct *si,
 			      unsigned long start_idx, unsigned long nr,
 			      bool link_free);
+static void xswap_free_phys_slot(struct swap_info_struct *si,
+				 swp_entry_t entry, swp_entry_t phys);
+static void xswap_release_slot_backend(struct swap_info_struct *si,
+				       struct swap_cluster_info *ci,
+				       unsigned int slot);
+static void xswap_free_xs_table(struct swap_info_struct *si,
+				struct swap_cluster_info *ci);
 
 static int xswap_create(int prio);
 static int xswap_create_by_name(const char *name, int swap_flags);
@@ -827,6 +834,14 @@ static void swap_cluster_schedule_discard(struct swap_info_struct *si,
 static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci)
 {
 	swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, false);
+#ifdef CONFIG_XSWAP
+	/*
+	 * An empty cluster can still hold records. Give them back first:
+	 * swap_cluster_free_table() frees the table the owner ID comes from.
+	 */
+	if (si->flags & SWP_XSWAP)
+		xswap_free_xs_table(si, ci);
+#endif
 	swap_cluster_free_table(ci);
 	move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
 	ci->order = 0;
@@ -1085,6 +1100,12 @@ static bool cluster_reclaim_range(struct swap_info_struct *si,
 	spin_unlock(&ci->lock);
 	do {
 		swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
+		/*
+		 * A pointer-tagged slot backs an xswap entry, not a cached
+		 * folio, so it can't be reclaimed here. Reject the range.
+		 */
+		if (swp_tb_is_pointer(swp_tb))
+			break;
 		if (swp_tb_get_count(swp_tb))
 			break;
 		if (swp_tb_is_folio(swp_tb))
@@ -1854,6 +1875,14 @@ static void __swap_cluster_put_entry(struct swap_cluster_info *ci,
 
 	lockdep_assert_held(&ci->lock);
 	swp_tb = __swap_table_get(ci, ci_off);
+	/*
+	 * A pointer-tagged slot has no count of its own. Putting one would
+	 * corrupt the reverse mapping, so never touch it here.
+	 */
+	if (swp_tb_is_pointer(swp_tb)) {
+		VM_WARN_ON_ONCE(1);
+		return;
+	}
 	count = __swp_tb_get_count(swp_tb);
 
 	VM_WARN_ON_ONCE(count <= 0);
@@ -1962,8 +1991,8 @@ static int __swap_cluster_dup_entry(struct swap_cluster_info *ci,
 
 	lockdep_assert_held(&ci->lock);
 	swp_tb = __swap_table_get(ci, ci_off);
-	/* Bad or special slots can't be handled */
-	if (WARN_ON_ONCE(swp_tb_is_bad(swp_tb)))
+	/* Bad, pointer-tagged and other special slots can't be handled */
+	if (WARN_ON_ONCE(swp_tb_is_bad(swp_tb) || swp_tb_is_pointer(swp_tb)))
 		return -EINVAL;
 	count = __swp_tb_get_count(swp_tb);
 	/* Must be either cached or have a count already */
@@ -2343,6 +2372,11 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 		VM_WARN_ON(!swp_tb_is_hibernation(old_tb) &&
 			   (!swp_tb_is_shadow(old_tb) || __swp_tb_get_count(old_tb) > 1));
 
+#ifdef CONFIG_XSWAP
+		if (ci->xs_table && ci->xs_table[ci_off])
+			xswap_release_slot_backend(si, ci, ci_off);
+#endif
+
 		/* Resetting the slot to NULL also clears the inline flags. */
 		__swap_table_set(ci, ci_off, null_to_swp_tb());
 		if (!SWAP_TABLE_HAS_ZEROFLAG)
@@ -3252,6 +3286,82 @@ static unsigned long find_next_to_unuse(struct swap_info_struct *si,
 
 	return 0;
 }
+
+#ifdef CONFIG_XSWAP
+/*
+ * Free the physical slot @phys and clear its reverse mapping. @entry is the
+ * xswap entry that recorded @phys. The slot is only freed while it still
+ * says it belongs to @entry: our record can go stale, and @phys may by then
+ * have been handed to another xswap entry, whose data must not be dropped.
+ *
+ * free_cluster()/partial_free_cluster() require the cluster lock.
+ */
+static void xswap_free_phys_slot(struct swap_info_struct *si,
+				 swp_entry_t entry, swp_entry_t phys)
+{
+	struct swap_cluster_info *ci;
+	unsigned long swp_tb;
+	unsigned long offset = swp_offset(phys);
+
+	/* The record can be stale: the device may be reused as xswap. */
+	if (!get_swap_device_info(si))
+		return;
+	if (si->flags & SWP_XSWAP)
+		goto out_put;
+	if (offset >= si->max)
+		goto out_put;
+
+	ci = swap_cluster_lock(si, offset);
+	if (!ci)
+		goto out_put;
+
+	if (!cluster_table_is_alloced(ci))
+		goto out_unlock;
+
+	swp_tb = __swap_table_get(ci, offset % SWAPFILE_CLUSTER);
+	if (!swp_tb_is_pointer(swp_tb) ||
+	    xswap_rmap_to_entry(swp_tb).val != entry.val) {
+		/* Already freed, or the slot was handed to someone else. */
+		goto out_unlock;
+	}
+
+	__swap_table_set(ci, offset % SWAPFILE_CLUSTER, null_to_swp_tb());
+	ci->count--;
+
+	/* The slot must not be allocatable before its invalidate hooks run. */
+	swap_range_free(si, offset, 1);
+
+	if (!ci->count)
+		free_cluster(si, ci);
+	else
+		partial_free_cluster(si, ci);
+out_unlock:
+	swap_cluster_unlock(ci);
+out_put:
+	put_swap_device(si);
+}
+
+/*
+ * An xswap slot being freed may still own a physical slot. Drop it, or the
+ * physical space and its reverse mapping leak. Caller holds the xswap
+ * cluster lock; the physical cluster lock is only ever taken below it.
+ */
+static void xswap_release_slot_backend(struct swap_info_struct *si,
+				       struct swap_cluster_info *ci,
+				       unsigned int slot)
+{
+	swp_entry_t entry = swp_entry(si->type, cluster_offset(si, ci) + slot);
+	struct swap_info_struct *psi;
+	swp_entry_t phys = { .val = ci->xs_table[slot] };
+
+	WRITE_ONCE(ci->xs_table[slot], 0);
+
+	psi = swap_type_to_info(swp_type(phys));
+	if (psi)
+		xswap_free_phys_slot(psi, entry, phys);
+}
+
+#endif /* CONFIG_XSWAP */
 static int try_to_unuse(unsigned int type)
 {
 	struct mm_struct *prev_mm;
@@ -3586,6 +3696,7 @@ static void free_swap_cluster_info(struct swap_info_struct *si)
 		for (i = 0; i < nr_mapped; i++) {
 			ci = &cluster_info[i];
 			spin_lock(&ci->lock);
+			xswap_free_xs_table(si, ci);
 			if (cluster_table_is_alloced(ci)) {
 				swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);
 				swap_cluster_free_table(ci);
@@ -4189,6 +4300,230 @@ static void xswap_publish_clusters(struct swap_info_struct *si,
 	spin_unlock(&si->lock);
 }
 
+/* The physical slot backing @slot, or zero. */
+swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot)
+{
+	unsigned long *xs = READ_ONCE(ci->xs_table);
+
+	if (!xs || !xs[slot])
+		return (swp_entry_t){};
+
+	return (swp_entry_t){ .val = xs[slot] };
+}
+
+/* Cluster lock held. The mapped prefix only grows while the device exists. */
+static unsigned long *xswap_xs_table_locked(struct swap_cluster_info *ci,
+					    gfp_t gfp)
+{
+	unsigned long *xs = ci->xs_table;
+
+	if (xs)
+		return xs;
+
+	/* The owning entry is pinned, so the cluster survives the relock. */
+	if (gfp & __GFP_DIRECT_RECLAIM) {
+		spin_unlock(&ci->lock);
+		xs = kcalloc(SWAPFILE_CLUSTER, sizeof(*xs), gfp);
+		spin_lock(&ci->lock);
+	} else {
+		xs = kcalloc(SWAPFILE_CLUSTER, sizeof(*xs), gfp);
+	}
+
+	if (!xs)
+		return NULL;
+	if (cmpxchg(&ci->xs_table, NULL, xs)) {
+		kfree(xs);
+		xs = ci->xs_table;
+	}
+	return xs;
+}
+
+/*
+ * 4K per cluster, and this runs in reclaim, so it has to be able to sleep.
+ */
+static bool xswap_slot_set_backend(struct swap_cluster_info *ci,
+				   unsigned int slot, swp_entry_t phys)
+{
+	unsigned long *xs = xswap_xs_table_locked(ci, GFP_KERNEL | __GFP_HIGH |
+						  __GFP_NOMEMALLOC);
+
+	if (!xs)
+		return false;
+	WRITE_ONCE(xs[slot], phys.val);
+	return true;
+}
+
+/*
+ * Drop the table of cluster @idx and every backend it still records. The
+ * cluster is going away, so nothing else will: the physical slots would stay
+ * allocated and their reverse mappings would keep pointing at an xswap entry
+ * whose cluster_info is about to be unmapped. Caller holds ci->lock.
+ */
+static void xswap_free_xs_table(struct swap_info_struct *si,
+				struct swap_cluster_info *ci)
+{
+	unsigned long *xs = ci->xs_table;
+	unsigned int slot;
+
+	if (!xs)
+		return;
+
+	for (slot = 0; slot < SWAPFILE_CLUSTER; slot++) {
+		if (xs[slot])
+			xswap_release_slot_backend(si, ci, slot);
+	}
+
+	kfree(xs);
+	ci->xs_table = NULL;
+}
+
+/* Order-0 slot from @si, no folio attached; goes through the per-CPU cache. */
+static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si)
+{
+	struct swap_cluster_info *ci;
+	unsigned long pcp_offset, offset = SWAP_ENTRY_INVALID;
+
+	local_lock(&percpu_swap_cluster.lock);
+	/*
+	 * A backend slot lands on a device the next swapout would not have
+	 * picked, so it must not become the cached cluster:
+	 * swap_alloc_fast() reuses that cache without picking a device
+	 * again.  Start from the cached cursor if it already points at this
+	 * device, but never install this device for the next swapout.
+	 */
+	if (this_cpu_read(percpu_swap_cluster.si[0]) == si) {
+		pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);
+		if (pcp_offset) {
+			ci = swap_cluster_lock(si, pcp_offset);
+			if (cluster_is_usable(ci, 0))
+				offset = alloc_swap_scan_cluster(si, ci, NULL,
+								 pcp_offset,
+								 true);
+			else
+				swap_cluster_unlock(ci);
+		}
+	}
+	if (offset == SWAP_ENTRY_INVALID)
+		offset = cluster_alloc_swap_entry(si, NULL, true);
+	local_unlock(&percpu_swap_cluster.lock);
+
+	return offset;
+}
+
+static swp_entry_t xswap_alloc_phys_slot(void)
+{
+	struct swap_info_struct *devs[MAX_SWAPFILES], *si;
+	int nr = 0, i;
+
+	/*
+	 * Snapshot the candidate devices in priority order. swap_info
+	 * structs are never freed, so the pointers stay valid; liveness is
+	 * re-checked below.
+	 */
+	spin_lock(&swap_avail_lock);
+	plist_for_each_entry(si, &swap_avail_head, avail_list) {
+		if (si->flags & SWP_XSWAP)
+			continue;
+		if (nr == MAX_SWAPFILES)
+			break;
+		devs[nr++] = si;
+	}
+	spin_unlock(&swap_avail_lock);
+
+	for (i = 0; i < nr; i++) {
+		unsigned long offset;
+
+		if (!get_swap_device_info(devs[i]))
+			continue;
+		/* The device may have been reused since the snapshot. */
+		if (devs[i]->flags & SWP_XSWAP) {
+			put_swap_device(devs[i]);
+			continue;
+		}
+		offset = xswap_alloc_slot_local(devs[i]);
+		put_swap_device(devs[i]);
+		if (offset && offset != SWAP_ENTRY_INVALID)
+			return swp_entry(devs[i]->type, offset);
+	}
+
+	return (swp_entry_t){};
+}
+
+/* Reverse mapping: record @entry as the owner of physical slot @phys. */
+static void xswap_install_rmap(swp_entry_t phys, swp_entry_t entry)
+{
+	struct swap_info_struct *si = swap_type_to_info(swp_type(phys));
+	struct swap_cluster_info *ci;
+	unsigned long off = swp_offset(phys);
+
+	if (!si)
+		return;
+	ci = swap_cluster_lock(si, off);
+	if (ci) {
+		__swap_table_set(ci, off % SWAPFILE_CLUSTER,
+				 xswap_entry_to_rmap(entry));
+		swap_cluster_unlock(ci);
+	}
+}
+
+swp_entry_t xswap_backend_alloc(swp_entry_t entry)
+{
+	struct swap_info_struct *si = __swap_entry_to_info(entry);
+	struct swap_cluster_info *ci;
+	unsigned long off = swp_offset(entry);
+	swp_entry_t phys;
+	bool recorded = false;
+
+	phys = xswap_alloc_phys_slot();
+	if (!phys.val)
+		return phys;
+
+	/*
+	 * The slot is a shadow until the reverse map is installed below.
+	 * Physical swapoff can see it and retry; the window is short and
+	 * try_to_unuse() reschedules.
+	 */
+	xswap_install_rmap(phys, entry);
+
+	ci = swap_cluster_lock(si, off);
+	if (ci) {
+		recorded = xswap_slot_set_backend(ci, off % SWAPFILE_CLUSTER, phys);
+		swap_cluster_unlock(ci);
+	}
+
+	if (!recorded) {
+		/* The backend is unrecorded, so the data would be unreachable. */
+		xswap_backend_free(entry, phys);
+		return (swp_entry_t){};
+	}
+
+	return phys;
+}
+
+/* Undo xswap_backend_alloc(): the zswap copy is still in place. */
+void xswap_backend_free(swp_entry_t entry, swp_entry_t phys)
+{
+	struct swap_info_struct *si = __swap_entry_to_info(entry);
+	struct swap_info_struct *psi;
+	struct swap_cluster_info *ci;
+	unsigned long off = swp_offset(entry);
+
+	ci = swap_cluster_lock(si, off);
+	if (ci) {
+		unsigned int slot = off % SWAPFILE_CLUSTER;
+		unsigned long *xs = ci->xs_table;
+
+		if (xs && xs[slot] == phys.val)
+			WRITE_ONCE(xs[slot], 0);
+		swap_cluster_unlock(ci);
+	}
+
+	/* xswap_free_phys_slot() clears the reverse mapping. */
+	psi = swap_type_to_info(swp_type(phys));
+	if (psi)
+		xswap_free_phys_slot(psi, entry, phys);
+}
+
 static int xswap_map_clusters(struct swap_info_struct *si,
 			      unsigned long start_idx, unsigned long nr,
 			      bool link_free)
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 05/32] mm, swap: support swapoff of an xswap physical backend
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (3 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 04/32] mm, swap: add a physical backend for xswap slots Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 06/32] mm, swap: use the " Baoquan He
                   ` (26 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

swapoff of a real swap device iterates its slots through try_to_unuse()
and reads each one back into memory. A slot that was written back
from an xswap entry has no folio in the swap cache, so the loop
skips it and the slot is freed without ever reading the data. While
the xswap entry will keep pointing at a slot that no longer holds
anything.

Now change try_to_unuse() to analyze such a slot through its reverse
mapping: bring the folio back, mark it dirty so that reclaim stores it
into zswap again, and only then drop the backend.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 150 +++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 149 insertions(+), 1 deletion(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 9eb4284e9bc0..a9d7ba3d2692 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -43,6 +43,7 @@
 #include <linux/suspend.h>
 #include <linux/zswap.h>
 #include <linux/plist.h>
+#include <linux/swap_ops.h>
 #include <linux/debugfs.h>
 
 #include <asm/tlbflush.h>
@@ -3361,6 +3362,140 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 		xswap_free_phys_slot(psi, entry, phys);
 }
 
+/*
+ * A written-back slot has no folio of its own here, so the unuse loop would
+ * skip it. Resolve it through the reverse mapping and free both sides.
+ */
+static int xswap_unuse_rmap(struct swap_info_struct *si, unsigned long offset)
+{
+	struct swap_cluster_info *pci, *xci;
+	struct swap_info_struct *xsi;
+	struct swap_io_ctx ctx = {};
+	struct mempolicy *mpol;
+	struct folio *folio;
+	unsigned long mapped, swp_tb, xoff;
+	swp_entry_t xentry, phys;
+	bool drop = false;
+	int ret = 0;
+
+	phys = swp_entry(si->type, offset);
+
+	pci = swap_cluster_lock(si, offset);
+	if (!pci)
+		return 0;
+	/*
+	 * The cluster can have emptied since find_next_to_unuse() read its
+	 * count without the lock, and freeing a cluster clears its table.
+	 */
+	if (!cluster_table_is_alloced(pci)) {
+		swap_cluster_unlock(pci);
+		return 0;
+	}
+	swp_tb = __swap_table_get(pci, offset % SWAPFILE_CLUSTER);
+	if (!swp_tb_is_pointer(swp_tb)) {
+		swap_cluster_unlock(pci);
+		return 0;
+	}
+	xentry = xswap_rmap_to_entry(swp_tb);
+	swap_cluster_unlock(pci);
+
+	xoff = swp_offset(xentry);
+
+	/*
+	 * Pin the owner before reading its flags or cluster_info:
+	 * free_swap_cluster_info() only unmaps that after killing si->users.
+	 * No owner left means the slot is dropped below.
+	 */
+	xsi = swap_type_to_info(swp_type(xentry));
+	if (!xsi || !get_swap_device_info(xsi))
+		goto out_free;
+	/* The record can outlive the device, or name a reused type slot. */
+	if (!(xsi->flags & SWP_XSWAP)) {
+		put_swap_device(xsi);
+		goto out_free;
+	}
+
+	/*
+	 * An owner's slot is inside its mapped range; one past it is gone.
+	 * Pairs with the smp_store_release() in xswap_map_clusters().
+	 */
+	mapped = smp_load_acquire(&xsi->nr_clusters_mapped);
+	if (xoff >= mapped * SWAPFILE_CLUSTER) {
+		/* Owner gone, so the slot is an orphan and has to go. */
+		drop = true;
+		goto out_put;
+	}
+
+	/*
+	 * Bring the data back before the slot goes. A dirty folio is what
+	 * reclaim stores into zswap next time.
+	 */
+	folio = swap_cache_get_folio(xentry);
+	if (!folio) {
+		mpol = get_task_policy(current);
+		folio = __swap_cache_alloc_folio(xentry, GFP_HIGHUSER_MOVABLE,
+						 BIT(0), NULL, mpol,
+						 NO_INTERLEAVE_INDEX);
+		if (IS_ERR(folio)) {
+			ret = PTR_ERR(folio) == -ENOMEM ? -ENOMEM : -EAGAIN;
+			goto out_put;
+		}
+		/* A folio off the LRU would be lost if a fault took it. */
+		folio_add_lru(folio);
+		swap_read_folio(&ctx, folio);
+		swap_read_submit(&ctx);
+		folio_lock(folio);
+	} else {
+		folio_lock(folio);
+	}
+
+	if (folio_matches_swap_entry(folio, xentry)) {
+		folio_wait_writeback(folio);
+		if (unlikely(!folio_test_uptodate(folio))) {
+			/* The read itself failed; a retry cannot help. */
+			swap_cache_del_folio(folio);
+			ret = -EIO;
+		} else {
+			folio_mark_dirty(folio);
+			drop = true;
+		}
+	} else {
+		/* Taken from under us, so nothing was read back either. */
+		ret = -EAGAIN;
+	}
+	folio_unlock(folio);
+	folio_put(folio);
+
+	/*
+	 * The slot is going away, so drop the record that names it. The
+	 * mapped range cannot shrink while the device is pinned, so @xoff
+	 * still has a cluster here whenever @drop is set.
+	 */
+	if (drop) {
+		xci = swap_cluster_lock(xsi, xoff);
+		if (xci) {
+			if (xswap_slot_backend(xci, xoff % SWAPFILE_CLUSTER).val ==
+			    phys.val)
+				WRITE_ONCE(xci->xs_table[xoff % SWAPFILE_CLUSTER],
+					   0);
+			swap_cluster_unlock(xci);
+		}
+	}
+out_put:
+	put_swap_device(xsi);
+	if (!drop)
+		return ret;
+out_free:
+	/* Leaving the mapping in place would make the unuse loop spin. */
+	xswap_free_phys_slot(si, xentry, phys);
+	return 0;
+}
+#else
+static inline int xswap_unuse_rmap(struct swap_info_struct *si,
+				   unsigned long offset)
+{
+	return 0;
+}
 #endif /* CONFIG_XSWAP */
 static int try_to_unuse(unsigned int type)
 {
@@ -3420,8 +3555,21 @@ static int try_to_unuse(unsigned int type)
 
 		entry = swp_entry(type, i);
 		folio = swap_cache_get_folio(entry);
-		if (!folio)
+		if (!folio) {
+			/*
+			 * Only a physical backend holds pointer entries. An
+			 * xswap device's slots are shadows, and its
+			 * cluster_info is what find_next_to_unuse() reads
+			 * without the lock.
+			 */
+			if (!(si->flags & SWP_XSWAP)) {
+				retval = xswap_unuse_rmap(si, i);
+				/* A lost race is retried on the next pass. */
+				if (retval && retval != -EAGAIN)
+					return retval;
+			}
 			continue;
+		}
 
 		/*
 		 * It is conceivable that a racing task removed this folio from
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 06/32] mm, swap: use the xswap physical backend
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (4 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 05/32] mm, swap: support swapoff of an xswap physical backend Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 07/32] mm, swap: fall back to disk when zswap refuses an xswap page Baoquan He
                   ` (25 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

An xswap entry that zswap evicts had nowhere to go. Send it to the
physical backend, and reserve the backend before decompressing so a
failed allocation wastes no work.

Now that an xswap entry can be written back, put it on the zswap
writeback LRU again. With no real swap device it stays on the LRU and
the shrinker rotates it until one appears, instead of staying pinned
until swapin or destroy.

An incompressible xswap page is stored uncompressed only while a real
swap device exists to hold its backend.

The zswap shrinker copies a swpentry and drops the LRU lock before
verifying it, while xswap maps cluster_info on demand. Check the range
under xswap_lock and reject a swpentry outside nr_clusters_mapped.
trylock avoids a deadlock: the allocation can trigger reclaim that
calls this path again.

A slot that was written out has no zswap copy, so swap_read_folio()
forwards its read to the physical entry.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/page_io.c | 32 ++++++++++++++++++----
 mm/zswap.c   | 75 ++++++++++++++++++++++++++++++++++++++++++++--------
 2 files changed, 91 insertions(+), 16 deletions(-)

diff --git a/mm/page_io.c b/mm/page_io.c
index 2bc3b46e5529..76e8d08961bb 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -481,9 +481,27 @@ static bool swap_read_folio_zeromap(struct folio *folio)
 void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 {
 	struct swap_info_struct *sis = __swap_entry_to_info(folio->swap);
-	bool synchronous = sis->flags & SWP_SYNCHRONOUS_IO;
+	swp_entry_t entry = folio->swap;
+	swp_entry_t phys = {};
+	bool synchronous;
 	bool workingset = folio_test_workingset(folio);
 
+	/* Resolved here: the batch and submit mode precede zswap_load(). */
+	if (unlikely(sis->flags & SWP_XSWAP)) {
+		struct swap_cluster_info *ci;
+		unsigned long offset = swp_offset(folio->swap);
+
+		ci = __swap_offset_to_cluster(sis, offset);
+		if (ci) {
+			spin_lock(&ci->lock);
+			phys = xswap_slot_backend(ci, offset % SWAPFILE_CLUSTER);
+			spin_unlock(&ci->lock);
+		}
+		if (phys.val)
+			entry = phys;
+	}
+	synchronous = __swap_entry_to_info(entry)->flags & SWP_SYNCHRONOUS_IO;
+
 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio) && !synchronous, folio);
 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
 	VM_BUG_ON_FOLIO(folio_test_uptodate(folio), folio);
@@ -493,7 +511,7 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	 * window opens, so that each batch is billed for its own read
 	 * rather than for the next folio's lookup and decompression.
 	 */
-	if (ctx->sio && !swap_can_merge(ctx, folio, folio->swap, READ))
+	if (ctx->sio && !swap_can_merge(ctx, folio, entry, READ))
 		swap_read_submit(ctx);
 
 	/*
@@ -522,8 +540,12 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	if (zswap_load(folio) != -ENOENT)
 		return;
 
-	if (unlikely(sis->flags & SWP_XSWAP)) {
-		/* An xswap entry only lives in zswap: zswap_load() must hit. */
+	if (unlikely(sis->flags & SWP_XSWAP) && !phys.val) {
+		/*
+		 * Neither zswap nor a physical slot has it. No
+		 * folio_mark_uptodate(), so do_swap_page() sees this as a
+		 * failed read and SIGBUSes silently.
+		 */
 		WARN_ON_ONCE(1);
 		folio_unlock(folio);
 		return;
@@ -531,7 +553,7 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
-	swap_add_folio(ctx, folio, folio->swap, READ);
+	swap_add_folio(ctx, folio, entry, READ);
 
 	/*
 	 * Synchronous devices do the whole read at submission time, submit
diff --git a/mm/zswap.c b/mm/zswap.c
index b6a328ab787a..188f763a8af9 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -935,9 +935,10 @@ static bool zswap_compress(struct folio *folio, long index,
 	 * save the content as is without a compression, to keep the LRU order
 	 * of writebacks.  If writeback is disabled, reject the page since it
 	 * only adds metadata overhead.  swap_writeout() will put the page back
-	 * to the active LRU list in the case.  An xswap entry in this phase
-	 * is never put on the LRU, so an incompressible page stored for it
-	 * could never be reclaimed: reject it the same way.
+	 * to the active LRU list in the case.  An xswap entry can be written
+	 * back only while a real swap device exists to hold its backend;
+	 * with none, an incompressible page stored for it could never be
+	 * reclaimed, so reject it the same way.
 	 */
 	if (comp_ret) {
 		if (!can_writeback)
@@ -1091,6 +1092,8 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	struct folio *folio;
 	struct mempolicy *mpol;
 	struct swap_info_struct *si;
+	swp_entry_t phys = {};
+	bool is_xswap;
 	int ret = 0;
 
 	/* try to allocate swap cache folio */
@@ -1098,14 +1101,33 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	if (IS_ERR_OR_NULL(si))
 		return -ENOENT;
 
-	if (si->flags & SWP_XSWAP) {
-		put_swap_device(si);
-		return -EINVAL;
+	is_xswap = !!(si->flags & SWP_XSWAP);
+
+	/*
+	 * The allocation can enter reclaim and grow this device, which takes
+	 * the lock again, so do not hold it across.  Check that the entry's
+	 * range is mapped before the allocation.
+	 */
+#ifdef CONFIG_XSWAP
+	if (is_xswap) {
+		if (!mutex_trylock(&si->xswap_lock)) {
+			put_swap_device(si);
+			return -EAGAIN;
+		}
+		if (swp_offset(swpentry) / SWAPFILE_CLUSTER >=
+		    READ_ONCE(si->nr_clusters_mapped)) {
+			mutex_unlock(&si->xswap_lock);
+			put_swap_device(si);
+			return -ENOENT;
+		}
+		mutex_unlock(&si->xswap_lock);
 	}
+#endif
 
 	mpol = get_task_policy(current);
 	folio = __swap_cache_alloc_folio(swpentry, GFP_KERNEL, BIT(0), NULL, mpol,
 					 NO_INTERLEAVE_INDEX);
+
 	put_swap_device(si);
 
 	/*
@@ -1135,6 +1157,15 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 		goto err;
 	}
 
+	/* Reserve the destination before dropping the zswap copy. */
+	if (is_xswap) {
+		phys = xswap_backend_alloc(swpentry);
+		if (!phys.val) {
+			ret = -ENOMEM;
+			goto err;
+		}
+	}
+
 	if (!zswap_decompress(entry, folio)) {
 		ret = -EIO;
 		goto err;
@@ -1167,11 +1198,13 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	folio_put(folio);
 
 	/* start writeback */
-	__swap_writeout(ctx, folio, folio->swap);
+	__swap_writeout(ctx, folio, is_xswap ? phys : folio->swap);
 
 	return 0;
 
 err:
+	if (is_xswap && phys.val)
+		xswap_backend_free(swpentry, phys);
 	swap_cache_del_folio(folio);
 	folio_unlock(folio);
 	folio_put(folio);
@@ -1207,10 +1240,12 @@ static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_o
 				       void *arg)
 {
 	struct zswap_entry *entry = container_of(item, struct zswap_entry, lru);
+	struct swap_info_struct *si;
 	struct zswap_shrink_ctl *ctl = arg;
 	swp_entry_t swpentry;
 	enum lru_status ret = LRU_REMOVED_RETRY;
 	int writeback_result;
+	bool no_backend;
 
 	/*
 	 * Second chance algorithm: if the entry has its referenced bit set, give it
@@ -1256,6 +1291,21 @@ static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_o
 	 */
 	swpentry = entry->swpentry;
 
+	/*
+	 * An xswap entry with no real swap device has nowhere to be
+	 * written back to, so keep it on the LRU for when one appears.
+	 * LRU_ROTATE needs the lru lock and the get/put_swap_device()
+	 * pair does not sleep, so this stays ahead of the unlock.
+	 */
+	si = get_swap_device(swpentry);
+	if (IS_ERR_OR_NULL(si))
+		return LRU_ROTATE;
+	no_backend = (si->flags & SWP_XSWAP) &&
+		     !atomic_read(&nr_real_swapfiles);
+	put_swap_device(si);
+	if (no_backend)
+		return LRU_ROTATE;
+
 	/*
 	 * It's safe to drop the lock here because we return either
 	 * LRU_REMOVED_RETRY, LRU_RETRY or LRU_STOP.
@@ -1555,8 +1605,12 @@ static bool zswap_store_page(struct folio *folio, long index,
 		return false;
 	}
 
-	/* In this phase xswap has no device to write the page back to. */
-	can_writeback = !(__swap_entry_to_info(page_swpentry)->flags & SWP_XSWAP);
+	/*
+	 * An xswap entry can be written back only while a real swap device
+	 * exists to hold its physical backend.
+	 */
+	can_writeback = !(__swap_entry_to_info(page_swpentry)->flags & SWP_XSWAP) ||
+			atomic_read(&nr_real_swapfiles);
 
 	if (!zswap_compress(folio, index, entry, pool, can_writeback))
 		goto compress_failed;
@@ -1617,8 +1671,7 @@ static bool zswap_store_page(struct folio *folio, long index,
 	entry->objcg = objcg;
 	entry->referenced = true;
 	INIT_LIST_HEAD(&entry->lru);
-	if (can_writeback)
-		zswap_lru_add(entry);
+	zswap_lru_add(entry);
 
 	return true;
 
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 07/32] mm, swap: fall back to disk when zswap refuses an xswap page
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (5 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 06/32] mm, swap: use the " Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 08/32] mm, swap: reclaim physical slots backing cache-only xswap entries Baoquan He
                   ` (24 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

zswap_store() can refuse a page if the pool may be at its limit, or
the page may not compress well enough. For an xswap device there was
no way to store it, so swap_writeout() put the page back on the LRU.
Under memory pressure that turns into a livelock: reclaim keeps picking
the same page and the pool keeps refusing it.

Now that xswap slots have a physical backend, write the page out
instead. If no backend can be reserved, keep the old behaviour.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 Documentation/admin-guide/mm/zswap.rst | 12 ++++++++++++
 mm/page_io.c                           | 16 +++++++++++++---
 2 files changed, 25 insertions(+), 3 deletions(-)

diff --git a/Documentation/admin-guide/mm/zswap.rst b/Documentation/admin-guide/mm/zswap.rst
index 2464425c783d..3c0b8c59599d 100644
--- a/Documentation/admin-guide/mm/zswap.rst
+++ b/Documentation/admin-guide/mm/zswap.rst
@@ -136,3 +136,15 @@ selected.
 A debugfs interface is provided for various statistic about pool size, number
 of pages stored, same-value filled pages and various counters for the reasons
 pages are rejected.
+
+xswap devices
+-------------
+
+An xswap device is a file-less swap device backed by zswap.  While such a
+device exists, do not disable zswap at runtime (``enabled=0``) or set
+``max_pool_percent`` to 0.  The device would have no backing: pages already
+in zswap can still be read, but new pages cannot be stored.  Destroy the
+xswap devices first.
+
+Writeback needs a real swap device.  Without one, a page that zswap refuses
+stays in memory.
diff --git a/mm/page_io.c b/mm/page_io.c
index 76e8d08961bb..30d46218122b 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -259,10 +259,20 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
-	/* No backing store: keep the folio; ctx->sis is not set yet. */
+	/* An xswap entry has no store of its own: use a physical slot. */
 	if (unlikely(__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP)) {
-		folio_mark_dirty(folio);
-		return AOP_WRITEPAGE_ACTIVATE;
+		swp_entry_t entry = folio->swap;
+		swp_entry_t phys;
+
+		/* The pool refused it: fall back to a real swap device. */
+		phys = xswap_backend_alloc(entry);
+		if (!phys.val) {
+			folio_mark_dirty(folio);
+			return AOP_WRITEPAGE_ACTIVATE;
+		}
+
+		__swap_writeout(ctx, folio, phys);
+		return 0;
 	}
 
 	__swap_writeout(ctx, folio, folio->swap);
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 08/32] mm, swap: reclaim physical slots backing cache-only xswap entries
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (6 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 07/32] mm, swap: fall back to disk when zswap refuses an xswap page Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 09/32] mm, swap: drop swap_folio_sector() Baoquan He
                   ` (23 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

The swap count of an xswap entry can drop to 0 while its folio is still
in the swap cache, which leaves the physical slot redundant but occupied
until the folio leaves the cache. This happens when the page is faulted
back in during its write to the backend: do_swap_page() does not wait for
writeback, folio_free_swap() refuses a folio under writeback, and a
real-device write does not drop the cache when it completes.

Mark the slot with a cache-only bit in the swap table entry that points
back to the owner, set when the count drops to 0 and cleared when the
slot is reused. Check that the physical slot still points back to the
entry before touching the bit. The physical reclaim scanner already walks
full clusters; make it free the slots with the bit set. It reads the bit
directly, without the xswap cluster lock, which would invert the lock
order. A cache-only slot in a non-full cluster waits until the cluster
fills.

Co-developed-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swap_table.h |  37 ++++++++++-
 mm/swapfile.c   | 168 +++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 201 insertions(+), 4 deletions(-)

diff --git a/mm/swap_table.h b/mm/swap_table.h
index eadd0547d2ad..f27cb1ba385e 100644
--- a/mm/swap_table.h
+++ b/mm/swap_table.h
@@ -95,21 +95,52 @@ struct swap_memcg_table {
  * Pointer-tagged swap table entry: the reverse map from a physical slot to
  * the xswap entry it backs. Layout:
  *
- *   Pointer:  | xswap_type(8) | xswap_offset(53) |100|
+ *   Pointer:  |C| xswap_type(7) | xswap_offset(53) |100|
  *
  * The low three bits identify the entry: 0b000 is a free, bad or hibernation
  * slot, a shadow entry ends in 0b01 and a cached folio in 0b10, which leaves
- * 0b100 as the only marker still free.
+ * 0b100 as the only marker still free. C is SWP_RMAP_CACHE_ONLY, the one
+ * bit left at the top.
  */
 #define SWP_TB_PTR_MARK			0b100UL
 #define SWP_TB_PTR_OFF_BITS		53
-#define SWP_TB_PTR_TYPE_BITS		8
+#define SWP_TB_PTR_TYPE_BITS		7
 #define SWP_TB_PTR_OFF_SHIFT		3
 #define SWP_TB_PTR_TYPE_SHIFT		(SWP_TB_PTR_OFF_SHIFT + \
 					 SWP_TB_PTR_OFF_BITS)
 #define SWP_TB_PTR_OFF_MASK		((1UL << SWP_TB_PTR_OFF_BITS) - 1)
 #define SWP_TB_PTR_TYPE_MASK		((1UL << SWP_TB_PTR_TYPE_BITS) - 1)
 
+/*
+ * Set when the xswap entry owning a physical slot has swap count 0 but its
+ * folio is still in the swap cache. The slot is redundant then, and the
+ * physical reclaim scanner may free it. The bit sits on the physical slot
+ * so that scanner can read it without the xswap cluster lock.
+ */
+#define SWP_RMAP_CACHE_ONLY		(1UL << (BITS_PER_LONG - 1))
+
+/* swp_type() must fit, and SWP_RMAP_CACHE_ONLY must own the top bit. */
+static_assert(BITS_PER_LONG - SWP_TYPE_SHIFT <= SWP_TB_PTR_TYPE_BITS,
+	      "xswap rmap type field is too narrow");
+static_assert(SWP_TB_PTR_TYPE_SHIFT + SWP_TB_PTR_TYPE_BITS == BITS_PER_LONG - 1,
+	      "xswap rmap fields do not pack");
+
+static inline void swap_rmap_mark_cache_only(struct swap_cluster_info *ci,
+					     unsigned int off)
+{
+	atomic_long_t *table = rcu_dereference_check(ci->table, true);
+
+	atomic_long_or(SWP_RMAP_CACHE_ONLY, &table[off]);
+}
+
+static inline void swap_rmap_clear_cache_only(struct swap_cluster_info *ci,
+					      unsigned int off)
+{
+	atomic_long_t *table = rcu_dereference_check(ci->table, true);
+
+	atomic_long_and(~SWP_RMAP_CACHE_ONLY, &table[off]);
+}
+
 static inline bool swp_tb_is_pointer(unsigned long swp_tb)
 {
 	return (swp_tb & (BIT(3) - 1)) == SWP_TB_PTR_MARK;
diff --git a/mm/swapfile.c b/mm/swapfile.c
index a9d7ba3d2692..aeaf36776ef7 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -95,6 +95,14 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 				       unsigned int slot);
 static void xswap_free_xs_table(struct swap_info_struct *si,
 				struct swap_cluster_info *ci);
+static void xswap_mark_cache_only(struct swap_info_struct *si,
+				  struct swap_cluster_info *ci,
+				  unsigned int slot);
+static void xswap_clear_cache_only(struct swap_info_struct *si,
+				   struct swap_cluster_info *ci,
+				   unsigned int start, unsigned int nr);
+static int xswap_reclaim_backing(struct swap_info_struct *si,
+				 unsigned long offset, swp_entry_t xentry);
 
 static int xswap_create(int prio);
 static int xswap_create_by_name(const char *name, int swap_flags);
@@ -1324,6 +1332,10 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 	if (force)
 		to_scan = swap_usage_in_pages(si) / SWAPFILE_CLUSTER;
 
+	/*
+	 * Only full clusters are scanned.  A cache-only slot in a non-full
+	 * cluster stays until the cluster fills or the device goes away.
+	 */
 	while ((ci = isolate_lock_cluster(si, &si->full_clusters))) {
 		offset = cluster_offset(si, ci);
 		end = min(si->max, offset + SWAPFILE_CLUSTER);
@@ -1340,6 +1352,18 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 					offset += abs(nr_reclaim);
 					continue;
 				}
+#ifdef CONFIG_XSWAP
+			} else if (swp_tb_is_pointer(swp_tb) &&
+				   (swp_tb & SWP_RMAP_CACHE_ONLY)) {
+				spin_unlock(&ci->lock);
+				nr_reclaim = xswap_reclaim_backing(si, offset,
+						xswap_rmap_to_entry(swp_tb));
+				spin_lock(&ci->lock);
+				if (nr_reclaim) {
+					offset += abs(nr_reclaim);
+					continue;
+				}
+#endif
 			}
 			offset++;
 		}
@@ -1953,6 +1977,10 @@ static void swap_put_entries_cluster(struct swap_info_struct *si,
 			}
 			/* count will be 0 after put, slot can be reclaimed */
 			need_reclaim = true;
+#ifdef CONFIG_XSWAP
+			if (ci->xs_table)
+				xswap_mark_cache_only(si, ci, ci_off);
+#endif
 		}
 		/*
 		 * A count != 1 or cached slot can't be freed. Put its swap
@@ -2059,6 +2087,10 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 			goto failed;
 		}
 	} while (++ci_off < ci_end);
+#ifdef CONFIG_XSWAP
+	if (ci->xs_table)
+		xswap_clear_cache_only(si, ci, ci_start, nr);
+#endif
 	swap_cluster_unlock(ci);
 	return 0;
 failed:
@@ -3362,6 +3394,129 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 		xswap_free_phys_slot(psi, entry, phys);
 }
 
+/*
+ * Mark the physical slot backing xswap slot @slot as cache-only. Its folio
+ * is in the swap cache, so the physical copy is redundant. The physical
+ * cluster lock is needed: xswap_free_phys_slot() clears the rmap under it.
+ *
+ * The caller holds the xci lock, so the backend record cannot be cleared.
+ * A live record keeps the physical slot counted, and physical teardown
+ * cannot free cluster_info while the slot is counted.
+ */
+static void xswap_mark_cache_only(struct swap_info_struct *si,
+				  struct swap_cluster_info *ci,
+				  unsigned int slot)
+{
+	struct swap_cluster_info *pci;
+	swp_entry_t xentry = swp_entry(si->type, cluster_offset(si, ci) + slot);
+	swp_entry_t phys = { .val = READ_ONCE(ci->xs_table[slot]) };
+	unsigned long swp_tb;
+
+	if (!phys.val)
+		return;			/* still in zswap, no backend */
+	pci = __swap_entry_to_cluster(phys);
+	spin_lock(&pci->lock);
+	swp_tb = __swap_table_get(pci, swp_cluster_offset(phys));
+	if (swp_tb_is_pointer(swp_tb) &&
+	    xswap_rmap_to_entry(swp_tb).val == xentry.val)
+		swap_rmap_mark_cache_only(pci, swp_cluster_offset(phys));
+	spin_unlock(&pci->lock);
+}
+
+/*
+ * Clear the cache-only mark of slots that were re-referenced. A slot that
+ * was cache-only had count 0, so count 1 is exactly the one to clear.
+ */
+static void xswap_clear_cache_only(struct swap_info_struct *si,
+				   struct swap_cluster_info *ci,
+				   unsigned int start, unsigned int nr)
+{
+	unsigned int slot;
+
+	for (slot = start; slot < start + nr; slot++) {
+		struct swap_cluster_info *pci;
+		swp_entry_t xentry = swp_entry(si->type,
+					       cluster_offset(si, ci) + slot);
+		unsigned long xswp_tb, pswp_tb;
+		swp_entry_t phys;
+
+		xswp_tb = __swap_table_get(ci, slot);
+		if (!swp_tb_is_folio(xswp_tb) || swp_tb_get_count(xswp_tb) != 1)
+			continue;
+		phys.val = READ_ONCE(ci->xs_table[slot]);
+		if (!phys.val)
+			continue;
+		pci = __swap_entry_to_cluster(phys);
+		spin_lock(&pci->lock);
+		pswp_tb = __swap_table_get(pci, swp_cluster_offset(phys));
+		if (swp_tb_is_pointer(pswp_tb) &&
+		    xswap_rmap_to_entry(pswp_tb).val == xentry.val)
+			swap_rmap_clear_cache_only(pci, swp_cluster_offset(phys));
+		spin_unlock(&pci->lock);
+	}
+}
+
+/*
+ * Try to reclaim the physical slot backing cache-only @xentry. The physical
+ * cluster lock must not be held. Returns the slots from @offset to the end
+ * of the slot range, negated if the free failed, or 0 if @offset
+ * turned out not to be the folio's slot.
+ */
+static int xswap_reclaim_backing(struct swap_info_struct *si,
+				 unsigned long offset, swp_entry_t xentry)
+{
+	struct swap_info_struct *xsi;
+	struct swap_cluster_info *xci;
+	swp_entry_t first;
+	struct folio *folio;
+	unsigned long xoff, i;
+	int ret = 0;
+
+	/* @xentry can name a device that is going away right now. */
+	xsi = get_swap_device(xentry);
+	if (IS_ERR_OR_NULL(xsi))
+		return 0;
+
+	folio = swap_cache_get_folio(xentry);
+	if (!folio)
+		goto out_put;
+	if (!folio_trylock(folio)) {
+		folio_put(folio);
+		goto out_put;
+	}
+
+	/*
+	 * The folio must own @xentry, and @offset must be the slot this device
+	 * holds for that page of the folio. Otherwise the rmap went stale.
+	 */
+	if (!folio_matches_swap_entry(folio, xentry))
+		goto out;
+	i = xentry.val - folio->swap.val;
+	xoff = swp_offset(folio->swap);
+	xci = swap_cluster_lock(xsi, xoff);
+	if (!xci)
+		goto out;
+	first = xswap_slot_backend(xci, xoff % SWAPFILE_CLUSTER);
+	swap_cluster_unlock(xci);
+	if (!first.val || swp_type(first) != si->type ||
+	    swp_offset(first) + i != offset)
+		goto out;
+
+	/*
+	 * The rest of the slot range is ours: skip it, whether or not the
+	 * free succeeds.
+	 */
+	ret = folio_nr_pages(folio) - i;
+	if (!folio_free_swap(folio))
+		ret = -ret;
+out:
+	folio_unlock(folio);
+	folio_put(folio);
+out_put:
+	put_swap_device(xsi);
+	return ret;
+}
+
 /*
  * A written-back slot has no folio of its own here, so the unuse loop would
  * skip it. Resolve it through the reverse mapping and free both sides.
@@ -4635,7 +4790,18 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry)
 
 	ci = swap_cluster_lock(si, off);
 	if (ci) {
-		recorded = xswap_slot_set_backend(ci, off % SWAPFILE_CLUSTER, phys);
+		unsigned int slot = off % SWAPFILE_CLUSTER;
+		unsigned long swp_tb;
+
+		recorded = xswap_slot_set_backend(ci, slot, phys);
+		/*
+		 * The folio can lose its last reference while the owner is
+		 * not recorded yet; that path cannot mark the slot for us.
+		 */
+		swp_tb = __swap_table_get(ci, slot);
+		if (recorded && swp_tb_is_folio(swp_tb) &&
+		    !swp_tb_get_count(swp_tb))
+			xswap_mark_cache_only(si, ci, slot);
 		swap_cluster_unlock(ci);
 	}
 
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 09/32] mm, swap: drop swap_folio_sector()
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (7 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 08/32] mm, swap: reclaim physical slots backing cache-only xswap entries Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 10/32] mm, swap: drop a stale xswap physical slot range before reallocating Baoquan He
                   ` (22 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

No one uses it now.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/swap.h |  1 -
 mm/swapfile.c        | 13 -------------
 2 files changed, 14 deletions(-)

diff --git a/include/linux/swap.h b/include/linux/swap.h
index 0c13f2c620e7..815aee556991 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -414,7 +414,6 @@ extern int __swap_count(swp_entry_t entry);
 extern bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry);
 extern int swp_swapcount(swp_entry_t entry);
 extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
-sector_t swap_folio_sector(struct folio *folio);
 sector_t swap_entry_sector(swp_entry_t entry);
 
 /*
diff --git a/mm/swapfile.c b/mm/swapfile.c
index aeaf36776ef7..f90bddce62a0 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -507,19 +507,6 @@ offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
 	BUG();
 }
 
-sector_t swap_folio_sector(struct folio *folio)
-{
-	struct swap_info_struct *sis = __swap_entry_to_info(folio->swap);
-	struct swap_extent *se;
-	sector_t sector;
-	pgoff_t offset;
-
-	offset = swp_offset(folio->swap);
-	se = offset_to_swap_extent(sis, offset);
-	sector = se->start_block + (offset - se->start_page);
-	return sector << (PAGE_SHIFT - 9);
-}
-
 sector_t swap_entry_sector(swp_entry_t entry)
 {
 	struct swap_info_struct *sis = __swap_entry_to_info(entry);
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 10/32] mm, swap: drop a stale xswap physical slot range before reallocating
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (8 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 09/32] mm, swap: drop swap_folio_sector() Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 11/32] mm, swap: publish the xswap backend owner before its reverse map Baoquan He
                   ` (21 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

A folio that was written back, redirtied while still in the swap
cache and is now written out again still records the old physical slot range.  Dropping it before the new allocation replaces it prevents the
old slot range from leaking.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index f90bddce62a0..e55711300169 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -4761,9 +4761,22 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry)
 	struct swap_info_struct *si = __swap_entry_to_info(entry);
 	struct swap_cluster_info *ci;
 	unsigned long off = swp_offset(entry);
-	swp_entry_t phys;
+	swp_entry_t phys, old;
 	bool recorded = false;
 
+	/*
+	 * A folio that was written back, redirtied while still in the swap
+	 * cache and is now written out again still records the old slot range.
+	 * Drop it before the new one replaces it.
+	 */
+	ci = swap_cluster_lock(si, off);
+	if (ci) {
+		old = xswap_slot_backend(ci, off % SWAPFILE_CLUSTER);
+		swap_cluster_unlock(ci);
+		if (old.val)
+			xswap_backend_free(entry, old);
+	}
+
 	phys = xswap_alloc_phys_slot();
 	if (!phys.val)
 		return phys;
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 11/32] mm, swap: publish the xswap backend owner before its reverse map
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (9 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 10/32] mm, swap: drop a stale xswap physical slot range before reallocating Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:12 ` [PATCH v2 12/32] mm, swap: skip a NOFS backend for xswap physical writeback Baoquan He
                   ` (20 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

Preallocate the backend table before allocating the physical slot, and
record the owner before installing the reverse map.  A slot is then
never visible to swapoff without its owner.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 51 ++++++++++++++++++++++++++++++---------------------
 1 file changed, 30 insertions(+), 21 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index e55711300169..adc7f41cd8a3 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -4761,8 +4761,8 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry)
 	struct swap_info_struct *si = __swap_entry_to_info(entry);
 	struct swap_cluster_info *ci;
 	unsigned long off = swp_offset(entry);
+	unsigned long swp_tb;
 	swp_entry_t phys, old;
-	bool recorded = false;
 
 	/*
 	 * A folio that was written back, redirtied while still in the swap
@@ -4777,6 +4777,19 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry)
 			xswap_backend_free(entry, old);
 	}
 
+	/*
+	 * Get the xswap side ready before a physical slot exists, so the
+	 * reverse map installed below cannot expose a slot with no owner.
+	 */
+	ci = swap_cluster_lock(si, off);
+	if (!ci)
+		return (swp_entry_t){};
+	if (!xswap_xs_table_locked(ci, GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC)) {
+		swap_cluster_unlock(ci);
+		return (swp_entry_t){};
+	}
+	swap_cluster_unlock(ci);
+
 	phys = xswap_alloc_phys_slot();
 	if (!phys.val)
 		return phys;
@@ -4785,31 +4798,27 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry)
 	 * The slot is a shadow until the reverse map is installed below.
 	 * Physical swapoff can see it and retry; the window is short and
 	 * try_to_unuse() reschedules.
+	 *
+	 * Owner first, then the reverse map, under one hold of the lock.
 	 */
-	xswap_install_rmap(phys, entry);
-
 	ci = swap_cluster_lock(si, off);
-	if (ci) {
-		unsigned int slot = off % SWAPFILE_CLUSTER;
-		unsigned long swp_tb;
-
-		recorded = xswap_slot_set_backend(ci, slot, phys);
-		/*
-		 * The folio can lose its last reference while the owner is
-		 * not recorded yet; that path cannot mark the slot for us.
-		 */
-		swp_tb = __swap_table_get(ci, slot);
-		if (recorded && swp_tb_is_folio(swp_tb) &&
-		    !swp_tb_get_count(swp_tb))
-			xswap_mark_cache_only(si, ci, slot);
-		swap_cluster_unlock(ci);
-	}
-
-	if (!recorded) {
-		/* The backend is unrecorded, so the data would be unreachable. */
+	if (!ci) {
 		xswap_backend_free(entry, phys);
 		return (swp_entry_t){};
 	}
+	/* The table is preallocated above, so this cannot fail. */
+	if (!xswap_slot_set_backend(ci, off % SWAPFILE_CLUSTER, phys))
+		VM_WARN_ON_ONCE(1);
+	xswap_install_rmap(phys, entry);
+
+	/*
+	 * The folio can lose its last reference while the owner is not
+	 * recorded yet; that path cannot mark the slot for us.
+	 */
+	swp_tb = __swap_table_get(ci, off % SWAPFILE_CLUSTER);
+	if (swp_tb_is_folio(swp_tb) && !swp_tb_get_count(swp_tb))
+		xswap_mark_cache_only(si, ci, off % SWAPFILE_CLUSTER);
+	swap_cluster_unlock(ci);
 
 	return phys;
 }
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 12/32] mm, swap: skip a NOFS backend for xswap physical writeback
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (10 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 11/32] mm, swap: publish the xswap backend owner before its reverse map Baoquan He
@ 2026-12-03 18:12 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 13/32] mm, swap: pass the folio order through the swap slot allocator Baoquan He
                   ` (19 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:12 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

An xswap folio's swap entry points at the xswap device, but its data
may be written to a real backend.  may_enter_fs() reads the device out
of that entry, so it checks the xswap device and not the backend: a
context that cannot enter the fs is still allowed to write, and
xswap_alloc_phys_slot() may pick NFS or SMB.  Writing there re-enters
the filesystem.

Pass may_enter_fs down in swap_io_ctx, from sc->gfp_mask and from the
zswap shrinker, and make xswap_alloc_phys_slot() skip a NOFS backend
when it is false.  Revalidate the candidate after pinning it, in case
the swap_info was reused as a NOFS device since it was snapshotted.
With none left, AOP_WRITEPAGE_ACTIVATE keeps the folio.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/swap_ops.h |  1 +
 include/linux/zswap.h    |  4 ++--
 mm/page_io.c             |  4 ++--
 mm/swap.h                |  4 ++--
 mm/swapfile.c            | 14 +++++++++++---
 mm/vmscan.c              |  4 +++-
 mm/zswap.c               | 23 +++++++++++++++--------
 7 files changed, 36 insertions(+), 18 deletions(-)

diff --git a/include/linux/swap_ops.h b/include/linux/swap_ops.h
index 58100dfac056..3e3f14e3b98f 100644
--- a/include/linux/swap_ops.h
+++ b/include/linux/swap_ops.h
@@ -28,6 +28,7 @@ struct swap_io_ctx {
 	bool			in_delayacct;
 	bool			in_thrashing;
 	unsigned long		in_memstall;
+	bool			may_enter_fs;	/* this context may enter the fs */
 };
 
 /*
diff --git a/include/linux/zswap.h b/include/linux/zswap.h
index 94746fb71bb6..6d6c791b1167 100644
--- a/include/linux/zswap.h
+++ b/include/linux/zswap.h
@@ -25,7 +25,7 @@ struct zswap_lruvec_state {
 };
 
 unsigned long zswap_total_pages(void);
-bool zswap_store(struct folio *folio);
+bool zswap_store(struct folio *folio, bool may_enter_fs);
 int zswap_load(struct folio *folio);
 void zswap_invalidate(int type, pgoff_t offset, unsigned long nr_entries);
 int zswap_swapon(int type, unsigned long nr_pages);
@@ -40,7 +40,7 @@ bool zswap_is_present(swp_entry_t entry, unsigned int nr);
 
 struct zswap_lruvec_state {};
 
-static inline bool zswap_store(struct folio *folio)
+static inline bool zswap_store(struct folio *folio, bool may_enter_fs)
 {
 	return false;
 }
diff --git a/mm/page_io.c b/mm/page_io.c
index 30d46218122b..5aa3717b3d70 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -246,7 +246,7 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	 */
 	swap_zeromap_folio_clear(folio);
 
-	if (zswap_store(folio)) {
+	if (zswap_store(folio, ctx->may_enter_fs)) {
 		count_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);
 		goto out_unlock;
 	}
@@ -265,7 +265,7 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 		swp_entry_t phys;
 
 		/* The pool refused it: fall back to a real swap device. */
-		phys = xswap_backend_alloc(entry);
+		phys = xswap_backend_alloc(entry, ctx->may_enter_fs);
 		if (!phys.val) {
 			folio_mark_dirty(folio);
 			return AOP_WRITEPAGE_ACTIVATE;
diff --git a/mm/swap.h b/mm/swap.h
index 73aadd0f2bc8..6e3128c54b4f 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -510,7 +510,7 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 
 #ifdef CONFIG_XSWAP
 swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot);
-swp_entry_t xswap_backend_alloc(swp_entry_t entry);
+swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs);
 void xswap_backend_free(swp_entry_t entry, swp_entry_t phys);
 #else
 static inline swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci,
@@ -519,7 +519,7 @@ static inline swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci,
 	return (swp_entry_t){};
 }
 
-static inline swp_entry_t xswap_backend_alloc(swp_entry_t entry)
+static inline swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs)
 {
 	return (swp_entry_t){};
 }
diff --git a/mm/swapfile.c b/mm/swapfile.c
index adc7f41cd8a3..7e0bdde39ab0 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -4700,7 +4700,7 @@ static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si)
 	return offset;
 }
 
-static swp_entry_t xswap_alloc_phys_slot(void)
+static swp_entry_t xswap_alloc_phys_slot(bool may_enter_fs)
 {
 	struct swap_info_struct *devs[MAX_SWAPFILES], *si;
 	int nr = 0, i;
@@ -4714,6 +4714,9 @@ static swp_entry_t xswap_alloc_phys_slot(void)
 	plist_for_each_entry(si, &swap_avail_head, avail_list) {
 		if (si->flags & SWP_XSWAP)
 			continue;
+		/* Writing there would re-enter the fs this context is in. */
+		if (!may_enter_fs && (si->ops->flags & SWAP_OPS_F_REQUIRE_NOFS))
+			continue;
 		if (nr == MAX_SWAPFILES)
 			break;
 		devs[nr++] = si;
@@ -4730,6 +4733,11 @@ static swp_entry_t xswap_alloc_phys_slot(void)
 			put_swap_device(devs[i]);
 			continue;
 		}
+		if (!may_enter_fs &&
+		    (devs[i]->ops->flags & SWAP_OPS_F_REQUIRE_NOFS)) {
+			put_swap_device(devs[i]);
+			continue;
+		}
 		offset = xswap_alloc_slot_local(devs[i]);
 		put_swap_device(devs[i]);
 		if (offset && offset != SWAP_ENTRY_INVALID)
@@ -4756,7 +4764,7 @@ static void xswap_install_rmap(swp_entry_t phys, swp_entry_t entry)
 	}
 }
 
-swp_entry_t xswap_backend_alloc(swp_entry_t entry)
+swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs)
 {
 	struct swap_info_struct *si = __swap_entry_to_info(entry);
 	struct swap_cluster_info *ci;
@@ -4790,7 +4798,7 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry)
 	}
 	swap_cluster_unlock(ci);
 
-	phys = xswap_alloc_phys_slot();
+	phys = xswap_alloc_phys_slot(may_enter_fs);
 	if (!phys.val)
 		return phys;
 
diff --git a/mm/vmscan.c b/mm/vmscan.c
index 443ee5d30531..c3ba8050ed89 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -1369,7 +1369,9 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 	unsigned int nr_reclaimed = 0, nr_demoted = 0;
 	unsigned int pgactivate = 0;
 	bool do_demote_pass;
-	struct swap_io_ctx ctx = {};
+	struct swap_io_ctx ctx = {
+		.may_enter_fs = !!(sc->gfp_mask & __GFP_FS),
+	};
 
 	folio_batch_init(&free_folios);
 	memset(stat, 0, sizeof(*stat));
diff --git a/mm/zswap.c b/mm/zswap.c
index 188f763a8af9..c367fd04551d 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1066,6 +1066,8 @@ struct zswap_shrink_ctl {
 	 * the swap cache, and set it to true.
 	 */
 	bool *encountered_page_in_swapcache;
+	/* Whether the backing allocation may enter the filesystem. */
+	bool may_enter_fs;
 };
 
 /*
@@ -1085,7 +1087,7 @@ struct zswap_shrink_ctl {
  */
 static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 				 struct zswap_entry *entry,
-				 swp_entry_t swpentry)
+				 swp_entry_t swpentry, bool may_enter_fs)
 {
 	struct xarray *tree;
 	pgoff_t offset = swp_offset(swpentry);
@@ -1159,7 +1161,7 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 
 	/* Reserve the destination before dropping the zswap copy. */
 	if (is_xswap) {
-		phys = xswap_backend_alloc(swpentry);
+		phys = xswap_backend_alloc(swpentry, may_enter_fs);
 		if (!phys.val) {
 			ret = -ENOMEM;
 			goto err;
@@ -1236,6 +1238,7 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
  *    can expect from writeback. We scale down the number of objects available
  *    for reclaim by this ratio.
  */
+
 static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_one *l,
 				       void *arg)
 {
@@ -1312,7 +1315,8 @@ static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_o
 	 */
 	spin_unlock(&l->lock);
 
-	writeback_result = zswap_writeback_entry(&ctl->io_ctx, entry, swpentry);
+	writeback_result = zswap_writeback_entry(&ctl->io_ctx, entry, swpentry,
+						 ctl->may_enter_fs);
 
 	if (writeback_result) {
 		zswap_reject_reclaim_fail++;
@@ -1340,6 +1344,7 @@ static unsigned long zswap_shrinker_scan(struct shrinker *shrinker,
 	bool encountered_page_in_swapcache = false;
 	struct zswap_shrink_ctl ctl = {
 		.encountered_page_in_swapcache = &encountered_page_in_swapcache,
+		.may_enter_fs = !!(sc->gfp_mask & __GFP_FS),
 	};
 	unsigned long shrink_ret;
 	struct blk_plug plug;
@@ -1459,9 +1464,11 @@ static struct shrinker *zswap_alloc_shrinker(void)
  * were scanned but none could be written back, or -ENOENT if @memcg has
  * writeback disabled, is a zombie cgroup, or has empty zswap LRUs.
  */
-static int shrink_memcg(struct mem_cgroup *memcg)
+static int shrink_memcg(struct mem_cgroup *memcg, bool may_enter_fs)
 {
-	struct zswap_shrink_ctl ctl = {};
+	struct zswap_shrink_ctl ctl = {
+		.may_enter_fs = may_enter_fs,
+	};
 	int nid, shrunk = 0, scanned = 0;
 	struct blk_plug plug;
 
@@ -1560,7 +1567,7 @@ static void shrink_worker(struct work_struct *w)
 			goto resched;
 		}
 
-		ret = shrink_memcg(memcg);
+		ret = shrink_memcg(memcg, true);
 		/* drop the extra reference */
 		mem_cgroup_put(memcg);
 
@@ -1682,7 +1689,7 @@ static bool zswap_store_page(struct folio *folio, long index,
 	return false;
 }
 
-bool zswap_store(struct folio *folio)
+bool zswap_store(struct folio *folio, bool may_enter_fs)
 {
 	long nr_pages = folio_nr_pages(folio);
 	swp_entry_t swp = folio->swap;
@@ -1701,7 +1708,7 @@ bool zswap_store(struct folio *folio)
 	objcg = get_obj_cgroup_from_folio(folio);
 	if (objcg && !obj_cgroup_may_zswap(objcg)) {
 		memcg = get_mem_cgroup_from_objcg(objcg);
-		if (shrink_memcg(memcg)) {
+		if (shrink_memcg(memcg, may_enter_fs)) {
 			mem_cgroup_put(memcg);
 			goto put_objcg;
 		}
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 13/32] mm, swap: pass the folio order through the swap slot allocator
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (11 preceding siblings ...)
  2026-12-03 18:12 ` [PATCH v2 12/32] mm, swap: skip a NOFS backend for xswap physical writeback Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 14/32] mm, swap: allocate a multi-slot range without a folio Baoquan He
                   ` (18 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

The allocation helpers derive the order from the folio.  A physical
xswap slot has no folio of its own, so pass the order explicitly.
Callers that have a folio pass folio_order(); hibernation and the
order-0 xswap backend pass 0.

No functional change.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 60 ++++++++++++++++++++++++++-------------------------
 1 file changed, 31 insertions(+), 29 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 7e0bdde39ab0..195fdc879311 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -1170,10 +1170,9 @@ static bool cluster_scan_range(struct swap_info_struct *si,
 static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 					 struct swap_cluster_info *ci,
 					 struct folio *folio,
-					 unsigned int ci_off)
+					 unsigned int ci_off, unsigned int order)
 {
-	unsigned int order;
-	unsigned long nr_pages;
+	unsigned long nr_pages = 1UL << order;
 
 	lockdep_assert_held(&ci->lock);
 
@@ -1192,14 +1191,10 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 	 * freed by its owner.
 	 */
 	if (likely(folio)) {
-		order = folio_order(folio);
-		nr_pages = 1 << order;
 		swap_cluster_assert_empty(ci, ci_off, nr_pages, false);
 		__swap_cache_add_folio(ci, folio, swp_entry(si->type,
 							    ci_off + cluster_offset(si, ci)));
 	} else {
-		order = 0;
-		nr_pages = 1;
 		swap_cluster_assert_empty(ci, ci_off, 1, false);
 		/* Owned by hibernation or the xswap backend; never cached. */
 		__swap_table_set(ci, ci_off, SWP_TB_HIB);
@@ -1232,13 +1227,13 @@ static bool swap_prefer_free_cluster(struct swap_info_struct *si)
 static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
 					     struct swap_cluster_info *ci,
 					     struct folio *folio,
-					     unsigned long offset, bool no_cache)
+					     unsigned long offset,
+					     unsigned int order, bool no_cache)
 {
 	unsigned long next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 	unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);
-	unsigned int order = likely(folio) ? folio_order(folio) : 0;
 	unsigned long end = start + SWAPFILE_CLUSTER;
-	unsigned int nr_pages = 1 << order;
+	unsigned long nr_pages = 1UL << order;
 	bool need_reclaim, ret, usable;
 
 	lockdep_assert_held(&ci->lock);
@@ -1261,7 +1256,8 @@ static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
 			if (!ret)
 				continue;
 		}
-		if (!__swap_cluster_alloc_entries(si, ci, folio, offset % SWAPFILE_CLUSTER))
+		if (!__swap_cluster_alloc_entries(si, ci, folio,
+						  offset % SWAPFILE_CLUSTER, order))
 			break;
 		found = offset;
 		offset += nr_pages;
@@ -1288,7 +1284,8 @@ static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
 static unsigned long alloc_swap_scan_list(struct swap_info_struct *si,
 					  struct list_head *list,
 					  struct folio *folio,
-					  bool scan_all, bool no_cache)
+					  unsigned int order, bool scan_all,
+					  bool no_cache)
 {
 	unsigned long found = SWAP_ENTRY_INVALID;
 
@@ -1299,7 +1296,7 @@ static unsigned long alloc_swap_scan_list(struct swap_info_struct *si,
 		if (!ci)
 			break;
 		offset = cluster_offset(si, ci);
-		found = alloc_swap_scan_cluster(si, ci, folio, offset,
+		found = alloc_swap_scan_cluster(si, ci, folio, offset, order,
 						no_cache);
 		if (found)
 			break;
@@ -1386,11 +1383,10 @@ static void swap_reclaim_work(struct work_struct *work)
  * cluster for current CPU too.
  */
 static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
-					      struct folio *folio,
+					      struct folio *folio, unsigned int order,
 					      bool no_cache)
 {
 	struct swap_cluster_info *ci;
-	unsigned int order = likely(folio) ? folio_order(folio) : 0;
 	unsigned long offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 #ifdef CONFIG_XSWAP
 	bool retried = false;
@@ -1422,7 +1418,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 		if (cluster_is_usable(ci, order)) {
 			if (cluster_is_empty(ci))
 				offset = cluster_offset(si, ci);
-			found = alloc_swap_scan_cluster(si, ci, folio, offset,
+			found = alloc_swap_scan_cluster(si, ci, folio, offset, order,
 							no_cache);
 		} else {
 			swap_cluster_unlock(ci);
@@ -1440,26 +1436,28 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	 */
 	if ((!folio || no_cache) && order < PMD_ORDER) {
 		found = alloc_swap_scan_list(si, &si->frag_clusters[order],
-					     folio, false, no_cache);
+					     folio, order, false, no_cache);
 		if (found)
 			goto done;
 	}
 
 	if (swap_prefer_free_cluster(si)) {
-		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false, no_cache);
+		found = alloc_swap_scan_list(si, &si->free_clusters,
+					     folio, order, false, no_cache);
 		if (found)
 			goto done;
 	}
 
 	if (order < PMD_ORDER) {
 		found = alloc_swap_scan_list(si, &si->nonfull_clusters[order],
-					     folio, true, no_cache);
+					     folio, order, true, no_cache);
 		if (found)
 			goto done;
 	}
 
 	if (!swap_prefer_free_cluster(si)) {
-		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false, no_cache);
+		found = alloc_swap_scan_list(si, &si->free_clusters,
+					     folio, order, false, no_cache);
 		if (found)
 			goto done;
 	}
@@ -1475,7 +1473,8 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 		 * failure is not critical. Scanning one cluster still
 		 * keeps the list rotated and reclaimed (for clean swap cache).
 		 */
-		found = alloc_swap_scan_list(si, &si->frag_clusters[order], folio, false, no_cache);
+		found = alloc_swap_scan_list(si, &si->frag_clusters[order],
+					     folio, order, false, no_cache);
 		if (found)
 			goto done;
 	}
@@ -1489,11 +1488,13 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 		 * Clusters here have at least one usable slots and can't fail order 0
 		 * allocation, but reclaim may drop si->lock and race with another user.
 		 */
-		found = alloc_swap_scan_list(si, &si->frag_clusters[o], folio, true, no_cache);
+		found = alloc_swap_scan_list(si, &si->frag_clusters[o],
+					     folio, order, true, no_cache);
 		if (found)
 			goto done;
 
-		found = alloc_swap_scan_list(si, &si->nonfull_clusters[o], folio, true, no_cache);
+		found = alloc_swap_scan_list(si, &si->nonfull_clusters[o],
+					     folio, order, true, no_cache);
 		if (found)
 			goto done;
 	}
@@ -1726,7 +1727,7 @@ static bool swap_alloc_fast(struct folio *folio, bool may_zswap)
 	if (cluster_is_usable(ci, order)) {
 		if (cluster_is_empty(ci))
 			offset = cluster_offset(si, ci);
-		alloc_swap_scan_cluster(si, ci, folio, offset, false);
+		alloc_swap_scan_cluster(si, ci, folio, offset, order, false);
 	} else {
 		swap_cluster_unlock(ci);
 	}
@@ -1753,7 +1754,8 @@ static void swap_alloc_slow(struct folio *folio, bool may_zswap)
 		plist_requeue(&si->avail_list, &swap_avail_head);
 		spin_unlock(&swap_avail_lock);
 		if (get_swap_device_info(si)) {
-			cluster_alloc_swap_entry(si, folio, !may_zswap);
+			cluster_alloc_swap_entry(si, folio, folio_order(folio),
+						 !may_zswap);
 			put_swap_device(si);
 			if (folio_test_swapcache(folio))
 				return;
@@ -2639,12 +2641,12 @@ swp_entry_t swap_alloc_hibernation_slot(int type)
 		ci = swap_cluster_lock(si, pcp_offset);
 		if (cluster_is_usable(ci, 0))
 			offset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset,
-							 false);
+							 0, false);
 		else
 			swap_cluster_unlock(ci);
 	}
 	if (!offset)
-		offset = cluster_alloc_swap_entry(si, NULL, false);
+		offset = cluster_alloc_swap_entry(si, NULL, 0, false);
 	local_unlock(&percpu_swap_cluster.lock);
 	if (offset)
 		entry = swp_entry(si->type, offset);
@@ -4687,14 +4689,14 @@ static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si)
 			ci = swap_cluster_lock(si, pcp_offset);
 			if (cluster_is_usable(ci, 0))
 				offset = alloc_swap_scan_cluster(si, ci, NULL,
-								 pcp_offset,
+								 pcp_offset, 0,
 								 true);
 			else
 				swap_cluster_unlock(ci);
 		}
 	}
 	if (offset == SWAP_ENTRY_INVALID)
-		offset = cluster_alloc_swap_entry(si, NULL, true);
+		offset = cluster_alloc_swap_entry(si, NULL, 0, true);
 	local_unlock(&percpu_swap_cluster.lock);
 
 	return offset;
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 14/32] mm, swap: allocate a multi-slot range without a folio
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (12 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 13/32] mm, swap: pass the folio order through the swap slot allocator Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 15/32] mm, swap: pass the folio order to the xswap physical backend Baoquan He
                   ` (17 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

The physical range backing a large xswap folio has no folio of its own.
Teach the exclusive allocation path to initialise every slot in the
range instead of only the first.  Existing callers are still order 0.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 26 ++++++++++----------------
 1 file changed, 10 insertions(+), 16 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 195fdc879311..0e4b468ad87b 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -1173,6 +1173,7 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 					 unsigned int ci_off, unsigned int order)
 {
 	unsigned long nr_pages = 1UL << order;
+	unsigned long i;
 
 	lockdep_assert_held(&ci->lock);
 
@@ -1181,29 +1182,23 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 
 	/*
 	 * All mm swap allocation starts with a folio (folio_alloc_swap),
-	 * it's also the only allocation path for large orders allocation.
-	 * Such swap slots starts with count == 0 and will be increased
-	 * upon folio unmap.
+	 * it's also the allocation path for large orders. Such swap slots
+	 * starts with count == 0 and will be increased upon folio unmap.
 	 *
-	 * Else, it's an exclusive order 0 allocation for a slot that has
-	 * no folio of its own: hibernation, and the physical slot that
-	 * backs an xswap entry.  The slot carries no swap count and is
-	 * freed by its owner.
+	 * Else, it's an exclusive allocation for a range of slots that has no
+	 * folio of its own: hibernation, and the range that backs an xswap
+	 * folio.  The slots carry no swap count and are freed by their owner.
 	 */
+	swap_cluster_assert_empty(ci, ci_off, nr_pages, false);
 	if (likely(folio)) {
-		swap_cluster_assert_empty(ci, ci_off, nr_pages, false);
 		__swap_cache_add_folio(ci, folio, swp_entry(si->type,
 							    ci_off + cluster_offset(si, ci)));
 	} else {
-		swap_cluster_assert_empty(ci, ci_off, 1, false);
 		/* Owned by hibernation or the xswap backend; never cached. */
-		__swap_table_set(ci, ci_off, SWP_TB_HIB);
+		for (i = 0; i < nr_pages; i++)
+			__swap_table_set(ci, ci_off + i, SWP_TB_HIB);
 	}
 
-	/*
-	 * The first allocation in a cluster makes the
-	 * cluster exclusive to this order
-	 */
 	if (cluster_is_empty(ci))
 		ci->order = order;
 	ci->count += nr_pages;
@@ -1256,8 +1251,7 @@ static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
 			if (!ret)
 				continue;
 		}
-		if (!__swap_cluster_alloc_entries(si, ci, folio,
-						  offset % SWAPFILE_CLUSTER, order))
+		if (!__swap_cluster_alloc_entries(si, ci, folio, offset % SWAPFILE_CLUSTER, order))
 			break;
 		found = offset;
 		offset += nr_pages;
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 15/32] mm, swap: pass the folio order to the xswap physical backend
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (13 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 14/32] mm, swap: allocate a multi-slot range without a folio Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 16/32] mm, swap: enable large xswap folios with a contiguous physical slot range Baoquan He
                   ` (16 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

An xswap folio can need more than one physical swap slot.  A large folio
needs 1 << order contiguous slots on the real device, so the physical
backend must know the order when it allocates.  Pass the order to the
backend functions, set up every slot in the range, and free the whole
range together.

Callers still pass order 0 for now.  Large xswap folios are not enabled
yet.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/page_io.c  |   3 +-
 mm/swap.h     |  10 +++--
 mm/swapfile.c | 120 +++++++++++++++++++++++++++++---------------------
 mm/zswap.c    |   4 +-
 4 files changed, 80 insertions(+), 57 deletions(-)

diff --git a/mm/page_io.c b/mm/page_io.c
index 5aa3717b3d70..71e442a8f744 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -265,7 +265,8 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 		swp_entry_t phys;
 
 		/* The pool refused it: fall back to a real swap device. */
-		phys = xswap_backend_alloc(entry, ctx->may_enter_fs);
+		phys = xswap_backend_alloc(entry, folio_order(folio),
+					   ctx->may_enter_fs);
 		if (!phys.val) {
 			folio_mark_dirty(folio);
 			return AOP_WRITEPAGE_ACTIVATE;
diff --git a/mm/swap.h b/mm/swap.h
index 6e3128c54b4f..9739f9d9e9db 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -510,8 +510,9 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 
 #ifdef CONFIG_XSWAP
 swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot);
-swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs);
-void xswap_backend_free(swp_entry_t entry, swp_entry_t phys);
+swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
+				bool may_enter_fs);
+void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order);
 #else
 static inline swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci,
 					     unsigned int slot)
@@ -519,12 +520,13 @@ static inline swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci,
 	return (swp_entry_t){};
 }
 
-static inline swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs)
+static inline swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
+					      bool may_enter_fs)
 {
 	return (swp_entry_t){};
 }
 
-static inline void xswap_backend_free(swp_entry_t entry, swp_entry_t phys)
+static inline void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order)
 {
 }
 #endif /* CONFIG_XSWAP */
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 0e4b468ad87b..6bc14f5d1618 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -4663,8 +4663,9 @@ static void xswap_free_xs_table(struct swap_info_struct *si,
 	ci->xs_table = NULL;
 }
 
-/* Order-0 slot from @si, no folio attached; goes through the per-CPU cache. */
-static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si)
+/* A range of 1 << @order slots, no folio attached. */
+static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si,
+					    unsigned int order)
 {
 	struct swap_cluster_info *ci;
 	unsigned long pcp_offset, offset = SWAP_ENTRY_INVALID;
@@ -4677,26 +4678,26 @@ static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si)
 	 * again.  Start from the cached cursor if it already points at this
 	 * device, but never install this device for the next swapout.
 	 */
-	if (this_cpu_read(percpu_swap_cluster.si[0]) == si) {
-		pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);
+	if (this_cpu_read(percpu_swap_cluster.si[order]) == si) {
+		pcp_offset = this_cpu_read(percpu_swap_cluster.offset[order]);
 		if (pcp_offset) {
 			ci = swap_cluster_lock(si, pcp_offset);
-			if (cluster_is_usable(ci, 0))
+			if (cluster_is_usable(ci, order))
 				offset = alloc_swap_scan_cluster(si, ci, NULL,
-								 pcp_offset, 0,
+								 pcp_offset, order,
 								 true);
 			else
 				swap_cluster_unlock(ci);
 		}
 	}
 	if (offset == SWAP_ENTRY_INVALID)
-		offset = cluster_alloc_swap_entry(si, NULL, 0, true);
+		offset = cluster_alloc_swap_entry(si, NULL, order, true);
 	local_unlock(&percpu_swap_cluster.lock);
 
 	return offset;
 }
 
-static swp_entry_t xswap_alloc_phys_slot(bool may_enter_fs)
+static swp_entry_t xswap_alloc_phys_slot(unsigned int order, bool may_enter_fs)
 {
 	struct swap_info_struct *devs[MAX_SWAPFILES], *si;
 	int nr = 0, i;
@@ -4734,7 +4735,7 @@ static swp_entry_t xswap_alloc_phys_slot(bool may_enter_fs)
 			put_swap_device(devs[i]);
 			continue;
 		}
-		offset = xswap_alloc_slot_local(devs[i]);
+		offset = xswap_alloc_slot_local(devs[i], order);
 		put_swap_device(devs[i]);
 		if (offset && offset != SWAP_ENTRY_INVALID)
 			return swp_entry(devs[i]->type, offset);
@@ -4760,25 +4761,33 @@ static void xswap_install_rmap(swp_entry_t phys, swp_entry_t entry)
 	}
 }
 
-swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs)
+/* Back the range of 1 << @order slots at @entry with contiguous physical slots. */
+swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
+				bool may_enter_fs)
 {
 	struct swap_info_struct *si = __swap_entry_to_info(entry);
 	struct swap_cluster_info *ci;
+	unsigned long nr = 1UL << order;
 	unsigned long off = swp_offset(entry);
-	unsigned long swp_tb;
-	swp_entry_t phys, old;
+	swp_entry_t phys;
+	unsigned int i;
 
 	/*
 	 * A folio that was written back, redirtied while still in the swap
 	 * cache and is now written out again still records the old slot range.
 	 * Drop it before the new one replaces it.
 	 */
-	ci = swap_cluster_lock(si, off);
-	if (ci) {
-		old = xswap_slot_backend(ci, off % SWAPFILE_CLUSTER);
-		swap_cluster_unlock(ci);
+	for (i = 0; i < nr; i++) {
+		struct swap_cluster_info *oci;
+		swp_entry_t old;
+
+		oci = swap_cluster_lock(si, off + i);
+		if (!oci)
+			continue;
+		old = xswap_slot_backend(oci, (off + i) % SWAPFILE_CLUSTER);
+		swap_cluster_unlock(oci);
 		if (old.val)
-			xswap_backend_free(entry, old);
+			xswap_backend_free(swp_entry(si->type, off + i), old, 0);
 	}
 
 	/*
@@ -4794,7 +4803,7 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs)
 	}
 	swap_cluster_unlock(ci);
 
-	phys = xswap_alloc_phys_slot(may_enter_fs);
+	phys = xswap_alloc_phys_slot(order, may_enter_fs);
 	if (!phys.val)
 		return phys;
 
@@ -4802,53 +4811,64 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, bool may_enter_fs)
 	 * The slot is a shadow until the reverse map is installed below.
 	 * Physical swapoff can see it and retry; the window is short and
 	 * try_to_unuse() reschedules.
-	 *
-	 * Owner first, then the reverse map, under one hold of the lock.
 	 */
+	/* One IO reads a large folio, so its range has to be contiguous. */
+	VM_WARN_ON_ONCE(swp_offset(phys) % nr);
+	VM_WARN_ON_ONCE(off % SWAPFILE_CLUSTER + nr > SWAPFILE_CLUSTER);
+
+	/* Owner first, then the reverse map, under one hold of the lock. */
 	ci = swap_cluster_lock(si, off);
-	if (!ci) {
-		xswap_backend_free(entry, phys);
-		return (swp_entry_t){};
-	}
-	/* The table is preallocated above, so this cannot fail. */
-	if (!xswap_slot_set_backend(ci, off % SWAPFILE_CLUSTER, phys))
-		VM_WARN_ON_ONCE(1);
-	xswap_install_rmap(phys, entry);
+	for (i = 0; i < nr; i++) {
+		unsigned int slot = (off + i) % SWAPFILE_CLUSTER;
+		swp_entry_t cur = swp_entry(swp_type(phys), swp_offset(phys) + i);
+		unsigned long swp_tb;
 
-	/*
-	 * The folio can lose its last reference while the owner is not
-	 * recorded yet; that path cannot mark the slot for us.
-	 */
-	swp_tb = __swap_table_get(ci, off % SWAPFILE_CLUSTER);
-	if (swp_tb_is_folio(swp_tb) && !swp_tb_get_count(swp_tb))
-		xswap_mark_cache_only(si, ci, off % SWAPFILE_CLUSTER);
+		/* The table is preallocated above, so this cannot fail. */
+		if (!xswap_slot_set_backend(ci, slot, cur))
+			VM_WARN_ON_ONCE(1);
+		xswap_install_rmap(cur, swp_entry(si->type, off + i));
+
+		/*
+		 * The folio can lose its last reference while the owner is
+		 * not recorded yet; that path cannot mark the slot for us.
+		 */
+		swp_tb = __swap_table_get(ci, slot);
+		if (swp_tb_is_folio(swp_tb) && !swp_tb_get_count(swp_tb))
+			xswap_mark_cache_only(si, ci, slot);
+	}
 	swap_cluster_unlock(ci);
 
 	return phys;
 }
 
 /* Undo xswap_backend_alloc(): the zswap copy is still in place. */
-void xswap_backend_free(swp_entry_t entry, swp_entry_t phys)
+void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order)
 {
 	struct swap_info_struct *si = __swap_entry_to_info(entry);
-	struct swap_info_struct *psi;
-	struct swap_cluster_info *ci;
+	struct swap_info_struct *psi = swap_type_to_info(swp_type(phys));
+	unsigned long nr = 1UL << order;
 	unsigned long off = swp_offset(entry);
+	unsigned long poff = swp_offset(phys);
+	unsigned int i;
 
-	ci = swap_cluster_lock(si, off);
-	if (ci) {
-		unsigned int slot = off % SWAPFILE_CLUSTER;
-		unsigned long *xs = ci->xs_table;
+	for (i = 0; i < nr; i++) {
+		struct swap_cluster_info *ci;
 
-		if (xs && xs[slot] == phys.val)
-			WRITE_ONCE(xs[slot], 0);
-		swap_cluster_unlock(ci);
-	}
+		ci = swap_cluster_lock(si, off + i);
+		if (ci) {
+			unsigned int slot = (off + i) % SWAPFILE_CLUSTER;
+			unsigned long *xs = ci->xs_table;
 
-	/* xswap_free_phys_slot() clears the reverse mapping. */
-	psi = swap_type_to_info(swp_type(phys));
-	if (psi)
-		xswap_free_phys_slot(psi, entry, phys);
+			if (xs && xs[slot] == phys.val + i)
+				WRITE_ONCE(xs[slot], 0);
+			swap_cluster_unlock(ci);
+		}
+
+		/* xswap_free_phys_slot() clears the reverse mapping. */
+		if (psi)
+			xswap_free_phys_slot(psi, swp_entry(si->type, off + i),
+					     swp_entry(swp_type(phys), poff + i));
+	}
 }
 
 static int xswap_map_clusters(struct swap_info_struct *si,
diff --git a/mm/zswap.c b/mm/zswap.c
index c367fd04551d..dfb7ea058d66 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1161,7 +1161,7 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 
 	/* Reserve the destination before dropping the zswap copy. */
 	if (is_xswap) {
-		phys = xswap_backend_alloc(swpentry, may_enter_fs);
+		phys = xswap_backend_alloc(swpentry, 0, may_enter_fs);
 		if (!phys.val) {
 			ret = -ENOMEM;
 			goto err;
@@ -1206,7 +1206,7 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 
 err:
 	if (is_xswap && phys.val)
-		xswap_backend_free(swpentry, phys);
+		xswap_backend_free(swpentry, phys, 0);
 	swap_cache_del_folio(folio);
 	folio_unlock(folio);
 	folio_put(folio);
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 16/32] mm, swap: enable large xswap folios with a contiguous physical slot range
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (14 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 15/32] mm, swap: pass the folio order to the xswap physical backend Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 17/32] mm, swap: enable THP swapin for xswap entries Baoquan He
                   ` (15 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

Allow a large order on an xswap device once a block device can back it.
The physical slot range has to be contiguous because the folio is read back with
a single IO from its first physical slot.

If the backend refuses a contiguous slot range, return a split request to
reclaim instead of activating the large folio over and over.  shmem
cannot repair its page cache state on such a return, so it keeps
can_split clear.

When reclaim cannot enter the fs, a REQUIRE_NOFS block device cannot
back the large slot range either.  Carry may_enter_fs into the large-backend
check and into folio_alloc_swap() so the folio is split instead of
allocating a slot range that writeback cannot use.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/swap_ops.h |  1 +
 mm/page_io.c             |  7 ++++
 mm/shmem.c               |  2 +-
 mm/swap.h                |  6 ++--
 mm/swapfile.c            | 77 +++++++++++++++++++++++++++++-----------
 mm/vmscan.c              | 44 ++++++++++++++++++++---
 6 files changed, 110 insertions(+), 27 deletions(-)

diff --git a/include/linux/swap_ops.h b/include/linux/swap_ops.h
index 3e3f14e3b98f..3962482fad9d 100644
--- a/include/linux/swap_ops.h
+++ b/include/linux/swap_ops.h
@@ -29,6 +29,7 @@ struct swap_io_ctx {
 	bool			in_thrashing;
 	unsigned long		in_memstall;
 	bool			may_enter_fs;	/* this context may enter the fs */
+	bool			can_split;	/* caller can handle a split folio */
 };
 
 /*
diff --git a/mm/page_io.c b/mm/page_io.c
index 71e442a8f744..080255ac7314 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -269,6 +269,13 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 					   ctx->may_enter_fs);
 		if (!phys.val) {
 			folio_mark_dirty(folio);
+			/*
+			 * No contiguous slot range: split instead of activating a
+			 * large folio over and over.  Only reclaim can take
+			 * the pieces back.
+			 */
+			if (folio_test_large(folio) && ctx->can_split)
+				return SWAP_WRITEOUT_SPLIT;
 			return AOP_WRITEPAGE_ACTIVATE;
 		}
 
diff --git a/mm/shmem.c b/mm/shmem.c
index 344f7edf5e15..f1c4b116c003 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -1954,7 +1954,7 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 		folio_mark_uptodate(folio);
 	}
 
-	ret = folio_alloc_swap(folio);
+	ret = folio_alloc_swap(folio, ctx->may_enter_fs);
 	if (!ret) {
 		bool first_swapped = shmem_recalc_inode(inode, 0, nr_pages);
 		int error;
diff --git a/mm/swap.h b/mm/swap.h
index 9739f9d9e9db..1260b0ac6f41 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -247,7 +247,7 @@ extern int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp);
  *
  * folio_put_swap(): does the opposite thing of folio_dup_swap().
  */
-int folio_alloc_swap(struct folio *folio);
+int folio_alloc_swap(struct folio *folio, bool may_enter_fs);
 int folio_dup_swap(struct folio *folio, struct page *page);
 void folio_put_swap(struct folio *folio, struct page *page);
 
@@ -258,6 +258,8 @@ extern void __swap_cluster_free_entries(struct swap_info_struct *si,
 
 /* linux/mm/page_io.c */
 int sio_pool_init(void);
+/* swap_writeout() wants a large folio split; reclaim only. */
+#define SWAP_WRITEOUT_SPLIT	0x80002
 void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio);
 void swap_read_submit(struct swap_io_ctx *ctx);
 void swap_write_submit(struct swap_io_ctx *ctx);
@@ -386,7 +388,7 @@ static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)
 	return NULL;
 }
 
-static inline int folio_alloc_swap(struct folio *folio)
+static inline int folio_alloc_swap(struct folio *folio, bool may_enter_fs)
 {
 	return -EINVAL;
 }
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 6bc14f5d1618..f1257ae98685 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -1372,13 +1372,35 @@ static void swap_reclaim_work(struct work_struct *work)
 	swap_reclaim_full_clusters(si, true);
 }
 
+#ifdef CONFIG_XSWAP
+/* Whether a block device that can back a large xswap folio is available. */
+static bool xswap_has_large_backend(bool may_enter_fs)
+{
+	struct swap_info_struct *si;
+	bool found = false;
+
+	spin_lock(&swap_avail_lock);
+	plist_for_each_entry(si, &swap_avail_head, avail_list) {
+		if ((si->flags & SWP_XSWAP) || !(si->flags & SWP_BLKDEV))
+			continue;
+		if (!may_enter_fs && (si->ops->flags & SWAP_OPS_F_REQUIRE_NOFS))
+			continue;
+		found = true;
+		break;
+	}
+	spin_unlock(&swap_avail_lock);
+
+	return found;
+}
+#endif /* CONFIG_XSWAP */
+
 /*
  * Try to allocate swap entries with specified order and try set a new
  * cluster for current CPU too.
  */
 static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 					      struct folio *folio, unsigned int order,
-					      bool no_cache)
+					      bool may_enter_fs, bool no_cache)
 {
 	struct swap_cluster_info *ci;
 	unsigned long offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
@@ -1388,13 +1410,24 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 
 	/*
 	 * Swapfile is not block device so unable
-	 * to allocate large entries.
+	 * to allocate large entries. xswap has no backing file, so it can.
 	 */
-	if (order && !(si->flags & SWP_BLKDEV))
+	if (order && !(si->flags & SWP_BLKDEV) && !(si->flags & SWP_XSWAP))
 		return 0;
 
 #ifdef CONFIG_XSWAP
-	/* Grow before allocating: mapping pages can sleep. */
+	/* A large xswap folio needs a contiguous block device slot range behind it. */
+	if (order && (si->flags & SWP_XSWAP) &&
+	    atomic_read(&nr_real_swapfiles) &&
+	    !xswap_has_large_backend(may_enter_fs))
+		return 0;
+
+	/*
+	 * Top the range up early.  Every path below leaves through `done`,
+	 * so this has to come first; mapping pages can sleep, and doing it
+	 * from the allocation that would otherwise fail leaves nothing to
+	 * fall back on.
+	 */
 	if ((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK) &&
 	    xswap_should_grow(si))
 		xswap_grow(si, false);
@@ -1696,7 +1729,8 @@ static bool get_swap_device_info(struct swap_info_struct *si)
  * Fast path try to get swap entries with specified order from current
  * CPU's swap entry pool (a cluster).
  */
-static bool swap_alloc_fast(struct folio *folio, bool may_zswap)
+static bool swap_alloc_fast(struct folio *folio, bool may_zswap,
+			    bool may_enter_fs)
 {
 	unsigned int order = folio_order(folio);
 	struct swap_cluster_info *ci;
@@ -1731,7 +1765,8 @@ static bool swap_alloc_fast(struct folio *folio, bool may_zswap)
 }
 
 /* Rotate the device and switch to a new cluster */
-static void swap_alloc_slow(struct folio *folio, bool may_zswap)
+static void swap_alloc_slow(struct folio *folio, bool may_zswap,
+			    bool may_enter_fs)
 {
 	struct swap_info_struct *si, *next;
 
@@ -1749,7 +1784,7 @@ static void swap_alloc_slow(struct folio *folio, bool may_zswap)
 		spin_unlock(&swap_avail_lock);
 		if (get_swap_device_info(si)) {
 			cluster_alloc_swap_entry(si, folio, folio_order(folio),
-						 !may_zswap);
+						 may_enter_fs, !may_zswap);
 			put_swap_device(si);
 			if (folio_test_swapcache(folio))
 				return;
@@ -2094,18 +2129,20 @@ static bool folio_may_zswap(struct folio *folio)
 	return may_zswap;
 }
 
-/* Can a non-xswap device still take a slot? */
-static bool real_swap_has_room(void)
+/* Can a non-xswap device take a slot in this context? */
+static bool real_swap_has_room(bool may_enter_fs)
 {
 	struct swap_info_struct *si;
 	bool room = false;
 
 	spin_lock(&swap_avail_lock);
 	plist_for_each_entry(si, &swap_avail_head, avail_list) {
-		if (!(si->flags & SWP_XSWAP)) {
-			room = true;
-			break;
-		}
+		if ((si->flags & SWP_XSWAP) ||
+		    (!may_enter_fs &&
+		     (si->ops->flags & SWAP_OPS_F_REQUIRE_NOFS)))
+			continue;
+		room = true;
+		break;
 	}
 	spin_unlock(&swap_avail_lock);
 	return room;
@@ -2123,7 +2160,7 @@ static bool real_swap_has_room(void)
  * %-ENOSPC if no global swap space is available, or %-ENOMEM if splitting
  * would not help.
  */
-int folio_alloc_swap(struct folio *folio)
+int folio_alloc_swap(struct folio *folio, bool may_enter_fs)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
@@ -2165,10 +2202,10 @@ int folio_alloc_swap(struct folio *folio)
 	 * A folio that cannot zswap can only use a real device; skip the
 	 * scan when none has room.  The failure is still reported below.
 	 */
-	if (may_zswap || real_swap_has_room()) {
+	if (may_zswap || real_swap_has_room(may_enter_fs)) {
 		local_lock(&percpu_swap_cluster.lock);
-		if (!swap_alloc_fast(folio, may_zswap))
-			swap_alloc_slow(folio, may_zswap);
+		if (!swap_alloc_fast(folio, may_zswap, may_enter_fs))
+			swap_alloc_slow(folio, may_zswap, may_enter_fs);
 		local_unlock(&percpu_swap_cluster.lock);
 	}
 
@@ -2212,7 +2249,7 @@ int folio_alloc_swap(struct folio *folio)
 	 * The folio can only use a real device and none has room; splitting
 	 * cannot help.
 	 */
-	if (!may_zswap && !real_swap_has_room())
+	if (!may_zswap && !real_swap_has_room(may_enter_fs))
 		return -ENOMEM;
 
 	return order ? -E2BIG : -ENOMEM;
@@ -2640,7 +2677,7 @@ swp_entry_t swap_alloc_hibernation_slot(int type)
 			swap_cluster_unlock(ci);
 	}
 	if (!offset)
-		offset = cluster_alloc_swap_entry(si, NULL, 0, false);
+		offset = cluster_alloc_swap_entry(si, NULL, 0, true, false);
 	local_unlock(&percpu_swap_cluster.lock);
 	if (offset)
 		entry = swp_entry(si->type, offset);
@@ -4691,7 +4728,7 @@ static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si,
 		}
 	}
 	if (offset == SWAP_ENTRY_INVALID)
-		offset = cluster_alloc_swap_entry(si, NULL, order, true);
+		offset = cluster_alloc_swap_entry(si, NULL, order, true, true);
 	local_unlock(&percpu_swap_cluster.lock);
 
 	return offset;
diff --git a/mm/vmscan.c b/mm/vmscan.c
index c3ba8050ed89..74920609a2b9 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -613,10 +613,46 @@ static pageout_t pageout(struct swap_io_ctx *ctx, struct address_space *mapping,
 	 * or we failed to allocate contiguous swap entries, in which case
 	 * the split out folios get added back to folio_list.
 	 */
-	if (shmem_mapping(mapping))
+	if (shmem_mapping(mapping)) {
+		/*
+		 * shmem_writeout() cannot repair its page cache state on a
+		 * split return.  ctx is reused across folios, so reset it
+		 * every call.
+		 */
+		ctx->can_split = false;
 		res = shmem_writeout(ctx, folio, folio_list);
-	else
+	} else {
+		ctx->can_split = true;
 		res = swap_writeout(ctx, folio);
+	}
+
+	/*
+	 * The backend refused a contiguous range.  Split here; nothing else
+	 * will, and an activated large folio just comes back.
+	 */
+	if (res == SWAP_WRITEOUT_SPLIT) {
+		int order = folio_order(folio);
+
+		/*
+		 * The slots exist but no backend is recorded yet, so the
+		 * split only has to re-point each piece at its own slot.
+		 */
+		if (!split_folio_to_list(folio, folio_list)) {
+#ifdef CONFIG_TRANSPARENT_HUGEPAGE
+			if (order >= HPAGE_PMD_ORDER) {
+				count_memcg_folio_events(folio,
+					THP_SWPOUT_FALLBACK, 1);
+				count_vm_event(THP_SWPOUT_FALLBACK);
+			}
+#endif
+			count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
+			/* Pieces are queued; the folio is still locked. */
+			folio_clear_reclaim(folio);
+			return PAGE_ACTIVATE;
+		}
+		folio_mark_dirty(folio);
+		res = AOP_WRITEPAGE_ACTIVATE;
+	}
 
 	if (res < 0)
 		handle_write_error(mapping, folio, res);
@@ -1587,7 +1623,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 				    split_folio_to_list(folio, folio_list))
 					goto activate_locked;
 			}
-			ret = folio_alloc_swap(folio);
+			ret = folio_alloc_swap(folio, ctx.may_enter_fs);
 			if (ret) {
 				int __maybe_unused order = folio_order(folio);
 
@@ -1606,7 +1642,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 				}
 #endif
 				count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
-				if (folio_alloc_swap(folio))
+				if (folio_alloc_swap(folio, ctx.may_enter_fs))
 					goto activate_locked_split;
 			}
 			/*
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 17/32] mm, swap: enable THP swapin for xswap entries
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (15 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 16/32] mm, swap: enable large xswap folios with a contiguous physical slot range Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 18/32] mm, swap: split the swap memcg charge helpers Baoquan He
                   ` (14 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

Read a large anon folio back as one unit when its xswap entries are
contiguous on one physical swap device; otherwise read it page by page
and retry at a smaller order. The device is SWP_SYNCHRONOUS_IO, which
THP swapin requires and which also skips readahead.

xswap_check_backing() refuses a zswap-backed or mixed range under the
cluster lock, before the folio is allocated, so zswap_load() takes the
physical path. If an earlier writeout fell back to a physical range and
zswap later accepts the folio, drop the stale range in swap_writeout()
on the zswap and zero-fill paths; reuse the backend loop as
xswap_backend_drop().

Co-developed-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/memory.c     | 25 ++++++++-------
 mm/page_io.c    |  6 +++-
 mm/swap.h       | 13 ++++++++
 mm/swap_state.c |  6 ++++
 mm/swapfile.c   | 82 +++++++++++++++++++++++++++++++++++++++++--------
 5 files changed, 107 insertions(+), 25 deletions(-)

diff --git a/mm/memory.c b/mm/memory.c
index 94b0b1921f54..aa9caf576564 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -4910,23 +4910,26 @@ static unsigned long thp_swapin_suitable_orders(struct swap_info_struct *si,
 	if (unlikely(userfaultfd_armed(vma)))
 		return 0;
 
+	entry = softleaf_from_pte(vmf->orig_pte);
+
 	/*
 	 * A large swapped out folio could be partially or fully in zswap. We
 	 * lack handling for such cases, so fallback to swapping in order-0
 	 * folio.
+	 * An xswap entry is deferred to __swap_cache_add_check() instead.
 	 */
-	if (!zswap_never_enabled())
-		return 0;
-
-	/*
-	 * Neighbouring slots of a swap file can lie in two extents, and a folio
-	 * is read with one bio. The flag is set in swapon() and stays, so the
-	 * race is benign.
-	 */
-	if (!data_race(si->flags & SWP_BLKDEV))
-		return 0;
+	if (!(__swap_entry_to_info(entry)->flags & SWP_XSWAP)) {
+		if (!zswap_never_enabled())
+			return 0;
 
-	entry = softleaf_from_pte(vmf->orig_pte);
+		/*
+		 * Neighbouring slots of a swap file can lie in two extents, and
+		 * a folio is read with one bio. The flag is set in swapon() and
+		 * stays, so the race is benign.
+		 */
+		if (!data_race(si->flags & SWP_BLKDEV))
+			return 0;
+	}
 	/*
 	 * Get a list of all the (large) orders below PMD_ORDER that are enabled
 	 * and suitable for swapping THP.
diff --git a/mm/page_io.c b/mm/page_io.c
index 080255ac7314..a49287162538 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -232,10 +232,12 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 		/*
 		 * The folio may have been stored in zswap before and dirtied
 		 * again while it stayed in the swap cache. Drop the old copy,
-		 * or zswap writeback would bring it back into the swap cache.
+		 * or zswap writeback would bring it back into the swap cache;
+		 * a physical slot range recorded for it is stale for the same reason.
 		 */
 		zswap_invalidate(swp_type(entry), swp_offset(entry),
 				 folio_nr_pages(folio));
+		xswap_backend_drop(entry, folio_order(folio));
 		goto out_unlock;
 	}
 
@@ -248,6 +250,8 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 
 	if (zswap_store(folio, ctx->may_enter_fs)) {
 		count_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);
+		/* A slot range recorded by an earlier writeout is stale now. */
+		xswap_backend_drop(folio->swap, folio_order(folio));
 		goto out_unlock;
 	}
 
diff --git a/mm/swap.h b/mm/swap.h
index 1260b0ac6f41..2cd87a26843a 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -515,6 +515,9 @@ swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot);
 swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 				bool may_enter_fs);
 void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order);
+void xswap_backend_drop(swp_entry_t entry, unsigned int order);
+int xswap_check_backing(struct swap_cluster_info *ci, unsigned int off,
+			unsigned int nr);
 #else
 static inline swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci,
 					     unsigned int slot)
@@ -531,6 +534,16 @@ static inline swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int or
 static inline void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order)
 {
 }
+
+static inline void xswap_backend_drop(swp_entry_t entry, unsigned int order)
+{
+}
+
+static inline int xswap_check_backing(struct swap_cluster_info *ci,
+				      unsigned int off, unsigned int nr)
+{
+	return nr;
+}
 #endif /* CONFIG_XSWAP */
 
 #endif /* _MM_SWAP_H */
diff --git a/mm/swap_state.c b/mm/swap_state.c
index 7298a9894737..044e4856b7d8 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -209,6 +209,12 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 	if (nr == 1)
 		return 0;
 
+	/* A zswap-backed or mixed batch falls back to a smaller order. */
+	if (__swap_entry_to_info(targ_entry)->flags & SWP_XSWAP) {
+		if (xswap_check_backing(ci, round_down(ci_off, nr), nr) != nr)
+			return -EBUSY;
+	}
+
 	is_zero = __swap_table_test_zero(ci, ci_off);
 	ci_off = round_down(ci_off, nr);
 	ci_end = ci_off + nr;
diff --git a/mm/swapfile.c b/mm/swapfile.c
index f1257ae98685..463f53286a05 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -4634,6 +4634,39 @@ swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot)
 	return (swp_entry_t){ .val = xs[slot] };
 }
 
+/*
+ * A large xswap folio is read back as one IO only when the whole range is
+ * backed by one device, contiguously. Returns how many leading slots are.
+ */
+int xswap_check_backing(struct swap_cluster_info *ci, unsigned int off,
+			unsigned int nr)
+{
+	swp_entry_t first;
+	unsigned int i;
+
+	lockdep_assert_held(&ci->lock);
+	/* A folio's slots never straddle a cluster, or the walk runs off. */
+	if (off + nr > SWAPFILE_CLUSTER) {
+		VM_WARN_ON_ONCE(1);
+		nr = SWAPFILE_CLUSTER - off;
+	}
+
+	/* In zswap, which cannot load a large folio. */
+	if (!ci->xs_table || !ci->xs_table[off])
+		return 1;
+
+	first.val = ci->xs_table[off];
+	for (i = 1; i < nr; i++) {
+		swp_entry_t cur = { .val = ci->xs_table[off + i] };
+
+		if (swp_type(cur) != swp_type(first) ||
+		    swp_offset(cur) != swp_offset(first) + i)
+			break;
+	}
+
+	return i;
+}
+
 /* Cluster lock held. The mapped prefix only grows while the device exists. */
 static unsigned long *xswap_xs_table_locked(struct swap_cluster_info *ci,
 					    gfp_t gfp)
@@ -4798,6 +4831,36 @@ static void xswap_install_rmap(swp_entry_t phys, swp_entry_t entry)
 	}
 }
 
+/*
+ * The data of the range of 1 << @order slots at @entry has been replaced,
+ * by zswap or by the zero mark.  Drop the physical slot range recorded for it:
+ * otherwise its slots stay held until the xswap entry is freed, and a
+ * large folio can be read from a stale physical copy.
+ */
+void xswap_backend_drop(swp_entry_t entry, unsigned int order)
+{
+	struct swap_info_struct *si = __swap_entry_to_info(entry);
+	unsigned long nr = 1UL << order;
+	unsigned long off = swp_offset(entry);
+	unsigned int i;
+
+	if (!(si->flags & SWP_XSWAP))
+		return;
+
+	for (i = 0; i < nr; i++) {
+		struct swap_cluster_info *ci;
+		swp_entry_t old;
+
+		ci = swap_cluster_lock(si, off + i);
+		if (!ci)
+			continue;
+		old = xswap_slot_backend(ci, (off + i) % SWAPFILE_CLUSTER);
+		swap_cluster_unlock(ci);
+		if (old.val)
+			xswap_backend_free(swp_entry(si->type, off + i), old, 0);
+	}
+}
+
 /* Back the range of 1 << @order slots at @entry with contiguous physical slots. */
 swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 				bool may_enter_fs)
@@ -4814,18 +4877,7 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 	 * cache and is now written out again still records the old slot range.
 	 * Drop it before the new one replaces it.
 	 */
-	for (i = 0; i < nr; i++) {
-		struct swap_cluster_info *oci;
-		swp_entry_t old;
-
-		oci = swap_cluster_lock(si, off + i);
-		if (!oci)
-			continue;
-		old = xswap_slot_backend(oci, (off + i) % SWAPFILE_CLUSTER);
-		swap_cluster_unlock(oci);
-		if (old.val)
-			xswap_backend_free(swp_entry(si->type, off + i), old, 0);
-	}
+	xswap_backend_drop(entry, order);
 
 	/*
 	 * Get the xswap side ready before a physical slot exists, so the
@@ -5281,7 +5333,11 @@ static int xswap_create(int prio)
 
 	si->bdev = NULL;
 	si->swap_file = NULL;
-	si->flags |= SWP_XSWAP | SWP_SOLIDSTATE;
+	/*
+	 * Reads are served from zswap, so no readahead. Only a synchronous
+	 * device can swap a large folio back in as a unit.
+	 */
+	si->flags |= SWP_XSWAP | SWP_SOLIDSTATE | SWP_SYNCHRONOUS_IO;
 	si->max = maxpages;
 	si->pages = maxpages - 1;
 	/*
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 18/32] mm, swap: split the swap memcg charge helpers
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (16 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 17/32] mm, swap: enable THP swapin for xswap entries Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 19/32] mm, swap: do not charge zswap-backed xswap entries Baoquan He
                   ` (13 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Nhat Pham <nphamcs@gmail.com>

Split __mem_cgroup_try_charge_swap() into separate get, charge, record,
uncharge and put helpers, and factor mem_cgroup_may_zswap() out of
obj_cgroup_may_zswap().  Recording the owner of a swap slot and charging
it no longer have to happen together, so a later patch can charge swap
only once it gets physical backing.

No functional change.

Suggested-by: Johannes Weiner <hannes@cmpxchg.org>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 .../admin-guide/cgroup-v1/memcg_test.rst      |   2 +-
 include/linux/memcontrol.h                    |   6 +
 include/linux/swap.h                          |  60 +++++++-
 mm/memcontrol-v1.c                            |   3 +-
 mm/memcontrol.c                               | 141 +++++++++++++-----
 mm/swapfile.c                                 |  28 +++-
 6 files changed, 185 insertions(+), 55 deletions(-)

diff --git a/Documentation/admin-guide/cgroup-v1/memcg_test.rst b/Documentation/admin-guide/cgroup-v1/memcg_test.rst
index d9951c319ef5..cd565626c435 100644
--- a/Documentation/admin-guide/cgroup-v1/memcg_test.rst
+++ b/Documentation/admin-guide/cgroup-v1/memcg_test.rst
@@ -43,7 +43,7 @@ Please note that implementation details can be changed.
 	mem_cgroup_uncharge()
 	  Called when a page's refcount goes down to 0.
 
-	mem_cgroup_uncharge_swap()
+	mem_cgroup_swap_uncharge()
 	  Called when swp_entry's refcnt goes down to 0. A charge against swap
 	  disappears.
 
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index c683b1a15ae5..aaa7a035007f 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -1968,6 +1968,7 @@ static inline void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_ZSWAP)
 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg);
+bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush);
 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size);
 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size);
 bool mem_cgroup_zswap_writeback_enabled(const struct mem_cgroup *memcg);
@@ -1976,6 +1977,11 @@ static inline bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
 {
 	return true;
 }
+
+static inline bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
+{
+	return true;
+}
 static inline void obj_cgroup_charge_zswap(struct obj_cgroup *objcg,
 					   size_t size)
 {
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 815aee556991..8c1131d924ae 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -528,36 +528,80 @@ static inline void folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
 #endif
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_SWAP)
-int __mem_cgroup_try_charge_swap(struct folio *folio);
-static inline int mem_cgroup_try_charge_swap(struct folio *folio)
+bool __mem_cgroup_swap_get(struct folio *folio, unsigned short *id);
+static inline bool mem_cgroup_swap_get(struct folio *folio, unsigned short *id)
+{
+	if (mem_cgroup_disabled())
+		return false;
+	return __mem_cgroup_swap_get(folio, id);
+}
+
+int __mem_cgroup_swap_charge(unsigned short id, unsigned int nr_pages);
+static inline int mem_cgroup_swap_charge(unsigned short id,
+					 unsigned int nr_pages)
 {
 	if (mem_cgroup_disabled())
 		return 0;
-	return __mem_cgroup_try_charge_swap(folio);
+	return __mem_cgroup_swap_charge(id, nr_pages);
 }
 
-extern void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages);
-static inline void mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
+void __mem_cgroup_swap_record(struct folio *folio, unsigned short id);
+static inline void mem_cgroup_swap_record(struct folio *folio,
+					  unsigned short id)
 {
 	if (mem_cgroup_disabled())
 		return;
-	__mem_cgroup_uncharge_swap(id, nr_pages);
+	__mem_cgroup_swap_record(folio, id);
+}
+
+void __mem_cgroup_swap_uncharge(unsigned short id, unsigned int nr_pages);
+static inline void mem_cgroup_swap_uncharge(unsigned short id,
+					    unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_swap_uncharge(id, nr_pages);
+}
+
+void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages);
+static inline void mem_cgroup_swap_put(unsigned short id,
+				       unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_swap_put(id, nr_pages);
 }
 
 long mem_cgroup_get_folio_swap_margin(const struct folio *folio);
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg);
 bool mem_cgroup_swap_full(const struct folio *folio);
 #else
-static inline int mem_cgroup_try_charge_swap(struct folio *folio)
+static inline bool mem_cgroup_swap_get(struct folio *folio, unsigned short *id)
+{
+	return false;
+}
+
+static inline int mem_cgroup_swap_charge(unsigned short id,
+					 unsigned int nr_pages)
 {
 	return 0;
 }
 
-static inline void mem_cgroup_uncharge_swap(unsigned short id,
+static inline void mem_cgroup_swap_record(struct folio *folio,
+					  unsigned short id)
+{
+}
+
+static inline void mem_cgroup_swap_uncharge(unsigned short id,
 					    unsigned int nr_pages)
 {
 }
 
+static inline void mem_cgroup_swap_put(unsigned short id,
+				       unsigned int nr_pages)
+{
+}
+
 static inline long mem_cgroup_get_folio_swap_margin(const struct folio *folio)
 {
 	return PAGE_COUNTER_MAX;
diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
index b7f286888507..b75478457a0e 100644
--- a/mm/memcontrol-v1.c
+++ b/mm/memcontrol-v1.c
@@ -371,7 +371,8 @@ void memcg1_swapin(struct folio *folio)
 	id = __swap_cgroup_clear(ci, swp_cluster_offset(folio->swap),
 				 nr_pages);
 	swap_cluster_unlock(ci);
-	mem_cgroup_uncharge_swap(id, nr_pages);
+	mem_cgroup_swap_uncharge(id, nr_pages);
+	mem_cgroup_swap_put(id, nr_pages);
 }
 #endif
 
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index b75a61ddeded..0a2ef04e17f5 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -6072,62 +6072,99 @@ int __init mem_cgroup_init(void)
 
 #ifdef CONFIG_SWAP
 /**
- * __mem_cgroup_try_charge_swap - try charging swap space for a folio
+ * __mem_cgroup_swap_get - take the private ID refs for a folio's swap slots
  * @folio: folio being added to swap
+ * @id: out, the ID to record and later charge against
  *
- * Try to charge @folio's memcg for the swap space at folio->swap.
+ * Takes one private ID ref per page of @folio on its memcg, or on its closest
+ * online ancestor if it has been offlined. The caller records and charges
+ * against whichever ID comes back, so both land on the same memcg.
  *
- * Returns 0 on success, -ENOMEM on failure.
+ * Return: true if an owner was taken, false when there is nothing to account
+ * for. Drop the refs with __mem_cgroup_swap_put().
  */
-int __mem_cgroup_try_charge_swap(struct folio *folio)
+bool __mem_cgroup_swap_get(struct folio *folio, unsigned short *id)
 {
 	unsigned int nr_pages = folio_nr_pages(folio);
-	struct swap_cluster_info *ci;
-	struct page_counter *counter;
 	struct mem_cgroup *memcg;
 	struct obj_cgroup *objcg;
-	unsigned short private_id;
 
 	if (do_memsw_account())
-		return 0;
+		return false;
 
 	objcg = folio_objcg(folio);
 	VM_WARN_ON_ONCE_FOLIO(!objcg, folio);
 	if (!objcg)
-		return 0;
+		return false;
 
 	scoped_guard(rcu) {
 		memcg = obj_cgroup_memcg(objcg);
 		if (!folio_test_swapcache(folio)) {
 			memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
-			return 0;
+			return false;
 		}
 
-		private_id = mem_cgroup_private_id_get(memcg, nr_pages);
+		*id = mem_cgroup_private_id_get(memcg, nr_pages);
+	}
+
+	return true;
+}
+
+/**
+ * __mem_cgroup_swap_charge - charge physical swap space
+ * @id: the ID the slots were recorded against
+ * @nr_pages: the amount of swap space to charge
+ *
+ * Return: 0 on success, -ENOMEM if memory.swap.max is exceeded.
+ */
+int __mem_cgroup_swap_charge(unsigned short id, unsigned int nr_pages)
+{
+	struct page_counter *counter;
+	struct mem_cgroup *memcg;
+
+	if (do_memsw_account())
+		return 0;
+
+	scoped_guard(rcu) {
+		memcg = mem_cgroup_from_private_id(id);
+		if (!memcg)
+			return 0;
 
-		if (!mem_cgroup_private_id_is_root(private_id) &&
+		if (!mem_cgroup_private_id_is_root(id) &&
 		    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
 			memcg_memory_event(memcg, MEMCG_SWAP_MAX);
 			memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
-			mem_cgroup_private_id_put(private_id, nr_pages);
 			return -ENOMEM;
 		}
 		mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
 	}
 
+	return 0;
+}
+
+/**
+ * __mem_cgroup_swap_record - record the owner of a folio's swap slots
+ * @folio: folio being added to swap
+ * @id: the ID taken by __mem_cgroup_swap_get()
+ */
+void __mem_cgroup_swap_record(struct folio *folio, unsigned short id)
+{
+	struct swap_cluster_info *ci;
+
 	ci = swap_cluster_get_and_lock(folio);
-	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_pages, private_id);
+	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap),
+			  folio_nr_pages(folio), id);
 	swap_cluster_unlock(ci);
-
-	return 0;
 }
 
 /**
- * __mem_cgroup_uncharge_swap - uncharge swap space
- * @id: cgroup id to uncharge
+ * __mem_cgroup_swap_uncharge - uncharge physical swap space
+ * @id: the ID the slots were recorded against
  * @nr_pages: the amount of swap space to uncharge
+ *
+ * The owner refs are not touched; drop them with __mem_cgroup_swap_put().
  */
-void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
+void __mem_cgroup_swap_uncharge(unsigned short id, unsigned int nr_pages)
 {
 	struct obj_cgroup *objcg;
 	struct mem_cgroup *memcg;
@@ -6143,11 +6180,33 @@ void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
 				page_counter_uncharge(&memcg->swap, nr_pages);
 		}
 		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
-		__mem_cgroup_private_id_put(objcg, id, nr_pages);
 	}
 	rcu_read_unlock();
 }
 
+/**
+ * __mem_cgroup_swap_put - drop the private ID refs taken for swap slots
+ * @id: the ID taken by __mem_cgroup_swap_get()
+ * @nr_pages: number of refs to drop
+ *
+ * A separate step from __mem_cgroup_swap_uncharge(): a slot's owner is held
+ * from the allocation and released when the slot is freed, while the
+ * counter is charged and uncharged whenever the physical backing comes and
+ * goes.
+ */
+void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages)
+{
+	/*
+	 * The refs are the thing being dropped, so an ID that no longer
+	 * resolves has none left and there is nothing to do.
+	 * mem_cgroup_private_id_put() would dereference the NULL instead.
+	 */
+	rcu_read_lock();
+	if (obj_cgroup_from_private_id(id))
+		mem_cgroup_private_id_put(id, nr_pages);
+	rcu_read_unlock();
+}
+
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg)
 {
 	long nr_swap_pages = get_nr_swap_pages();
@@ -6344,8 +6403,10 @@ static struct cftype swap_files[] = {
 
 #ifdef CONFIG_ZSWAP
 /**
- * obj_cgroup_may_zswap - check if this cgroup can zswap
- * @objcg: the object cgroup
+ * mem_cgroup_may_zswap - check if this cgroup can zswap
+ * @memcg: the memcg to query
+ * @may_flush: force-flush stats for an accurate check (sleeps). Pass false
+ *             from atomic contexts; the check is then best-effort.
  *
  * Check if the hierarchical zswap limit has been reached.
  *
@@ -6355,36 +6416,38 @@ static struct cftype swap_files[] = {
  * spending cycles on compression when there is already no room left
  * or zswap is disabled altogether somewhere in the hierarchy.
  */
-bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
+bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
 {
-	struct mem_cgroup *memcg, *original_memcg;
-	bool ret = true;
-
 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
 		return true;
 
-	original_memcg = get_mem_cgroup_from_objcg(objcg);
-	for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
-	     memcg = parent_mem_cgroup(memcg)) {
+	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
 		unsigned long max = READ_ONCE(memcg->zswap_max);
 		unsigned long pages;
 
 		if (max == PAGE_COUNTER_MAX)
 			continue;
-		if (max == 0) {
-			ret = false;
-			break;
-		}
+		if (max == 0)
+			return false;
 
 		/* Force flush to get accurate stats for charging */
-		__mem_cgroup_flush_stats(memcg, true);
+		if (may_flush)
+			__mem_cgroup_flush_stats(memcg, true);
 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
-		if (pages < max)
-			continue;
-		ret = false;
-		break;
+		if (pages >= max)
+			return false;
 	}
-	mem_cgroup_put(original_memcg);
+	return true;
+}
+
+bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
+{
+	struct mem_cgroup *memcg;
+	bool ret;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	ret = mem_cgroup_may_zswap(memcg, true);
+	mem_cgroup_put(memcg);
 	return ret;
 }
 
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 463f53286a05..3ac91e88c24d 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2164,6 +2164,8 @@ int folio_alloc_swap(struct folio *folio, bool may_enter_fs)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
+	unsigned short swap_id = 0;
+	/* True unless the gate below finds an xswap device to route away from. */
 	bool may_zswap = true;
 	bool zswap_checked = false;
 
@@ -2228,10 +2230,17 @@ int folio_alloc_swap(struct folio *folio, bool may_enter_fs)
 		}
 	}
 
-	/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */
-	if (unlikely(mem_cgroup_try_charge_swap(folio))) {
-		swap_cache_del_folio(folio);
-		goto failed;
+	/*
+	 * Need to call this even if allocation failed, for MEMCG_SWAP_FAIL.
+	 * The owner is taken here, then charged and recorded.
+	 */
+	if (mem_cgroup_swap_get(folio, &swap_id)) {
+		if (unlikely(mem_cgroup_swap_charge(swap_id, size))) {
+			mem_cgroup_swap_put(swap_id, size);
+			swap_cache_del_folio(folio);
+			goto failed;
+		}
+		mem_cgroup_swap_record(folio, swap_id);
 	}
 
 	if (unlikely(!folio_test_swapcache(folio)))
@@ -2398,6 +2407,13 @@ struct swap_info_struct *get_swap_device(swp_entry_t entry)
 	return ERR_PTR(-EIO);
 }
 
+/* Uncharge a batch of freed swap slots and drop their owner refs. */
+static void memcg_swap_free(unsigned short id, unsigned int nr)
+{
+	mem_cgroup_swap_uncharge(id, nr);
+	mem_cgroup_swap_put(id, nr);
+}
+
 /*
  * Free a set of swap slots after their swap count dropped to zero, or will be
  * zero after putting the last ref (saves one __swap_cluster_put_entry call).
@@ -2442,14 +2458,14 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 		id_cur = __swap_cgroup_clear(ci, ci_off, 1);
 		if (batch_id != id_cur) {
 			if (batch_id)
-				mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
+				memcg_swap_free(batch_id, ci_off - batch_off);
 			batch_id = id_cur;
 			batch_off = ci_off;
 		}
 	} while (++ci_off < ci_end);
 
 	if (batch_id)
-		mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
+		memcg_swap_free(batch_id, ci_off - batch_off);
 
 	swap_range_free(si, ci_head + ci_start, nr_pages);
 	swap_cluster_assert_empty(ci, ci_start, nr_pages, false);
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 19/32] mm, swap: do not charge zswap-backed xswap entries
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (17 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 18/32] mm, swap: split the swap memcg charge helpers Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 20/32] mm, swap: charge an xswap entry when it gets physical backing Baoquan He
                   ` (12 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Nhat Pham <nphamcs@gmail.com>

An xswap entry occupies no physical swap space: its data lives in zswap
until a backend is taken.  It was nevertheless charged against
memcg->swap at allocation, as if it did.

Record the memcg at allocation but do not charge.  The charge is taken
when the entry acquires physical backing, and released with it.

memory.swap.current therefore counts only on-disk swap usage, not
zswap-backed xswap entries.  A cgroup can reclaim its anon memory with
memory.swap.max set to 0, provided zswap is allowed for it.

Suggested-by: Johannes Weiner <hannes@cmpxchg.org>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 3ac91e88c24d..313aa2af0b73 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2235,7 +2235,12 @@ int folio_alloc_swap(struct folio *folio, bool may_enter_fs)
 	 * The owner is taken here, then charged and recorded.
 	 */
 	if (mem_cgroup_swap_get(folio, &swap_id)) {
-		if (unlikely(mem_cgroup_swap_charge(swap_id, size))) {
+		/*
+		 * An xswap entry has no physical swap yet, so only record the
+		 * owner here.  Its backing is charged when one is taken.
+		 */
+		if (!(__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP) &&
+		    unlikely(mem_cgroup_swap_charge(swap_id, size))) {
 			mem_cgroup_swap_put(swap_id, size);
 			swap_cache_del_folio(folio);
 			goto failed;
@@ -2407,10 +2412,15 @@ struct swap_info_struct *get_swap_device(swp_entry_t entry)
 	return ERR_PTR(-EIO);
 }
 
-/* Uncharge a batch of freed swap slots and drop their owner refs. */
-static void memcg_swap_free(unsigned short id, unsigned int nr)
+/*
+ * An xswap entry was not charged at allocation, so there is nothing to
+ * uncharge here and only the owner refs go.  Its backing, if any, was
+ * uncharged when it was released.
+ */
+static void memcg_swap_free(unsigned short id, unsigned int nr, bool is_xswap)
 {
-	mem_cgroup_swap_uncharge(id, nr);
+	if (!is_xswap)
+		mem_cgroup_swap_uncharge(id, nr);
 	mem_cgroup_swap_put(id, nr);
 }
 
@@ -2427,6 +2437,7 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 	unsigned int ci_off = ci_start, ci_end = ci_start + nr_pages;
 	unsigned long ci_head = cluster_offset(si, ci);
 	unsigned int batch_off = ci_off;
+	bool is_xswap = si->flags & SWP_XSWAP;
 
 	VM_WARN_ON(ci->count < nr_pages);
 
@@ -2458,14 +2469,14 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 		id_cur = __swap_cgroup_clear(ci, ci_off, 1);
 		if (batch_id != id_cur) {
 			if (batch_id)
-				memcg_swap_free(batch_id, ci_off - batch_off);
+				memcg_swap_free(batch_id, ci_off - batch_off, is_xswap);
 			batch_id = id_cur;
 			batch_off = ci_off;
 		}
 	} while (++ci_off < ci_end);
 
 	if (batch_id)
-		memcg_swap_free(batch_id, ci_off - batch_off);
+		memcg_swap_free(batch_id, ci_off - batch_off, is_xswap);
 
 	swap_range_free(si, ci_head + ci_start, nr_pages);
 	swap_cluster_assert_empty(ci, ci_start, nr_pages, false);
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 20/32] mm, swap: charge an xswap entry when it gets physical backing
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (18 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 19/32] mm, swap: do not charge zswap-backed xswap entries Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 21/32] mm, swap: don't gate xswap on the physical swap free count Baoquan He
                   ` (11 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Nhat Pham <nphamcs@gmail.com>

An xswap entry is recorded but not charged at allocation.  Charge
memcg->swap when the entry takes a physical backend slot, in
xswap_backend_alloc(), and uncharge it when the backend is released.

memory.swap.current therefore still counts the pages that do reach the
disk, and memory.swap.max is still enforced on them.

Suggested-by: Johannes Weiner <hannes@cmpxchg.org>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 57 +++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 55 insertions(+), 2 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 313aa2af0b73..02724de7811a 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -103,6 +103,11 @@ static void xswap_clear_cache_only(struct swap_info_struct *si,
 				   unsigned int start, unsigned int nr);
 static int xswap_reclaim_backing(struct swap_info_struct *si,
 				 unsigned long offset, swp_entry_t xentry);
+static unsigned short xswap_entry_id(struct swap_cluster_info *ci,
+				     unsigned long off);
+static void xswap_backend_uncharge(swp_entry_t entry, unsigned int nr);
+static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
+				   unsigned int order);
 
 static int xswap_create(int prio);
 static int xswap_create_by_name(const char *name, int swap_flags);
@@ -3439,6 +3444,8 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 	psi = swap_type_to_info(swp_type(phys));
 	if (psi)
 		xswap_free_phys_slot(psi, entry, phys);
+
+	xswap_backend_uncharge(entry, 1);
 }
 
 /*
@@ -4896,6 +4903,7 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 	struct swap_cluster_info *ci;
 	unsigned long nr = 1UL << order;
 	unsigned long off = swp_offset(entry);
+	unsigned short id = 0;
 	swp_entry_t phys;
 	unsigned int i;
 
@@ -4927,7 +4935,21 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 	 * The slot is a shadow until the reverse map is installed below.
 	 * Physical swapoff can see it and retry; the window is short and
 	 * try_to_unuse() reschedules.
+	 *
+	 * The xswap entry was only recorded at allocation, so charge the
+	 * physical swap here.  On failure, drop the physical slot range without
+	 * uncharging it.
 	 */
+	ci = swap_cluster_lock(si, off);
+	if (ci) {
+		id = xswap_entry_id(ci, off);
+		swap_cluster_unlock(ci);
+	}
+	if (mem_cgroup_swap_charge(id, nr)) {
+		__xswap_backend_unlink(entry, phys, order);
+		return (swp_entry_t){};
+	}
+
 	/* One IO reads a large folio, so its range has to be contiguous. */
 	VM_WARN_ON_ONCE(swp_offset(phys) % nr);
 	VM_WARN_ON_ONCE(off % SWAPFILE_CLUSTER + nr > SWAPFILE_CLUSTER);
@@ -4957,8 +4979,32 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 	return phys;
 }
 
-/* Undo xswap_backend_alloc(): the zswap copy is still in place. */
-void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order)
+/* The ID that owns an xswap entry, or 0 if it has no owner recorded. */
+static unsigned short xswap_entry_id(struct swap_cluster_info *ci,
+				     unsigned long off)
+{
+	return __swap_cgroup_get(ci, off % SWAPFILE_CLUSTER);
+}
+
+static void xswap_backend_uncharge(swp_entry_t entry, unsigned int nr)
+{
+	struct swap_info_struct *si = __swap_entry_to_info(entry);
+	struct swap_cluster_info *ci;
+	unsigned long off = swp_offset(entry);
+	unsigned short id = 0;
+
+	ci = swap_cluster_lock(si, off);
+	if (ci) {
+		id = xswap_entry_id(ci, off);
+		swap_cluster_unlock(ci);
+	}
+	if (id)
+		mem_cgroup_swap_uncharge(id, nr);
+}
+
+/* Drop the physical slot range and the reverse mapping, without any charging. */
+static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
+				   unsigned int order)
 {
 	struct swap_info_struct *si = __swap_entry_to_info(entry);
 	struct swap_info_struct *psi = swap_type_to_info(swp_type(phys));
@@ -4987,6 +5033,13 @@ void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order)
 	}
 }
 
+/* Undo xswap_backend_alloc(): the zswap copy is still in place. */
+void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order)
+{
+	__xswap_backend_unlink(entry, phys, order);
+	xswap_backend_uncharge(entry, 1UL << order);
+}
+
 static int xswap_map_clusters(struct swap_info_struct *si,
 			      unsigned long start_idx, unsigned long nr,
 			      bool link_free)
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 21/32] mm, swap: don't gate xswap on the physical swap free count
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (19 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 20/32] mm, swap: charge an xswap entry when it gets physical backing Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 22/32] mm, swap: do not retake the cluster lock when uncharging an xswap slot Baoquan He
                   ` (10 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Nhat Pham <nphamcs@gmail.com>

An xswap entry is charged only when it gets physical backing, so a
zswap-capable memcg can keep swapping out through xswap even when its
physical swap margin is zero.  mem_cgroup_get_nr_swap_pages() would
otherwise starve anon reclaim with memory.swap.max set to 0.

Return PAGE_COUNTER_MAX when an xswap device is active, zswap is on,
and the memcg allows zswap.  Track active xswap devices in nr_xswap_files,
mirroring nr_real_swapfiles.

Suggested-by: Johannes Weiner <hannes@cmpxchg.org>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/memcontrol.h |  4 ++--
 include/linux/swap.h       |  6 ++++++
 mm/memcontrol.c            | 31 ++++++++++++++++++++++++-------
 mm/swapfile.c              |  2 +-
 4 files changed, 33 insertions(+), 10 deletions(-)

diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index aaa7a035007f..0f320fec0b88 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -1968,7 +1968,7 @@ static inline void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_ZSWAP)
 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg);
-bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush);
+bool mem_cgroup_may_zswap(const struct mem_cgroup *memcg, bool may_flush);
 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size);
 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size);
 bool mem_cgroup_zswap_writeback_enabled(const struct mem_cgroup *memcg);
@@ -1978,7 +1978,7 @@ static inline bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
 	return true;
 }
 
-static inline bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
+static inline bool mem_cgroup_may_zswap(const struct mem_cgroup *memcg, bool may_flush)
 {
 	return true;
 }
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 8c1131d924ae..43c2e258a5df 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -387,6 +387,12 @@ void free_pages_and_swap_cache(struct encoded_page **, int);
 /* linux/mm/swapfile.c */
 extern atomic_long_t nr_swap_pages;
 extern atomic_t nr_real_swapfiles;
+extern atomic_t nr_xswap_files;
+
+static inline bool xswap_enabled(void)
+{
+	return atomic_read(&nr_xswap_files) > 0;
+}
 extern long total_swap_pages;
 extern atomic_t nr_rotate_swap;
 
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 0a2ef04e17f5..9091af061ff8 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -6209,8 +6209,20 @@ void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages)
 
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg)
 {
-	long nr_swap_pages = get_nr_swap_pages();
+	long nr_swap_pages;
 
+	/*
+	 * xswap charges physical backing, not allocation, so virtual swap is
+	 * unbounded for a zswap-capable memcg and the swap.max walk below
+	 * would starve anon reclaim.  swap.max is still enforced when the
+	 * backing is charged.
+	 */
+	if (xswap_enabled() && zswap_is_enabled() &&
+	    (mem_cgroup_disabled() || do_memsw_account() ||
+	     mem_cgroup_may_zswap(memcg, false)))
+		return PAGE_COUNTER_MAX;
+
+	nr_swap_pages = get_nr_swap_pages();
 	if (!mem_cgroup_disabled() && !do_memsw_account())
 		nr_swap_pages = min(nr_swap_pages, page_counter_margin(&memcg->swap));
 
@@ -6416,13 +6428,15 @@ static struct cftype swap_files[] = {
  * spending cycles on compression when there is already no room left
  * or zswap is disabled altogether somewhere in the hierarchy.
  */
-bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
+bool mem_cgroup_may_zswap(const struct mem_cgroup *memcg, bool may_flush)
 {
+	const struct mem_cgroup *pos;
+
 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
 		return true;
 
-	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
-		unsigned long max = READ_ONCE(memcg->zswap_max);
+	for (pos = memcg; !mem_cgroup_is_root(pos); pos = parent_mem_cgroup(pos)) {
+		unsigned long max = READ_ONCE(pos->zswap_max);
 		unsigned long pages;
 
 		if (max == PAGE_COUNTER_MAX)
@@ -6430,10 +6444,13 @@ bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
 		if (max == 0)
 			return false;
 
-		/* Force flush to get accurate stats for charging */
+		/*
+		 * Force flush to get accurate stats for charging. The flush
+		 * only reads the counters, but takes the memcg mutable.
+		 */
 		if (may_flush)
-			__mem_cgroup_flush_stats(memcg, true);
-		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
+			__mem_cgroup_flush_stats((struct mem_cgroup *)pos, true);
+		pages = memcg_page_state(pos, MEMCG_ZSWAP_B) / PAGE_SIZE;
 		if (pages >= max)
 			return false;
 	}
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 02724de7811a..f7ffbc659716 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -250,7 +250,7 @@ static unsigned int nr_swapfiles;
 atomic_long_t nr_swap_pages;
 atomic_t nr_real_swapfiles;
 /* Active xswap devices, as in nr_real_swapfiles. */
-static atomic_t nr_xswap_files;
+atomic_t nr_xswap_files;
 /*
  * Some modules use swappable objects and may try to swap them out under
  * memory pressure (via the shrinker). Before doing so, they may wish to
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 22/32] mm, swap: do not retake the cluster lock when uncharging an xswap slot
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (20 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 21/32] mm, swap: don't gate xswap on the physical swap free count Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 23/32] mm, swap: uncharge an xswap backend where its record is cleared Baoquan He
                   ` (9 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

xswap_release_slot_backend() runs with ci->lock held. Its callers free
the slots of a cluster they have locked. It called
xswap_backend_uncharge() to give the swap charge back, and that takes
the same cluster lock again to read the owner out of the swap table.

A spinlock is not recursive, so it spins forever. The swapin path hangs
on it:

  do_swap_page
    folio_free_swap
      swap_cache_del_folio
        __swap_cluster_free_entries
          xswap_release_slot_backend
            xswap_backend_uncharge      <- spins here

Read the owner from ci directly instead. The lock is already held, and
the cgroup id is still in the swap table at this point: the loop clears
it after this call.

xswap_backend_uncharge() stays for xswap_backend_free(), which runs
without the cluster lock.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index f7ffbc659716..baebd30cf889 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -3437,6 +3437,7 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 {
 	swp_entry_t entry = swp_entry(si->type, cluster_offset(si, ci) + slot);
 	struct swap_info_struct *psi;
+	unsigned short id = xswap_entry_id(ci, slot);
 	swp_entry_t phys = { .val = ci->xs_table[slot] };
 
 	WRITE_ONCE(ci->xs_table[slot], 0);
@@ -3445,7 +3446,13 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 	if (psi)
 		xswap_free_phys_slot(psi, entry, phys);
 
-	xswap_backend_uncharge(entry, 1);
+	/*
+	 * ci->lock is held here, so read the owner out of the swap table
+	 * directly. xswap_backend_uncharge() would take the same lock
+	 * again, and a spinlock is not recursive.
+	 */
+	if (id)
+		mem_cgroup_swap_uncharge(id, 1);
 }
 
 /*
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 23/32] mm, swap: uncharge an xswap backend where its record is cleared
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (21 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 22/32] mm, swap: do not retake the cluster lock when uncharging an xswap slot Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 24/32] mm, swap: account xswap backends for cgroup v1 Baoquan He
                   ` (8 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

swapoff of a physical device drops the xswap entries that were written
to it.  The charge taken when the backend was allocated is released by
xswap_release_slot_backend() when the xswap slot itself is freed, or by
xswap_backend_free() when an allocation is rolled back.

The record can be cleared before either runs:

- the swapoff path clears it under the cluster lock, but uncharged
  outside it: a concurrent slot free can uncharge twice, or clear the
  id before the swapoff path reads it;
- xswap_backend_free() clears it through __xswap_backend_unlink(),
  which does nothing when the record no longer matches, but it then
  uncharged unconditionally.

Capture the owner id, clear the record, and uncharge only when the
record still points at this entry, under the same cluster lock.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 56 ++++++++++++++++++++++-----------------------------
 1 file changed, 24 insertions(+), 32 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index baebd30cf889..5de905970668 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -105,7 +105,6 @@ static int xswap_reclaim_backing(struct swap_info_struct *si,
 				 unsigned long offset, swp_entry_t xentry);
 static unsigned short xswap_entry_id(struct swap_cluster_info *ci,
 				     unsigned long off);
-static void xswap_backend_uncharge(swp_entry_t entry, unsigned int nr);
 static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
 				   unsigned int order);
 
@@ -3446,11 +3445,7 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 	if (psi)
 		xswap_free_phys_slot(psi, entry, phys);
 
-	/*
-	 * ci->lock is held here, so read the owner out of the swap table
-	 * directly. xswap_backend_uncharge() would take the same lock
-	 * again, and a spinlock is not recursive.
-	 */
+	/* ci->lock is held here, so read the owner out of the swap table directly. */
 	if (id)
 		mem_cgroup_swap_uncharge(id, 1);
 }
@@ -3683,17 +3678,23 @@ static int xswap_unuse_rmap(struct swap_info_struct *si, unsigned long offset)
 	folio_put(folio);
 
 	/*
-	 * The slot is going away, so drop the record that names it. The
-	 * mapped range cannot shrink while the device is pinned, so @xoff
-	 * still has a cluster here whenever @drop is set.
+	 * Clear the record and uncharge under one lock. A concurrent slot
+	 * free then cannot uncharge twice or clear the id before we read it.
+	 * The mapped range cannot shrink while the device is pinned, so
+	 * @xoff still has a cluster here whenever @drop is set.
 	 */
 	if (drop) {
 		xci = swap_cluster_lock(xsi, xoff);
 		if (xci) {
-			if (xswap_slot_backend(xci, xoff % SWAPFILE_CLUSTER).val ==
-			    phys.val)
-				WRITE_ONCE(xci->xs_table[xoff % SWAPFILE_CLUSTER],
-					   0);
+			unsigned int slot = xoff % SWAPFILE_CLUSTER;
+			unsigned short id;
+
+			if (xswap_slot_backend(xci, slot).val == phys.val) {
+				id = xswap_entry_id(xci, slot);
+				WRITE_ONCE(xci->xs_table[slot], 0);
+				if (id)
+					mem_cgroup_swap_uncharge(id, 1);
+			}
 			swap_cluster_unlock(xci);
 		}
 	}
@@ -4993,23 +4994,10 @@ static unsigned short xswap_entry_id(struct swap_cluster_info *ci,
 	return __swap_cgroup_get(ci, off % SWAPFILE_CLUSTER);
 }
 
-static void xswap_backend_uncharge(swp_entry_t entry, unsigned int nr)
-{
-	struct swap_info_struct *si = __swap_entry_to_info(entry);
-	struct swap_cluster_info *ci;
-	unsigned long off = swp_offset(entry);
-	unsigned short id = 0;
-
-	ci = swap_cluster_lock(si, off);
-	if (ci) {
-		id = xswap_entry_id(ci, off);
-		swap_cluster_unlock(ci);
-	}
-	if (id)
-		mem_cgroup_swap_uncharge(id, nr);
-}
-
-/* Drop the physical slot range and the reverse mapping, without any charging. */
+/*
+ * Drop the physical slot range and the reverse mapping, and uncharge what
+ * we clear.
+ */
 static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
 				   unsigned int order)
 {
@@ -5028,8 +5016,13 @@ static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
 			unsigned int slot = (off + i) % SWAPFILE_CLUSTER;
 			unsigned long *xs = ci->xs_table;
 
-			if (xs && xs[slot] == phys.val + i)
+			if (xs && xs[slot] == phys.val + i) {
+				unsigned short id = xswap_entry_id(ci, slot);
+
 				WRITE_ONCE(xs[slot], 0);
+				if (id)
+					mem_cgroup_swap_uncharge(id, 1);
+			}
 			swap_cluster_unlock(ci);
 		}
 
@@ -5044,7 +5037,6 @@ static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
 void xswap_backend_free(swp_entry_t entry, swp_entry_t phys, unsigned int order)
 {
 	__xswap_backend_unlink(entry, phys, order);
-	xswap_backend_uncharge(entry, 1UL << order);
 }
 
 static int xswap_map_clusters(struct swap_info_struct *si,
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 24/32] mm, swap: account xswap backends for cgroup v1
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (22 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 23/32] mm, swap: uncharge an xswap backend where its record is cleared Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 25/32] mm, swap: drop a refused xswap backend slot range directly Baoquan He
                   ` (7 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

Cgroup v1 keeps the memsw charge on the swap slot, while v2 charges the
physical backing.  xswap uncharges the backing in several paths, so it
must not touch memsw in v1 mode:

- memcg_swap_free() skipped the uncharge for every xswap slot, so a
  zswap-only xswap slot leaked its memsw charge;
- the physical release paths uncharged memsw early, and swapin or slot
  free then uncharged it again.

Add mem_cgroup_swap_memsw_accounted() so the swap code can tell the two
modes apart.  In v1, leave memsw to the slot free/swapin path; in v2,
keep uncharging the physical backing when it is released.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/swap.h |  6 ++++++
 mm/memcontrol.c      |  6 ++++++
 mm/swapfile.c        | 26 ++++++++++++++------------
 3 files changed, 26 insertions(+), 12 deletions(-)

diff --git a/include/linux/swap.h b/include/linux/swap.h
index 43c2e258a5df..749fbd363eee 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -581,6 +581,7 @@ static inline void mem_cgroup_swap_put(unsigned short id,
 long mem_cgroup_get_folio_swap_margin(const struct folio *folio);
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg);
 bool mem_cgroup_swap_full(const struct folio *folio);
+bool mem_cgroup_swap_memsw_accounted(void);
 #else
 static inline bool mem_cgroup_swap_get(struct folio *folio, unsigned short *id)
 {
@@ -622,6 +623,11 @@ static inline bool mem_cgroup_swap_full(const struct folio *folio)
 {
 	return vm_swap_full();
 }
+
+static inline bool mem_cgroup_swap_memsw_accounted(void)
+{
+	return false;
+}
 #endif
 
 /* for_each_managed_zone_pgdat - helper macro to iterate over all managed zones in a pgdat up to
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 9091af061ff8..583aef97e4d8 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -6207,6 +6207,12 @@ void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages)
 	rcu_read_unlock();
 }
 
+/* Cgroup v1 keeps the swap charge on the slot; v2 keeps it on the backing. */
+bool mem_cgroup_swap_memsw_accounted(void)
+{
+	return do_memsw_account();
+}
+
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg)
 {
 	long nr_swap_pages;
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 5de905970668..d8f09f46123a 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2417,13 +2417,12 @@ struct swap_info_struct *get_swap_device(swp_entry_t entry)
 }
 
 /*
- * An xswap entry was not charged at allocation, so there is nothing to
- * uncharge here and only the owner refs go.  Its backing, if any, was
- * uncharged when it was released.
+ * v2 charges the physical backing, not the xswap slot, so the backing
+ * release uncharged it. v1 keeps the memsw charge on the slot.
  */
 static void memcg_swap_free(unsigned short id, unsigned int nr, bool is_xswap)
 {
-	if (!is_xswap)
+	if (!is_xswap || mem_cgroup_swap_memsw_accounted())
 		mem_cgroup_swap_uncharge(id, nr);
 	mem_cgroup_swap_put(id, nr);
 }
@@ -3445,8 +3444,11 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 	if (psi)
 		xswap_free_phys_slot(psi, entry, phys);
 
-	/* ci->lock is held here, so read the owner out of the swap table directly. */
-	if (id)
+	/*
+	 * ci->lock is held here, so read the owner out of the swap table
+	 * directly. v1 keeps the charge on the slot, so do not uncharge here.
+	 */
+	if (id && !mem_cgroup_swap_memsw_accounted())
 		mem_cgroup_swap_uncharge(id, 1);
 }
 
@@ -3678,10 +3680,10 @@ static int xswap_unuse_rmap(struct swap_info_struct *si, unsigned long offset)
 	folio_put(folio);
 
 	/*
-	 * Clear the record and uncharge under one lock. A concurrent slot
-	 * free then cannot uncharge twice or clear the id before we read it.
-	 * The mapped range cannot shrink while the device is pinned, so
-	 * @xoff still has a cluster here whenever @drop is set.
+	 * Clear the record and uncharge (v2) under one lock. A concurrent
+	 * slot free then cannot uncharge twice or clear the id before we
+	 * read it. The mapped range cannot shrink while the device is
+	 * pinned, so @xoff still has a cluster here whenever @drop is set.
 	 */
 	if (drop) {
 		xci = swap_cluster_lock(xsi, xoff);
@@ -3692,7 +3694,7 @@ static int xswap_unuse_rmap(struct swap_info_struct *si, unsigned long offset)
 			if (xswap_slot_backend(xci, slot).val == phys.val) {
 				id = xswap_entry_id(xci, slot);
 				WRITE_ONCE(xci->xs_table[slot], 0);
-				if (id)
+				if (id && !mem_cgroup_swap_memsw_accounted())
 					mem_cgroup_swap_uncharge(id, 1);
 			}
 			swap_cluster_unlock(xci);
@@ -5020,7 +5022,7 @@ static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
 				unsigned short id = xswap_entry_id(ci, slot);
 
 				WRITE_ONCE(xs[slot], 0);
-				if (id)
+				if (id && !mem_cgroup_swap_memsw_accounted())
 					mem_cgroup_swap_uncharge(id, 1);
 			}
 			swap_cluster_unlock(ci);
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 25/32] mm, swap: drop a refused xswap backend slot range directly
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (23 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 24/32] mm, swap: account xswap backends for cgroup v1 Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 26/32] mm, swap: route xswap by the zswap eligibility without flushing Baoquan He
                   ` (6 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

On a refused charge, xswap_backend_alloc() gave the physical slot range back
with __xswap_backend_unlink(), which finds the slot range through the reverse
mapping. That mapping is not installed yet at this point, so it
recognised nothing and freed nothing: every refused charge leaked the slot range and tripped a VM_WARN_ON_ONCE().

Drop the slot range directly instead; the caller holds it and nothing points
at it yet.  Free the range while the cluster is still locked and before
free_cluster() can hand it to another user, so the invalidate hooks
cannot run against a new owner's table.

Seen with a cgroup at memory.swap.max: the backend held 48663 pages
while memory.swap.current was 0.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 40 +++++++++++++++++++++++++++++++++++++++-
 1 file changed, 39 insertions(+), 1 deletion(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index d8f09f46123a..c6df87019df0 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -3424,6 +3424,44 @@ static void xswap_free_phys_slot(struct swap_info_struct *si,
 	put_swap_device(si);
 }
 
+/*
+ * Give a backend slot range back. Nothing points at them yet, so there is
+ * no reverse mapping to look up and no record to clear.
+ */
+static void xswap_drop_phys_slots(swp_entry_t phys, unsigned int nr)
+{
+	struct swap_info_struct *psi = swap_type_to_info(swp_type(phys));
+	unsigned long poff = swp_offset(phys);
+	struct swap_cluster_info *pci;
+	unsigned int i;
+
+	if (!psi)
+		return;
+
+	pci = swap_cluster_lock(psi, poff);
+	if (!pci)
+		return;
+
+	VM_WARN_ON(pci->count < nr);
+	pci->count -= nr;
+	for (i = 0; i < nr; i++)
+		__swap_table_set(pci, (poff + i) % SWAPFILE_CLUSTER,
+				 null_to_swp_tb());
+
+	/*
+	 * The slot must not be allocatable before its invalidate hooks run:
+	 * free_cluster() can hand the cluster to another user, and the
+	 * invalidate would then walk that user's backend.
+	 */
+	swap_range_free(psi, poff, nr);
+
+	if (!pci->count)
+		free_cluster(psi, pci);
+	else
+		partial_free_cluster(psi, pci);
+	swap_cluster_unlock(pci);
+}
+
 /*
  * An xswap slot being freed may still own a physical slot. Drop it, or the
  * physical space and its reverse mapping leak. Caller holds the xswap
@@ -4956,7 +4994,7 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 		swap_cluster_unlock(ci);
 	}
 	if (mem_cgroup_swap_charge(id, nr)) {
-		__xswap_backend_unlink(entry, phys, order);
+		xswap_drop_phys_slots(phys, nr);
 		return (swp_entry_t){};
 	}
 
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 26/32] mm, swap: route xswap by the zswap eligibility without flushing
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (24 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 25/32] mm, swap: drop a refused xswap backend slot range directly Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 27/32] mm, swap: keep a per-cluster backend record for every swap device Baoquan He
                   ` (5 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

The xswap routing check calls obj_cgroup_may_zswap(), which walks the
memcg hierarchy and flushes the stats of every ancestor with a zswap
limit, to read how full it is. The check only picks the device: a page
zswap refuses falls back to a physical backend.

Use mem_cgroup_may_zswap() with may_flush set to false, which the charge
helper split added, and keep the rstat lock out of the swapout path.  A
stale "full" cannot be ignored, though: without a physical backend, the
folio would be routed away from the only xswap device and the allocation
would fail.  Flush and check again when the lockless check says there is
no room.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index c6df87019df0..2bd573b159ee 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2126,10 +2126,22 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 static bool folio_may_zswap(struct folio *folio)
 {
 	struct obj_cgroup *objcg = get_obj_cgroup_from_folio(folio);
-	bool may_zswap = !objcg || obj_cgroup_may_zswap(objcg);
+	struct mem_cgroup *memcg;
+	bool may_zswap = true;
 
-	if (objcg)
+	if (objcg) {
+		memcg = get_mem_cgroup_from_objcg(objcg);
+		/*
+		 * The lockless check reads a stale snapshot. If it says
+		 * full, flush and look again: a false negative would route
+		 * the folio away from the only xswap device and fail the
+		 * allocation.
+		 */
+		may_zswap = mem_cgroup_may_zswap(memcg, false) ||
+			    mem_cgroup_may_zswap(memcg, true);
+		mem_cgroup_put(memcg);
 		obj_cgroup_put(objcg);
+	}
 	return may_zswap;
 }
 
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 27/32] mm, swap: keep a per-cluster backend record for every swap device
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (25 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 26/32] mm, swap: route xswap by the zswap eligibility without flushing Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 28/32] mm, swap: encode the per-slot backend record Baoquan He
                   ` (4 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

xswap keeps an xs_table per cluster to record the physical slot backing
each xswap slot.  Give every swap device that table instead, renamed to
backend_table, so a future user does not need a second per-cluster
array.  The table is allocated on demand and freed with the cluster in
__free_cluster() and at teardown; a device that never records a backend
pays only the pointer.

At teardown, give the backend records back before the swap table that
holds the owner id.  Allocate the table without entering direct reclaim:
the caller's folio is locked, and reclaim could wait for it.

Only xswap uses the table for now, so this is a no-op.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swap.h     |   4 +-
 mm/swapfile.c | 112 ++++++++++++++++++++++++++++----------------------
 2 files changed, 63 insertions(+), 53 deletions(-)

diff --git a/mm/swap.h b/mm/swap.h
index 2cd87a26843a..cdb82504269b 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -58,9 +58,7 @@ struct swap_cluster_info {
 	u8 order;
 	atomic_long_t __rcu *table;	/* Swap table entries, see mm/swap_table.h */
 	unsigned int *extend_table;	/* For large swap count, protected by ci->lock */
-#ifdef CONFIG_XSWAP
-	unsigned long *xs_table;	/* Physical backend per slot, lazily allocated */
-#endif
+	unsigned long *backend_table;
 #ifdef CONFIG_MEMCG
 	struct swap_memcg_table *memcg_table;	/* Swap table entries' cgroup record */
 #endif
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 2bd573b159ee..4bf4d4d3f597 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -63,6 +63,9 @@
 /* File-less, so /proc/swaps shows this name; swapoff -a passes it back. */
 #define XSWAP_NAME	"xswap"
 
+static void swap_backend_table_free(struct swap_info_struct *si,
+				    struct swap_cluster_info *ci);
+
 #ifdef CONFIG_XSWAP
 /*
  * Clusters mapped per grow: one page worth of cluster_info, so the
@@ -93,8 +96,6 @@ static void xswap_free_phys_slot(struct swap_info_struct *si,
 static void xswap_release_slot_backend(struct swap_info_struct *si,
 				       struct swap_cluster_info *ci,
 				       unsigned int slot);
-static void xswap_free_xs_table(struct swap_info_struct *si,
-				struct swap_cluster_info *ci);
 static void xswap_mark_cache_only(struct swap_info_struct *si,
 				  struct swap_cluster_info *ci,
 				  unsigned int slot);
@@ -834,14 +835,11 @@ static void swap_cluster_schedule_discard(struct swap_info_struct *si,
 static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci)
 {
 	swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, false);
-#ifdef CONFIG_XSWAP
 	/*
 	 * An empty cluster can still hold records. Give them back first:
 	 * swap_cluster_free_table() frees the table the owner ID comes from.
 	 */
-	if (si->flags & SWP_XSWAP)
-		xswap_free_xs_table(si, ci);
-#endif
+	swap_backend_table_free(si, ci);
 	swap_cluster_free_table(ci);
 	move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
 	ci->order = 0;
@@ -2000,7 +1998,7 @@ static void swap_put_entries_cluster(struct swap_info_struct *si,
 			/* count will be 0 after put, slot can be reclaimed */
 			need_reclaim = true;
 #ifdef CONFIG_XSWAP
-			if (ci->xs_table)
+			if (ci->backend_table)
 				xswap_mark_cache_only(si, ci, ci_off);
 #endif
 		}
@@ -2110,7 +2108,7 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 		}
 	} while (++ci_off < ci_end);
 #ifdef CONFIG_XSWAP
-	if (ci->xs_table)
+	if (ci->backend_table)
 		xswap_clear_cache_only(si, ci, ci_start, nr);
 #endif
 	swap_cluster_unlock(ci);
@@ -2468,7 +2466,7 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 			   (!swp_tb_is_shadow(old_tb) || __swp_tb_get_count(old_tb) > 1));
 
 #ifdef CONFIG_XSWAP
-		if (ci->xs_table && ci->xs_table[ci_off])
+		if (ci->backend_table && ci->backend_table[ci_off])
 			xswap_release_slot_backend(si, ci, ci_off);
 #endif
 
@@ -3486,9 +3484,9 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 	swp_entry_t entry = swp_entry(si->type, cluster_offset(si, ci) + slot);
 	struct swap_info_struct *psi;
 	unsigned short id = xswap_entry_id(ci, slot);
-	swp_entry_t phys = { .val = ci->xs_table[slot] };
+	swp_entry_t phys = { .val = ci->backend_table[slot] };
 
-	WRITE_ONCE(ci->xs_table[slot], 0);
+	WRITE_ONCE(ci->backend_table[slot], 0);
 
 	psi = swap_type_to_info(swp_type(phys));
 	if (psi)
@@ -3517,7 +3515,7 @@ static void xswap_mark_cache_only(struct swap_info_struct *si,
 {
 	struct swap_cluster_info *pci;
 	swp_entry_t xentry = swp_entry(si->type, cluster_offset(si, ci) + slot);
-	swp_entry_t phys = { .val = READ_ONCE(ci->xs_table[slot]) };
+	swp_entry_t phys = { .val = READ_ONCE(ci->backend_table[slot]) };
 	unsigned long swp_tb;
 
 	if (!phys.val)
@@ -3551,7 +3549,7 @@ static void xswap_clear_cache_only(struct swap_info_struct *si,
 		xswp_tb = __swap_table_get(ci, slot);
 		if (!swp_tb_is_folio(xswp_tb) || swp_tb_get_count(xswp_tb) != 1)
 			continue;
-		phys.val = READ_ONCE(ci->xs_table[slot]);
+		phys.val = READ_ONCE(ci->backend_table[slot]);
 		if (!phys.val)
 			continue;
 		pci = __swap_entry_to_cluster(phys);
@@ -3743,7 +3741,7 @@ static int xswap_unuse_rmap(struct swap_info_struct *si, unsigned long offset)
 
 			if (xswap_slot_backend(xci, slot).val == phys.val) {
 				id = xswap_entry_id(xci, slot);
-				WRITE_ONCE(xci->xs_table[slot], 0);
+				WRITE_ONCE(xci->backend_table[slot], 0);
 				if (id && !mem_cgroup_swap_memsw_accounted())
 					mem_cgroup_swap_uncharge(id, 1);
 			}
@@ -4113,7 +4111,7 @@ static void free_swap_cluster_info(struct swap_info_struct *si)
 		for (i = 0; i < nr_mapped; i++) {
 			ci = &cluster_info[i];
 			spin_lock(&ci->lock);
-			xswap_free_xs_table(si, ci);
+			swap_backend_table_free(si, ci);
 			if (cluster_table_is_alloced(ci)) {
 				swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);
 				swap_cluster_free_table(ci);
@@ -4134,6 +4132,7 @@ static void free_swap_cluster_info(struct swap_info_struct *si)
 		ci = cluster_info + i;
 		/* Cluster with bad marks count will have a remaining table */
 		spin_lock(&ci->lock);
+		swap_backend_table_free(si, ci);
 		if (cluster_table_is_alloced(ci)) {
 			swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);
 			swap_cluster_free_table(ci);
@@ -4686,6 +4685,35 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 	return maxpages;
 }
 
+/*
+ * Drop the table of a cluster that is going away. A recorded backend is
+ * given back first, or its physical slot and reverse mapping would leak.
+ * Caller holds ci->lock.
+ */
+static void swap_backend_table_free(struct swap_info_struct *si,
+				    struct swap_cluster_info *ci)
+{
+	unsigned long *tbl = ci->backend_table;
+	unsigned int slot;
+
+	if (!tbl)
+		return;
+
+	for (slot = 0; slot < SWAPFILE_CLUSTER; slot++) {
+		unsigned long val = READ_ONCE(tbl[slot]);
+
+#ifdef CONFIG_XSWAP
+		if (val)
+			xswap_release_slot_backend(si, ci, slot);
+#else
+		VM_WARN_ON_ONCE(val);
+#endif
+	}
+
+	WRITE_ONCE(ci->backend_table, NULL);
+	kfree(tbl);
+}
+
 #ifdef CONFIG_XSWAP
 /*
  * Link the new clusters and publish the larger range in one si->lock
@@ -4720,7 +4748,7 @@ static void xswap_publish_clusters(struct swap_info_struct *si,
 /* The physical slot backing @slot, or zero. */
 swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot)
 {
-	unsigned long *xs = READ_ONCE(ci->xs_table);
+	unsigned long *xs = READ_ONCE(ci->backend_table);
 
 	if (!xs || !xs[slot])
 		return (swp_entry_t){};
@@ -4746,12 +4774,12 @@ int xswap_check_backing(struct swap_cluster_info *ci, unsigned int off,
 	}
 
 	/* In zswap, which cannot load a large folio. */
-	if (!ci->xs_table || !ci->xs_table[off])
+	if (!ci->backend_table || !ci->backend_table[off])
 		return 1;
 
-	first.val = ci->xs_table[off];
+	first.val = ci->backend_table[off];
 	for (i = 1; i < nr; i++) {
-		swp_entry_t cur = { .val = ci->xs_table[off + i] };
+		swp_entry_t cur = { .val = ci->backend_table[off + i] };
 
 		if (swp_type(cur) != swp_type(first) ||
 		    swp_offset(cur) != swp_offset(first) + i)
@@ -4762,18 +4790,26 @@ int xswap_check_backing(struct swap_cluster_info *ci, unsigned int off,
 }
 
 /* Cluster lock held. The mapped prefix only grows while the device exists. */
-static unsigned long *xswap_xs_table_locked(struct swap_cluster_info *ci,
+static unsigned long *xswap_backend_table_locked(struct swap_cluster_info *ci,
 					    gfp_t gfp)
 {
-	unsigned long *xs = ci->xs_table;
+	unsigned long *xs = ci->backend_table;
 
 	if (xs)
 		return xs;
 
 	/* The owning entry is pinned, so the cluster survives the relock. */
 	if (gfp & __GFP_DIRECT_RECLAIM) {
+		unsigned int noreclaim_flags;
+
 		spin_unlock(&ci->lock);
+		/*
+		 * The folio being stored is locked.  Do not recurse into
+		 * reclaim, which could wait for that folio.
+		 */
+		noreclaim_flags = memalloc_noreclaim_save();
 		xs = kcalloc(SWAPFILE_CLUSTER, sizeof(*xs), gfp);
+		memalloc_noreclaim_restore(noreclaim_flags);
 		spin_lock(&ci->lock);
 	} else {
 		xs = kcalloc(SWAPFILE_CLUSTER, sizeof(*xs), gfp);
@@ -4781,9 +4817,9 @@ static unsigned long *xswap_xs_table_locked(struct swap_cluster_info *ci,
 
 	if (!xs)
 		return NULL;
-	if (cmpxchg(&ci->xs_table, NULL, xs)) {
+	if (cmpxchg(&ci->backend_table, NULL, xs)) {
 		kfree(xs);
-		xs = ci->xs_table;
+		xs = ci->backend_table;
 	}
 	return xs;
 }
@@ -4794,7 +4830,7 @@ static unsigned long *xswap_xs_table_locked(struct swap_cluster_info *ci,
 static bool xswap_slot_set_backend(struct swap_cluster_info *ci,
 				   unsigned int slot, swp_entry_t phys)
 {
-	unsigned long *xs = xswap_xs_table_locked(ci, GFP_KERNEL | __GFP_HIGH |
+	unsigned long *xs = xswap_backend_table_locked(ci, GFP_KERNEL | __GFP_HIGH |
 						  __GFP_NOMEMALLOC);
 
 	if (!xs)
@@ -4803,30 +4839,6 @@ static bool xswap_slot_set_backend(struct swap_cluster_info *ci,
 	return true;
 }
 
-/*
- * Drop the table of cluster @idx and every backend it still records. The
- * cluster is going away, so nothing else will: the physical slots would stay
- * allocated and their reverse mappings would keep pointing at an xswap entry
- * whose cluster_info is about to be unmapped. Caller holds ci->lock.
- */
-static void xswap_free_xs_table(struct swap_info_struct *si,
-				struct swap_cluster_info *ci)
-{
-	unsigned long *xs = ci->xs_table;
-	unsigned int slot;
-
-	if (!xs)
-		return;
-
-	for (slot = 0; slot < SWAPFILE_CLUSTER; slot++) {
-		if (xs[slot])
-			xswap_release_slot_backend(si, ci, slot);
-	}
-
-	kfree(xs);
-	ci->xs_table = NULL;
-}
-
 /* A range of 1 << @order slots, no folio attached. */
 static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si,
 					    unsigned int order)
@@ -4981,7 +4993,7 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 	ci = swap_cluster_lock(si, off);
 	if (!ci)
 		return (swp_entry_t){};
-	if (!xswap_xs_table_locked(ci, GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC)) {
+	if (!xswap_backend_table_locked(ci, GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC)) {
 		swap_cluster_unlock(ci);
 		return (swp_entry_t){};
 	}
@@ -5066,7 +5078,7 @@ static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
 		ci = swap_cluster_lock(si, off + i);
 		if (ci) {
 			unsigned int slot = (off + i) % SWAPFILE_CLUSTER;
-			unsigned long *xs = ci->xs_table;
+			unsigned long *xs = ci->backend_table;
 
 			if (xs && xs[slot] == phys.val + i) {
 				unsigned short id = xswap_entry_id(ci, slot);
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 28/32] mm, swap: encode the per-slot backend record
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (26 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 27/32] mm, swap: keep a per-cluster backend record for every swap device Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 29/32] mm, swap: add accessors for the " Baoquan He
                   ` (3 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

A backend record holds either the physical swap entry that backs an
xswap slot, or, once zswap records its entries here, a zswap entry.
Encode the two so they can share a word:

  0          no backend
  entry << 1 physical backend swap entry
  ptr | 1    zswap entry pointer

A zswap entry comes from a slab cache and is aligned to at least
sizeof(void *), so bit 0 is free for the tag.  Tagging it in place
leaves every other bit of the pointer alone, including any PAC/MTE tag,
and works on 32-bit too.  The physical entry is shifted, so it needs
the top bit of the entry clear; swp_entry() leaves it clear.

A word from this table must never be handed to the swp_tb_* helpers; it
is only a swp_entry_t after swap_backend_decode_phys().

Only xswap writes the table today, so this is a no-op.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 94 +++++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 77 insertions(+), 17 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 4bf4d4d3f597..96019307ce75 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -63,6 +63,38 @@
 /* File-less, so /proc/swaps shows this name; swapoff -a passes it back. */
 #define XSWAP_NAME	"xswap"
 
+/*
+ * The backend table holds one word per slot:
+ *
+ *   0          - no backend
+ *   entry << 1 - physical backend swap entry (bit 0 clear)
+ *   ptr | 1    - zswap entry pointer (bit 0 set)
+ *
+ * A zswap entry comes from a slab cache, so it is aligned to at least
+ * sizeof(void *): bit 0 is free for the tag.  Only that bit is touched:
+ * the rest of the pointer, including any PAC/MTE tag, is kept as is.
+ *
+ * This is not the swap table: a word here must never be handed to the
+ * swp_tb_* helpers, and the shifted entry is not a swp_entry_t until it
+ * goes through swap_backend_decode_phys().
+ */
+static inline unsigned long swap_backend_encode_phys(swp_entry_t entry)
+{
+	/* The shift needs the top bit free.  swp_entry() leaves it clear. */
+	VM_WARN_ON_ONCE(entry.val & (1UL << (BITS_PER_LONG - 1)));
+	return entry.val << 1;
+}
+
+static inline swp_entry_t swap_backend_decode_phys(unsigned long val)
+{
+	return (swp_entry_t){ .val = val >> 1 };
+}
+
+static inline bool swap_backend_is_zswap(unsigned long val)
+{
+	return val & 1UL;
+}
+
 static void swap_backend_table_free(struct swap_info_struct *si,
 				    struct swap_cluster_info *ci);
 
@@ -3484,8 +3516,18 @@ static void xswap_release_slot_backend(struct swap_info_struct *si,
 	swp_entry_t entry = swp_entry(si->type, cluster_offset(si, ci) + slot);
 	struct swap_info_struct *psi;
 	unsigned short id = xswap_entry_id(ci, slot);
-	swp_entry_t phys = { .val = ci->backend_table[slot] };
+	unsigned long val = READ_ONCE(ci->backend_table[slot]);
+	swp_entry_t phys;
 
+	/*
+	 * Still in zswap: zswap_invalidate() drops the entry once the slot
+	 * is released, and this pointer must not be taken for a physical
+	 * slot here.
+	 */
+	if (!val || swap_backend_is_zswap(val))
+		return;
+
+	phys = swap_backend_decode_phys(val);
 	WRITE_ONCE(ci->backend_table[slot], 0);
 
 	psi = swap_type_to_info(swp_type(phys));
@@ -3515,11 +3557,13 @@ static void xswap_mark_cache_only(struct swap_info_struct *si,
 {
 	struct swap_cluster_info *pci;
 	swp_entry_t xentry = swp_entry(si->type, cluster_offset(si, ci) + slot);
-	swp_entry_t phys = { .val = READ_ONCE(ci->backend_table[slot]) };
+	unsigned long val = READ_ONCE(ci->backend_table[slot]);
 	unsigned long swp_tb;
+	swp_entry_t phys;
 
-	if (!phys.val)
+	if (!val || swap_backend_is_zswap(val))
 		return;			/* still in zswap, no backend */
+	phys = swap_backend_decode_phys(val);
 	pci = __swap_entry_to_cluster(phys);
 	spin_lock(&pci->lock);
 	swp_tb = __swap_table_get(pci, swp_cluster_offset(phys));
@@ -3543,15 +3587,16 @@ static void xswap_clear_cache_only(struct swap_info_struct *si,
 		struct swap_cluster_info *pci;
 		swp_entry_t xentry = swp_entry(si->type,
 					       cluster_offset(si, ci) + slot);
-		unsigned long xswp_tb, pswp_tb;
+		unsigned long xswp_tb, pswp_tb, val;
 		swp_entry_t phys;
 
 		xswp_tb = __swap_table_get(ci, slot);
 		if (!swp_tb_is_folio(xswp_tb) || swp_tb_get_count(xswp_tb) != 1)
 			continue;
-		phys.val = READ_ONCE(ci->backend_table[slot]);
-		if (!phys.val)
+		val = READ_ONCE(ci->backend_table[slot]);
+		if (!val || swap_backend_is_zswap(val))
 			continue;
+		phys = swap_backend_decode_phys(val);
 		pci = __swap_entry_to_cluster(phys);
 		spin_lock(&pci->lock);
 		pswp_tb = __swap_table_get(pci, swp_cluster_offset(phys));
@@ -4702,8 +4747,9 @@ static void swap_backend_table_free(struct swap_info_struct *si,
 	for (slot = 0; slot < SWAPFILE_CLUSTER; slot++) {
 		unsigned long val = READ_ONCE(tbl[slot]);
 
+		VM_WARN_ON_ONCE(swap_backend_is_zswap(val));
 #ifdef CONFIG_XSWAP
-		if (val)
+		if (val && !swap_backend_is_zswap(val))
 			xswap_release_slot_backend(si, ci, slot);
 #else
 		VM_WARN_ON_ONCE(val);
@@ -4748,12 +4794,17 @@ static void xswap_publish_clusters(struct swap_info_struct *si,
 /* The physical slot backing @slot, or zero. */
 swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot)
 {
-	unsigned long *xs = READ_ONCE(ci->backend_table);
+	unsigned long *tbl = READ_ONCE(ci->backend_table);
+	unsigned long val;
+
+	if (!tbl)
+		return (swp_entry_t){};
 
-	if (!xs || !xs[slot])
+	val = READ_ONCE(tbl[slot]);
+	if (!val || swap_backend_is_zswap(val))
 		return (swp_entry_t){};
 
-	return (swp_entry_t){ .val = xs[slot] };
+	return swap_backend_decode_phys(val);
 }
 
 /*
@@ -4763,6 +4814,7 @@ swp_entry_t xswap_slot_backend(struct swap_cluster_info *ci, unsigned int slot)
 int xswap_check_backing(struct swap_cluster_info *ci, unsigned int off,
 			unsigned int nr)
 {
+	unsigned long val;
 	swp_entry_t first;
 	unsigned int i;
 
@@ -4774,13 +4826,20 @@ int xswap_check_backing(struct swap_cluster_info *ci, unsigned int off,
 	}
 
 	/* In zswap, which cannot load a large folio. */
-	if (!ci->backend_table || !ci->backend_table[off])
+	if (!ci->backend_table)
+		return 1;
+	val = READ_ONCE(ci->backend_table[off]);
+	if (!val || swap_backend_is_zswap(val))
 		return 1;
+	first = swap_backend_decode_phys(val);
 
-	first.val = ci->backend_table[off];
 	for (i = 1; i < nr; i++) {
-		swp_entry_t cur = { .val = ci->backend_table[off + i] };
+		swp_entry_t cur;
 
+		val = READ_ONCE(ci->backend_table[off + i]);
+		if (!val || swap_backend_is_zswap(val))
+			break;
+		cur = swap_backend_decode_phys(val);
 		if (swp_type(cur) != swp_type(first) ||
 		    swp_offset(cur) != swp_offset(first) + i)
 			break;
@@ -4835,7 +4894,7 @@ static bool xswap_slot_set_backend(struct swap_cluster_info *ci,
 
 	if (!xs)
 		return false;
-	WRITE_ONCE(xs[slot], phys.val);
+	WRITE_ONCE(xs[slot], swap_backend_encode_phys(phys));
 	return true;
 }
 
@@ -5078,12 +5137,13 @@ static void __xswap_backend_unlink(swp_entry_t entry, swp_entry_t phys,
 		ci = swap_cluster_lock(si, off + i);
 		if (ci) {
 			unsigned int slot = (off + i) % SWAPFILE_CLUSTER;
-			unsigned long *xs = ci->backend_table;
+			unsigned long *tbl = ci->backend_table;
 
-			if (xs && xs[slot] == phys.val + i) {
+			if (tbl && tbl[slot] == swap_backend_encode_phys(
+					swp_entry(swp_type(phys), poff + i))) {
 				unsigned short id = xswap_entry_id(ci, slot);
 
-				WRITE_ONCE(xs[slot], 0);
+				WRITE_ONCE(tbl[slot], 0);
 				if (id && !mem_cgroup_swap_memsw_accounted())
 					mem_cgroup_swap_uncharge(id, 1);
 			}
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 29/32] mm, swap: add accessors for the backend record
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (27 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 28/32] mm, swap: encode the per-slot backend record Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 30/32] mm, zswap: index entries in the swap device's backend table Baoquan He
                   ` (2 subsequent siblings)
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

Add swap_backend_get(), swap_backend_set(), swap_backend_erase() and
swap_backend_present() to read and update a swap device's per-slot
backend record, plus the zswap entry encoding. The next patch wires
zswap to them.

get, erase and present read without the cluster lock: the table is
allocated before the first record is published and freed only when the
cluster is empty, so an in-use slot can always reach it. Updates are
serialized by the folio lock (store, load, writeback) or the cluster
lock (slot free). Only set takes the cluster lock, only to allocate,
and it avoids direct reclaim because the caller's folio is locked.

present() walks a range within one cluster and returns early without a
table; a range that would cross the cluster is refused after a warning.
Setting the same handle is a no-op; only a different handle is reported
as displaced.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swap.h     |   5 ++
 mm/swapfile.c | 208 +++++++++++++++++++++++++++++++++++++++-----------
 2 files changed, 170 insertions(+), 43 deletions(-)

diff --git a/mm/swap.h b/mm/swap.h
index cdb82504269b..9b2d8d556bd0 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -226,6 +226,11 @@ static inline void swap_cluster_unlock_irq(struct swap_cluster_info *ci)
 
 extern int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp);
 
+void *swap_backend_get(swp_entry_t entry);
+void *swap_backend_set(swp_entry_t entry, void *handle);
+void *swap_backend_erase(swp_entry_t entry);
+bool swap_backend_present(swp_entry_t entry, unsigned int nr);
+
 /*
  * Below are the core routines for doing swap for a folio.
  * All helpers requires the folio to be locked, and a locked folio
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 96019307ce75..1862f0b93c92 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -90,6 +90,19 @@ static inline swp_entry_t swap_backend_decode_phys(unsigned long val)
 	return (swp_entry_t){ .val = val >> 1 };
 }
 
+static inline unsigned long swap_backend_encode_zswap(void *handle)
+{
+	unsigned long val = (unsigned long)handle;
+
+	VM_WARN_ON_ONCE(val & 1UL);
+	return val | 1UL;
+}
+
+static inline void *swap_backend_decode_zswap(unsigned long val)
+{
+	return (void *)(val & ~1UL);
+}
+
 static inline bool swap_backend_is_zswap(unsigned long val)
 {
 	return val & 1UL;
@@ -4731,9 +4744,151 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 }
 
 /*
- * Drop the table of a cluster that is going away. A recorded backend is
- * given back first, or its physical slot and reverse mapping would leak.
- * Caller holds ci->lock.
+ * Per-slot backend record of a cluster, allocated on demand and freed
+ * with the cluster.
+ */
+static unsigned long *swap_backend_table_locked(struct swap_cluster_info *ci,
+						gfp_t gfp)
+{
+	unsigned long *tbl = ci->backend_table;
+
+	if (tbl)
+		return tbl;
+
+	/* The owning entry is pinned, so the cluster survives the relock. */
+	if (gfp & __GFP_DIRECT_RECLAIM) {
+		unsigned int noreclaim_flags;
+
+		spin_unlock(&ci->lock);
+		/*
+		 * The folio being stored is locked.  Do not recurse into
+		 * reclaim, which could wait for that folio.
+		 */
+		noreclaim_flags = memalloc_noreclaim_save();
+		tbl = kcalloc(SWAPFILE_CLUSTER, sizeof(*tbl), gfp);
+		memalloc_noreclaim_restore(noreclaim_flags);
+		spin_lock(&ci->lock);
+	} else {
+		tbl = kcalloc(SWAPFILE_CLUSTER, sizeof(*tbl), gfp);
+	}
+
+	if (!tbl)
+		return NULL;
+	if (cmpxchg(&ci->backend_table, NULL, tbl)) {
+		kfree(tbl);
+		tbl = ci->backend_table;
+	}
+	return tbl;
+}
+
+/*
+ * The zswap side of the table.
+ *
+ * The table pointer and its slots are read without taking the cluster lock:
+ * the table is allocated before the first entry is published and freed only
+ * once the cluster has no in-use slot left, so a caller that holds an
+ * in-use slot can always reach it. Per-slot updates are serialized by the
+ * folio lock (store, load and writeback all run with the folio locked) or
+ * by the cluster lock (the slot free path runs under it). Only set takes
+ * the cluster lock, and only to allocate the table.
+ */
+void *swap_backend_get(swp_entry_t swp)
+{
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(swp);
+	unsigned long *tbl = READ_ONCE(ci->backend_table);
+	unsigned long val;
+
+	if (!tbl)
+		return NULL;
+
+	val = READ_ONCE(tbl[swp_cluster_offset(swp)]);
+	return swap_backend_is_zswap(val) ? swap_backend_decode_zswap(val) : NULL;
+}
+
+/* Is any slot in [swp, swp + nr) in zswap? The range sits in one cluster. */
+bool swap_backend_present(swp_entry_t swp, unsigned int nr)
+{
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(swp);
+	unsigned long *tbl = READ_ONCE(ci->backend_table);
+	unsigned int slot = swp_cluster_offset(swp);
+	unsigned int i;
+
+	/* The range is aligned to its own size and never straddles a cluster. */
+	if (slot + nr > SWAPFILE_CLUSTER) {
+		VM_WARN_ON_ONCE(1);
+		return false;
+	}
+
+	if (!tbl)
+		return false;
+
+	for (i = 0; i < nr; i++) {
+		if (swap_backend_is_zswap(READ_ONCE(tbl[slot + i])))
+			return true;
+	}
+	return false;
+}
+
+void *swap_backend_set(swp_entry_t swp, void *handle)
+{
+	struct swap_info_struct *si = __swap_entry_to_info(swp);
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(swp);
+	unsigned int slot = swp_cluster_offset(swp);
+	unsigned long *tbl, old, encoded;
+
+	tbl = READ_ONCE(ci->backend_table);
+	if (!tbl) {
+		ci = swap_cluster_lock(si, swp_offset(swp));
+		tbl = swap_backend_table_locked(ci, GFP_KERNEL | __GFP_HIGH |
+						__GFP_NOMEMALLOC);
+		swap_cluster_unlock(ci);
+		if (!tbl)
+			return ERR_PTR(-ENOMEM);
+	}
+
+	encoded = swap_backend_encode_zswap(handle);
+	old = READ_ONCE(tbl[slot]);
+	/* Re-setting the same handle is a no-op, not a displaced entry. */
+	if (old == encoded)
+		return NULL;
+
+	/*
+	 * A folio written back and then redirtied while still in the swap
+	 * cache is swapped out again into the same slot. The physical copy
+	 * is stale then, and zswap takes the slot over.
+	 */
+#ifdef CONFIG_XSWAP
+	if (old && !swap_backend_is_zswap(old))
+		xswap_backend_free(swp, swap_backend_decode_phys(old), 0);
+#endif
+
+	WRITE_ONCE(tbl[slot], encoded);
+
+	return swap_backend_is_zswap(old) ? swap_backend_decode_zswap(old) : NULL;
+}
+
+void *swap_backend_erase(swp_entry_t swp)
+{
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(swp);
+	unsigned long *tbl = READ_ONCE(ci->backend_table);
+	unsigned int slot = swp_cluster_offset(swp);
+	unsigned long val;
+
+	if (!tbl)
+		return NULL;
+
+	val = READ_ONCE(tbl[slot]);
+	if (!swap_backend_is_zswap(val))
+		return NULL;
+
+	WRITE_ONCE(tbl[slot], 0);
+	return swap_backend_decode_zswap(val);
+}
+
+/*
+ * Drop the table of a cluster that is going away. An untagged value is an
+ * xswap physical backend that has to be given back; a tagged one would be a
+ * leak, the slot free path invalidates those first. Caller holds ci->lock.
  */
 static void swap_backend_table_free(struct swap_info_struct *si,
 				    struct swap_cluster_info *ci)
@@ -4848,56 +5003,23 @@ int xswap_check_backing(struct swap_cluster_info *ci, unsigned int off,
 	return i;
 }
 
-/* Cluster lock held. The mapped prefix only grows while the device exists. */
-static unsigned long *xswap_backend_table_locked(struct swap_cluster_info *ci,
-					    gfp_t gfp)
-{
-	unsigned long *xs = ci->backend_table;
-
-	if (xs)
-		return xs;
-
-	/* The owning entry is pinned, so the cluster survives the relock. */
-	if (gfp & __GFP_DIRECT_RECLAIM) {
-		unsigned int noreclaim_flags;
-
-		spin_unlock(&ci->lock);
-		/*
-		 * The folio being stored is locked.  Do not recurse into
-		 * reclaim, which could wait for that folio.
-		 */
-		noreclaim_flags = memalloc_noreclaim_save();
-		xs = kcalloc(SWAPFILE_CLUSTER, sizeof(*xs), gfp);
-		memalloc_noreclaim_restore(noreclaim_flags);
-		spin_lock(&ci->lock);
-	} else {
-		xs = kcalloc(SWAPFILE_CLUSTER, sizeof(*xs), gfp);
-	}
-
-	if (!xs)
-		return NULL;
-	if (cmpxchg(&ci->backend_table, NULL, xs)) {
-		kfree(xs);
-		xs = ci->backend_table;
-	}
-	return xs;
-}
-
 /*
  * 4K per cluster, and this runs in reclaim, so it has to be able to sleep.
  */
 static bool xswap_slot_set_backend(struct swap_cluster_info *ci,
 				   unsigned int slot, swp_entry_t phys)
 {
-	unsigned long *xs = xswap_backend_table_locked(ci, GFP_KERNEL | __GFP_HIGH |
-						  __GFP_NOMEMALLOC);
+	unsigned long *tbl = swap_backend_table_locked(ci, GFP_KERNEL |
+						       __GFP_HIGH |
+						       __GFP_NOMEMALLOC);
 
-	if (!xs)
+	if (!tbl)
 		return false;
-	WRITE_ONCE(xs[slot], swap_backend_encode_phys(phys));
+	WRITE_ONCE(tbl[slot], swap_backend_encode_phys(phys));
 	return true;
 }
 
+
 /* A range of 1 << @order slots, no folio attached. */
 static unsigned long xswap_alloc_slot_local(struct swap_info_struct *si,
 					    unsigned int order)
@@ -5052,7 +5174,7 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry, unsigned int order,
 	ci = swap_cluster_lock(si, off);
 	if (!ci)
 		return (swp_entry_t){};
-	if (!xswap_backend_table_locked(ci, GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC)) {
+	if (!swap_backend_table_locked(ci, GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC)) {
 		swap_cluster_unlock(ci);
 		return (swp_entry_t){};
 	}
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 30/32] mm, zswap: index entries in the swap device's backend table
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (28 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 29/32] mm, swap: add accessors for the " Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 31/32] mm, swap: release a range of backend handles at once Baoquan He
  2026-12-03 18:13 ` [PATCH v2 32/32] mm, swap: only run the xswap backend hooks on xswap devices Baoquan He
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

Every swap device already has a lazily allocated per-cluster backend
table, so record zswap entries there instead of in a per-type xarray:
O(1) lookup by cluster, no radix tree, and no per-type tree to allocate
at swapon or free at swapoff. The swap table is untouched, so the count
and fault paths are unchanged.

xswap shares the table: an untagged word is its physical backend. A
tagged zswap handle replaced by a physical backend is left for the
writeback path that is freeing it, and released after the data has been
decompressed.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/zswap.h |   7 --
 mm/swapfile.c         |  21 +++---
 mm/zswap.c            | 156 ++++++++++++++----------------------------
 3 files changed, 59 insertions(+), 125 deletions(-)

diff --git a/include/linux/zswap.h b/include/linux/zswap.h
index 6d6c791b1167..c7faad1d1b42 100644
--- a/include/linux/zswap.h
+++ b/include/linux/zswap.h
@@ -28,8 +28,6 @@ unsigned long zswap_total_pages(void);
 bool zswap_store(struct folio *folio, bool may_enter_fs);
 int zswap_load(struct folio *folio);
 void zswap_invalidate(int type, pgoff_t offset, unsigned long nr_entries);
-int zswap_swapon(int type, unsigned long nr_pages);
-void zswap_swapoff(int type);
 void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg);
 void zswap_lruvec_state_init(struct lruvec *lruvec);
 void zswap_folio_swapin(struct folio *folio);
@@ -55,11 +53,6 @@ static inline void zswap_invalidate(int type, pgoff_t offset,
 {
 }
 
-static inline int zswap_swapon(int type, unsigned long nr_pages)
-{
-	return 0;
-}
-static inline void zswap_swapoff(int type) {}
 static inline void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg) {}
 static inline void zswap_lruvec_state_init(struct lruvec *lruvec) {}
 static inline void zswap_folio_swapin(struct folio *folio) {}
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 1862f0b93c92..66a7682e29f0 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -4376,7 +4376,6 @@ static int __swapoff(struct swap_info_struct *p)
 	spin_unlock(&p->lock);
 	spin_unlock(&swap_lock);
 	arch_swap_invalidate_area(p->type);
-	zswap_swapoff(p->type);
 	mutex_unlock(&swapon_mutex);
 	kfree(p->global_cluster);
 	p->global_cluster = NULL;
@@ -5141,6 +5140,14 @@ void xswap_backend_drop(swp_entry_t entry, unsigned int order)
 		ci = swap_cluster_lock(si, off + i);
 		if (!ci)
 			continue;
+		/*
+		 * A fresh cluster has no table yet, and therefore no old slot range
+		 * to drop.
+		 */
+		if (!ci->backend_table) {
+			swap_cluster_unlock(ci);
+			continue;
+		}
 		old = xswap_slot_backend(ci, (off + i) % SWAPFILE_CLUSTER);
 		swap_cluster_unlock(ci);
 		if (old.val)
@@ -5678,10 +5685,6 @@ static int xswap_create(int prio)
 	if (error)
 		goto bad_swap;
 
-	error = zswap_swapon(si->type, si->max);
-	if (error)
-		goto bad_swap;
-
 	mutex_lock(&swapon_mutex);
 	xswap_debugfs_add(si);
 	si->prio = prio;
@@ -5952,10 +5955,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		}
 	}
 
-	error = zswap_swapon(si->type, maxpages);
-	if (error)
-		goto bad_swap_unlock_inode;
-
 	/*
 	 * Flush any pending IO and dirty mappings before we start using this
 	 * swap device.
@@ -5964,7 +5963,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	error = inode_drain_writes(inode);
 	if (error) {
 		inode->i_flags &= ~S_SWAPFILE;
-		goto free_swap_zswap;
+		goto bad_swap_unlock_inode;
 	}
 
 	mutex_lock(&swapon_mutex);
@@ -5998,8 +5997,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 
 	error = 0;
 	goto out;
-free_swap_zswap:
-	zswap_swapoff(si->type);
 bad_swap_unlock_inode:
 	inode_unlock(inode);
 bad_swap:
diff --git a/mm/zswap.c b/mm/zswap.c
index dfb7ea058d66..1903367a9576 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -158,10 +158,10 @@ struct crypto_acomp_ctx {
 };
 
 /*
- * The lock ordering is zswap_tree.lock -> zswap_pool.lru_lock.
- * The only case where lru_lock is not acquired while holding tree.lock is
- * when a zswap_entry is taken off the lru for writeback, in that case it
- * needs to be verified that it's still valid in the tree.
+ * The lock ordering is swap cluster lock -> zswap_pool.lru_lock.
+ * The only case where lru_lock is not acquired while holding the cluster
+ * lock is when a zswap_entry is taken off the lru for writeback, in that
+ * case it needs to be verified that it is still recorded in the slot.
  */
 struct zswap_pool {
 	struct zs_pool *zs_pool;
@@ -199,7 +199,7 @@ static struct shrinker *zswap_shrinker;
  * This structure contains the metadata for tracking a single compressed
  * page within zswap.
  *
- * swpentry - associated swap entry, the offset indexes into the xarray
+ * swpentry - associated swap entry, the slot's backend record points here
  * length - the length in bytes of the compressed page data.  Needed during
  *          decompression.
  * referenced - true if the entry recently entered the zswap pool. Unset by the
@@ -231,9 +231,6 @@ static struct zswap_pool *zswap_entry_pool(struct zswap_entry *entry)
 	return xa_load(&zswap_pools, entry->pool_idx);
 }
 
-static struct xarray *zswap_trees[MAX_SWAPFILES];
-static unsigned int nr_zswap_trees[MAX_SWAPFILES];
-
 /* pool counter to provide unique names to zsmalloc */
 static atomic_t zswap_pools_count = ATOMIC_INIT(0);
 
@@ -255,20 +252,6 @@ static bool zswap_has_pool;
 * helpers and fwd declarations
 **********************************/
 
-/* One swap address space for each 64M swap space */
-#define ZSWAP_ADDRESS_SPACE_SHIFT 14
-#define ZSWAP_ADDRESS_SPACE_PAGES (1 << ZSWAP_ADDRESS_SPACE_SHIFT)
-
-static inline struct xarray *zswap_tree(int type, pgoff_t offset)
-{
-	return &zswap_trees[type][offset >> ZSWAP_ADDRESS_SPACE_SHIFT];
-}
-
-static inline struct xarray *swap_zswap_tree(swp_entry_t swp)
-{
-	return zswap_tree(swp_type(swp), swp_offset(swp));
-}
-
 #define zswap_pool_debug(msg, p)			\
 	pr_debug("%s pool %s\n", msg, (p)->tfm_name)
 
@@ -1089,8 +1072,6 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 				 struct zswap_entry *entry,
 				 swp_entry_t swpentry, bool may_enter_fs)
 {
-	struct xarray *tree;
-	pgoff_t offset = swp_offset(swpentry);
 	struct folio *folio;
 	struct mempolicy *mpol;
 	struct swap_info_struct *si;
@@ -1147,14 +1128,13 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	/*
 	 * folio is locked, and the swapcache is now secured against
 	 * concurrent swapping to and from the slot, and concurrent
-	 * swapoff so we can safely dereference the zswap tree here.
+	 * swapoff so we can safely dereference the backend table here.
 	 * Verify that the swap entry hasn't been invalidated and recycled
 	 * behind our backs, to avoid overwriting a new swap folio with
 	 * old compressed data. Only when this is successful can the entry
 	 * be dereferenced.
 	 */
-	tree = swap_zswap_tree(swpentry);
-	if (entry != xa_load(tree, offset)) {
+	if (entry != swap_backend_get(swpentry)) {
 		ret = -ENOMEM;
 		goto err;
 	}
@@ -1173,7 +1153,11 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 		goto err;
 	}
 
-	xa_erase(tree, offset);
+	/*
+	 * On an xswap device the physical slot was recorded first, so the
+	 * entry this clears was already replaced and nothing is returned.
+	 */
+	swap_backend_erase(swpentry);
 
 	count_vm_event(ZSWPWB);
 	if (entry->objcg)
@@ -1205,8 +1189,21 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	return 0;
 
 err:
-	if (is_xswap && phys.val)
+	if (is_xswap && phys.val) {
+		void *old;
+
 		xswap_backend_free(swpentry, phys, 0);
+		/*
+		 * Reserving the destination displaced the entry from the
+		 * backend table, and it is still in zswap: put it back.
+		 * The table exists by now, so this cannot fail.  A handle
+		 * that was already there is stale; do not leak it.
+		 */
+		old = swap_backend_set(swpentry, entry);
+		WARN_ON_ONCE(IS_ERR(old));
+		if (!IS_ERR_OR_NULL(old) && old != entry)
+			zswap_entry_free(old);
+	}
 	swap_cache_del_folio(folio);
 	folio_unlock(folio);
 	folio_put(folio);
@@ -1290,7 +1287,7 @@ static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_o
 	/*
 	 * Once the lru lock is dropped, the entry might get freed. The
 	 * swpentry is copied to the stack, and entry isn't deref'd again
-	 * until the entry is verified to still be alive in the tree.
+	 * until the entry is verified to still be in the backend table.
 	 */
 	swpentry = entry->swpentry;
 
@@ -1623,19 +1620,17 @@ static bool zswap_store_page(struct folio *folio, long index,
 		goto compress_failed;
 
 	/*
-	 * Set pool_idx before the xa_store() below publishes the entry, or a
-	 * concurrent reader could resolve a stale pool_idx left by slab reuse
-	 * to an unrelated live pool.
+	 * Set pool_idx before swap_backend_set() below publishes the entry,
+	 * or a concurrent reader could resolve a stale pool_idx left by slab
+	 * reuse to an unrelated live pool.
 	 */
 	entry->pool_idx = pool->idx;
 
-	old = xa_store(swap_zswap_tree(page_swpentry),
-		       swp_offset(page_swpentry),
-		       entry, GFP_KERNEL);
-	if (xa_is_err(old)) {
-		int err = xa_err(old);
+	old = swap_backend_set(page_swpentry, entry);
+	if (IS_ERR(old)) {
+		int err = PTR_ERR(old);
 
-		WARN_ONCE(err != -ENOMEM, "unexpected xarray error: %d\n", err);
+		WARN_ONCE(err != -ENOMEM, "unexpected backend index error: %d\n", err);
 		zswap_reject_alloc_fail++;
 		goto store_failed;
 	}
@@ -1649,11 +1644,8 @@ static bool zswap_store_page(struct folio *folio, long index,
 		zswap_entry_free(old);
 
 	/*
-	 * The entry is successfully compressed and stored in the tree, there is
-	 * no further possibility of failure. Grab refs to the pool and objcg,
-	 * charge zswap memory, and increment zswap_stored_pages.
-	 * The opposite actions will be performed by zswap_entry_free()
-	 * when the entry is removed from the tree.
+	 * The entry is stored and cannot fail now.  Take the pool and objcg
+	 * refs and charge zswap memory; zswap_entry_free() undoes them.
 	 */
 	zswap_pool_get(pool);
 	if (objcg) {
@@ -1665,8 +1657,8 @@ static bool zswap_store_page(struct folio *folio, long index,
 		atomic_long_inc(&zswap_stored_incompressible_pages);
 
 	/*
-	 * We finish initializing the entry while it's already in xarray.
-	 * This is safe because:
+	 * We finish initializing the entry while it's already in the backend
+	 * table.  This is safe because:
 	 *
 	 * 1. Concurrent stores and invalidations are excluded by folio lock.
 	 *
@@ -1773,22 +1765,13 @@ bool zswap_store(struct folio *folio, bool may_enter_fs)
  */
 bool zswap_is_present(swp_entry_t entry, unsigned int nr)
 {
-	pgoff_t offset = swp_offset(entry);
-	struct xarray *tree = swap_zswap_tree(entry);
-	unsigned long index = offset;
-
-	if (zswap_never_enabled() || xa_empty(tree))
-		return false;
-
 	/*
 	 * A pinned range is at most SWAPFILE_CLUSTER slots and is aligned to
-	 * its own size, so one tree covers all of it and a single lookup is
-	 * enough. Scanning only part of the range would report a false
+	 * its own size, so the whole range sits in one cluster and one
+	 * table. Scanning only part of the range would report a false
 	 * "absent" and let the caller read a stale copy from the device.
 	 */
-	BUILD_BUG_ON(SWAPFILE_CLUSTER > ZSWAP_ADDRESS_SPACE_PAGES);
-
-	return xa_find(tree, &index, offset + nr - 1, XA_PRESENT);
+	return swap_backend_present(entry, nr);
 }
 
 /**
@@ -1811,8 +1794,6 @@ bool zswap_is_present(swp_entry_t entry, unsigned int nr)
 int zswap_load(struct folio *folio)
 {
 	swp_entry_t swp = folio->swap;
-	pgoff_t offset = swp_offset(swp);
-	struct xarray *tree = swap_zswap_tree(swp);
 	struct zswap_entry *entry;
 
 	VM_WARN_ON_ONCE(!folio_test_locked(folio));
@@ -1836,7 +1817,7 @@ int zswap_load(struct folio *folio)
 		return -ENOENT;
 	}
 
-	entry = xa_load(tree, offset);
+	entry = swap_backend_get(swp);
 	if (!entry)
 		return -ENOENT;
 
@@ -1859,7 +1840,7 @@ int zswap_load(struct folio *folio)
 	 * compression work.
 	 */
 	folio_mark_dirty(folio);
-	xa_erase(tree, offset);
+	swap_backend_erase(swp);
 	zswap_entry_free(entry);
 
 	folio_unlock(folio);
@@ -1868,62 +1849,25 @@ int zswap_load(struct folio *folio)
 
 void zswap_invalidate(int type, pgoff_t offset, unsigned long nr_entries)
 {
-	struct zswap_entry *entry;
-	struct xarray *tree;
 	unsigned long i;
 
 	if (zswap_never_enabled())
 		return;
 
+	/*
+	 * The slot free path runs under the cluster lock once the slots are
+	 * no longer allocatable, and the store rollback holds the folio
+	 * lock, so only one caller can see a tagged handle.
+	 */
 	for (i = 0; i < nr_entries; i++) {
-		tree = zswap_tree(type, offset + i);
-
-		if (xa_empty(tree))
-			continue;
+		struct zswap_entry *entry;
 
-		entry = xa_erase(tree, offset + i);
+		entry = swap_backend_erase(swp_entry(type, offset + i));
 		if (entry)
 			zswap_entry_free(entry);
 	}
 }
 
-int zswap_swapon(int type, unsigned long nr_pages)
-{
-	struct xarray *trees, *tree;
-	unsigned int nr, i;
-
-	nr = DIV_ROUND_UP(nr_pages, ZSWAP_ADDRESS_SPACE_PAGES);
-	trees = kvzalloc_objs(*tree, nr);
-	if (!trees) {
-		pr_err("alloc failed, zswap disabled for swap type %d\n", type);
-		return -ENOMEM;
-	}
-
-	for (i = 0; i < nr; i++)
-		xa_init(trees + i);
-
-	nr_zswap_trees[type] = nr;
-	zswap_trees[type] = trees;
-	return 0;
-}
-
-void zswap_swapoff(int type)
-{
-	struct xarray *trees = zswap_trees[type];
-	unsigned int i;
-
-	if (!trees)
-		return;
-
-	/* try_to_unuse() invalidated all the entries already */
-	for (i = 0; i < nr_zswap_trees[type]; i++)
-		WARN_ON_ONCE(!xa_empty(trees + i));
-
-	kvfree(trees);
-	nr_zswap_trees[type] = 0;
-	zswap_trees[type] = NULL;
-}
-
 /*********************************
 * debugfs functions
 **********************************/
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 31/32] mm, swap: release a range of backend handles at once
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (29 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 30/32] mm, zswap: index entries in the swap device's backend table Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  2026-12-03 18:13 ` [PATCH v2 32/32] mm, swap: only run the xswap backend hooks on xswap devices Baoquan He
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

Freeing a range of swap slots calls swap_backend_erase() for every slot,
which resolves the device and the cluster again each time: two
percpu_ref_is_zero() calls and a division per slot.  A slot range is a folio's
slots or a cluster's free batch, so it never crosses a cluster.

Resolve the cluster once and walk the slots.  A tagged handle is only
ever a zswap entry, so the walk releases those directly, which is why
zswap_entry_free() is no longer static.  The backend table is the only
owner of a stored zswap entry, so the range erase is where it goes;
collecting the handles first would only add an array or a callback to
the free path.  Release a tagged entry that is still in a cluster's
table when the table goes as well, instead of only warning about it, so
a broken invariant cannot leak it.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 include/linux/zswap.h |  4 ++++
 mm/swap.h             |  1 +
 mm/swapfile.c         | 43 +++++++++++++++++++++++++++++++++++++++----
 mm/zswap.c            | 12 ++----------
 4 files changed, 46 insertions(+), 14 deletions(-)

diff --git a/include/linux/zswap.h b/include/linux/zswap.h
index c7faad1d1b42..df9e0f29480e 100644
--- a/include/linux/zswap.h
+++ b/include/linux/zswap.h
@@ -6,6 +6,7 @@
 #include <linux/mm_types.h>
 
 struct lruvec;
+struct zswap_entry;
 
 extern atomic_long_t zswap_stored_pages;
 
@@ -25,6 +26,7 @@ struct zswap_lruvec_state {
 };
 
 unsigned long zswap_total_pages(void);
+void zswap_entry_free(struct zswap_entry *entry);
 bool zswap_store(struct folio *folio, bool may_enter_fs);
 int zswap_load(struct folio *folio);
 void zswap_invalidate(int type, pgoff_t offset, unsigned long nr_entries);
@@ -38,6 +40,8 @@ bool zswap_is_present(swp_entry_t entry, unsigned int nr);
 
 struct zswap_lruvec_state {};
 
+static inline void zswap_entry_free(struct zswap_entry *entry) {}
+
 static inline bool zswap_store(struct folio *folio, bool may_enter_fs)
 {
 	return false;
diff --git a/mm/swap.h b/mm/swap.h
index 9b2d8d556bd0..4f6e2c2de16f 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -229,6 +229,7 @@ extern int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp);
 void *swap_backend_get(swp_entry_t entry);
 void *swap_backend_set(swp_entry_t entry, void *handle);
 void *swap_backend_erase(swp_entry_t entry);
+void swap_backend_erase_range(swp_entry_t entry, unsigned long nr);
 bool swap_backend_present(swp_entry_t entry, unsigned int nr);
 
 /*
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 66a7682e29f0..3098a4086cdb 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -4884,10 +4884,40 @@ void *swap_backend_erase(swp_entry_t swp)
 	return swap_backend_decode_zswap(val);
 }
 
+/*
+ * Drop the handles of a range of slots. A range is a folio's slots or a
+ * cluster's free batch, so it never crosses a cluster: the caller holds
+ * either the cluster lock (slot free) or the folio lock (store rollback).
+ *
+ * Clamp and warn if the one-cluster invariant ever breaks; the next
+ * cluster is not protected here and the remaining slots are not erased.
+ */
+void swap_backend_erase_range(swp_entry_t swp, unsigned long nr)
+{
+	struct swap_cluster_info *ci = __swap_entry_to_cluster(swp);
+	unsigned int slot = swp_cluster_offset(swp);
+	unsigned long *tbl = READ_ONCE(ci->backend_table);
+	unsigned long n = min_t(unsigned long, nr, SWAPFILE_CLUSTER - slot);
+
+	VM_WARN_ON_ONCE(nr > SWAPFILE_CLUSTER - slot);
+	if (!tbl)
+		return;
+
+	for (unsigned int i = 0; i < n; i++) {
+		unsigned long val = READ_ONCE(tbl[slot + i]);
+
+		if (!swap_backend_is_zswap(val))
+			continue;
+		WRITE_ONCE(tbl[slot + i], 0);
+		zswap_entry_free(swap_backend_decode_zswap(val));
+	}
+}
+
 /*
  * Drop the table of a cluster that is going away. An untagged value is an
- * xswap physical backend that has to be given back; a tagged one would be a
- * leak, the slot free path invalidates those first. Caller holds ci->lock.
+ * xswap physical backend that has to be given back; a tagged one should
+ * have been invalidated by the slot free path, but release it here too so a
+ * broken invariant cannot leak it. Caller holds ci->lock.
  */
 static void swap_backend_table_free(struct swap_info_struct *si,
 				    struct swap_cluster_info *ci)
@@ -4901,9 +4931,14 @@ static void swap_backend_table_free(struct swap_info_struct *si,
 	for (slot = 0; slot < SWAPFILE_CLUSTER; slot++) {
 		unsigned long val = READ_ONCE(tbl[slot]);
 
-		VM_WARN_ON_ONCE(swap_backend_is_zswap(val));
+		if (swap_backend_is_zswap(val)) {
+			VM_WARN_ON_ONCE(1);
+			WRITE_ONCE(tbl[slot], 0);
+			zswap_entry_free(swap_backend_decode_zswap(val));
+			continue;
+		}
 #ifdef CONFIG_XSWAP
-		if (val && !swap_backend_is_zswap(val))
+		if (val)
 			xswap_release_slot_backend(si, ci, slot);
 #else
 		VM_WARN_ON_ONCE(val);
diff --git a/mm/zswap.c b/mm/zswap.c
index 1903367a9576..9df2eaf4a21c 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -766,7 +766,7 @@ static void zswap_entry_cache_free(struct zswap_entry *entry)
  * Carries out the common pattern of freeing an entry's zsmalloc allocation,
  * freeing the entry itself, and decrementing the number of stored pages.
  */
-static void zswap_entry_free(struct zswap_entry *entry)
+void zswap_entry_free(struct zswap_entry *entry)
 {
 	struct zswap_pool *pool = zswap_entry_pool(entry);
 
@@ -1849,8 +1849,6 @@ int zswap_load(struct folio *folio)
 
 void zswap_invalidate(int type, pgoff_t offset, unsigned long nr_entries)
 {
-	unsigned long i;
-
 	if (zswap_never_enabled())
 		return;
 
@@ -1859,13 +1857,7 @@ void zswap_invalidate(int type, pgoff_t offset, unsigned long nr_entries)
 	 * no longer allocatable, and the store rollback holds the folio
 	 * lock, so only one caller can see a tagged handle.
 	 */
-	for (i = 0; i < nr_entries; i++) {
-		struct zswap_entry *entry;
-
-		entry = swap_backend_erase(swp_entry(type, offset + i));
-		if (entry)
-			zswap_entry_free(entry);
-	}
+	swap_backend_erase_range(swp_entry(type, offset), nr_entries);
 }
 
 /*********************************
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

* [PATCH v2 32/32] mm, swap: only run the xswap backend hooks on xswap devices
  2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
                   ` (30 preceding siblings ...)
  2026-12-03 18:13 ` [PATCH v2 31/32] mm, swap: release a range of backend handles at once Baoquan He
@ 2026-12-03 18:13 ` Baoquan He
  31 siblings, 0 replies; 33+ messages in thread
From: Baoquan He @ 2026-12-03 18:13 UTC (permalink / raw)
  To: linux-mm
  Cc: akpm, david, chrisl, kasong, hannes, corbet, yosry, nphamcs,
	muchun.song, baohua, youngjun.park, hughd, baolin.wang,
	baoquan.he, Baoquan He

From: Baoquan He <hebaoquan@kylinos.cn>

The backend table used to exist only on xswap devices, so the xswap
hooks in the slot free and swapout paths tested for the table.  zswap
now records its entries there too, so a table no longer tells whether
the device can own a physical backend.

Test the device type instead.  The table pointer is resolved once per
range, and a slot that still holds a zswap entry skips the backend
release without the out-of-line call.  The teardown path that drops a
cluster's table does the same: an untagged handle on a non-xswap device
is reported instead of being handed to the xswap release.

Signed-off-by: Baoquan He <hebaoquan@kylinos.cn>
---
 mm/swapfile.c | 48 ++++++++++++++++++++++++++++++++++++------------
 1 file changed, 36 insertions(+), 12 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index 3098a4086cdb..a55f96623037 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -111,6 +111,18 @@ static inline bool swap_backend_is_zswap(unsigned long val)
 static void swap_backend_table_free(struct swap_info_struct *si,
 				    struct swap_cluster_info *ci);
 
+#ifndef CONFIG_XSWAP
+static inline void xswap_mark_cache_only(struct swap_info_struct *si,
+					 struct swap_cluster_info *ci,
+					 unsigned int slot) { }
+static inline void xswap_clear_cache_only(struct swap_info_struct *si,
+					  struct swap_cluster_info *ci,
+					  unsigned int start, unsigned int nr) { }
+static inline void xswap_release_slot_backend(struct swap_info_struct *si,
+					      struct swap_cluster_info *ci,
+					      unsigned int slot) { }
+#endif
+
 #ifdef CONFIG_XSWAP
 /*
  * Clusters mapped per grow: one page worth of cluster_info, so the
@@ -2027,8 +2039,12 @@ static void swap_put_entries_cluster(struct swap_info_struct *si,
 	unsigned int nr_reclaimed;
 	unsigned long swp_tb;
 	int ci_batch = -1;
+	unsigned long *backend_tbl = NULL;
 
 	ci = swap_cluster_lock(si, offset);
+	/* Only an xswap slot can own a physical backend. */
+	if (IS_ENABLED(CONFIG_XSWAP) && (si->flags & SWP_XSWAP))
+		backend_tbl = ci->backend_table;
 	ci_off = offset % SWAPFILE_CLUSTER;
 	ci_end = ci_off + nr;
 	do {
@@ -2042,10 +2058,8 @@ static void swap_put_entries_cluster(struct swap_info_struct *si,
 			}
 			/* count will be 0 after put, slot can be reclaimed */
 			need_reclaim = true;
-#ifdef CONFIG_XSWAP
-			if (ci->backend_table)
+			if (backend_tbl)
 				xswap_mark_cache_only(si, ci, ci_off);
-#endif
 		}
 		/*
 		 * A count != 1 or cached slot can't be freed. Put its swap
@@ -2152,10 +2166,9 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 			goto failed;
 		}
 	} while (++ci_off < ci_end);
-#ifdef CONFIG_XSWAP
-	if (ci->backend_table)
+	if (IS_ENABLED(CONFIG_XSWAP) && (si->flags & SWP_XSWAP) &&
+	    ci->backend_table)
 		xswap_clear_cache_only(si, ci, ci_start, nr);
-#endif
 	swap_cluster_unlock(ci);
 	return 0;
 failed:
@@ -2496,6 +2509,10 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 	unsigned long ci_head = cluster_offset(si, ci);
 	unsigned int batch_off = ci_off;
 	bool is_xswap = si->flags & SWP_XSWAP;
+	unsigned long *backend_tbl = NULL;
+
+	if (IS_ENABLED(CONFIG_XSWAP) && is_xswap)
+		backend_tbl = ci->backend_table;
 
 	VM_WARN_ON(ci->count < nr_pages);
 
@@ -2510,10 +2527,12 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 		VM_WARN_ON(!swp_tb_is_hibernation(old_tb) &&
 			   (!swp_tb_is_shadow(old_tb) || __swp_tb_get_count(old_tb) > 1));
 
-#ifdef CONFIG_XSWAP
-		if (ci->backend_table && ci->backend_table[ci_off])
-			xswap_release_slot_backend(si, ci, ci_off);
-#endif
+		if (backend_tbl) {
+			unsigned long val = READ_ONCE(backend_tbl[ci_off]);
+
+			if (val && !swap_backend_is_zswap(val))
+				xswap_release_slot_backend(si, ci, ci_off);
+		}
 
 		/* Resetting the slot to NULL also clears the inline flags. */
 		__swap_table_set(ci, ci_off, null_to_swp_tb());
@@ -4938,8 +4957,13 @@ static void swap_backend_table_free(struct swap_info_struct *si,
 			continue;
 		}
 #ifdef CONFIG_XSWAP
-		if (val)
-			xswap_release_slot_backend(si, ci, slot);
+		if (!val)
+			continue;
+		if (!(si->flags & SWP_XSWAP)) {
+			VM_WARN_ON_ONCE(1);
+			continue;
+		}
+		xswap_release_slot_backend(si, ci, slot);
 #else
 		VM_WARN_ON_ONCE(val);
 #endif
-- 
2.54.0



^ permalink raw reply related	[flat|nested] 33+ messages in thread

end of thread, other threads:[~2026-12-03 18:17 UTC | newest]

Thread overview: 33+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-03 18:12 [PATCH v2 00/32] mm, swap: extendable swap devices (xswap phases II-IV) Baoquan He
2026-12-03 18:12 ` [PATCH v2 01/32] mm, swap: prepare the swap IO path for xswap backends Baoquan He
2026-12-03 18:12 ` [PATCH v2 02/32] mm, swap: tag a swap table entry with its owning xswap entry Baoquan He
2026-12-03 18:12 ` [PATCH v2 03/32] mm, swap: prepare the folio-less allocation path for xswap Baoquan He
2026-12-03 18:12 ` [PATCH v2 04/32] mm, swap: add a physical backend for xswap slots Baoquan He
2026-12-03 18:12 ` [PATCH v2 05/32] mm, swap: support swapoff of an xswap physical backend Baoquan He
2026-12-03 18:12 ` [PATCH v2 06/32] mm, swap: use the " Baoquan He
2026-12-03 18:12 ` [PATCH v2 07/32] mm, swap: fall back to disk when zswap refuses an xswap page Baoquan He
2026-12-03 18:12 ` [PATCH v2 08/32] mm, swap: reclaim physical slots backing cache-only xswap entries Baoquan He
2026-12-03 18:12 ` [PATCH v2 09/32] mm, swap: drop swap_folio_sector() Baoquan He
2026-12-03 18:12 ` [PATCH v2 10/32] mm, swap: drop a stale xswap physical slot range before reallocating Baoquan He
2026-12-03 18:12 ` [PATCH v2 11/32] mm, swap: publish the xswap backend owner before its reverse map Baoquan He
2026-12-03 18:12 ` [PATCH v2 12/32] mm, swap: skip a NOFS backend for xswap physical writeback Baoquan He
2026-12-03 18:13 ` [PATCH v2 13/32] mm, swap: pass the folio order through the swap slot allocator Baoquan He
2026-12-03 18:13 ` [PATCH v2 14/32] mm, swap: allocate a multi-slot range without a folio Baoquan He
2026-12-03 18:13 ` [PATCH v2 15/32] mm, swap: pass the folio order to the xswap physical backend Baoquan He
2026-12-03 18:13 ` [PATCH v2 16/32] mm, swap: enable large xswap folios with a contiguous physical slot range Baoquan He
2026-12-03 18:13 ` [PATCH v2 17/32] mm, swap: enable THP swapin for xswap entries Baoquan He
2026-12-03 18:13 ` [PATCH v2 18/32] mm, swap: split the swap memcg charge helpers Baoquan He
2026-12-03 18:13 ` [PATCH v2 19/32] mm, swap: do not charge zswap-backed xswap entries Baoquan He
2026-12-03 18:13 ` [PATCH v2 20/32] mm, swap: charge an xswap entry when it gets physical backing Baoquan He
2026-12-03 18:13 ` [PATCH v2 21/32] mm, swap: don't gate xswap on the physical swap free count Baoquan He
2026-12-03 18:13 ` [PATCH v2 22/32] mm, swap: do not retake the cluster lock when uncharging an xswap slot Baoquan He
2026-12-03 18:13 ` [PATCH v2 23/32] mm, swap: uncharge an xswap backend where its record is cleared Baoquan He
2026-12-03 18:13 ` [PATCH v2 24/32] mm, swap: account xswap backends for cgroup v1 Baoquan He
2026-12-03 18:13 ` [PATCH v2 25/32] mm, swap: drop a refused xswap backend slot range directly Baoquan He
2026-12-03 18:13 ` [PATCH v2 26/32] mm, swap: route xswap by the zswap eligibility without flushing Baoquan He
2026-12-03 18:13 ` [PATCH v2 27/32] mm, swap: keep a per-cluster backend record for every swap device Baoquan He
2026-12-03 18:13 ` [PATCH v2 28/32] mm, swap: encode the per-slot backend record Baoquan He
2026-12-03 18:13 ` [PATCH v2 29/32] mm, swap: add accessors for the " Baoquan He
2026-12-03 18:13 ` [PATCH v2 30/32] mm, zswap: index entries in the swap device's backend table Baoquan He
2026-12-03 18:13 ` [PATCH v2 31/32] mm, swap: release a range of backend handles at once Baoquan He
2026-12-03 18:13 ` [PATCH v2 32/32] mm, swap: only run the xswap backend hooks on xswap devices Baoquan He

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox