Skip to contentSkip to conversation

mm, swap: extendable swap devices (xswap phase I)

PATCH New Baoquan He 2 participants 20 messages Nov 29 – Nov 30

Subsystems (6)
lore
Share & tools
lore

Baoquan He

author reviewer
#0 lore raw

v7 cover mm, swap: extendable swap devices (xswap phase I)

From: Baoquan He <[email protected]>

A normal swap device has a fixed size, set when it is enabled. This does not fit zswap well. With zswap the swapped data stays in RAM in compressed form, so how much swap a machine can really use depends on how well the workload compresses, not on a number we pick before we know the workload. Size the device for the worst case and most of it is never used; size it for the average case and the machine runs out of swap while zswap still has free room.

xswap is a swap device with no backing file. In this phase its swap entries hold pages in zswap, and its cluster_info array lives in a VM_SPARSE area that is mapped a chunk at a time, so the device covers a large swap address space and costs only the chunks it has actually used. The device grows as the workload needs it.

This series is the device itself: the sparse cluster array, growth, and the interfaces that create and destroy one. It is phase I of five; the physical backend, the swap accounting, the swap-table backend records, and the runtime shrink build on it.

Runtime shrink is left for a later series. The plan is to run it only when the device has nothing live: no entry and no backend record points into the tail, so no swap reader has to be tracked. It would lower nr_clusters_mapped under si->lock and unmap the pages behind it; cluster 0 stays mapped because it holds the bad-header slot. The details are still being worked out. Note that without shrink nothing breaks: the device keeps the peak range, and only the cluster metadata for that range stays allocated.

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

In this phase the device is only a swap address space. si->max is set when the device is created and does not move for its lifetime; what moves is how much of it is mapped. swap_info_struct carries nr_clusters_max (the swap address space) and nr_clusters_mapped (how many clusters are mapped, always from cluster 0). get_swap_device() rejects an entry past the mapped range, and the walkers that scan a device stop there.

Growth starts when 85% of the mapped range is in use and maps until 65%. The call comes from the cluster allocation path: growing maps pages into the VM_SPARSE area, and mapping can sleep, so it happens before the allocation that would otherwise fail. One grow maps at most four chunks, and one chunk is PAGE_SIZE / sizeof(struct swap_cluster_info) clusters:
85 with the current struct size. Mapping a chunk and putting its clusters on the free list happen in one si->lock section, and the larger nr_clusters_mapped is published after the clusters are linked. An allocator takes a cluster from the free list under si->lock, so it can never see a cluster that the published range does not cover, and a reader can never see an entry in one.

A burst of allocators can hold every mapped cluster off the free lists while usage is still below the threshold. When an allocation finds no usable cluster, it maps one more chunk and retries once.

Creation and teardown
---------------------

The device has no path. swapon(2) opens the given name as a path first, and only when that open fails with -ENOENT is the name taken as a request name; the exact string "xswap" asks for the file-less device. A real file or directory called "xswap" keeps precedence, a path that fails for another reason is returned unchanged, and "./xswap" or an absolute path is a file as usual. This is the same rule swapoff(2) uses, and the path is copied from userspace once.

There is one xswap device per system; a second create returns -EBUSY. /proc/swaps shows it as "xswap", so swapoff xswap and swapoff -a both tear it down. Its counters are in /sys/kernel/debug/xswap/xswap.stats:

type 0
clusters_max 5120
clusters_mapped 85
usage_pages 0
tail_free 84
grows 0

With xswap.max=10G the device has 5120 clusters (with a 2 MB swap cluster); an idle device maps one chunk of 85 clusters and the tail scan leaves 84 of them free.

Hibernation device discovery skips xswap devices: there is no block device to resume from.

Configuration
-------------

CONFIG_XSWAP depends on SWAP, 64BIT and ZSWAP. CONFIG_XSWAP_DEFAULT_MAX sets the default size of a new device; it takes a percentage of RAM, a size, or "max", and defaults to "200%":

CONFIG_XSWAP_DEFAULT_MAX="200%"

xswap.max= on the kernel command line overrides it:

  xswap.max=8G          8 GiB
  xswap.max=300%        three times RAM
  xswap.max=max         the largest size the device can address

The address space cannot move once the device exists, so the size is settled at creation. That is why this is a boot parameter and not a runtime knob. The default priority is the highest, SWAP_FLAG_PRIO_MASK, so xswap is tried ahead of an ordinary swap device; a lower priority can be passed in the swapon(2) flags.

The device needs zswap: without it swapout takes a swap entry and frees no memory, so creating one fails with -EOPNOTSUPP.

A cgroup that cannot zswap (its zswap limit is zero) is not given an xswap slot; the allocator skips the xswap devices for that folio.

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

This phase has no physical backend. If zswap refuses a page the folio stays in memory, so an xswap-only system can run out of memory once the zswap pool is full. Keep a real swap device on such systems; phase II adds the physical backend.

An incompressible page is refused for an xswap entry even when the pool has room. An xswap entry is not put on the zswap writeback LRU in this phase, so a page stored uncompressed could never be reclaimed. Phase II gives xswap a writeback target and the page can then be stored and written back.

xswap does not allocate large folios in this phase. The allocation walk stops at the first device for a large folio, and a new xswap device defaults to the highest priority, so the folio is offered to xswap, rejected there, and split into base pages; a lower-priority block device never gets it whole. Creating the xswap device below a block device in priority avoids the split, at the cost of offering every page to the block device first. The data is still swapped, in base pages.

The device does not return its unused tail while it is enabled; destroying it returns the whole range.

When every mapped cluster is held elsewhere, the allocator maps one more chunk and retries once. If that still finds nothing, the folio stays in memory; it is not a correctness failure, but under pressure it can look like a false OOM.

Overcommit
----------

An xswap device advertises its whole swap address space as swap
capacity: si->pages is what /proc/swaps and SwapTotal report, and what nr_swap_pages uses to decide that anonymous memory can be reclaimed. The backing is the zswap pool in this phase, and real swap devices in the later phases; the swap address space is not backing store in either case, yet it raises the commit limit that __vm_enough_memory() enforces.

Which semantics this should follow is not settled here. Counting the swap address space lets a workload commit memory it can never back; not counting it changes what SwapTotal means. swap_info_remove() skips its commit-limit probe for xswap, so destroying a device does not fail on headroom the device added and a workload may have committed into, and real swap devices keep the probe. The limit can then fall below Committed_AS; new allocations fail until Committed_AS drops. This is left to a follow-up, together with the rest of the swap accounting.

Testing
-------

QEMU KVM guest, 8G RAM, booted with xswap.max=10G.

The shell's swapon(8) opens the path and reads the swap header itself, so the util-linux swapon(8) cannot pass the request name through unless it knows about "xswap"; a matching util-linux change that lets "swapon xswap" do it will be posted separately. swapoff(8) passes the name to swapoff(2), so "swapoff xswap" works as is. Without that change, create the device with a small helper that calls swapon(2) directly:

  #define _GNU_SOURCE
  #include <errno.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <sys/syscall.h>
  #include <unistd.h>

  #define SWAP_FLAG_PREFER	0x8000
  #define SWAP_FLAG_PRIO_MASK	0x7fff

int main(int argc, char **argv)

  {
	int flags = 0;

	/* The request name is never a path; stay out of any cwd file. */
	if (chdir("/"))
		return 1;

	if (argc > 1)
		flags = SWAP_FLAG_PREFER |
			(atoi(argv[1]) & SWAP_FLAG_PRIO_MASK);

	if (syscall(SYS_swapon, "xswap", flags)) {
		fprintf(stderr, "swapon(xswap): %s\n", strerror(errno));
		return 1;
	}
	return 0;

}

  # echo 1 > /sys/module/zswap/parameters/enabled
  # ./xswap_on 100
  # awk 'NR == 1 || /xswap/' /proc/swaps
  Filename                Type        Size        Used        Priority
  xswap                   xswap       10485756    0           100

The functional test reports 30 checks passed and 0 failed; the overcommit case was run separately with vm.overcommit_memory=2:

- create and read the size; SwapTotal stays fixed and SwapFree stays in [0, SwapTotal]
- grow past RAM; stop at the device size (the cgroup runs out of room and the OOM killer takes the workload)
- an incompressible page is refused and stays resident
- a cgroup that cannot zswap gets no xswap slot
- swapoff xswap, swapoff -a, and a recreate at the same size
- 2000 create/destroy cycles
- overcommit: with vm.overcommit_memory=2, 8.15G of RAM and overcommit_ratio 50 (CommitLimit 14.56G, Committed_AS 4.65G), a 10.49G device and its swapoff both succeed

The whole matrix ran on the 14 patches alone, on top of 23cd68262288; no later phase was present. In addition:

- swapoff name semantics, 11 cases: a real file keeps precedence, a dangling symlink reaches the device, a directory is EISDIR, only the exact name is accepted, a stale name reports ENOENT, -a tears it down, and destroying with 653,556 kB of live pages keeps the workload alive
- 2000 create/destroy cycles: no per-cluster state is leaked (largest slab growth 215 objects; vmap_area's +1565 is the known lazy vmap_area freeing)
- dmesg is clean; the only unusual line is the memcg OOM kill that the cgroup gate test asks for

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

The phase I configuration has no physical backend: the swap address space only names pages that zswap holds, so the capacity is the zswap pool.

The measurement that matches this phase gives the base kernel a zram swap device and xswap its sparse array, with both keeping every page in
zswap: memory.zswap.writeback=0 on the test cgroup, so nothing is written back to the device, and THP off. The xswap arm has no other swap device, so the physical backend added by later phases is not used. On an x86-64 server (2 nodes, 72 CPUs, 252 GiB), usemem touches 64G in a 48G cgroup, one thread, interleaved NUMA:

  kernel  rounds  median wall  swapout pages   pswpout
  base    6       151.8 s      6,833,914       0
  xswap   5       145.2 s      6,833,856       0

The medians differ by 4.3%, which is below the run-to-run spread (base 131-166 s, xswap 138-161 s): the sparse slot array does not cost more than the zram slot namespace. This usemem run was taken on the previous mm-new snapshot (3d27e49eb905); the series in this posting is on 23cd68262288. The pageout and kernel-build runs reported in v6 exercise the physical backend added by later phases and are not repeated here.

Changes since v6
================

- Rebased onto 23cd68262288 (mm-new, 7.4.0-rc4).

- Patch 1: the struct page array behind a VM_SPARSE area now grows with the mapped range, to a power-of-two capacity, instead of being sized for the whole address space on the first grow; if the allocation fails, the old array is kept. vread_iter() also stops walking the area when nr_pages is zero. (Sashiko)

- Patch 2: rebased over the current zswap store path; the entry is initialized on every store and is put on the writeback LRU only when it can be written back.

- Patch 11: when the allocator cannot find a mapped cluster below the growth threshold, it maps one more chunk and retries once.

- Patch 13: a folio that cannot zswap no longer installs the device it picked in the per-CPU cluster cache, and an xswap-only system fails before walking the allocator.

- The other patches are unchanged.

- The functional matrix, swapoff-name and leak tests were rerun on the 14 patches alone.

Baoquan He (13):
mm/vmalloc: support vmalloc-backed VM_SPARSE areas
mm, swap: refactor free_swap_cluster_info to take swap_info_struct mm, swap: use a VM_SPARSE cluster array for xswap devices mm, swap: widen swap_info_struct max/pages to unsigned long mm, swap: create the xswap device from swapon(2)
mm, swap: refactor swapoff and add xswap_destroy
mm, swap: require zswap for xswap devices
mm, swap: let the command line set the xswap device size mm, swap: add CONFIG_XSWAP_DEFAULT_MAX
mm, swap: add xswap grow trigger on cluster allocation mm, swap: add debugfs counters for xswap
mm, swap: do not give an xswap slot to a cgroup that cannot zswap mm, swap: skip the overcommit probe when removing xswap

Chris Li (1):
mm: xswap support for zswap

 .../admin-guide/kernel-parameters.txt         |    9 +
 include/linux/swap.h                          |   15 +-
 include/linux/vmalloc.h                       |    2 +
 mm/Kconfig                                    |   20 +
 mm/page_io.c                                  |   13 +
 mm/swap_state.c                               |   24 +-
 mm/swapfile.c                                 | 1078 +++++++++++++++--
 mm/vmalloc.c                                  |  171 ++-
 mm/zswap.c                                    |   34 +-
 9 files changed, 1235 insertions(+), 131 deletions(-)

base-commit: 23cd682622886800b912219e307cf46a99f69c10

Signature · 1 line
2.54.0
author reviewer
#1 lore raw

PATCH v7 1/14 mm/vmalloc: support vmalloc-backed VM_SPARSE areas

From: Baoquan He <[email protected]>

VM_SPARSE areas are created with get_vm_area() and filled in by the caller via vm_area_map_pages(), so the caller need to allocate the pages, keep the struct page array and free everything by itself.

Add vm_area_grow_pages() and vm_area_shrink_pages() for VM_SPARSE | VM_ALLOC areas. Pages come from the page allocator and are tracked in area->pages, so the area is released with a single vfree(). The backed pages always start at the beginning of the area: growing maps [nr_pages, end) and shrinking unmaps and frees [end, nr_pages). Callers serialize the two helpers.

nr_pages keeps its existing meaning of "number of backed pages", as with vrealloc() and vread_iter(), and is updated under the vmap node's busy.lock so /proc/vmallocinfo never sees a page that is already gone. Only areas populated through vm_area_map_pages() stay a memory hole. vm_area_map_pages() now rejects VM_ALLOC areas, because vfree() owns their pages, to avoid double frees; free_vm_area() warns for the same combination but not for plain VM_ALLOC areas.

---
 include/linux/vmalloc.h |   2 +
 mm/vmalloc.c            | 171 +++++++++++++++++++++++++++++++++++++---
 2 files changed, 160 insertions(+), 13 deletions(-)
include/linux/vmalloc.h +2 -0
index 034a693777ca..9f40edcddfa8 100644
@@ -296,6 +296,8 @@ int vm_area_map_pages(struct vm_struct *area, unsigned long start,
 		      unsigned long end, struct page **pages);
 void vm_area_unmap_pages(struct vm_struct *area, unsigned long start,
 			 unsigned long end);
+int vm_area_grow_pages(struct vm_struct *area, unsigned long end, gfp_t gfp);
+void vm_area_shrink_pages(struct vm_struct *area, unsigned long end);
 void vunmap_range(unsigned long addr, unsigned long end);
 
 static inline void set_vm_flush_reset_perms(void *addr)
mm/vmalloc.c +158 -13

206 lines not on this page · raw message

Signature · 1 line
2.54.0
#2 lore raw

Re: [PATCH v7 01/14] mm/vmalloc: support vmalloc-backed VM_SPARSE areas

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm/vmalloc: UAF of area->pages in vm_area_grow_pages() under /proc/vmallocinfo --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm/vmalloc: UAF of area->pages in vm_area_grow_pages() under /proc/vmallocinfo
--

commit 2e45495fef5d4025d05ff1c330990787ce60eee4
Author: Baoquan He <[email protected]>

mm/vmalloc: support vmalloc-backed VM_SPARSE areas

This commit introduces vm_area_grow_pages() and vm_area_shrink_pages() to lazily allocate and release backing pages for VM_SPARSE | VM_ALLOC areas.

Quoted 4 lines
mm/vmalloc.c +0 -0
index ee722162da7c9..4a8c35b958bb9 100644

[ ... ]

Quoted 43 lines
mm/vmalloc.c +39 -0
@@ -4174,6 +4176,136 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
 	return NULL;
 }
 
+/**
+ * vm_area_grow_pages - back more of a sparse area with pages
+ * @area: area created with %VM_SPARSE | %VM_ALLOC
+ * @end: end of the range to back, %PAGE_SIZE aligned
+ * @gfp: gfp flags for the page allocation
+ *
+ * Allocate and map pages for [@area->nr_pages << PAGE_SHIFT, @end). The
+ * pages are zeroed when %__GFP_ZERO is set. Pages are always backed from
+ * the start of the area, so a grow only extends that range. An @end that
+ * is already backed is a no-op. On failure nothing is mapped and
+ * @area->nr_pages is unchanged.
+ *
+ * The area must be released with vfree(@area->addr). Callers must
+ * serialize calls to this function.
+ *
+ * Return: 0 on success, -errno on failure.
+ */
+int vm_area_grow_pages(struct vm_struct *area, unsigned long end, gfp_t gfp)
+{
+	unsigned long start = (unsigned long)area->nr_pages << PAGE_SHIFT;
+	unsigned long addr = (unsigned long)area->addr;
+	unsigned long nr_pages, nr_allocated, nr_end, cap;
+	gfp_t nested_gfp = (gfp & GFP_RECLAIM_MASK) | __GFP_ZERO;
+	struct vmap_node *vn;
+	struct page **pages;
+	unsigned int flags;
+	int ret;
+
+	might_sleep();
+
+	if (WARN_ON_ONCE(!(area->flags & VM_ALLOC) ||
+			 !(area->flags & VM_SPARSE)))
+		return -EINVAL;
+	if (WARN_ON_ONCE(!IS_ALIGNED(end, PAGE_SIZE)))
+		return -EINVAL;
+	if (WARN_ON_ONCE(end > get_vm_area_size(area)))
+		return -EINVAL;
+	if (end <= start)
+		return 0;

mm/vmalloc.c static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, · line 4227

Quoted 10 lines
mm/vmalloc.c +10 -0
+	if ((end - start) >> PAGE_SHIFT > totalram_pages())
+		return -E2BIG;
+
+	nr_end = end >> PAGE_SHIFT;
+	cap = roundup_pow_of_two(nr_end);
+	pages = kvrealloc(area->pages, cap * sizeof(*area->pages),
+			  nested_gfp);
+	if (!pages)
+		return -ENOMEM;
+	area->pages = pages;

[Severity: Medium]
Can a concurrent /proc/vmallocinfo reader dereference freed memory in area->pages when a partially backed area grows across a capacity boundary?

Once the first vm_area_grow_pages() sets area->nr_pages, show_busy_info() and show_numa_info() walk area->pages[0 .. area->nr_pages - 1] under vn->busy.lock:

mm/vmalloc.c:show_numa_info() {
    ...
	for (i = 0; i < v->nr_pages; i += step)
		counters[page_to_nid(v->pages[i])] += step;
    ...
}

On a later grow that reallocates the array, kvrealloc() frees the old area->pages buffer via kfree() or vfree() before returning, while area->nr_pages is still non-zero and vn->busy.lock is not held:

CPU0 CPU1
vm_area_grow_pages()
kvrealloc(area->pages, ...)

    /* allocates new buffer */
    /* frees old area->pages */
                                      vmalloc_info_show()
                                        show_busy_info()
                                          spin_lock(&vn->busy.lock)
                                          show_numa_info(m, v)
                                            page_to_nid(v->pages[i])
                                              <-- use-after-free

area->pages = pages;

Allocating the new array separately, copying the existing pointers, swapping area->pages under vn->busy.lock, and only then freeing the old array would avoid freeing area->pages under concurrent readers.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author reviewer
#3 lore raw

PATCH v7 2/14 mm: xswap support for zswap

In reply to Baoquan He

From: Chris Li <[email protected]>

Introduce extendable swap device support - xswap.

An xswap device has no backing storage and no swap data section, so it wastes no disk space. Creation is via swapon(2) with the name "xswap", added in a later patch.

Zswap writeback is gated on whether a real (non-xswap) swap device is active. nr_real_swapfiles counts such devices and is maintained at swapon/swapoff only, so the gate reflects "a device exists to write back to" rather than "a device currently has free slots". This keeps writeback working even when the real swap device is full, and avoids a double decrement when a full device is swapped off.

An xswap entry is not added to the zswap writeback LRU: with no backing store there is nothing to write it back to. zswap_lru_del() tolerates that, since an entry that was never added is on no list.

An incompressible page is stored uncompressed only because it can be written back later, in LRU order. In this phase an xswap entry has no writeback target and never reaches the LRU, so such a page would be pinned in the pool for the lifetime of the entry. Reject it instead, the same way a writeback-disabled memcg is handled. A later phase gives xswap a physical backend, and the test becomes "this device has a writeback target".

A VMA readahead walks the page table and can reach an entry on another device. Skip an xswap device there: its entries live only in zswap, so there is no IO to read ahead and a speculative read would take the entry out of zswap.

An xswap entry is kept out of the zswap writeback LRU but still counts towards the pool size. With memcg disabled the shrinker walks the root LRU, finds no entry it can write back and is told -ENOENT without counting a failure, so the accept-threshold loop would spin. Count that as a failure; the worker then stops after its retry budget.

---
 include/linux/swap.h |  2 ++
 mm/page_io.c         | 13 +++++++++++++
 mm/swap_state.c      | 24 +++++++++++++++++++-----
 mm/swapfile.c        | 34 ++++++++++++++++++++++++++++------
 mm/zswap.c           | 34 +++++++++++++++++++++++++++-------
 5 files changed, 89 insertions(+), 18 deletions(-)
include/linux/swap.h +2 -0
index a3a98dc474c3..9b73a038e542 100644
@@ -201,6 +201,7 @@ enum {
 	SWP_STABLE_WRITES = (1 << 11),	/* no overwrite PG_writeback pages */
 	SWP_SYNCHRONOUS_IO = (1 << 12),	/* synchronous IO is efficient */
 	SWP_HIBERNATION = (1 << 13),	/* pinned for hibernation */
+	SWP_XSWAP	= (1 << 14),	/* extendable swap device */
 					/* add others here before... */
 };
 
@@ -378,6 +379,7 @@ void free_folio_and_swap_cache(struct folio *folio);
 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 long total_swap_pages;
 extern atomic_t nr_rotate_swap;
 
mm/page_io.c +13 -0
index a57cdcf2892d..4b541c50cd59 100644
@@ -258,6 +258,12 @@ 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. */
+	if (unlikely(__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP)) {
+		folio_mark_dirty(folio);
+		return AOP_WRITEPAGE_ACTIVATE;
+	}
+
 	__swap_writeout(ctx, folio);
 	return 0;
 out_unlock:
@@ -515,6 +521,13 @@ 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. */
+		WARN_ON_ONCE(1);
+		folio_unlock(folio);
+		return;
+	}
+
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
 	swap_add_folio(ctx, folio, READ);
mm/swap_state.c +19 -5
index da65d75ceead..90cd99c25dfe 100644
@@ -899,6 +899,10 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 	struct blk_plug plug;
 	swp_entry_t ra_entry;
 
+	/* xswap entries live only in zswap; readahead does not help. */
+	if (si->flags & SWP_XSWAP)
+		goto skip;
+
 	mask = swapin_nr_pages(offset) - 1;
 	if (!mask)
 		goto skip;
@@ -984,6 +988,7 @@ static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
 {
+	struct swap_info_struct *si = __swap_entry_to_info(targ_entry);
 	struct swap_io_ctx ctx = {};
 	struct blk_plug plug;
 	struct folio *folio;
@@ -992,6 +997,10 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 	unsigned long start, end, addr;
 	pgoff_t ilx = targ_ilx;
 
+	/* xswap entries live only in zswap; readahead does not help. */
+	if (si->flags & SWP_XSWAP)
+		goto skip;
+
 	win = swap_vma_ra_win(vmf, &start, &end);
 	if (win == 1)
 		goto skip;
@@ -1000,7 +1009,7 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 
 	blk_start_plug(&plug);
 	for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) {
-		struct swap_info_struct *si = NULL;
+		struct swap_info_struct *entry_si = NULL;
 		softleaf_t entry;
 
 		if (!pte++) {
@@ -1020,14 +1029,19 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 		 * holding a reference to, try to grab a reference, or skip.
 		 */
 		if (swp_type(entry) != swp_type(targ_entry)) {
-			si = get_swap_device(entry);
-			if (IS_ERR_OR_NULL(si))
+			entry_si = get_swap_device(entry);
+			if (IS_ERR_OR_NULL(entry_si))
+				continue;
+			/* An xswap entry lives only in zswap; there is no IO. */
+			if (entry_si->flags & SWP_XSWAP) {
+				put_swap_device(entry_si);
 				continue;
+			}
 		}
 		folio = swap_cache_read_folio(&ctx, entry, gfp_mask, mpol, ilx,
 					      addr != vmf->address);
-		if (si)
-			put_swap_device(si);
+		if (entry_si)
+			put_swap_device(entry_si);
 		if (!folio)
 			continue;
 		folio_put(folio);
mm/swapfile.c +28 -6
index d59fa8220862..558c4b75bf92 100644
@@ -66,6 +66,7 @@ static void move_cluster(struct swap_info_struct *si,
 static DEFINE_SPINLOCK(swap_lock);
 static unsigned int nr_swapfiles;
 atomic_long_t nr_swap_pages;
+atomic_t nr_real_swapfiles;
 /*
  * 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
@@ -775,7 +776,8 @@ static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info *
 	/*
 	 * If the swap is discardable, prepare discard the cluster
 	 * instead of free it immediately. The cluster will be freed
-	 * after discard.
+	 * after discard.  xswap has no bdev and never sets
+	 * SWP_PAGE_DISCARD, so it always takes the free path below.
 	 */
 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
@@ -1277,6 +1279,9 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)
 		 */
 		lockdep_assert_held(&si->lock);
 		si->flags &= ~SWP_WRITEOK;
+		/* Count active devices, not merely those on the avail list. */
+		if (!(si->flags & SWP_XSWAP))
+			atomic_sub(1, &nr_real_swapfiles);
 		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 	} else {
 		/*
@@ -1310,6 +1315,9 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	if (swapon) {
 		lockdep_assert_held(&si->lock);
 		si->flags |= SWP_WRITEOK;
+		/* A full device is still active and skips the add below. */
+		if (!(si->flags & SWP_XSWAP))
+			atomic_add(1, &nr_real_swapfiles);
 	} else {
 		if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
 			goto skip;
@@ -1323,10 +1331,11 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	/*
 	 * When device is full and device is on the plist, only one updater will
 	 * see (inuse_pages == si->pages) and will call del_from_avail_list. If
-	 * that updater happen to be here, just skip adding.
+	 * that updater happen to be here, just skip adding.  @val still has
+	 * the off-list bit, so compare its counter part.
 	 */
 	pages = si->pages;
-	if (val == pages) {
+	if ((val & SWAP_USAGE_COUNTER_MASK) == pages) {
 		/* Just like the cmpxchg in del_from_avail_list */
 		if (atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
 					    pages | SWAP_USAGE_OFFLIST_BIT))
@@ -3330,7 +3339,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	destroy_swap_extents(p, p->swap_file);
 
-	if (!(p->flags & SWP_SOLIDSTATE))
+	if (!(p->flags & SWP_XSWAP) &&
+	    !(p->flags & SWP_SOLIDSTATE))
 		atomic_dec(&nr_rotate_swap);
 
 	mutex_lock(&swapon_mutex);
@@ -3440,6 +3450,19 @@ static void swap_stop(struct seq_file *swap, void *v)
 	mutex_unlock(&swapon_mutex);
 }
 
+static const char *swap_type_str(struct swap_info_struct *si)
+{
+	struct file *file = si->swap_file;
+
+	if (si->flags & SWP_XSWAP)
+		return "xswap\t";
+
+	if (S_ISBLK(file_inode(file)->i_mode))
+		return "partition";
+
+	return "file\t";
+}
+
 static int swap_show(struct seq_file *swap, void *v)
 {
 	struct swap_info_struct *si = v;
@@ -3459,8 +3482,7 @@ static int swap_show(struct seq_file *swap, void *v)
 	len = seq_file_path(swap, file, " \t\n\\");
 	seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
 			len < 40 ? 40 - len : 1, " ",
-			S_ISBLK(file_inode(file)->i_mode) ?
-				"partition" : "file\t",
+			swap_type_str(si),
 			bytes, bytes < 10000000 ? "\t" : "",
 			inuse, inuse < 10000000 ? "\t" : "",
 			si->prio);
mm/zswap.c +27 -7
index 6a66b898ab47..52f350b2c452 100644
@@ -885,7 +885,8 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node)
 }
 
 static bool zswap_compress(struct folio *folio, long index,
-			   struct zswap_entry *entry, struct zswap_pool *pool)
+			   struct zswap_entry *entry, struct zswap_pool *pool,
+			   bool can_writeback)
 {
 	struct zswap_comp_ctx *comp_ctx;
 	struct scatterlist input, output;
@@ -934,9 +935,13 @@ 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.
+	 * 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.
 	 */
 	if (comp_ret) {
+		if (!can_writeback)
+			goto unlock;
 		rcu_read_lock();
 		if (!mem_cgroup_zswap_writeback_enabled(folio_memcg(folio))) {
 			rcu_read_unlock();
@@ -1093,6 +1098,11 @@ 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;
+	}
+
 	mpol = get_task_policy(current);
 	folio = __swap_cache_alloc_folio(swpentry, GFP_KERNEL, BIT(0), NULL, mpol,
 					 NO_INTERLEAVE_INDEX);
@@ -1508,10 +1518,15 @@ static void shrink_worker(struct work_struct *w)
 		 * There are no writeback-candidate pages in the memcg.
 		 * This is not an issue as long as we can find another memcg
 		 * with pages in zswap. Skip this without incrementing attempts
-		 * and failures.
+		 * and failures.  With memcg disabled there is no other memcg,
+		 * so an empty walk is the last one and has to count.
 		 */
-		if (ret == -ENOENT)
+		if (ret == -ENOENT) {
+			if (mem_cgroup_disabled() &&
+			    ++failures == MAX_RECLAIM_RETRIES)
+				break;
 			goto resched;
+		}
 		++attempts;
 
 		if (ret && ++failures == MAX_RECLAIM_RETRIES)
@@ -1531,6 +1546,7 @@ static bool zswap_store_page(struct folio *folio, long index,
 {
 	swp_entry_t page_swpentry = folio_swap_entry(folio, index);
 	struct zswap_entry *entry, *old;
+	bool can_writeback;
 
 	/* allocate entry */
 	entry = zswap_entry_cache_alloc(GFP_KERNEL, folio_nid(folio));
@@ -1539,7 +1555,10 @@ static bool zswap_store_page(struct folio *folio, long index,
 		return false;
 	}
 
-	if (!zswap_compress(folio, index, entry, pool))
+	/* In this phase xswap has no device to write the page back to. */
+	can_writeback = !(__swap_entry_to_info(page_swpentry)->flags & SWP_XSWAP);
+
+	if (!zswap_compress(folio, index, entry, pool, can_writeback))
 		goto compress_failed;
 
 	/*
@@ -1598,7 +1617,8 @@ static bool zswap_store_page(struct folio *folio, long index,
 	entry->objcg = objcg;
 	entry->referenced = true;
 	INIT_LIST_HEAD(&entry->lru);
-	zswap_lru_add(entry);
+	if (can_writeback)
+		zswap_lru_add(entry);
 
 	return true;
 
@@ -1667,7 +1687,7 @@ bool zswap_store(struct folio *folio)
 	zswap_pool_put(pool);
 put_objcg:
 	obj_cgroup_put(objcg);
-	if (!ret && zswap_pool_reached_full)
+	if (!ret && zswap_pool_reached_full && atomic_read(&nr_real_swapfiles))
 		queue_work(shrink_wq, &zswap_shrink_work);
 check_old:
 	/*
Signature · 1 line
2.54.0
author reviewer
#4 lore raw

PATCH v7 3/14 mm, swap: refactor free_swap_cluster_info to take swap_info_struct

In reply to Baoquan He

From: Baoquan He <[email protected]>

Change free_swap_cluster_info() to take struct swap_info_struct* instead of (cluster_info, maxpages). It now extracts the fields from si and clears si->cluster_info after freeing to avoid a double free on the swapon() error path.

The new parameter also lets the xswap path access si->flags in the function.

---
 mm/swapfile.c | 26 ++++++++++++++------------
 1 file changed, 14 insertions(+), 12 deletions(-)
mm/swapfile.c +14 -12
index 558c4b75bf92..35a079f2bb76 100644
@@ -3208,14 +3208,17 @@ static void wait_for_allocation(struct swap_info_struct *si)
 	}
 }
 
-static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
-				   unsigned long maxpages)
+static void free_swap_cluster_info(struct swap_info_struct *si)
 {
+	struct swap_cluster_info *cluster_info = si->cluster_info;
+	unsigned long maxpages = si->max;
 	struct swap_cluster_info *ci;
-	int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
+	int i, nr_clusters;
 
 	if (!cluster_info)
 		return;
+
+	nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 	for (i = 0; i < nr_clusters; i++) {
 		ci = cluster_info + i;
 		/* Cluster with bad marks count will have a remaining table */
@@ -3227,6 +3230,7 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
 		spin_unlock(&ci->lock);
 	}
 	kvfree(cluster_info);
+	si->cluster_info = NULL;
 }
 
 /*
@@ -3254,11 +3258,9 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 {
 	struct swap_info_struct *p = NULL;
-	struct swap_cluster_info *cluster_info;
 	struct file *swap_file, *victim;
 	struct address_space *mapping;
 	struct inode *inode;
-	unsigned int maxpages;
 	int err, found = 0;
 
 	if (!capable(CAP_SYS_ADMIN))
@@ -3350,10 +3352,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	swap_file = p->swap_file;
 	p->swap_file = NULL;
-	maxpages = p->max;
-	cluster_info = p->cluster_info;
-	p->max = 0;
-	p->cluster_info = NULL;
 	spin_unlock(&p->lock);
 	spin_unlock(&swap_lock);
 	arch_swap_invalidate_area(p->type);
@@ -3361,7 +3359,9 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	mutex_unlock(&swapon_mutex);
 	kfree(p->global_cluster);
 	p->global_cluster = NULL;
-	free_swap_cluster_info(cluster_info, maxpages);
+	free_swap_cluster_info(p);
+	p->max = 0;
+	p->cluster_info = NULL;
 
 	inode = mapping->host;
 
@@ -3728,6 +3728,8 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	if (!cluster_info)
 		goto err;
 
+	si->cluster_info = cluster_info;
+
 	for (i = 0; i < nr_clusters; i++)
 		spin_lock_init(&cluster_info[i].lock);
 
@@ -3791,7 +3793,7 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	si->cluster_info = cluster_info;
 	return 0;
 err:
-	free_swap_cluster_info(cluster_info, maxpages);
+	free_swap_cluster_info(si);
 	return err;
 }
 
@@ -4013,7 +4015,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	si->global_cluster = NULL;
 	inode = NULL;
 	destroy_swap_extents(si, swap_file);
-	free_swap_cluster_info(si->cluster_info, si->max);
+	free_swap_cluster_info(si);
 	si->cluster_info = NULL;
 	/*
 	 * Clear the SWP_USED flag after all resources are freed so
Signature · 1 line
2.54.0
author reviewer
#5 lore raw

PATCH v7 4/14 mm, swap: use a VM_SPARSE cluster array for xswap devices

In reply to Baoquan He

From: Baoquan He <[email protected]>

Add CONFIG_XSWAP and the per-device state for the sparse cluster array.

An xswap device does not have to allocate cluster_info for its whole address space at once. Create the array as a VM_SPARSE | VM_ALLOC area, which reserves the whole range but lets vmalloc allocate and track the backing pages, and map only the first chunk at setup. The map helper extends the mapped range as clusters become visible, and a failed grow leaves the previous backing in place.

Setup, free and the two cluster_info scans must change together; free uses vfree(), which drops the mapping and the pages together.

---
 include/linux/swap.h |   6 ++
 mm/Kconfig           |   9 ++
 mm/swapfile.c        | 203 +++++++++++++++++++++++++++++++++++++++++--
 3 files changed, 209 insertions(+), 9 deletions(-)
include/linux/swap.h +6 -0
index 9b73a038e542..3b4fd8e9781c 100644
@@ -242,6 +242,12 @@ struct swap_info_struct {
 	signed char	type;		/* strange name for an index */
 	unsigned int	max;		/* size of this swap device */
 	struct swap_cluster_info *cluster_info; /* array, one entry per cluster */
+#ifdef CONFIG_XSWAP
+	struct vm_struct	*cluster_vm;	/* VM_SPARSE | VM_ALLOC area */
+	unsigned long		nr_clusters_max;/* total clusters in the xswap address space */
+	unsigned long		nr_clusters_mapped; /* currently mapped cluster count */
+	struct mutex		xswap_lock;	/* serialize map/unmap operations */
+#endif
 	struct list_head free_clusters; /* free clusters list */
 	struct list_head full_clusters; /* full clusters list */
 	struct list_head nonfull_clusters[SWAP_NR_ORDERS];
mm/Kconfig +9 -0
index 18925ccb4adc..d238a4971b1e 100644
@@ -122,6 +122,15 @@ config ZSWAP_COMPRESSOR_DEFAULT
        default "zstd" if ZSWAP_COMPRESSOR_DEFAULT_ZSTD
        default ""
 
+config XSWAP
+	bool "Extendable (virtual) swap device"
+	depends on SWAP && 64BIT && ZSWAP
+	help
+	  Adds support for extendable swap devices (xswap) that decouple
+	  PTE swap entries from physical backing storage. The cluster_info
+	  array is backed by a sparse vmalloc area that is mapped lazily
+	  in chunks, avoiding static pre-allocation overhead.
+
 config ZSMALLOC
 	tristate
 
mm/swapfile.c +194 -9

276 lines not on this page · raw message

Signature · 1 line
2.54.0
author reviewer
#6 lore raw

PATCH v7 5/14 mm, swap: widen swap_info_struct max/pages to unsigned long

In reply to Baoquan He

From: Baoquan He <[email protected]>

si->max and si->pages are unsigned int. With 4 KiB pages, this limits an xswap device to 16 TB, and xswap may need a larger address space. Change both fields to unsigned long, together with the offsets and indexes that carry them.

A real swap device is still limited by swap_header.info.last_page, which is __u32, so this only widens the xswap address space. The old overflow clamp in read_swap_header() is no longer needed; the header check still limits real devices.

count_swap_pages() returns unsigned int and is only used by hibernation, which never selects an xswap device. If that ever changes, WARN and return 0 instead of silently truncating the value.

---
 include/linux/swap.h |  4 ++--
 mm/swapfile.c        | 57 +++++++++++++++++++++++---------------------
 2 files changed, 32 insertions(+), 29 deletions(-)
include/linux/swap.h +2 -2
index 3b4fd8e9781c..b01f5661b450 100644
@@ -240,7 +240,7 @@ struct swap_info_struct {
 	signed short	prio;		/* swap priority of this type */
 	struct plist_node list;		/* entry in swap_active_head */
 	signed char	type;		/* strange name for an index */
-	unsigned int	max;		/* size of this swap device */
+	unsigned long	max;		/* size of this swap device */
 	struct swap_cluster_info *cluster_info; /* array, one entry per cluster */
 #ifdef CONFIG_XSWAP
 	struct vm_struct	*cluster_vm;	/* VM_SPARSE | VM_ALLOC area */
@@ -254,7 +254,7 @@ struct swap_info_struct {
 					/* list of cluster that contains at least one free slot */
 	struct list_head frag_clusters[SWAP_NR_ORDERS];
 					/* list of cluster that are fragmented or contented */
-	unsigned int pages;		/* total of usable pages of swap */
+	unsigned long pages;		/* total of usable pages of swap */
 	atomic_long_t inuse_pages;	/* number of those currently in use */
 	struct swap_sequential_cluster *global_cluster; /* Use one global cluster for rotating device */
 	spinlock_t global_cluster_lock;	/* Serialize usage of global cluster */
mm/swapfile.c +30 -27

127 lines not on this page · raw message

Signature · 1 line
2.54.0
author reviewer
#7 lore raw

PATCH v7 6/14 mm, swap: create the xswap device from swapon(2)

In reply to Baoquan He

From: Baoquan He <[email protected]>

An xswap device has no backing file, so it has no path for swapon(2) to open, and it needs a way to be activated. Give swapon(2) a name that says exactly that:

	swapon("xswap", SWAP_FLAG_PREFER | prio);

The name is not a path: swapon(2) opens specialfile the usual way first and falls back to the device only when that fails with -ENOENT. A file or directory called "xswap" therefore keeps precedence, and only the exact string matches, so "./xswap" and absolute paths are files as usual. This is the same rule swapoff(2) uses. There is no separate flag and no second way to create it.

The call is still an activation: it takes a priority, it fails with -EBUSY when the device exists, and /proc/swaps shows it as the fixed "xswap" next to the real devices. Discard flags are rejected: there is no storage to discard.

The device is sized at twice RAM, and its cluster array is mapped lazily, so only the part that is used costs memory.

Hibernation device discovery skips xswap devices: there is no bdev to store a resume image.

---
 include/linux/swap.h |   1 -
 mm/swapfile.c        | 187 +++++++++++++++++++++++++++++++++++++++----
 2 files changed, 172 insertions(+), 16 deletions(-)
include/linux/swap.h +0 -1
index b01f5661b450..ba1bf7e09893 100644
@@ -21,7 +21,6 @@
 #define SWAP_FLAG_DISCARD	0x10000 /* enable discard for swap */
 #define SWAP_FLAG_DISCARD_ONCE	0x20000 /* discard swap area at swapon-time */
 #define SWAP_FLAG_DISCARD_PAGES 0x40000 /* discard page-clusters after use */
-
 #define SWAP_FLAGS_VALID	(SWAP_FLAG_PRIO_MASK | SWAP_FLAG_PREFER | \
 				 SWAP_FLAG_DISCARD | SWAP_FLAG_DISCARD_ONCE | \
 				 SWAP_FLAG_DISCARD_PAGES)
mm/swapfile.c +172 -15

270 lines not on this page · raw message

Signature · 1 line
2.54.0
#8 lore raw

Re: [PATCH v7 06/14] mm, swap: create the xswap device from swapon(2)

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm, swap: xswap_create() breaks large-folio swapout by omitting SWP_BLKDEV --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm, swap: xswap_create() breaks large-folio swapout by omitting SWP_BLKDEV
--

commit 282f185a2ad0b754fef5ebdb7c9c3e00cfa24f2b
Author: Baoquan He <[email protected]>

mm, swap: create the xswap device from swapon(2)

This commit adds support for activating a file-less xswap device via swapon("xswap", ...), sized at twice RAM with lazily mapped clusters.

Quoted 4 lines
mm/swapfile.c +0 -0
index 912cfa68ba01a..4e598ab8da656 100644

[ ... ]

Quoted 43 lines
mm/swapfile.c +39 -0
@@ -3985,6 +4021,117 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	return err;
 }
 
+#ifdef CONFIG_XSWAP
+/*
+ * Create the file-less xswap device, sized at twice RAM.  Called from
+ * swapon(2) with SWAP_FLAG_XSWAP; there is at most one device per system.
+ */
+static int xswap_create(int prio)
+{
+	struct swap_info_struct *si;
+	unsigned long ram, maxpages;
+	unsigned int type;
+	int error;
+
+	mutex_lock(&xswap_ctl_lock);
+
+	spin_lock(&swap_lock);
+	for (type = 0; type < nr_swapfiles; type++) {
+		struct swap_info_struct *q = swap_info[type];
+
+		if (q && (q->flags & SWP_XSWAP)) {
+			spin_unlock(&swap_lock);
+			error = -EBUSY;
+			goto out;
+		}
+	}
+	spin_unlock(&swap_lock);
+
+	si = alloc_swap_info();
+	if (IS_ERR(si)) {
+		error = PTR_ERR(si);
+		goto out;
+	}
+
+	INIT_WORK(&si->discard_work, swap_discard_work);
+	INIT_WORK(&si->reclaim_work, swap_reclaim_work);
+
+	ram = totalram_pages();
+	maxpages = min_t(unsigned long, ram * 2, swapfile_maximum_size);
+	/* A cluster index is an unsigned int, so cap the cluster count. */
+	if (maxpages / SWAPFILE_CLUSTER > UINT_MAX)

mm/swapfile.c static int setup_swap_clusters_info(struct swap_info_struct *si, · line 4072

Quoted 10 lines
mm/swapfile.c +10 -0
+		maxpages = (unsigned long)UINT_MAX * SWAPFILE_CLUSTER;
+	/* Cluster-aligned, so no cluster holds a slot past si->max. */
+	if (maxpages > SWAPFILE_CLUSTER)
+		maxpages = rounddown(maxpages, SWAPFILE_CLUSTER);
+	if (maxpages < 2)
+		maxpages = 2;
+
+	si->bdev = NULL;
+	si->swap_file = NULL;
+	si->flags |= SWP_XSWAP | SWP_SOLIDSTATE;

[Severity: Medium]
Does leaving SWP_BLKDEV unset on the xswap device break large-folio swapout across the system once xswap is activated?

cluster_alloc_swap_entry() rejects order > 0 allocations unless SWP_BLKDEV is set:

mm/swapfile.c:cluster_alloc_swap_entry() {
    ...
	if (order && !(si->flags & SWP_BLKDEV))
		return 0;
    ...
}

Because xswap defaults to DEF_XSWAP_PRIO (0x7fff), it sits at the head of swap_avail_head. When swap_alloc_slow() tries the xswap device first for a large folio, cluster_alloc_swap_entry() fails and swap_alloc_slow() immediately returns on folio_test_large(folio) without trying any lower-priority SWP_BLKDEV devices:

mm/swapfile.c:swap_alloc_slow() {
    ...
		if (get_swap_device_info(si)) {
			cluster_alloc_swap_entry(si, folio);
			put_swap_device(si);
			if (folio_test_swapcache(folio))
				return;
			if (folio_test_large(folio))
				return;
		}
    ...
}

As a result, folio_alloc_swap() fails with -E2BIG for every large folio, forcing reclaim to split all large folios into order-0 pages on swapout. Should cluster_alloc_swap_entry() also allow SWP_XSWAP (e.g. checking !(si->flags & (SWP_BLKDEV | SWP_XSWAP)))?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author reviewer
#9 lore raw

PATCH v7 7/14 mm, swap: refactor swapoff and add xswap_destroy

In reply to Baoquan He

From: Baoquan He <[email protected]>

Extract __swapoff() from sys_swapoff() so the teardown logic can be shared, and make it work for file-less devices.

Add xswap_destroy(), reached through the name /proc/swaps prints. "xswap" is not a path, so the name cannot be opened, and "swapoff -a" passes it back unchanged.

A real file or directory keeps precedence: only a name that cannot be opened (-ENOENT) is taken for the device, so a plain file is never mistaken for it. The name is compared with strcmp() against the one name the kernel prints, so there is no parsing.

Destroy is serialized with create by xswap_ctl_lock, and it refuses a device that is pinned for hibernation.

---
 mm/swapfile.c | 148 +++++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 127 insertions(+), 21 deletions(-)
mm/swapfile.c +127 -21
index 4e598ab8da65..1f319e365b68 100644
@@ -69,6 +69,8 @@
 
 static int xswap_create(int prio);
 static int xswap_create_by_name(const char *name, int swap_flags);
+static int xswap_destroy(void);
+static int xswap_destroy_by_name(const char *name);
 
 /* Serializes create and destroy: at most one xswap device exists. */
 static DEFINE_MUTEX(xswap_ctl_lock);
@@ -77,6 +79,11 @@ static inline int xswap_create_by_name(const char *name, int swap_flags)
 {
 	return -ENOENT;
 }
+
+static inline int xswap_destroy_by_name(const char *name)
+{
+	return -ENOENT;
+}
 #endif /* CONFIG_XSWAP */
 
 static void swap_range_alloc(struct swap_info_struct *si,
@@ -3360,13 +3367,14 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 	}
 }
 
+static int swap_info_remove(struct swap_info_struct *p);
+static int __swapoff(struct swap_info_struct *p);
 
 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 {
 	struct swap_info_struct *p = NULL;
-	struct file *swap_file, *victim;
+	struct file *victim;
 	struct address_space *mapping;
-	struct inode *inode;
 	int err, found = 0;
 
 	if (!capable(CAP_SYS_ADMIN))
@@ -3375,15 +3383,30 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	BUG_ON(!current->mm);
 
 	CLASS(filename, pathname)(specialfile);
+	if (IS_ERR(pathname))
+		return PTR_ERR(pathname);
+
 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
-	if (IS_ERR(victim))
-		return PTR_ERR(victim);
+	if (IS_ERR(victim)) {
+		/*
+		 * /proc/swaps shows a name that cannot be opened; accept it
+		 * so swapoff -a works.  Only -ENOENT means "no such path",
+		 * so a file of that name keeps precedence.
+		 */
+		if (PTR_ERR(victim) != -ENOENT)
+			return PTR_ERR(victim);
+
+		err = xswap_destroy_by_name(pathname->name);
+		if (err == -ENOENT)
+			return PTR_ERR(victim);
+		return err;
+	}
 
 	mapping = victim->f_mapping;
 	spin_lock(&swap_lock);
 	plist_for_each_entry(p, &swap_active_head, list) {
 		if (p->flags & SWP_WRITEOK) {
-			if (p->swap_file->f_mapping == mapping) {
+			if (p->swap_file && p->swap_file->f_mapping == mapping) {
 				found = 1;
 				break;
 			}
@@ -3402,20 +3425,50 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 		goto out_dput;
 	}
 
-	if (!security_vm_enough_memory_mm(current->mm, p->pages))
-		vm_unacct_memory(p->pages);
-	else {
-		err = -ENOMEM;
+	err = swap_info_remove(p);
+	if (err) {
 		spin_unlock(&swap_lock);
 		goto out_dput;
 	}
+	spin_unlock(&swap_lock);
+
+	err = __swapoff(p);
+
+out_dput:
+	filp_close(victim, NULL);
+	return err;
+}
+
+/*
+ * Drop @p from the avail and active lists and undo its accounting.  The
+ * caller must hold swap_lock and have checked that @p is WRITEOK and not
+ * pinned for hibernation.
+ *
+ * Returns 0, or -ENOMEM with swap_lock still held.
+ */
+static int swap_info_remove(struct swap_info_struct *p)
+{
+	if (!security_vm_enough_memory_mm(current->mm, p->pages))
+		vm_unacct_memory(p->pages);
+	else
+		return -ENOMEM;
+
 	spin_lock(&p->lock);
 	del_from_avail_list(p, true);
 	plist_del(&p->list, &swap_active_head);
 	atomic_long_sub(p->pages, &nr_swap_pages);
 	total_swap_pages -= p->pages;
 	spin_unlock(&p->lock);
-	spin_unlock(&swap_lock);
+	return 0;
+}
+
+/* Common swap teardown after list removal; shared by sys_swapoff() and
+ * xswap_destroy().
+ */
+static int __swapoff(struct swap_info_struct *p)
+{
+	struct file *swap_file = NULL;
+	int err;
 
 	wait_for_allocation(p);
 
@@ -3426,7 +3479,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	if (err) {
 		/* re-insert swap space back into swap_list */
 		reinsert_swap_info(p);
-		goto out_dput;
+		return err;
 	}
 
 	/*
@@ -3466,15 +3519,21 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	kfree(p->global_cluster);
 	p->global_cluster = NULL;
 	free_swap_cluster_info(p);
+	/*
+	 * The device is off swap_active_head and no longer WRITEOK, so no
+	 * reader can observe these; clearing them here needs no lock.
+	 */
 	p->max = 0;
 	p->cluster_info = NULL;
 
-	inode = mapping->host;
+	if (swap_file) {
+		struct inode *inode = swap_file->f_mapping->host;
 
-	inode_lock(inode);
-	inode->i_flags &= ~S_SWAPFILE;
-	inode_unlock(inode);
-	filp_close(swap_file, NULL);
+		inode_lock(inode);
+		inode->i_flags &= ~S_SWAPFILE;
+		inode_unlock(inode);
+		filp_close(swap_file, NULL);
+	}
 
 	/*
 	 * Clear the SWP_USED flag after all resources are freed so that swapon
@@ -3485,13 +3544,10 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	p->flags = 0;
 	spin_unlock(&swap_lock);
 
-	err = 0;
 	atomic_inc(&proc_poll_event);
 	wake_up_interruptible(&proc_poll_wait);
 
-out_dput:
-	filp_close(victim, NULL);
-	return err;
+	return 0;
 }
 
 #ifdef CONFIG_PROC_FS
@@ -4114,7 +4170,57 @@ static int xswap_create(int prio)
 	goto out;
 }
 
-/* A name, not a path: only -ENOENT from opening it gets here. */
+/* Tear down the file-less xswap device. */
+static int xswap_destroy(void)
+{
+	struct swap_info_struct *p = NULL;
+	unsigned int type;
+	int err;
+
+	mutex_lock(&xswap_ctl_lock);
+
+	spin_lock(&swap_lock);
+	/* Only a fully enabled device; a half-created one does not count. */
+	for (type = 0; type < nr_swapfiles; type++) {
+		struct swap_info_struct *q = swap_info[type];
+
+		if (q && (q->flags & (SWP_XSWAP | SWP_WRITEOK)) ==
+			 (SWP_XSWAP | SWP_WRITEOK)) {
+			p = q;
+			break;
+		}
+	}
+	if (!p) {
+		spin_unlock(&swap_lock);
+		err = -ENOENT;
+		goto out;
+	}
+	/* Refuse swapoff while the device is pinned for hibernation */
+	if (p->flags & SWP_HIBERNATION) {
+		spin_unlock(&swap_lock);
+		err = -EBUSY;
+		goto out;
+	}
+
+	err = swap_info_remove(p);
+	spin_unlock(&swap_lock);
+	if (!err)
+		err = __swapoff(p);
+out:
+	mutex_unlock(&xswap_ctl_lock);
+	return err;
+}
+
+/* /proc/swaps shows XSWAP_NAME; accept it so swapoff -a works. */
+static int xswap_destroy_by_name(const char *name)
+{
+	if (strcmp(name, XSWAP_NAME))
+		return -ENOENT;
+
+	return xswap_destroy();
+}
+
+/* The swapon counterpart of xswap_destroy_by_name(). */
 static int xswap_create_by_name(const char *name, int swap_flags)
 {
 	int prio = DEF_XSWAP_PRIO;
Signature · 1 line
2.54.0
author reviewer
#10 lore raw

PATCH v7 8/14 mm, swap: require zswap for xswap devices

In reply to Baoquan He

From: Baoquan He <[email protected]>

xswap pages live only in zswap. Without zswap, swapout cannot free the page, but still takes a swap entry. So the device consumes swap entries without freeing memory. Fail to create a device when zswap is unavailable.

---
 mm/swapfile.c | 4 ++++
 1 file changed, 4 insertions(+)
mm/swapfile.c +4 -0
index 1f319e365b68..ba899e349e99 100644
@@ -4089,6 +4089,10 @@ static int xswap_create(int prio)
 	unsigned int type;
 	int error;
 
+	/* xswap has no backing store, it relies on zswap. */
+	if (!zswap_is_enabled())
+		return -EOPNOTSUPP;
+
 	mutex_lock(&xswap_ctl_lock);
 
 	spin_lock(&swap_lock);
Signature · 1 line
2.54.0
author reviewer
#11 lore raw

PATCH v7 9/14 mm, swap: let the command line set the xswap device size

In reply to Baoquan He

From: Baoquan He <[email protected]>

By default, a new xswap device is 200% of RAM, which is twice RAM. Add xswap.max= to set the size of devices created after it:

  xswap.max=300%      three times RAM
  xswap.max=8G        eight GiB
  xswap.max=max       the largest size the device can address

The default is fine for most users. But a machine with a lot of RAM and a small working set can get a SwapTotal much larger than it needs.

The size is resolved at device creation, not at parameter parsing, because a percentage depends on RAM, which is not known yet when the parameters are parsed.

An explicit size that is too large or overflows is refused; the default is clamped instead. A size below one cluster is also refused.

---
 .../admin-guide/kernel-parameters.txt         |   7 +
 mm/swapfile.c                                 | 135 ++++++++++++++++--
 2 files changed, 130 insertions(+), 12 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +7 -0
index dce9b8f3ae98..2b0fc585e0c7 100644
@@ -8734,3 +8734,10 @@ Kernel parameters
 				memory, and other data can't be written using
 				xmon commands.
 			off	xmon is disabled.
+
+	xswap.max=	[KNL,SWAP]
+			Maximum size of a new xswap device. The value is a
+			size in bytes with an optional KMGTPE suffix, a
+			percentage of RAM, or "max" for the largest size
+			the device can address.
+			Format: <size>[KMGTPE] | <percent>% | max
mm/swapfile.c +123 -12

170 lines not on this page · raw message

Signature · 1 line
2.54.0
#12 lore raw

Re: [PATCH v7 09/14] mm, swap: let the command line set the xswap device size

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm, swap: multi-GiB eager zswap allocation in xswap_create() on xswap.max=max --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm, swap: multi-GiB eager zswap allocation in xswap_create() on xswap.max=max
--

commit 907eeff02d0e504aa197c941cec5a5a165686a5e
Author: Baoquan He <[email protected]>

mm, swap: let the command line set the xswap device size

This commit adds the xswap.max= kernel command-line parameter to configure the size of new xswap devices as a percentage of RAM, a byte size, or "max".

Quoted 4 lines
mm/swapfile.c +0 -0
index ba899e349e992..6ce5dbb3b1035 100644

[ ... ]

Quoted 12 lines
mm/swapfile.c +12 -0
+/*
+ * The most a device can address, whatever xswap.max= asked for.  An xswap
+ * slot is still a swap entry, so the swap offset limit applies even though
+ * the data never goes through a physical address.
+ */
+static unsigned long xswap_size_limit(void)
+{
+	unsigned long limit = swapfile_maximum_size;
+
+	/* A cluster index is an unsigned int. */
+	if (limit / SWAPFILE_CLUSTER > UINT_MAX)
+		limit = (unsigned long)UINT_MAX * SWAPFILE_CLUSTER;

mm/swapfile.c static int xswap_destroy_by_name(const char *name); · line 161

Quoted 10 lines
mm/swapfile.c +10 -0
+
+	return limit;
+}
+
+static unsigned long xswap_size_pages(void)
+{
+	unsigned long long pages;
+
+	if (xswap_size_max)
+		return xswap_size_limit();

[Severity: Medium]
Can setting xswap.max=max cause xswap_create() to allocate multiple gigabytes of physical memory upfront in zswap_swapon() or exhaust vmalloc address space in setup_swap_clusters_info()?

On 64-bit systems, xswap_size_limit() caps si->max at UINT_MAX * SWAPFILE_CLUSTER (~2.2 trillion pages with 4K pages and CONFIG_THP_SWAP=y, or ~35.2 trillion pages with 64K pages). xswap_create() then passes si->max to zswap_swapon(), which eagerly allocates and initializes one struct xarray per ZSWAP_ADDRESS_SPACE_PAGES (16,384) pages:

mm/zswap.c:zswap_swapon() {
    ...
	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);
    ...
}

At that limit, trees requires 134,217,728 xarrays (2 GiB of physical RAM on 4K-page systems, or 32 GiB on 64K-page systems) initialized in an unscheduled loop before any page is swapped, failing with -ENOMEM on smaller machines. In addition, setup_swap_clusters_info() reserves UINT_MAX * sizeof(struct swap_cluster_info) (~192 GiB) of vmalloc virtual address space via get_vm_area(), which exceeds the entire vmalloc space on 39-bit VA configurations.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author reviewer
#13 lore raw

PATCH v7 10/14 mm, swap: add CONFIG_XSWAP_DEFAULT_MAX

In reply to Baoquan He

From: Baoquan He <[email protected]>

Add a build-time default for the size of a new xswap device. The value can be a percentage of RAM, a size in bytes, or "max". "max" means the largest size the device can address. xswap.max= on the command line overrides this default.

The build-time default is clamped to the device limit. An explicit xswap.max= that is too large is refused.

If the build-time default cannot be parsed, or is a byte size below one cluster, use 200% instead. A percentage default can still be below one cluster after RAM is known. In that case, device creation fails.

---
 .../admin-guide/kernel-parameters.txt         |  6 ++--
 mm/Kconfig                                    | 11 ++++++
 mm/swapfile.c                                 | 34 ++++++++++++-------
 3 files changed, 37 insertions(+), 14 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +4 -2
index 2b0fc585e0c7..2a28aaa3cb32 100644
@@ -8736,8 +8736,10 @@ Kernel parameters
 			off	xmon is disabled.
 
 	xswap.max=	[KNL,SWAP]
-			Maximum size of a new xswap device. The value is a
+			Maximum size of a new xswap device, which is created
+			with swapon(2) and the spec "xswap". The value is a
 			size in bytes with an optional KMGTPE suffix, a
 			percentage of RAM, or "max" for the largest size
-			the device can address.
+			the device can address. The default is set by
+			CONFIG_XSWAP_DEFAULT_MAX.
 			Format: <size>[KMGTPE] | <percent>% | max
mm/Kconfig +11 -0
index d238a4971b1e..16958240a066 100644
@@ -131,6 +131,17 @@ config XSWAP
 	  array is backed by a sparse vmalloc area that is mapped lazily
 	  in chunks, avoiding static pre-allocation overhead.
 
+config XSWAP_DEFAULT_MAX
+	string "Default maximum size of a new xswap device"
+	depends on XSWAP
+	default "200%"
+	help
+	  The maximum size of a newly created xswap device. It accepts a
+	  percentage of RAM (for example "200%"), a size (for example "2T"),
+	  or "max" for the largest size the device can address.
+
+	  xswap.max= on the kernel command line overrides this value.
+
 config ZSMALLOC
 	tristate
 
mm/swapfile.c +22 -12
index 6ce5dbb3b103..074c5114d129 100644
@@ -77,9 +77,9 @@ static int xswap_destroy_by_name(const char *name);
 static DEFINE_MUTEX(xswap_ctl_lock);
 
 /*
- * Size of a new device: xswap.max= if given, otherwise the built-in
- * default.  A percentage unless bytes is set; "max" asks for the largest
- * size the device can address.
+ * Size of a new device: xswap.max= if given, otherwise
+ * CONFIG_XSWAP_DEFAULT_MAX.  A percentage unless bytes is set; "max" asks
+ * for the largest size the device can address.
  */
 static unsigned int xswap_size_pct = 200;
 static unsigned long xswap_size_bytes;
@@ -87,9 +87,12 @@ static bool xswap_size_max;
 static bool xswap_size_set;	/* xswap.max= was given */
 
 /*
- * Parse "200%", "2T" or "max".  @str is not modified.
+ * Parse "200%", "2T" or "max". @str is not modified. @cmdline tells an
+ * explicit xswap.max= from the build-time default, which is clamped
+ * instead of refused when it is too large.
  */
-static int __init xswap_parse_size(const char *str, const char *what)
+static int __init xswap_parse_size(const char *str, const char *what,
+				   bool cmdline)
 {
 	const char *pct;
 	char buf[16];
@@ -118,12 +121,16 @@ static int __init xswap_parse_size(const char *str, const char *what)
 		bytes = memparse(str, &end);
 		if (*end || bytes < PAGE_SIZE)
 			goto bad;
+		/* A default below one cluster would fail every create. */
+		if (!cmdline && bytes < (unsigned long)SWAPFILE_CLUSTER * PAGE_SIZE)
+			goto bad;
 		xswap_size_bytes = bytes;
 		xswap_size_pct = 0;
 		xswap_size_max = false;
 	}
 
-	xswap_size_set = true;
+	if (cmdline)
+		xswap_size_set = true;
 	return 0;
 bad:
 	pr_err("xswap: bad %s=%s\n", what, str);
@@ -132,7 +139,7 @@ static int __init xswap_parse_size(const char *str, const char *what)
 
 static int __init xswap_max_setup(char *str)
 {
-	xswap_parse_size(str, "xswap.max");
+	xswap_parse_size(str, "xswap.max", true);
 	return 1;
 }
 __setup("xswap.max=", xswap_max_setup);
@@ -4175,11 +4182,7 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 }
 
 #ifdef CONFIG_XSWAP
-/*
- * Create the file-less xswap device, sized by xswap.max= or the built-in
- * default.  Called from swapon(2) with SWAP_FLAG_XSWAP; there is at most
- * one device per system.
- */
+/* Create the file-less xswap device from swapon(2). */
 static int xswap_create(int prio)
 {
 	struct swap_info_struct *si;
@@ -4694,6 +4697,13 @@ static int __init swapfile_init(void)
 {
 	swapfile_maximum_size = arch_max_swapfile_size();
 
+#ifdef CONFIG_XSWAP
+	/* xswap.max= on the command line overrides the build-time default. */
+	if (!xswap_size_set)
+		xswap_parse_size(CONFIG_XSWAP_DEFAULT_MAX,
+				 "CONFIG_XSWAP_DEFAULT_MAX", false);
+#endif
+
 	/*
 	 * Once a cluster is freed, it's swap table content is read
 	 * only, and all swap cache readers (swap_cache_*) verifies
Signature · 1 line
2.54.0
author reviewer
#14 lore raw

PATCH v7 11/14 mm, swap: add xswap grow trigger on cluster allocation

In reply to Baoquan He

From: Baoquan He <[email protected]>

Grow the mapped xswap range before it runs out. When usage reaches 85% of the mapped range, map more clusters from cluster_alloc_swap_entry().

Grow to about 65% usage. This leaves free space in the mapped range before the next grow at 85%, so one grow is not immediately followed by another.

A burst of concurrent allocators can take every mapped cluster off the free list while usage is still below the threshold. When the allocator cannot find a cluster, it forces one grow chunk and retries, instead of failing while unmapped clusters remain.

Mapping pages can sleep. Grow before the allocation that needs them, not after it fails.

---
 include/linux/swap.h |   1 +
 mm/swapfile.c        | 135 ++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 129 insertions(+), 7 deletions(-)
include/linux/swap.h +1 -0
index ba1bf7e09893..55649ad5b145 100644
@@ -246,6 +246,7 @@ struct swap_info_struct {
 	unsigned long		nr_clusters_max;/* total clusters in the xswap address space */
 	unsigned long		nr_clusters_mapped; /* currently mapped cluster count */
 	struct mutex		xswap_lock;	/* serialize map/unmap operations */
+	atomic_long_t		xswap_grows;	/* grow operations so far */
 #endif
 	struct list_head free_clusters; /* free clusters list */
 	struct list_head full_clusters; /* full clusters list */
mm/swapfile.c +128 -7

181 lines not on this page · raw message

Signature · 1 line
2.54.0
#15 lore raw

Re: [PATCH v7 11/14] mm, swap: add xswap grow trigger on cluster allocation

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] mm: missing SWP_WRITEOK check in cluster_alloc_swap_entry() fallback grow - [Medium] mm: premature…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] mm: missing SWP_WRITEOK check in cluster_alloc_swap_entry() fallback grow
- [Medium] mm: premature xswap allocation failure on concurrent xswap_grow() bursts
- [Medium] mm: swap: xswap_grow() 4-chunk cap defeats XSWAP_GROW_UNTIL target
--

commit d8e2d7959fb110ba7aca71775df5f4699fac8fc6
Author: Baoquan He <[email protected]>

mm, swap: add xswap grow trigger on cluster allocation

This commit adds proactive and fallback grow triggers in cluster_alloc_swap_entry() to map additional xswap cluster_info pages and publish new clusters onto free_clusters as swap usage rises.

Quoted 16 lines
mm/swapfile.c +8 -0
index 074c5114d129a..9dc6bdc1a6dec 100644
@@ -68,6 +68,21 @@
 #define XSWAP_GROW_CLUSTERS \
 	max_t(unsigned long, PAGE_SIZE / sizeof(struct swap_cluster_info), 16)
 
+/*
+ * Grow thresholds, as a percentage of the mapped range in use.  The target
+ * sits below the next grow trigger, so a grow that follows a rise in usage
+ * does not immediately trigger another one.
+ */
+#define XSWAP_GROW_UNTIL	65
+#define XSWAP_GROW_WHEN		85
+#define XSWAP_GROW_CHUNKS	4

[ ... ]

Quoted 10 lines
mm/swapfile.c +6 -0
@@ -1325,6 +1340,13 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	if (order && !(si->flags & SWP_BLKDEV))
 		return 0;
 
+#ifdef CONFIG_XSWAP
+	/* Grow before allocating: mapping pages can sleep. */
+	if ((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK) &&
+	    xswap_should_grow(si))
+		xswap_grow(si, false);
+#endif

[ ... ]

Quoted 8 lines
mm/swapfile.c +4 -0
@@ -1397,6 +1419,20 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 		if (found)
 			goto done;
 	}
+
+#ifdef CONFIG_XSWAP
+	/*
+	 * A burst of allocators can hold every mapped cluster while usage is

mm/swapfile.c static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, · line 1435

Quoted 10 lines
mm/swapfile.c +10 -0
+	 * still below the growth threshold, so grow before retrying.
+	 */
+	if (!found && (si->flags & SWP_XSWAP)) {
+		if (READ_ONCE(si->nr_clusters_mapped) <
+		    READ_ONCE(si->nr_clusters_max))
+			xswap_grow(si, true);
+		found = alloc_swap_scan_list(si, &si->free_clusters,
+					     folio, false);
+	}
+#endif

[Severity: Medium]
Should this fallback grow also check si->flags & SWP_WRITEOK, and should xswap_publish_clusters() recheck SWP_WRITEOK under si->lock?

Once swap_info_remove() clears SWP_WRITEOK during swapoff, every list scan in cluster_alloc_swap_entry() fails because isolate_lock_cluster() bails out when SWP_WRITEOK is clear. An in-flight order-0 allocator reaching this fallback then mistakes !found for cluster exhaustion and calls xswap_grow(si, true), sleeping to allocate and map new cluster_vm pages, linking new clusters onto si->free_clusters, and advancing si->nr_clusters_mapped on a device being torn down.

Quoted 44 lines
mm/swapfile.c +32 -1
 done:
 	if (!(si->flags & SWP_SOLIDSTATE))
 		spin_unlock(&si->global_cluster_lock);
@@ -3986,8 +4022,39 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 }
 
 #ifdef CONFIG_XSWAP
+/*
+ * Link the new clusters and publish the larger range in one si->lock
+ * section: linking first makes a cluster visible to an allocator only
+ * after it is on the free list.  @link_free is false for the first
+ * chunk, whose free list is not initialized yet.
+ */
+static void xswap_publish_clusters(struct swap_info_struct *si,
+				   unsigned long start_idx, unsigned long nr,
+				   bool link_free)
+{
+	unsigned long i;
+
+	spin_lock(&si->lock);
+	if (link_free) {
+		for (i = start_idx; i < start_idx + nr; i++) {
+			struct swap_cluster_info *ci = &si->cluster_info[i];
+
+			/* A concurrent grower cannot take these: xswap_lock. */
+			if (ci->flags != CLUSTER_FLAG_NONE)
+				continue;
+			list_add_tail(&ci->list, &si->free_clusters);
+			WRITE_ONCE(ci->flags, CLUSTER_FLAG_FREE);
+			ci->order = 0;
+		}
+	}
+	/* Pairs with the smp_load_acquire() in the readers of the range. */
+	smp_store_release(&si->nr_clusters_mapped, start_idx + nr);
+	spin_unlock(&si->lock);
+}
+
 static int xswap_map_clusters(struct swap_info_struct *si,
-			      unsigned long start_idx, unsigned long nr)
+			      unsigned long start_idx, unsigned long nr,
+			      bool link_free)
 {
 	/* vm_area_grow_pages() takes an offset into the area, not an address. */
 	unsigned long vm_end = PAGE_ALIGN((size_t)(start_idx + nr) *

[ ... ]

Quoted 40 lines
mm/swapfile.c +28 -5
@@ -4023,14 +4090,65 @@ static int xswap_map_clusters(struct swap_info_struct *si,
 	for (i = start_idx; i < start_idx + nr; i++)
 		spin_lock_init(&si->cluster_info[i].lock);
 
-	/*
-	 * Publish the new mappings and cluster lock initialization before
-	 * the count; walkers without xswap_lock use smp_load_acquire().
-	 */
-	smp_store_release(&si->nr_clusters_mapped, start_idx + nr);
+	/* The mappings and the locks are in place; make them visible. */
+	xswap_publish_clusters(si, start_idx, nr, link_free);
 	mutex_unlock(&si->xswap_lock);
 	return 0;
 }
+static bool xswap_should_grow(struct swap_info_struct *si)
+{
+	unsigned long mapped = READ_ONCE(si->nr_clusters_mapped);
+
+	if (mapped >= READ_ONCE(si->nr_clusters_max))
+		return false;
+
+	return swap_usage_in_pages(si) * 100 >=
+	       mapped * SWAPFILE_CLUSTER * XSWAP_GROW_WHEN;
+}
+
+/*
+ * Map more of the cluster_info array, up to GROW_UNTIL in use.  The caller
+ * holds percpu_swap_cluster.lock, which this drops while it sleeps.
+ */
+static unsigned long xswap_grow(struct swap_info_struct *si, bool force)
+{
+	unsigned long mapped = READ_ONCE(si->nr_clusters_mapped);
+	unsigned long nr_new, want;
+	int ret;
+
+	lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock);
+
+	want = DIV_ROUND_UP(swap_usage_in_pages(si) * 100,
+			    XSWAP_GROW_UNTIL * SWAPFILE_CLUSTER);
+	if (want <= mapped) {

mm/swapfile.c static int xswap_map_clusters(struct swap_info_struct *si, · line 4133

Quoted 10 lines
mm/swapfile.c +10 -0
+		if (!force)
+			return 0;
+		nr_new = XSWAP_GROW_CLUSTERS;
+	} else {
+		nr_new = rounddown(want - mapped, XSWAP_GROW_CLUSTERS);
+	}
+	if (!nr_new)
+		nr_new = XSWAP_GROW_CLUSTERS;
+	if (nr_new > XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS)
+		nr_new = XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS;

[Severity: Medium]
Does clamping nr_new to XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS defeat the XSWAP_GROW_UNTIL (65%) hysteresis target once si->nr_clusters_mapped reaches 13 chunks?

Bringing usage from 85% down to 65% requires growing by at least 4/13 of mapped. Once mapped exceeds 13 * XSWAP_GROW_CLUSTERS (~2.16 GiB with 48 byte swap_cluster_info), want - mapped is always larger than 4 chunks, so xswap_grow() maps at most 4 chunks per call, keeping usage near 85% and causing back-to-back synchronous xswap_grow() calls on subsequent cluster_alloc_swap_entry() invocations.

Quoted 7 lines
mm/swapfile.c +7 -0
+	nr_new = min(nr_new, READ_ONCE(si->nr_clusters_max) - mapped);
+	if (!nr_new)
+		return 0;
+
+	/*
+	 * Mapping pages can sleep.  The lock only guards the per-cpu
+	 * cluster cache, which this path does not touch.

mm/swapfile.c static int xswap_map_clusters(struct swap_info_struct *si, · line 4150

Quoted 10 lines
mm/swapfile.c +10 -0
+	 */
+	local_unlock(&percpu_swap_cluster.lock);
+	ret = xswap_map_clusters(si, mapped, nr_new, true);
+	local_lock(&percpu_swap_cluster.lock);
+	if (ret)
+		return 0;
+
+	atomic_long_inc(&si->xswap_grows);
+	return nr_new;
+}

[Severity: Medium]
Can a burst of concurrent allocators still fail in cluster_alloc_swap_entry() while unmapped clusters and free slots in si->frag_clusters[0] remain?

CPU0 CPU1
cluster_alloc_swap_entry()
xswap_grow(si, true)

    mapped = si->nr_clusters_mapped
    xswap_map_clusters(si, mapped, ...)
      mutex_lock(&si->xswap_lock)
      vm_area_grow_pages()
                                      cluster_alloc_swap_entry()
                                        xswap_grow(si, true)
                                          mapped = si->nr_clusters_mapped
                                          xswap_map_clusters(si, mapped, ...)
                                            mutex_lock(&si->xswap_lock)
      xswap_publish_clusters()
      mutex_unlock(&si->xswap_lock)
                                            start_idx != nr_clusters_mapped
                                            return -EAGAIN

While CPU0 sleeps in vm_area_grow_pages(), any concurrent allocator that also enters xswap_grow() snapshots the same si->nr_clusters_mapped and blocks on si->xswap_lock, only to abort with -EAGAIN after CPU0 publishes one chunk. In the fallback path, each waking thread then scans only si->free_clusters once, even though any newly published cluster from which another CPU has allocated a single slot is immediately moved by relocate_cluster() to si->frag_clusters[0] with SWAPFILE_CLUSTER - 1 free slots remaining. If concurrent allocators drain si->free_clusters before a waiter reaches alloc_swap_scan_list(si, &si->free_clusters, ...), cluster_alloc_swap_entry() returns 0 despite free slots in si->frag_clusters[0] and unmapped clusters below si->nr_clusters_max.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author reviewer
#16 lore raw

PATCH v7 12/14 mm, swap: add debugfs counters for xswap

In reply to Baoquan He

From: Baoquan He <[email protected]>

The mapped range and the grow count are not visible from userspace. This makes it hard to check if the grow thresholds work: we cannot see how large the mapped range is, how much it grows, or how much free tail it keeps.

Put this information in debugfs. It is a debugging aid, not a stable interface, so it does not belong in sysfs or the ABI:

  # cat /sys/kernel/debug/xswap/xswap.stats
  type 0
  clusters_max 2038783
  clusters_mapped 255
  usage_pages 91456
  tail_free 16
  grows 3
---
 include/linux/swap.h |  1 +
 mm/swapfile.c        | 69 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 70 insertions(+)
include/linux/swap.h +1 -0
index 55649ad5b145..7979b56e5224 100644
@@ -246,6 +246,7 @@ struct swap_info_struct {
 	unsigned long		nr_clusters_max;/* total clusters in the xswap address space */
 	unsigned long		nr_clusters_mapped; /* currently mapped cluster count */
 	struct mutex		xswap_lock;	/* serialize map/unmap operations */
+	struct dentry		*xswap_debugfs;	/* mapped range and counters */
 	atomic_long_t		xswap_grows;	/* grow operations so far */
 #endif
 	struct list_head free_clusters; /* free clusters list */
mm/swapfile.c +69 -0

117 lines not on this page · raw message

Signature · 1 line
2.54.0
author reviewer
#17 lore raw

PATCH v7 13/14 mm, swap: do not give an xswap slot to a cgroup that cannot zswap

In reply to Baoquan He

From: Baoquan He <[email protected]>

At this point, an xswap slot holds only a zswap-backed page. It has no storage of its own. If the folio's cgroup cannot take another zswap page, giving it an xswap slot is wasted: zswap refuses the page and the slot cannot hold it.

Skip xswap devices when the cgroup cannot zswap, and try a physical swap device instead.

The check is obj_cgroup_may_zswap(): zswap_store() uses the same check but first tries to shrink the memcg, while the allocation-time check does not, so it is stricter.

---
 mm/swapfile.c | 119 ++++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 97 insertions(+), 22 deletions(-)
mm/swapfile.c +97 -22
index 8b2082bdac08..3a84dbd7a54c 100644
@@ -226,6 +226,8 @@ static DEFINE_SPINLOCK(swap_lock);
 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;
 /*
  * 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
@@ -1197,7 +1199,7 @@ 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)
+					     unsigned long offset, bool no_cache)
 {
 	unsigned long next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 	unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);
@@ -1238,6 +1240,9 @@ static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
 	relocate_cluster(si, ci);
 	swap_cluster_unlock(ci);
 	if (si->flags & SWP_SOLIDSTATE) {
+		if (no_cache &&
+		    this_cpu_read(percpu_swap_cluster.si[order]) != si)
+			return found;
 		this_cpu_write(percpu_swap_cluster.offset[order], next);
 		this_cpu_write(percpu_swap_cluster.si[order], si);
 	} else {
@@ -1249,7 +1254,7 @@ 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 scan_all, bool no_cache)
 {
 	unsigned long found = SWAP_ENTRY_INVALID;
 
@@ -1260,7 +1265,8 @@ 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,
+						no_cache);
 		if (found)
 			break;
 	} while (scan_all);
@@ -1330,7 +1336,8 @@ 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,
+					      bool no_cache)
 {
 	struct swap_cluster_info *ci;
 	unsigned int order = likely(folio) ? folio_order(folio) : 0;
@@ -1362,7 +1369,8 @@ 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,
+							no_cache);
 		} else {
 			swap_cluster_unlock(ci);
 		}
@@ -1372,19 +1380,20 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 
 new_cluster:
 	if (swap_prefer_free_cluster(si)) {
-		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
+		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false, no_cache);
 		if (found)
 			goto done;
 	}
 
 	if (order < PMD_ORDER) {
-		found = alloc_swap_scan_list(si, &si->nonfull_clusters[order], folio, true);
+		found = alloc_swap_scan_list(si, &si->nonfull_clusters[order],
+					     folio, true, no_cache);
 		if (found)
 			goto done;
 	}
 
 	if (!swap_prefer_free_cluster(si)) {
-		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
+		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false, no_cache);
 		if (found)
 			goto done;
 	}
@@ -1400,7 +1409,7 @@ 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);
+		found = alloc_swap_scan_list(si, &si->frag_clusters[order], folio, false, no_cache);
 		if (found)
 			goto done;
 	}
@@ -1414,11 +1423,11 @@ 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);
+		found = alloc_swap_scan_list(si, &si->frag_clusters[o], folio, true, no_cache);
 		if (found)
 			goto done;
 
-		found = alloc_swap_scan_list(si, &si->nonfull_clusters[o], folio, true);
+		found = alloc_swap_scan_list(si, &si->nonfull_clusters[o], folio, true, no_cache);
 		if (found)
 			goto done;
 	}
@@ -1433,7 +1442,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 		    READ_ONCE(si->nr_clusters_max))
 			xswap_grow(si, true);
 		found = alloc_swap_scan_list(si, &si->free_clusters,
-					     folio, false);
+					     folio, false, no_cache);
 	}
 #endif
 done:
@@ -1460,7 +1469,9 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)
 		lockdep_assert_held(&si->lock);
 		si->flags &= ~SWP_WRITEOK;
 		/* Count active devices, not merely those on the avail list. */
-		if (!(si->flags & SWP_XSWAP))
+		if (si->flags & SWP_XSWAP)
+			atomic_sub(1, &nr_xswap_files);
+		else
 			atomic_sub(1, &nr_real_swapfiles);
 		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 	} else {
@@ -1496,7 +1507,9 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 		lockdep_assert_held(&si->lock);
 		si->flags |= SWP_WRITEOK;
 		/* A full device is still active and skips the add below. */
-		if (!(si->flags & SWP_XSWAP))
+		if (si->flags & SWP_XSWAP)
+			atomic_add(1, &nr_xswap_files);
+		else
 			atomic_add(1, &nr_real_swapfiles);
 	} else {
 		if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
@@ -1620,7 +1633,7 @@ 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)
+static bool swap_alloc_fast(struct folio *folio, bool may_zswap)
 {
 	unsigned int order = folio_order(folio);
 	struct swap_cluster_info *ci;
@@ -1636,11 +1649,16 @@ static bool swap_alloc_fast(struct folio *folio)
 	if (!si || !offset || !get_swap_device_info(si))
 		return false;
 
+	if (!may_zswap && (si->flags & SWP_XSWAP)) {
+		put_swap_device(si);
+		return false;
+	}
+
 	ci = swap_cluster_lock(si, offset);
 	if (cluster_is_usable(ci, order)) {
 		if (cluster_is_empty(ci))
 			offset = cluster_offset(si, ci);
-		alloc_swap_scan_cluster(si, ci, folio, offset);
+		alloc_swap_scan_cluster(si, ci, folio, offset, false);
 	} else {
 		swap_cluster_unlock(ci);
 	}
@@ -1650,18 +1668,24 @@ static bool swap_alloc_fast(struct folio *folio)
 }
 
 /* Rotate the device and switch to a new cluster */
-static void swap_alloc_slow(struct folio *folio)
+static void swap_alloc_slow(struct folio *folio, bool may_zswap)
 {
 	struct swap_info_struct *si, *next;
 
 	spin_lock(&swap_avail_lock);
 start_over:
 	plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
+		/*
+		 * Do not rotate a skipped device: the walk follows the
+		 * rotation and would spin forever.
+		 */
+		if (!may_zswap && (si->flags & SWP_XSWAP))
+			continue;
 		/* Rotate the device and switch to a new cluster */
 		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);
+			cluster_alloc_swap_entry(si, folio, !may_zswap);
 			put_swap_device(si);
 			if (folio_test_swapcache(folio))
 				return;
@@ -1979,6 +2003,17 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 	return err;
 }
 
+/* Can the folio's cgroup take another zswap page? */
+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);
+
+	if (objcg)
+		obj_cgroup_put(objcg);
+	return may_zswap;
+}
+
 /**
  * folio_alloc_swap - allocate swap space for a folio
  * @folio: folio we want to move to swap
@@ -1995,10 +2030,21 @@ int folio_alloc_swap(struct folio *folio)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
+	bool may_zswap = true;
+	bool zswap_checked = false;
 
 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
 	VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio);
 
+	/*
+	 * A folio zswap will not take must not get an xswap slot; without
+	 * a device to route away from, skip the lookup.
+	 */
+	if (atomic_read(&nr_xswap_files)) {
+		may_zswap = folio_may_zswap(folio);
+		zswap_checked = true;
+	}
+
 	if (order) {
 		/*
 		 * Reject large allocation when THP_SWAP is disabled. Check below
@@ -2017,10 +2063,17 @@ int folio_alloc_swap(struct folio *folio)
 		}
 	}
 
+	/*
+	 * Only xswap devices exist and this folio cannot use them; there is
+	 * no slot to find.
+	 */
+	if (!may_zswap && !atomic_read(&nr_real_swapfiles))
+		goto failed;
+
 again:
 	local_lock(&percpu_swap_cluster.lock);
-	if (!swap_alloc_fast(folio))
-		swap_alloc_slow(folio);
+	if (!swap_alloc_fast(folio, may_zswap))
+		swap_alloc_slow(folio, may_zswap);
 	local_unlock(&percpu_swap_cluster.lock);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
@@ -2028,6 +2081,20 @@ int folio_alloc_swap(struct folio *folio)
 			goto again;
 	}
 
+	/*
+	 * The gate was skipped when there was no device; one may have
+	 * appeared since, so ask the slot itself.
+	 */
+	if (unlikely(!zswap_checked && folio_test_swapcache(folio) &&
+		     (__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP))) {
+		zswap_checked = true;
+		may_zswap = folio_may_zswap(folio);
+		if (!may_zswap) {
+			swap_cache_del_folio(folio);
+			goto again;
+		}
+	}
+
 	/* 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);
@@ -2045,6 +2112,13 @@ int folio_alloc_swap(struct folio *folio)
 	if (mem_cgroup_get_folio_swap_margin(folio) <= 0)
 		return -ENOMEM;
 
+	/*
+	 * Only xswap devices exist and the folio cannot use them; splitting
+	 * cannot help.
+	 */
+	if (!may_zswap && !atomic_read(&nr_real_swapfiles))
+		return -ENOMEM;
+
 	return order ? -E2BIG : -ENOMEM;
 }
 
@@ -2459,12 +2533,13 @@ swp_entry_t swap_alloc_hibernation_slot(int type)
 	if (pcp_si == si && 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);
+			offset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset,
+							 false);
 		else
 			swap_cluster_unlock(ci);
 	}
 	if (!offset)
-		offset = cluster_alloc_swap_entry(si, NULL);
+		offset = cluster_alloc_swap_entry(si, NULL, false);
 	local_unlock(&percpu_swap_cluster.lock);
 	if (offset)
 		entry = swp_entry(si->type, offset);
Signature · 1 line
2.54.0
#18 lore raw

Re: [PATCH v7 13/14] mm, swap: do not give an xswap slot to a cgroup that cannot zswap

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] mm, swap: no_cache in alloc_swap_scan_cluster() fragments SSD free clusters - [Medium] mm, swap…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] mm, swap: no_cache in alloc_swap_scan_cluster() fragments SSD free clusters
- [Medium] mm, swap: early goto failed in folio_alloc_swap() skips MEMCG_SWAP_FAIL
- [Medium] mm, swap: folio_alloc_swap() returns -E2BIG when real swapfiles are full
--

commit 635affe850d5047e3d0a27127b5b71819aadffb6
Author: Baoquan He <[email protected]>

mm, swap: do not give an xswap slot to a cgroup that cannot zswap

This commit skips xswap devices during swap slot allocation when the folio's cgroup cannot accept another zswap page, falling back to physical swap devices instead.

Quoted 4 lines
mm/swapfile.c +0 -0
index 8b2082bdac082..3a84dbd7a54c6 100644

[ ... ]

Quoted 10 lines
mm/swapfile.c +1 -1
@@ -1197,7 +1199,7 @@ 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)
+					     unsigned long offset, bool no_cache)
 {
 	unsigned long next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 	unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);

mm/swapfile.c static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si, · line 1248

Quoted 9 lines
mm/swapfile.c +3 -0
@@ -1238,6 +1240,9 @@ static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
 	relocate_cluster(si, ci);
 	swap_cluster_unlock(ci);
 	if (si->flags & SWP_SOLIDSTATE) {
+		if (no_cache &&
+		    this_cpu_read(percpu_swap_cluster.si[order]) != si)
+			return found;
 		this_cpu_write(percpu_swap_cluster.offset[order], next);
 		this_cpu_write(percpu_swap_cluster.si[order], si);
 	} else {

[Severity: High]
Does skipping the percpu_swap_cluster update when no_cache is true fragment si->free_clusters on SWP_SOLIDSTATE physical swap devices?

For SWP_SOLIDSTATE devices, relocate_cluster() moves a newly allocated, partially used cluster straight to si->frag_clusters[ci->order], relying on percpu_swap_cluster to retain the cursor for the remaining free slots. When a cgroup with !may_zswap falls back to a physical SSD while percpu_swap_cluster.si[order] is NULL or points to the higher-priority xswap device, returning early discards next. The next !may_zswap allocation on that CPU misses swap_alloc_fast() and re-enters cluster_alloc_swap_entry(), which drains another fresh cluster from si->free_clusters before consulting si->frag_clusters[order]. Each order-0 allocation therefore strands a 2 MiB free cluster on si->frag_clusters[0] with only 1 of 512 slots used, exhausting free clusters for large folio allocations.

Conversely, if percpu_swap_cluster.si[order] already equals the physical device si (for example, left over with offset == 0 after a previous cluster filled up), this check is false and caches next on the physical device, causing subsequent may_zswap allocations on this CPU to use the lower-priority physical device instead of xswap.

[ ... ]

Quoted 31 lines
mm/swapfile.c +16 -2
@@ -2017,10 +2063,17 @@ int folio_alloc_swap(struct folio *folio)
 		}
 	}
 
+	/*
+	 * Only xswap devices exist and this folio cannot use them; there is
+	 * no slot to find.
+	 */
+	if (!may_zswap && !atomic_read(&nr_real_swapfiles))
+		goto failed;
+
 again:
 	local_lock(&percpu_swap_cluster.lock);
-	if (!swap_alloc_fast(folio))
-		swap_alloc_slow(folio);
+	if (!swap_alloc_fast(folio, may_zswap))
+		swap_alloc_slow(folio, may_zswap);
 	local_unlock(&percpu_swap_cluster.lock);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
@@ -2028,6 +2081,20 @@ int folio_alloc_swap(struct folio *folio)
 			goto again;
 	}
 
+	/*
+	 * The gate was skipped when there was no device; one may have
+	 * appeared since, so ask the slot itself.
+	 */
+	if (unlikely(!zswap_checked && folio_test_swapcache(folio) &&
+		     (__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP))) {
+		zswap_checked = true;

mm/swapfile.c int folio_alloc_swap(struct folio *folio) · line 2100

Quoted 10 lines
mm/swapfile.c +7 -0
+		may_zswap = folio_may_zswap(folio);
+		if (!may_zswap) {
+			swap_cache_del_folio(folio);
+			goto again;
+		}
+	}
+
 	/* 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);

[Severity: Medium]
Does jumping directly to failed when !may_zswap && !nr_real_swapfiles skip MEMCG_SWAP_FAIL accounting in mem_cgroup_try_charge_swap()?

In addition, because again is placed after that check, if the post-allocation !zswap_checked path detects !may_zswap after racing with xswap activation, goto again bypasses the !nr_real_swapfiles shortcut and scans the swap lists even when no real swapfiles exist.

mm/swapfile.c int folio_alloc_swap(struct folio *folio) · line 2123

Quoted 13 lines
mm/swapfile.c +7 -0
@@ -2045,6 +2112,13 @@ int folio_alloc_swap(struct folio *folio)
 	if (mem_cgroup_get_folio_swap_margin(folio) <= 0)
 		return -ENOMEM;
 
+	/*
+	 * Only xswap devices exist and the folio cannot use them; splitting
+	 * cannot help.
+	 */
+	if (!may_zswap && !atomic_read(&nr_real_swapfiles))
+		return -ENOMEM;
+
 	return order ? -E2BIG : -ENOMEM;
 }

[Severity: Medium]
Can folio_alloc_swap() still return -E2BIG for a !may_zswap large folio when all real swapfiles are full?

del_from_avail_list() only decrements nr_real_swapfiles on swapoff, not when a real swap device fills up, while get_nr_swap_pages() includes free pages on xswap devices. If real swapfiles are active but full and xswap still has free pages, both get_nr_swap_pages() <= 0 and !nr_real_swapfiles are false, so folio_alloc_swap() returns -E2BIG and causes callers to split the large folio even though order-0 swap allocation cannot succeed either.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
author reviewer
#19 lore raw

PATCH v7 14/14 mm, swap: skip the overcommit probe when removing xswap

In reply to Baoquan He

From: Baoquan He <[email protected]>

swap_info_remove() probes whether Committed_AS still fits under the commit limit left after the device's pages are subtracted. An xswap device's pages are its address space, not backing storage, but they raised the commit limit at creation. A workload can commit into that headroom, after which the probe refuses to destroy the device.

Skip the probe for xswap until the overcommit accounting for it is settled. Real swap devices keep the existing protection.

---
 mm/swapfile.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
mm/swapfile.c +11 -4
index 3a84dbd7a54c..c650db1e1159 100644
@@ -3667,10 +3667,17 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
  */
 static int swap_info_remove(struct swap_info_struct *p)
 {
-	if (!security_vm_enough_memory_mm(current->mm, p->pages))
-		vm_unacct_memory(p->pages);
-	else
-		return -ENOMEM;
+	/*
+	 * The device's pages are its address space, not backing storage.
+	 * The commit limit it added may have been committed against, so
+	 * skip the probe until the limit stops counting that space.
+	 */
+	if (!(p->flags & SWP_XSWAP)) {
+		if (!security_vm_enough_memory_mm(current->mm, p->pages))
+			vm_unacct_memory(p->pages);
+		else
+			return -ENOMEM;
+	}
 
 	spin_lock(&p->lock);
 	del_from_avail_list(p, true);
Signature · 1 line
2.54.0