Skip to contentSkip to conversation

Virtual Swap Space (Swap Table Edition)

PATCH Superseded Nhat Pham 5 participants 32 messages Sep 18 – Sep 28

Subsystems (10)

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Nhat Pham

author maintainer
#0 lore raw

v5 cover Virtual Swap Space (Swap Table Edition)

Changelog:
* v4 [v4] -> v5
* OVERCOMMIT_GUESS now allows for 3xRAM margin when vswap is enabled, to take into account swapfile-less zswap usage (proposed by Johannes Weiner).
* Limit vswap swapfile size to 8TB and drop the last patch, to avoid memcg private id refcnt saturation.
* More assorted cleanups and fixes: anon swappability check, etc.
* RFC: Replace the xarray with a new data structure (vmalloc array) (new patch 11).
* Rebased onto mm-unstable.
* v3 [v3] -> v4
* Replaced the runtime sysctl with a cmdline param, and remove CONFIG_VSWAP (suggested by Johannes Weiner). CONFIG_VSWAP_DEFAULT_ON now only gives the default value of the vswap cmdline parameter.
* Refactor swap-related memcg operations into composable building
blocks: reference acquisitions, charging, etc. (patch 8, suggested by Johannes Weiner).
* Fixed vtable UAF bug reported by syzbot and Kunwu.
* Rebased onto mm-unstable (minimal merge conflicts).
* Re-run benchmarks (no signal change).
* v2 [v2] -> v3:
* Rebased onto current mm-unstable.
* Add a runtime vm.vswap_enabled sysctl and CONFIG_VSWAP_DEFAULT_ON to gate vswap allocation.
* More cleanups and small bug fixes.
* Split THP swapin enablement into its own patch (patch 5).
* Add production workload benchmark results, and drop RFC tag.
* v1 [v1] -> v2:
* Rebased to a newer mm-unstable tip.
* Fix a bunch of assorted issues (incorrect zswap store failure rollback, vswap_init() failure handling, rmap-encoding collision, etc.) and clean up the code (rename a bunch of functions to more closely follow existing patterns, etc.).
* Some more code clean up and simplification: some renamings to more closely follow existing patterns, move vswap backing check to __swap_cache_add_check, store zero state in the swap_table for vswap entries, etc.. Many of these are proposed by Kairui Song in [1].
* Defer memcg_table allocation on physical clusters until the first vswap-backing slot installs. Saves ~512 bytes per physical cluster that only serves vswap-backing slots (this is the new patch 8).
* Widen swap_info_struct->max and ->pages (and the swapoff unuse-path index) so vswap supports ~8 PB of swap space (this is the new patch 9).
* Split the physical-swap-backend patch into three for reviewability:
the core backend (patch 3), zswap writeback to physical swap (patch 4), and reclaim of cache-only physical slots (patch 5). No functional change.
* Add kerneldoc for the vswap API.
* Add some benchmark numbers for zswap case.

Patch 11 is an RFC. It swaps vswap's cluster xarray for the VM_SPARSE vmalloc array Baoquan He designed for xswap, to show that the data structure and the device model are separable: moving to his is one self-contained patch that adds no userspace interface. Note that per Baoquan's commentary (see [5]), I have skipped shrink for now, only freeing vtable when the cluster becomes free to minimize metadata overhead while keeping the skeleton in the free list. I have not done performance testing on this patch yet (the number is from the old design), but I have run a suite of simple stress tests.

It is adapted almost entirely from Baoquan's code (see [6]), so I have kept Baoquan's Co-developed-by and Signed-off-by tag.

I. Context and Motivation
=========================

Currently, when an anon page is swapped out, a slot in a backing swap device is allocated and stored in the page table entries that refer to the original page. This slot is also used as the "key" to find the swapped out content, as well as the index to swap data structures, such as the swap cache, or the swap cgroup mapping. Tying a swap entry to its backing slot in this way is performant and efficient when swap is purely just disk space, and swapoff is rare.

However, the advent of many swap optimizations has exposed major drawbacks of this design. The first problem is that we occupy a physical slot in the swap space, even for pages that are NEVER expected to hit the disk: pages compressed and stored in the zswap pool, zero-filled pages, or pages rejected by both of these optimizations when zswap writeback is disabled. This is arguably the central shortcoming of zswap:
* Resource-wise, it is hugely wasteful in terms of disk usage. At Meta, we size swapfile in the order of 25-50% of host RAM, depending on flash availability. This is a lot of flash for a fleet of our size, and with universal zswap enablement, most of this is wasted for zswap entries.

* In deployments when no disk space can be afforded for swap (such as mobile and embedded devices), users cannot adopt zswap, and are forced to use zram. This is confusing for users, and creates extra burdens for developers, having to develop and maintain similar features for two separate swap backends (writeback, cgroup charging, THP support, etc.). For instance, see the discussion in [2].

* Tying zswap (and more generally, other in-memory swap backends) to the current physical swapfile infrastructure makes zswap implicitly statically sized. This does not make sense, as unlike disk swap, in which we consume a limited resource (disk space or swapfile space) to save another resource (memory), zswap consumes the same resource it is saving (memory). The more we zswap, the more memory we have available, not less. We are not rationing a limited resource when we limit the size of the zswap pool, but rather we are capping the resource (memory) saving potential of zswap. Under memory pressure, using more zswap is almost always better than the alternative (disk IOs, or even worse, OOMs), and dynamically sizing the zswap pool on demand allows the system to flexibly respond to these precarious scenarios.

* Operationally, static provisioning the swapfile for zswap poses significant challenges, because the sysadmin has to prescribe how much swap is needed a priori, for each combination of (memory size x disk space x workload usage). It is even more complicated when we take into account the variance of memory compression, which changes the reclaim dynamics (and as a result, swap space size requirement). The problem is further exacerbated for users who rely on swap utilization (and exhaustion) as an OOM signal.

All of these factors make it very difficult to configure the swapfile for zswap: too small of a swapfile and we risk preventable OOMs and limit the memory saving potentials of zswap; too big of a swapfile and we waste disk space and memory due to swap metadata overhead. This dilemma becomes more drastic in high memory systems, which can have up to TBs worth of memory.

Swap virtualization is the answer to these issues, with three properties:

1. Decoupled backends. For zswap in particular, this means we eliminate the unused storage space, and allows zswap to be used in systems that do not have enough storage capacity for physical swap (without having to resort to silly hacks). Zero-filled swap pages and swap-cache-only folios also benefit here.

2. Dynamic swap space. Since virtual swap is not tied to any physical resource, we can make it effectively infinite and dynamically grow it on demand.
This massively simplifies operational provisioning, and increases the utilization of compressed swap backends (zswap). Dynamicity also reduces overhead on unused swap capacity.

3. Efficient backend transfer. The virtualization scheme should not introduce PTE/rmap walking overhead for backend transfer. This is crucial for systems that want to support multiple swap backends in a tiering fashion (for e.g zswap -> disk swap).

For more historical contexts and references, please take a look at the cover letter of the older vswap submissions ([3] and [v2]).

II. Design
==========

When vswap is enabled (via vswap=on cmdline parameter), a special vswap device is allocated at boot time. Anon pages that can be zswapped will obtain a vswap slot at swap allocation time.

These swap entries can subsequently acquire backend on-demand, such as a zswap entry, or a slot on a physical swap device (as a fallback option or at zswap writeback time).

We repurpose much of the existing swap_table infrastructure and swapfile allocator for this new vswap device, with two notable differences:
* Clusters are dynamically allocated on demand and managed through an xarray. This in turn allows us to avoid static provisioning and let swap space grow dynamically.

* Each cluster of this new vswap device has a virtual_table that stores the backend information of the entries in the cluster (see below).

Diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +---------------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)          |
                       | +----------------------------+  |
                       | | swap_table                 |  |
                       | |   PFN / Shadow             |  |
                       | | memcg_table                |  |
                       | | count,flags,order          |  |
                       | | lock, list                 |  |
                       | +----------------------------+  |
                       |                                 |
                       | virtual_table                   |
                       | +----------------------------+  |
                       | | NONE                       |  |
                       | | SWAPFILE(swp_entry_t)      |  |
                       | | ZSWAP(struct zswap_entry*) |  |
                       | +----------------------------+  |
                       +---------------------------------+
                              |
                              | SWAPFILE resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate the backend type:

  NONE:     |----- 0000 ------|000|  free / unbacked
  ZSWAP:    |--- zswap_entry* |001|  compressed in zswap
  SWAPFILE: |- type:5,off:56 -|010|  on a physical swapfile

Other design highlights:

* Note that for the vswap device, we have merged the zswap xarray tree with the swapfile-level clusters. This means that for zswap only users, we have negligible extra space overhead.

* Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens.

* Backend transitions in the virtual_table are synchronized through the swap cache and the folio lock - the same mechanism that already serializes ordinary swap operations (swapin, swapout, zswap writeback, swap cache reclaim). IOW, we can only assume that the backend of a vswap entry is stable through swap cache/folio lock. Looking at the backend without this should be done at best for optimization purposes, as there is no guarantee that the backend will not change under the observer.

* Pointer-tagged swap_table entries on physical clusters provide the rmap (physical -> virtual) lookup.

* Virtual swap slots not backed by physical swap are not charged to memcg swap counters - only physical backing is charged (I made the case for this in [4]).

III. Benchmarks
===============

Note that the goal is not to match vswap performance with baseline on every single case yet - running with vswap off is still supported. We can optimize further once we have landed this new feature.

A. Production Workload: Instagram
=================================

To test vswap's stability and performance, I ran an A/B experiment on Instagram (django) workload, with zswap as the swap backend. On these hosts, the swapfiles' size is 50% of RAM.

Compared to baseline, vswap gives:

* On par request throughput.
* Lower request serving latency (by about 1-3%).
* Lower memory pressure in the system service cgroups running alongside the workload. PSI-based proactive reclaimer can therefore recover more from them, lowering their overall memory footprint, allowing the main workload to expand.
* Elimination of swapfile footprint for all zswap users in the host.

B. Semi-synthetic Workloads (memhog, usemem, kernel build)
==========================================================

All values are mean +/- standard deviation across rounds.

Test system: x86_64, 52 cores, 64 GB swapfile for all 3 benchmarks. Swap backend: zswap (zstd) with the traditional active/inactive LRU. We focus on zswap here because it is the motivating use case for vswap.

For each benchmark, we test 3 kernels:
* Baseline: mm-unstable, no vswap patches.
* VSS off: vswap series applied, vswap=off, to verify that there is no regression to existing swap paths when we disable vswap.
* VSS on: vswap series applied, vswap=on.

1. Memhog: single-threaded, 48GB allocation on a host with 16GB RAM, 20 rounds.

Baseline VSS off VSS on

   real (s)        124.05 +/- 11.64   122.31 +/- 10.29   118.57 +/- 15.68
   sys (s)         106.75 +/- 10.86   105.01 +/- 9.64    101.34 +/- 13.97
   user (s)        10.81 +/- 0.11     10.85 +/- 0.09     10.79 +/- 0.09
   delta real              -              -1.4%              -4.4%
   delta sys               -              -1.6%              -5.1%

Dropping the best and the worst round to reduce variance:

memhog Baseline VSS off VSS on

   real (s)        123.75 +/- 10.39   122.04 +/- 9.10    116.06 +/- 8.22
   sys (s)         106.80 +/- 10.21   104.99 +/- 8.86    99.29 +/- 8.27
   user (s)        10.82 +/- 0.11     10.85 +/- 0.08     10.79 +/- 0.10
   delta real              -              -1.4%              -6.2%
   delta sys               -              -1.7%              -7.0%

2. Usemem single-threaded: 56GB allocation on a host with 32GB RAM, 16 rounds.

Baseline VSS off VSS on

   real (s)        178.75 +/- 6.47    178.95 +/- 6.56    175.97 +/- 7.74
   sys (s)         127.03 +/- 6.56    128.08 +/- 6.59    124.71 +/- 7.90
   tput (KB/s)     386662 +/- 14648   386264 +/- 15150   390443 +/- 17532
   free (ms)       7669 +/- 146       7678 +/- 136       6439 +/- 111
   delta real              -              +0.1%              -1.6%
   delta sys               -              +0.8%              -1.8%
   delta tput              -              -0.1%              +1.0%
   delta free              -              +0.1%             -16.0%

3. Kernel build: 52 workers (one per processor), memory.max=3GB, 10 rounds.

Baseline VSS off VSS on

   real (s)        165.58 +/- 0.45    165.83 +/- 0.49    166.01 +/- 0.58
   sys (s)         694.24 +/- 26.13   710.76 +/- 19.83   705.06 +/- 21.40
   user (s)       5132.62 +/- 1.12   5133.69 +/- 1.57   5134.68 +/- 1.68
   delta real              -              +0.2%              +0.3%
   delta sys               -              +2.4%              +1.6%
   delta user              -              +0.0%              +0.0%

For zswap backend, vswap outperforms baseline on usemem freeing, and is on par with baseline on the rest.

IV. References
==============

[v1]: https://lore.kernel.org/all/[email protected]/
[v2]: https://lore.kernel.org/all/[email protected]/
[v3]: https://lore.kernel.org/all/[email protected]/
[v4]: https://lore.kernel.org/all/[email protected]/
[1]: https://lore.kernel.org/all/CAMgjq7BhOn48xEyC=2j837R7qddfjeBVHMiRqdx8no4ZEBpBLg@mail.gmail.com/
[2]: https://lore.kernel.org/all/[email protected]/
[3]: https://lore.kernel.org/all/[email protected]/
[4]: https://lore.kernel.org/linux-mm/CAKEwX=P4syV38jAVCWq198r2OHXXc=xA-fx1dk6+qYef6yzxWQ@mail.gmail.com/
[5]: https://lore.kernel.org/all/aqjpYHbZ14A8xRtK@fedora/
[6]: https://lore.kernel.org/all/[email protected]/

Nhat Pham (11):
mm, swap: add virtual swap device infrastructure
mm, swap: support zswap and zero-filled swap pages as vswap backends mm, swap: prepare the swap IO path for vswap
mm, swap: support physical swap as a vswap backend
mm, swap: enable THP swapin for vswap entries
mm, swap: write back vswap zswap entries to physical swap mm, swap: reclaim physical slots backing cache-only vswap entries mm, swap: only charge physical swap entries
mm, swap: add debugfs counters for vswap
mm, swap: defer memcg_table allocation for physical swap clusters mm, swap: back vswap clusters with a VM_SPARSE array

 .../admin-guide/cgroup-v1/memcg_test.rst      |    2 +-
 Documentation/admin-guide/cgroup-v2.rst       |   46 +-
 .../admin-guide/kernel-parameters.txt         |    7 +
 MAINTAINERS                                   |    1 +
 include/linux/memcontrol.h                    |    6 +
 include/linux/swap.h                          |   88 +-
 include/linux/swap_ops.h                      |    9 +-
 include/linux/zswap.h                         |    4 +
 mm/Kconfig                                    |   20 +
 mm/memcontrol-v1.c                            |   10 +-
 mm/memcontrol.c                               |  147 +-
 mm/memory.c                                   |   21 +-
 mm/page_io.c                                  |  101 +-
 mm/shmem.c                                    |    4 +-
 mm/swap.h                                     |   28 +-
 mm/swap_state.c                               |   50 +-
 mm/swap_table.h                               |   64 +-
 mm/swapfile.c                                 | 1254 +++++++++++++++--
 mm/util.c                                     |   13 +-
 mm/vmscan.c                                   |   18 +-
 mm/vswap.h                                    |  422 ++++++
 mm/workingset.c                               |    2 +-
 mm/zswap.c                                    |  132 +-
 23 files changed, 2180 insertions(+), 269 deletions(-)
 create mode 100644 mm/vswap.h

base-commit: 27e4e1835109ef599d72abe6c09711e0b1916033

Signature · 1 line
2.53.0-Meta
author maintainer
#1 lore raw

PATCH v5 1/11 mm, swap: add virtual swap device infrastructure

Create a virtual swap device (just under 8 TiB with 4 KiB pages), along with the dynamic cluster infrastructure that the rest of the vswap layer is built on. swap_cluster_info_dynamic keeps per-cluster info in an xarray, so a device can be sized without a static cluster_info[] array. For now, vswap requires a 64-bit architecture.

swap_table_lookup() resolves a swap entry's cluster and reads its slot, both under RCU. A vswap cluster is allocated on demand and freed by kfree_rcu(), so an unpinned entry cannot have its cluster resolved beforehand, and the lookup can return NULL. Callers holding a pinned entry keep resolving it themselves: the pin holds ci->count above zero, so the cluster cannot be destroyed. mm/workingset.c includes swap_table.h with CONFIG_SWAP off, so the helpers swap_table_lookup() calls gain !CONFIG_SWAP stubs.

The dynamic-cluster allocator is wired in, but nothing reaches it yet. vswap_si is kept off the swap device lists, and no allocation path can select it. Backends (zswap, zero, physical disk) and the vswap-aware swap-out / swap-in / writeback paths arrive in subsequent patches.

Routing is controlled by the "vswap=" kernel parameter, defaulting to CONFIG_VSWAP_DEFAULT_ON. When off, no device exists, every vswap path is skipped, and swap behavior is unchanged. When on, vswap_init() creates the device and enables a static key only after it is fully published, so callers never observe a half-built device. The device lives for the lifetime of the kernel and cannot be swapon'd or swapoff'd.

The device is capped at REFCOUNT_MAX pages, just under 8 TiB with 4 KiB pages. Every swapped page takes a reference on its cgroup's memcg->private_id_ref, a 32-bit refcount_t, so a cgroup that swaps past that saturates it and leaks the memcg until reboot. The limit is not specific to vswap, a physical swapfile that large hits it too, but vswap is the first device that can reach it without provisioning the storage.

---
 .../admin-guide/kernel-parameters.txt         |   7 +
 MAINTAINERS                                   |   1 +
 include/linux/swap.h                          |   9 +
 mm/Kconfig                                    |  20 ++
 mm/page_io.c                                  |  14 +
 mm/swap.h                                     |  77 ++++-
 mm/swap_state.c                               |  40 +--
 mm/swap_table.h                               |  27 ++
 mm/swapfile.c                                 | 275 ++++++++++++++++--
 mm/vswap.h                                    |  34 +++
 mm/zswap.c                                    |   6 +
 11 files changed, 468 insertions(+), 42 deletions(-)
 create mode 100644 mm/vswap.h
Documentation/admin-guide/kernel-parameters.txt +7 -0
index 68647ff4bdd2..646e689d9e80 100644
@@ -8431,6 +8431,13 @@ Kernel parameters
 			force		- force vulnerability detection even on
 					  unaffected processors
 
+	vswap=		[MM,EARLY]
+			Route swapouts through the virtual swap layer, which
+			allows zswap and zero-filled pages to be used without
+			a physical swap device. 64-bit only.
+			Format: { on | off }
+			Default: on if CONFIG_VSWAP_DEFAULT_ON=y, else off.
+
 	vsyscall=	[X86-64,EARLY]
 			Controls the behavior of vsyscalls (i.e. calls to
 			fixed addresses of 0xffffffffff600x00 from legacy
MAINTAINERS +1 -0
index e4412c3d8d45..e49a3d4e332b 100644
@@ -17411,6 +17411,7 @@ F:	mm/swap.h
 F:	mm/swap_table.h
 F:	mm/swap_state.c
 F:	mm/swapfile.c
+F:	mm/vswap.h
 
 MEMORY MANAGEMENT - THP (TRANSPARENT HUGE PAGE)
 M:	Andrew Morton <[email protected]>
include/linux/swap.h +9 -0
index 61005501888c..0b341301d8fa 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_VSWAP	= (1 << 14),	/* virtual swap device */
 					/* add others here before... */
 };
 
@@ -270,8 +271,14 @@ struct swap_info_struct {
 	struct list_head discard_clusters; /* discard clusters list */
 	struct plist_node avail_list;   /* entry in swap_avail_head */
 	const struct swap_ops *ops;
+	struct xarray cluster_info_pool; /* Xarray for vswap dynamic cluster info */
 };
 
+static inline bool swap_is_vswap(struct swap_info_struct *si)
+{
+	return si->flags & SWP_VSWAP;
+}
+
 /**
  * folio_swap_entry - Return the swap entry at a page index within a folio.
  * @folio: The folio.
@@ -427,6 +434,8 @@ void swap_free_hibernation_slot(swp_entry_t entry);
 
 static inline void put_swap_device(struct swap_info_struct *si)
 {
+	if (swap_is_vswap(si))
+		return;
 	percpu_ref_put(&si->users);
 }
 
mm/Kconfig +20 -0
index 30170a936f1f..beef56e870ce 100644
@@ -19,6 +19,26 @@ menuconfig SWAP
 	  used to provide more virtual memory than the actual RAM present
 	  in your computer.  If unsure say Y.
 
+config VSWAP_DEFAULT_ON
+	bool "Route swapouts through virtual swap by default"
+	depends on SWAP && 64BIT
+	default n
+	help
+	  Virtual swap allows zswap and zero-filled pages to be used
+	  without swapping on a physical device first, and lets a page
+	  move between zswap and a swapfile without invalidating the page
+	  table entries that refer to it.
+
+	  Swap entries are handed out by a virtual swap device instead of
+	  naming a slot on a real one, so the backing can be chosen and
+	  changed after the entry exists.
+
+	  Say Y to make "vswap=on" the default, routing swapouts through
+	  the virtual swap layer from boot.
+
+	  Say N (default) to leave vswap off unless "vswap=on" is passed
+	  on the kernel command line.
+
 config ZSWAP
 	bool "Compressed cache for swap pages"
 	depends on SWAP
mm/page_io.c +14 -0
index 1da4ff484f09..5cd77bd1b12c 100644
@@ -28,6 +28,7 @@
 #include <linux/swap_ops.h>
 #include "swap.h"
 #include "swap_table.h"
+#include "vswap.h"
 
 int generic_swapfile_activate(struct swap_info_struct *sis,
 				struct file *swap_file,
@@ -248,6 +249,14 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
+	/*
+	 * A vswap folio has no physical slot to write to, so keep it dirty.
+	 */
+	if (is_vswap_entry(folio->swap)) {
+		folio_mark_dirty(folio);
+		return AOP_WRITEPAGE_ACTIVATE;
+	}
+
 	__swap_writeout(ctx, folio);
 	return 0;
 out_unlock:
@@ -482,6 +491,11 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	if (zswap_load(folio) != -ENOENT)
 		goto finish;
 
+	if (unlikely(swap_is_vswap(sis))) {
+		folio_unlock(folio);
+		goto finish;
+	}
+
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
 	swap_add_folio(ctx, folio, READ);
mm/swap.h +74 -3

130 lines not on this page · raw message

mm/swap_state.c +22 -18
index cef44aadee61..424a0040b4b8 100644
@@ -96,8 +96,7 @@ struct folio *swap_cache_get_folio(swp_entry_t entry)
 	struct folio *folio;
 
 	for (;;) {
-		swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-					swp_cluster_offset(entry));
+		swp_tb = swap_table_lookup(entry);
 		if (!swp_tb_is_folio(swp_tb))
 			return NULL;
 		folio = swp_tb_to_folio(swp_tb);
@@ -119,8 +118,7 @@ bool swap_cache_has_folio(swp_entry_t entry)
 {
 	unsigned long swp_tb;
 
-	swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-				swp_cluster_offset(entry));
+	swp_tb = swap_table_lookup(entry);
 	return swp_tb_is_folio(swp_tb);
 }
 
@@ -136,8 +134,7 @@ void *swap_cache_get_shadow(swp_entry_t entry)
 {
 	unsigned long swp_tb;
 
-	swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-				swp_cluster_offset(entry));
+	swp_tb = swap_table_lookup(entry);
 	if (swp_tb_is_shadow(swp_tb))
 		return swp_tb_to_shadow(swp_tb);
 	return NULL;
@@ -414,14 +411,16 @@ void __swap_cache_replace_folio(struct swap_cluster_info *ci,
  * -ENOENT / -EEXIST: Target swap entry is unavailable or cached, the caller
  *                    should abort or try to use the cached folio instead
  */
-static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
-					swp_entry_t targ_entry, gfp_t gfp,
+static struct folio *__swap_cache_alloc(swp_entry_t targ_entry, gfp_t gfp,
 					unsigned int order, struct vm_fault *vmf,
 					struct mempolicy *mpol, pgoff_t ilx)
 {
 	int err;
 	swp_entry_t entry;
 	struct folio *folio;
+	struct swap_cluster_info *ci;
+	struct swap_info_struct *si = __swap_entry_to_info(targ_entry);
+	unsigned long offset = swp_offset(targ_entry);
 	void *shadow = NULL;
 	unsigned short memcg_id;
 	unsigned long address, nr_pages = 1UL << order;
@@ -431,9 +430,12 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
 	entry.val = round_down(targ_entry.val, nr_pages);
 
 	/* Check if the slot and range are available, skip allocation if not */
-	spin_lock(&ci->lock);
-	err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
-	spin_unlock(&ci->lock);
+	err = -ENOENT;
+	ci = swap_cluster_lock(si, offset);
+	if (ci) {
+		err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
+		swap_cluster_unlock(ci);
+	}
 	if (unlikely(err))
 		return ERR_PTR(err);
 
@@ -454,10 +456,13 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
 		return ERR_PTR(-ENOMEM);
 
 	/* Double check the range is still not in conflict */
-	spin_lock(&ci->lock);
-	err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
+	err = -ENOENT;
+	ci = swap_cluster_lock(si, offset);
+	if (ci)
+		err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
 	if (unlikely(err)) {
-		spin_unlock(&ci->lock);
+		if (ci)
+			swap_cluster_unlock(ci);
 		folio_put(folio);
 		return ERR_PTR(err);
 	}
@@ -465,10 +470,11 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
 	__folio_set_locked(folio);
 	__folio_set_swapbacked(folio);
 	__swap_cache_do_add_folio(ci, folio, entry);
-	spin_unlock(&ci->lock);
+	swap_cluster_unlock(ci);
 
 	if (mem_cgroup_swapin_charge_folio(folio, memcg_id,
 					   vmf ? vmf->vma->vm_mm : NULL, gfp)) {
+		/* The folio pins the cluster */
 		spin_lock(&ci->lock);
 		__swap_cache_do_del_folio(ci, folio, entry, shadow);
 		spin_unlock(&ci->lock);
@@ -525,9 +531,7 @@ struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,
 {
 	int order, err;
 	struct folio *ret;
-	struct swap_cluster_info *ci;
 
-	ci = __swap_entry_to_cluster(targ_entry);
 	order = highest_order(orders);
 
 	/* orders must be non-zero, and must not exceed cluster size. */
@@ -535,7 +539,7 @@ struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,
 		return ERR_PTR(-EINVAL);
 
 	do {
-		ret = __swap_cache_alloc(ci, targ_entry, gfp, order,
+		ret = __swap_cache_alloc(targ_entry, gfp, order,
 					 vmf, mpol, ilx);
 		if (!IS_ERR(ret))
 			break;
mm/swap_table.h +27 -0
index e6613e62f8d0..3d64d1629882 100644
@@ -6,6 +6,8 @@
 #include <linux/atomic.h>
 #include "swap.h"
 
+extern struct swap_info_struct *vswap_si;
+
 /* A typical flat array in each cluster as swap table */
 struct swap_table {
 	atomic_long_t entries[SWAPFILE_CLUSTER];
@@ -264,6 +266,31 @@ static inline unsigned long swap_table_get(struct swap_cluster_info *ci,
 	return swp_tb;
 }
 
+/*
+ * Resolve @entry's cluster and read its slot, both under RCU. A vswap
+ * cluster is allocated on demand and freed by kfree_rcu(), so a caller
+ * starting from an entry cannot resolve it beforehand.
+ */
+static inline unsigned long swap_table_lookup(swp_entry_t entry)
+{
+	struct swap_cluster_info *ci;
+	atomic_long_t *table;
+	unsigned long swp_tb;
+
+	rcu_read_lock();
+	ci = __swap_entry_to_cluster(entry);
+	if (!ci) {
+		rcu_read_unlock();
+		return null_to_swp_tb();
+	}
+	table = rcu_dereference(ci->table);
+	swp_tb = table ? atomic_long_read(&table[swp_cluster_offset(entry)])
+		       : null_to_swp_tb();
+	rcu_read_unlock();
+
+	return swp_tb;
+}
+
 static inline void __swap_table_set_zero(struct swap_cluster_info *ci,
 					 unsigned int ci_off)
 {
mm/swapfile.c +254 -21

468 lines not on this page · raw message

mm/vswap.h new file +34 -0
new file mode 100644
index 000000000000..16395f357955
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Virtual swap space
+ *
+ * Copyright (C) 2026 Nhat Pham
+ */
+#ifndef _MM_VSWAP_H
+#define _MM_VSWAP_H
+
+#include <linux/jump_label.h>
+#include <linux/swap.h>
+#include "swap.h"
+
+#ifdef CONFIG_SWAP
+
+DECLARE_STATIC_KEY_FALSE(vswap_key);
+
+/*
+ * Only true once vswap_init() has published vswap_si, so callers never
+ * see the device half built.
+ */
+static inline bool vswap_is_enabled(void)
+{
+	return static_branch_unlikely(&vswap_key);
+}
+
+static inline bool is_vswap_entry(swp_entry_t entry)
+{
+	return swap_is_vswap(__swap_entry_to_info(entry));
+}
+
+#endif /* CONFIG_SWAP */
+
+#endif /* _MM_VSWAP_H */
mm/zswap.c +6 -0
index 507f2d19fd2a..73728b510ff6 100644
@@ -1018,6 +1018,12 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	if (IS_ERR_OR_NULL(si))
 		return -ENOENT;
 
+	/* Vswap entries have no physical backing to write to. */
+	if (swap_is_vswap(si)) {
+		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);
Signature · 1 line
2.53.0-Meta
maintainer
#2 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 177 lines · Nhat Pham

Create a virtual swap device (just under 8 TiB with 4 KiB pages), along with the dynamic cluster infrastructure that the rest of the vswap layer is built on. swap_cluster_info_dynamic keeps per-cluster info in an xarray, so a device can be sized without a static cluster_info[] array. For now, vswap requires a 64-bit architecture.

swap_table_lookup() resolves a swap entry's cluster and reads its slot, both under RCU. A vswap cluster is allocated on demand and freed by kfree_rcu(), so an unpinned entry cannot have its cluster resolved beforehand, and the lookup can return NULL. Callers holding a pinned entry keep resolving it themselves: the pin holds ci->count above zero, so the cluster cannot be destroyed. mm/workingset.c includes swap_table.h with CONFIG_SWAP off, so the helpers swap_table_lookup() calls gain !CONFIG_SWAP stubs.

The dynamic-cluster allocator is wired in, but nothing reaches it yet. vswap_si is kept off the swap device lists, and no allocation path can select it. Backends (zswap, zero, physical disk) and the vswap-aware swap-out / swap-in / writeback paths arrive in subsequent patches.

Routing is controlled by the "vswap=" kernel parameter, defaulting to CONFIG_VSWAP_DEFAULT_ON. When off, no device exists, every vswap path is skipped, and swap behavior is unchanged. When on, vswap_init() creates the device and enables a static key only after it is fully published, so callers never observe a half-built device. The device lives for the lifetime of the kernel and cannot be swapon'd or swapoff'd.

The device is capped at REFCOUNT_MAX pages, just under 8 TiB with 4 KiB pages. Every swapped page takes a reference on its cgroup's memcg->private_id_ref, a 32-bit refcount_t, so a cgroup that swaps past that saturates it and leaks the memcg until reboot. The limit is not specific to vswap, a physical swapfile that large hits it too, but vswap is the first device that can reach it without provisioning the storage.

---
 .../admin-guide/kernel-parameters.txt         |   7 +
 MAINTAINERS                                   |   1 +
 include/linux/swap.h                          |   9 +
 mm/Kconfig                                    |  20 ++
 mm/page_io.c                                  |  14 +
 mm/swap.h                                     |  77 ++++-
 mm/swap_state.c                               |  40 +--
 mm/swap_table.h                               |  27 ++
 mm/swapfile.c                                 | 275 ++++++++++++++++--
 mm/vswap.h                                    |  34 +++
 mm/zswap.c                                    |   6 +
 11 files changed, 468 insertions(+), 42 deletions(-)
 create mode 100644 mm/vswap.h
Documentation/admin-guide/kernel-parameters.txt +7 -0
index 68647ff4bdd2..646e689d9e80 100644
@@ -8431,6 +8431,13 @@ Kernel parameters
                        force           - force vulnerability detection even on
                                          unaffected processors
 
+       vswap=          [MM,EARLY]
+                       Route swapouts through the virtual swap layer, which
+                       allows zswap and zero-filled pages to be used without
+                       a physical swap device. 64-bit only.
+                       Format: { on | off }
+                       Default: on if CONFIG_VSWAP_DEFAULT_ON=y, else off.
+
        vsyscall=       [X86-64,EARLY]
                        Controls the behavior of vsyscalls (i.e. calls to
                        fixed addresses of 0xffffffffff600x00 from legacy
MAINTAINERS +1 -0
index e4412c3d8d45..e49a3d4e332b 100644
@@ -17411,6 +17411,7 @@ F:      mm/swap.h
 F:     mm/swap_table.h
 F:     mm/swap_state.c
 F:     mm/swapfile.c
+F:     mm/vswap.h
 
 MEMORY MANAGEMENT - THP (TRANSPARENT HUGE PAGE)
 M:     Andrew Morton <[email protected]>
include/linux/swap.h +9 -0
index 61005501888c..0b341301d8fa 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_VSWAP       = (1 << 14),    /* virtual swap device */
                                        /* add others here before... */
 };
 
@@ -270,8 +271,14 @@ struct swap_info_struct {
        struct list_head discard_clusters; /* discard clusters list */
        struct plist_node avail_list;   /* entry in swap_avail_head */
        const struct swap_ops *ops;
+       struct xarray cluster_info_pool; /* Xarray for vswap dynamic cluster info */
 };
 
+static inline bool swap_is_vswap(struct swap_info_struct *si)
+{
+       return si->flags & SWP_VSWAP;
+}
+
 /**
  * folio_swap_entry - Return the swap entry at a page index within a folio.
  * @folio: The folio.
@@ -427,6 +434,8 @@ void swap_free_hibernation_slot(swp_entry_t entry);
 
 static inline void put_swap_device(struct swap_info_struct *si)
 {
+       if (swap_is_vswap(si))
+               return;
        percpu_ref_put(&si->users);
 }
 
mm/Kconfig +20 -0
index 30170a936f1f..beef56e870ce 100644
@@ -19,6 +19,26 @@ menuconfig SWAP
          used to provide more virtual memory than the actual RAM present
          in your computer.  If unsure say Y.
 
+config VSWAP_DEFAULT_ON
+       bool "Route swapouts through virtual swap by default"
+       depends on SWAP && 64BIT
+       default n
+       help
+         Virtual swap allows zswap and zero-filled pages to be used
+         without swapping on a physical device first, and lets a page
+         move between zswap and a swapfile without invalidating the page
+         table entries that refer to it.
+
+         Swap entries are handed out by a virtual swap device instead of
+         naming a slot on a real one, so the backing can be chosen and
+         changed after the entry exists.
+
+         Say Y to make "vswap=on" the default, routing swapouts through
+         the virtual swap layer from boot.
+
+         Say N (default) to leave vswap off unless "vswap=on" is passed
+         on the kernel command line.
+
 config ZSWAP
        bool "Compressed cache for swap pages"
        depends on SWAP
mm/page_io.c +9 -0
index 1da4ff484f09..5cd77bd1b12c 100644
@@ -28,6 +28,7 @@
 #include <linux/swap_ops.h>
 #include "swap.h"
 #include "swap_table.h"
+#include "vswap.h"
 
 int generic_swapfile_activate(struct swap_info_struct *sis,
                                struct file *swap_file,
@@ -248,6 +249,14 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
        }
        rcu_read_unlock();
 
+       /*
+        * A vswap folio has no physical slot to write to, so keep it dirty.
+        */
+       if (is_vswap_entry(folio->swap)) {
+               folio_mark_dirty(folio);
+               return AOP_WRITEPAGE_ACTIVATE;
+       }
+
        __swap_writeout(ctx, folio);
        return 0;
 out_unlock:

mm/page_io.c void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio) · line 494

Quoted 4 lines
mm/page_io.c +1 -0
@@ -482,6 +491,11 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
        if (zswap_load(folio) != -ENOENT)
                goto finish;
 
+       if (unlikely(swap_is_vswap(sis))) {

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

I consider this the biggest drawback of this series. This fragmentation of the code path.

Quoted 488 lines
mm/page_io.c +4 -0
+               folio_unlock(folio);
+               goto finish;
+       }
+
        /* We have to read from slower devices. Increase zswap protection. */
        zswap_folio_swapin(folio);
        swap_add_folio(ctx, folio, READ);
mm/swap.h +74 -3
index b3b54c28929a..528a27afb335 100644
@@ -67,6 +67,12 @@ struct swap_cluster_info {
        struct list_head list;
 };
 
+struct swap_cluster_info_dynamic {
+       struct swap_cluster_info ci;
+       unsigned int index;             /* for cluster_index() */
+       struct rcu_head rcu;
+};
+
 /* All on-list cluster must have a non-zero flag. */
 enum swap_cluster_flags {
        CLUSTER_FLAG_NONE = 0, /* For temporary off-list cluster */
@@ -77,6 +83,7 @@ enum swap_cluster_flags {
        CLUSTER_FLAG_USABLE = CLUSTER_FLAG_FRAG,
        CLUSTER_FLAG_FULL,
        CLUSTER_FLAG_DISCARD,
+       CLUSTER_FLAG_DEAD,      /* Vswap dynamic cluster pending kfree_rcu */
        CLUSTER_FLAG_MAX,
 };
 
@@ -119,12 +126,33 @@ static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)
        return __swap_type_to_info(swp_type(entry));
 }
 
+/**
+ * __swap_offset_to_cluster - look up the cluster holding a swap offset
+ * @si: the swap device
+ * @offset: the swap entry offset
+ *
+ * Context: A vswap cluster is freed by kfree_rcu(). Callers must hold the
+ * RCU read lock, or know the cluster is pinned by an in-use entry.
+ *
+ * Return: the cluster, or NULL if @si is a vswap device with no cluster
+ * allocated at @offset.
+ */
 static inline struct swap_cluster_info *__swap_offset_to_cluster(
                struct swap_info_struct *si, pgoff_t offset)
 {
+       unsigned int cluster_idx = offset / SWAPFILE_CLUSTER;
+
        VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */
        VM_WARN_ON_ONCE(offset >= roundup(si->max, SWAPFILE_CLUSTER));
-       return &si->cluster_info[offset / SWAPFILE_CLUSTER];
+
+       if (swap_is_vswap(si)) {
+               struct swap_cluster_info_dynamic *ci_dyn;
+
+               ci_dyn = xa_load(&si->cluster_info_pool, cluster_idx);
+               return ci_dyn ? &ci_dyn->ci : NULL;
+       }
+
+       return &si->cluster_info[cluster_idx];
 }
 
 static inline struct swap_cluster_info *__swap_entry_to_cluster(swp_entry_t entry)
@@ -133,10 +161,36 @@ static inline struct swap_cluster_info *__swap_entry_to_cluster(swp_entry_t entr
                                        swp_offset(entry));
 }
 
+static inline struct swap_cluster_info *__vswap_cluster_lock(
+               struct swap_info_struct *si, unsigned long offset, bool irq)
+{
+       struct swap_cluster_info *ci;
+
+       rcu_read_lock();
+       ci = __swap_offset_to_cluster(si, offset);
+       if (ci) {
+               if (irq)
+                       spin_lock_irq(&ci->lock);
+               else
+                       spin_lock(&ci->lock);
+
+               /* The cluster can be torn down while we wait for the lock. */
+               if (ci->flags == CLUSTER_FLAG_DEAD) {
+                       if (irq)
+                               spin_unlock_irq(&ci->lock);
+                       else
+                               spin_unlock(&ci->lock);
+                       ci = NULL;
+               }
+       }
+       rcu_read_unlock();
+       return ci;
+}
+
 static __always_inline struct swap_cluster_info *__swap_cluster_lock(
                struct swap_info_struct *si, unsigned long offset, bool irq)
 {
-       struct swap_cluster_info *ci = __swap_offset_to_cluster(si, offset);
+       struct swap_cluster_info *ci;
 
        /*
         * Nothing modifies swap cache in an IRQ context. All access to
@@ -149,6 +203,11 @@ static __always_inline struct swap_cluster_info *__swap_cluster_lock(
         */
        VM_WARN_ON_ONCE(!in_task());
        VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */
+
+       if (swap_is_vswap(si))
+               return __vswap_cluster_lock(si, offset, irq);
+
+       ci = __swap_offset_to_cluster(si, offset);
        if (irq)
                spin_lock_irq(&ci->lock);
        else
@@ -159,10 +218,12 @@ static __always_inline struct swap_cluster_info *__swap_cluster_lock(
 /**
  * swap_cluster_lock - Lock and return the swap cluster of given offset.
  * @si: swap device the cluster belongs to.
- * @offset: the swap entry offset, pointing to a valid slot.
+ * @offset: the swap entry offset.
  *
  * Context: The caller must ensure the offset is in the valid range and
  * protect the swap device with reference count or locks.
+ * Return: the locked cluster, or NULL if it is gone. Only a vswap device
+ * can return NULL, as its clusters are allocated and freed on demand.
  */
 static inline struct swap_cluster_info *swap_cluster_lock(
                struct swap_info_struct *si, unsigned long offset)
@@ -363,6 +424,16 @@ static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)
        return NULL;
 }
 
+static inline struct swap_cluster_info *__swap_entry_to_cluster(swp_entry_t entry)
+{
+       return NULL;
+}
+
+static inline unsigned int swp_cluster_offset(swp_entry_t entry)
+{
+       return 0;
+}
+
 static inline int folio_alloc_swap(struct folio *folio)
 {
        return -EINVAL;
mm/swap_state.c +22 -18
index cef44aadee61..424a0040b4b8 100644
@@ -96,8 +96,7 @@ struct folio *swap_cache_get_folio(swp_entry_t entry)
        struct folio *folio;
 
        for (;;) {
-               swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-                                       swp_cluster_offset(entry));
+               swp_tb = swap_table_lookup(entry);
                if (!swp_tb_is_folio(swp_tb))
                        return NULL;
                folio = swp_tb_to_folio(swp_tb);
@@ -119,8 +118,7 @@ bool swap_cache_has_folio(swp_entry_t entry)
 {
        unsigned long swp_tb;
 
-       swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-                               swp_cluster_offset(entry));
+       swp_tb = swap_table_lookup(entry);
        return swp_tb_is_folio(swp_tb);
 }
 
@@ -136,8 +134,7 @@ void *swap_cache_get_shadow(swp_entry_t entry)
 {
        unsigned long swp_tb;
 
-       swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-                               swp_cluster_offset(entry));
+       swp_tb = swap_table_lookup(entry);
        if (swp_tb_is_shadow(swp_tb))
                return swp_tb_to_shadow(swp_tb);
        return NULL;
@@ -414,14 +411,16 @@ void __swap_cache_replace_folio(struct swap_cluster_info *ci,
  * -ENOENT / -EEXIST: Target swap entry is unavailable or cached, the caller
  *                    should abort or try to use the cached folio instead
  */
-static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
-                                       swp_entry_t targ_entry, gfp_t gfp,
+static struct folio *__swap_cache_alloc(swp_entry_t targ_entry, gfp_t gfp,
                                        unsigned int order, struct vm_fault *vmf,
                                        struct mempolicy *mpol, pgoff_t ilx)
 {
        int err;
        swp_entry_t entry;
        struct folio *folio;
+       struct swap_cluster_info *ci;
+       struct swap_info_struct *si = __swap_entry_to_info(targ_entry);
+       unsigned long offset = swp_offset(targ_entry);
        void *shadow = NULL;
        unsigned short memcg_id;
        unsigned long address, nr_pages = 1UL << order;
@@ -431,9 +430,12 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
        entry.val = round_down(targ_entry.val, nr_pages);
 
        /* Check if the slot and range are available, skip allocation if not */
-       spin_lock(&ci->lock);
-       err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
-       spin_unlock(&ci->lock);
+       err = -ENOENT;
+       ci = swap_cluster_lock(si, offset);
+       if (ci) {
+               err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
+               swap_cluster_unlock(ci);
+       }
        if (unlikely(err))
                return ERR_PTR(err);
 
@@ -454,10 +456,13 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
                return ERR_PTR(-ENOMEM);
 
        /* Double check the range is still not in conflict */
-       spin_lock(&ci->lock);
-       err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
+       err = -ENOENT;
+       ci = swap_cluster_lock(si, offset);
+       if (ci)
+               err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
        if (unlikely(err)) {
-               spin_unlock(&ci->lock);
+               if (ci)
+                       swap_cluster_unlock(ci);
                folio_put(folio);
                return ERR_PTR(err);
        }
@@ -465,10 +470,11 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
        __folio_set_locked(folio);
        __folio_set_swapbacked(folio);
        __swap_cache_do_add_folio(ci, folio, entry);
-       spin_unlock(&ci->lock);
+       swap_cluster_unlock(ci);
 
        if (mem_cgroup_swapin_charge_folio(folio, memcg_id,
                                           vmf ? vmf->vma->vm_mm : NULL, gfp)) {
+               /* The folio pins the cluster */
                spin_lock(&ci->lock);
                __swap_cache_do_del_folio(ci, folio, entry, shadow);
                spin_unlock(&ci->lock);
@@ -525,9 +531,7 @@ struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,
 {
        int order, err;
        struct folio *ret;
-       struct swap_cluster_info *ci;
 
-       ci = __swap_entry_to_cluster(targ_entry);
        order = highest_order(orders);
 
        /* orders must be non-zero, and must not exceed cluster size. */
@@ -535,7 +539,7 @@ struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,
                return ERR_PTR(-EINVAL);
 
        do {
-               ret = __swap_cache_alloc(ci, targ_entry, gfp, order,
+               ret = __swap_cache_alloc(targ_entry, gfp, order,
                                         vmf, mpol, ilx);
                if (!IS_ERR(ret))
                        break;
mm/swap_table.h +27 -0
index e6613e62f8d0..3d64d1629882 100644
@@ -6,6 +6,8 @@
 #include <linux/atomic.h>
 #include "swap.h"
 
+extern struct swap_info_struct *vswap_si;
+
 /* A typical flat array in each cluster as swap table */
 struct swap_table {
        atomic_long_t entries[SWAPFILE_CLUSTER];
@@ -264,6 +266,31 @@ static inline unsigned long swap_table_get(struct swap_cluster_info *ci,
        return swp_tb;
 }
 
+/*
+ * Resolve @entry's cluster and read its slot, both under RCU. A vswap
+ * cluster is allocated on demand and freed by kfree_rcu(), so a caller
+ * starting from an entry cannot resolve it beforehand.
+ */
+static inline unsigned long swap_table_lookup(swp_entry_t entry)
+{
+       struct swap_cluster_info *ci;
+       atomic_long_t *table;
+       unsigned long swp_tb;
+
+       rcu_read_lock();
+       ci = __swap_entry_to_cluster(entry);
+       if (!ci) {
+               rcu_read_unlock();
+               return null_to_swp_tb();
+       }
+       table = rcu_dereference(ci->table);
+       swp_tb = table ? atomic_long_read(&table[swp_cluster_offset(entry)])
+                      : null_to_swp_tb();
+       rcu_read_unlock();
+
+       return swp_tb;
+}
+
 static inline void __swap_table_set_zero(struct swap_cluster_info *ci,
                                         unsigned int ci_off)
 {
mm/swapfile.c +79 -5
index c1c5fbb3c909..edd7bddf7ff9 100644
@@ -36,6 +36,7 @@
 #include <linux/poll.h>
 #include <linux/oom.h>
 #include <linux/swapfile.h>
+#include <linux/swap_ops.h>
 #include <linux/export.h>
 #include <linux/sort.h>
 #include <linux/completion.h>
@@ -46,6 +47,7 @@
 #include <asm/tlbflush.h>
 #include <linux/leafops.h>
 #include "swap_table.h"
+#include "vswap.h"
 #include "internal.h"
 #include "swap.h"
 
@@ -399,6 +401,8 @@ static inline bool cluster_is_usable(struct swap_cluster_info *ci, int order)
 static inline unsigned int cluster_index(struct swap_info_struct *si,
                                         struct swap_cluster_info *ci)
 {
+       if (swap_is_vswap(si))
+               return container_of(ci, struct swap_cluster_info_dynamic, ci)->index;
        return ci - si->cluster_info;
 }
 
@@ -594,10 +598,15 @@ static void move_cluster(struct swap_info_struct *si,
        lockdep_assert_held(&ci->lock);
 
        spin_lock(&si->lock);
-       if (ci->flags == CLUSTER_FLAG_NONE)
+       if (!list) {
+               /* Going away. An isolated cluster is already off its list. */
+               if (ci->flags != CLUSTER_FLAG_NONE)
+                       list_del(&ci->list);
+       } else if (ci->flags == CLUSTER_FLAG_NONE) {
                list_add_tail(&ci->list, list);
-       else
+       } else {
                list_move_tail(&ci->list, list);
+       }
        spin_unlock(&si->lock);
        ci->flags = new_flags;
 }
@@ -615,6 +624,18 @@ static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info
 {
        swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, false);
        swap_cluster_free_table(ci);
+
+       if (swap_is_vswap(si)) {
+               struct swap_cluster_info_dynamic *ci_dyn;
+
+               /* vswap clusters are destroyed, not returned to free_clusters. */
+               ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+               xa_erase(&si->cluster_info_pool, ci_dyn->index);
+               move_cluster(si, ci, NULL, CLUSTER_FLAG_DEAD);
+               kfree_rcu(ci_dyn, rcu);
+               return;
+       }
+
        move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
        ci->order = 0;
 }
@@ -851,6 +872,8 @@ static bool cluster_reclaim_range(struct swap_info_struct *si,
        unsigned long offset = start, end = start + nr_pages;
        unsigned long swp_tb;
 
+       VM_WARN_ON_ONCE(swap_is_vswap(si));
+
        spin_unlock(&ci->lock);
        do {
                swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
@@ -1042,6 +1065,44 @@ static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,
        return found;
 }
 
+static unsigned int vswap_alloc_cluster(struct swap_info_struct *si,
+                                       struct folio *folio)
+{
+       struct swap_cluster_info_dynamic *ci_dyn;
+       struct swap_cluster_info *ci;
+       unsigned long offset;
+
+       VM_WARN_ON(!swap_is_vswap(si));
+
+       ci_dyn = kzalloc_obj(*ci_dyn, GFP_ATOMIC | __GFP_NOWARN);
+       if (!ci_dyn)
+               return SWAP_ENTRY_INVALID;
+
+       spin_lock_init(&ci_dyn->ci.lock);
+       INIT_LIST_HEAD(&ci_dyn->ci.list);
+
+       if (swap_cluster_alloc_table(&ci_dyn->ci, GFP_ATOMIC | __GFP_NOWARN)) {
+               kfree(ci_dyn);
+               return SWAP_ENTRY_INVALID;
+       }
+
+       /* Lock before publishing: xa_alloc makes the cluster findable by offset. */
+       ci = &ci_dyn->ci;
+       spin_lock(&ci->lock);
+
+       if (xa_alloc(&si->cluster_info_pool, &ci_dyn->index, ci_dyn,
+                    XA_LIMIT(1, DIV_ROUND_UP(si->max, SWAPFILE_CLUSTER) - 1),
+                    GFP_ATOMIC | __GFP_NOWARN)) {
+               spin_unlock(&ci->lock);
+               swap_cluster_free_table(&ci_dyn->ci);
+               kfree(ci_dyn);
+               return SWAP_ENTRY_INVALID;
+       }
+
+       offset = cluster_offset(si, ci);
+       return alloc_swap_scan_cluster(si, ci, folio, offset);
+}
+
 static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 {
        long to_scan = 1;
@@ -1064,7 +1125,9 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
                                spin_unlock(&ci->lock);
                                nr_reclaim = __try_to_reclaim_swap(si, offset,
                                                                   TTRS_ANYWAY);
-                               spin_lock(&ci->lock);
+                               ci = swap_cluster_lock(si, offset);
+                               if (!ci)
+                                       goto next;
                                if (nr_reclaim) {
                                        offset += abs(nr_reclaim);
                                        continue;
@@ -1078,6 +1141,7 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
                        relocate_cluster(si, ci);
 
                swap_cluster_unlock(ci);
+next:
                if (to_scan <= 0)
                        break;
 
@@ -1154,6 +1218,12 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
                        goto done;
        }
 
+       if (swap_is_vswap(si)) {
+               found = vswap_alloc_cluster(si, folio);
+               if (found)
+                       goto done;
+       }
+
        if (!(si->flags & SWP_PAGE_DISCARD)) {
                found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
                if (found)
@@ -1290,8 +1360,10 @@ static bool swap_usage_add(struct swap_info_struct *si, unsigned int nr_entries)
        /*
         * If device is full, and SWAP_USAGE_OFFLIST_BIT is not set,
         * remove it from the plist.
+        *
+        * Vswap is never on the avail list, so skip it.
         */
-       if (unlikely(val == si->pages)) {
+       if (unlikely(val == si->pages) && !swap_is_vswap(si)) {
                del_from_avail_list(si, false);
                return true;
        }
@@ -1306,8 +1378,10 @@ static void swap_usage_sub(struct swap_info_struct *si, unsigned int nr_entries)
        /*
         * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,
         * add it to the plist.
+        *
+        * Vswap is never on the avail list, so skip it.
         */
-       if (unlikely(val & SWAP_USAGE_OFFLIST_BIT))
+       if (unlikely(val & SWAP_USAGE_OFFLIST_BIT) && !swap_is_vswap(si))
                add_to_avail_list(si, false);
 }
 

mm/swapfile.c static void swap_range_free(struct swap_info_struct *si, unsigned long offset, · line 1431

Quoted 6 lines
mm/swapfile.c +3 -0
@@ -1352,6 +1426,10 @@ static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
 
 static bool get_swap_device_info(struct swap_info_struct *si)
 {
+       /* The vswap device is always alive, so it needs no refcount. */
+       if (swap_is_vswap(si))
+               return true;

This is questionable. A vswap device does not go through swap on.

This changes the behavior where swap devices always go through swap on/off.

I wish the swap device went through swap on to be able to start swapping.

Chris

Quoted 378 lines
mm/swapfile.c +172 -16
+
        if (!percpu_ref_tryget_live(&si->users))
                return false;
        /*
@@ -1387,11 +1465,11 @@ static bool swap_alloc_fast(struct folio *folio)
                return false;
 
        ci = swap_cluster_lock(si, offset);
-       if (cluster_is_usable(ci, order)) {
+       if (ci && cluster_is_usable(ci, order)) {
                if (cluster_is_empty(ci))
                        offset = cluster_offset(si, ci);
                alloc_swap_scan_cluster(si, ci, folio, offset);
-       } else {
+       } else if (ci) {
                swap_cluster_unlock(ci);
        }
 
@@ -1513,6 +1591,7 @@ int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp)
        if (IS_ERR_OR_NULL(si))
                return 0;
 
+       /* The source PTE pins the entry, so its cluster is alive. */
        ci = __swap_offset_to_cluster(si, offset);
        ret = swap_extend_table_alloc(si, ci, swp_cluster_offset(entry), gfp);
 
@@ -1923,7 +2002,7 @@ struct swap_info_struct *get_swap_device(swp_entry_t entry)
        return NULL;
 put_out:
        pr_err_ratelimited("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
-       percpu_ref_put(&si->users);
+       put_swap_device(si);
        return ERR_PTR(-EIO);
 }
 
@@ -2002,7 +2081,7 @@ bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry)
        unsigned long swp_tb;
 
        ci = swap_cluster_lock(si, offset);
-       swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
+       swp_tb = __swap_table_get(ci, swp_cluster_offset(entry));
        swap_cluster_unlock(ci);
 
        return swp_tb_get_count(swp_tb) > 0;
@@ -2055,6 +2134,7 @@ static bool folio_maybe_swapped(struct folio *folio)
        VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
        VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
 
+       /* Folio is locked and in swap cache, so ci->count > 0: cluster is alive. */
        ci = __swap_entry_to_cluster(entry);
        ci_off = swp_cluster_offset(entry);
        ci_end = ci_off + folio_nr_pages(folio);
@@ -2249,6 +2329,9 @@ static int __find_hibernation_swap_type(dev_t device, sector_t offset)
 
                if (!(sis->flags & SWP_WRITEOK))
                        continue;
+               /* vswap has no bdev, so it is never a hibernation target. */
+               if (swap_is_vswap(sis))
+                       continue;
 
                if (device == sis->bdev->bd_dev) {
                        struct swap_extent *se = first_se(sis);
@@ -2375,6 +2458,9 @@ int find_first_swap(dev_t *device)
 
                if (!(sis->flags & SWP_WRITEOK))
                        continue;
+               /* vswap has no bdev, so it is never a hibernation target. */
+               if (swap_is_vswap(sis))
+                       continue;
                *device = sis->bdev->bd_dev;
                spin_unlock(&swap_lock);
                return type;
@@ -2591,8 +2677,7 @@ static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
                                                &vmf);
                }
                if (!folio) {
-                       swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
-                                               swp_cluster_offset(entry));
+                       swp_tb = swap_table_lookup(entry);
                        if (swp_tb_get_count(swp_tb) <= 0)
                                continue;
                        return -ENOMEM;
@@ -3022,15 +3107,24 @@ static int setup_swap_extents(struct swap_info_struct *sis,
 
 static void _enable_swap_info(struct swap_info_struct *si)
 {
-       atomic_long_add(si->pages, &nr_swap_pages);
-       total_swap_pages += si->pages;
+       if (!swap_is_vswap(si)) {
+               atomic_long_add(si->pages, &nr_swap_pages);
+               total_swap_pages += si->pages;
+       }
 
        assert_spin_locked(&swap_lock);
 
-       plist_add(&si->list, &swap_active_head);
+       /*
+        * Vswap has no backing file and no swapoff support, so keep it
+        * off swap_active_head (used by swapoff filename lookup and
+        * swap_sync_discard) and swap_avail_head (physical allocator).
+        */
+       if (!swap_is_vswap(si)) {
+               plist_add(&si->list, &swap_active_head);
 
-       /* Add back to available list */
-       add_to_avail_list(si, true);
+               /* Add back to available list */
+               add_to_avail_list(si, true);
+       }
 }
 
 /*
@@ -3074,12 +3168,31 @@ static void wait_for_allocation(struct swap_info_struct *si)
        }
 }
 
-static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
+static void free_swap_cluster_info(struct swap_info_struct *si,
+                                  struct swap_cluster_info *cluster_info,
                                   unsigned long maxpages)
 {
+       struct swap_cluster_info_dynamic *ci_dyn;
        struct swap_cluster_info *ci;
+       unsigned long idx;
        int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 
+       if (swap_is_vswap(si)) {
+               xa_for_each(&si->cluster_info_pool, idx, ci_dyn) {
+                       ci = &ci_dyn->ci;
+                       spin_lock(&ci->lock);
+                       if (cluster_table_is_alloced(ci)) {
+                               swap_cluster_assert_empty(ci, 0,
+                                                         SWAPFILE_CLUSTER, true);
+                               swap_cluster_free_table(ci);
+                       }
+                       spin_unlock(&ci->lock);
+                       kfree(ci_dyn);
+               }
+               xa_destroy(&si->cluster_info_pool);
+               return;
+       }
+
        if (!cluster_info)
                return;
        for (i = 0; i < nr_clusters; i++) {
@@ -3226,7 +3339,7 @@ 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, cluster_info, maxpages);
 
        inode = mapping->host;
 
@@ -3573,10 +3686,39 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
                                    unsigned long maxpages)
 {
        unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
-       struct swap_cluster_info *cluster_info;
+       struct swap_cluster_info *cluster_info = NULL;
+       struct swap_cluster_info_dynamic *ci_dyn = NULL;
        int err = -ENOMEM;
        unsigned long i;
 
+       /* A vswap device uses an xarray pool instead of a static array. */
+       if (swap_is_vswap(si)) {
+               nr_clusters = 0;
+               xa_init_flags(&si->cluster_info_pool, XA_FLAGS_ALLOC);
+
+               /*
+                * Pre-allocate cluster 0 and mark slot 0 (header page)
+                * as bad so the allocator never hands out page offset 0.
+                */
+               ci_dyn = kzalloc_obj(*ci_dyn, GFP_KERNEL);
+               if (!ci_dyn)
+                       goto err;
+               spin_lock_init(&ci_dyn->ci.lock);
+               INIT_LIST_HEAD(&ci_dyn->ci.list);
+
+               err = xa_insert(&si->cluster_info_pool, 0, ci_dyn, GFP_KERNEL);
+               if (err) {
+                       kfree(ci_dyn);
+                       goto err;
+               }
+
+               err = swap_cluster_setup_bad_slot(si, &ci_dyn->ci, 0, false);
+               if (err)
+                       goto err;
+
+               goto setup_cluster_info;
+       }
+
        cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
        if (!cluster_info)
                goto err;
@@ -3620,6 +3762,7 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
                        goto err;
        }
 
+setup_cluster_info:
        INIT_LIST_HEAD(&si->free_clusters);
        INIT_LIST_HEAD(&si->full_clusters);
        INIT_LIST_HEAD(&si->discard_clusters);
@@ -3641,10 +3784,16 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
                }
        }
 
+       /* Slot 0 is bad, so cluster 0 never empties. The rest of it is usable. */
+       if (swap_is_vswap(si)) {
+               ci_dyn->ci.flags = CLUSTER_FLAG_NONFULL;
+               list_add_tail(&ci_dyn->ci.list, &si->nonfull_clusters[0]);
+       }
+
        si->cluster_info = cluster_info;
        return 0;
 err:
-       free_swap_cluster_info(cluster_info, maxpages);
+       free_swap_cluster_info(si, cluster_info, maxpages);
        return err;
 }
 
@@ -3866,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, si->max);
        si->cluster_info = NULL;
        /*
         * Clear the SWP_USED flag after all resources are freed so
@@ -3997,3 +4146,87 @@ static int __init swapfile_init(void)
        return 0;
 }
 subsys_initcall(swapfile_init);
+
+struct swap_info_struct *vswap_si;
+DEFINE_STATIC_KEY_FALSE(vswap_key);
+
+static bool vswap_enabled_early __initdata = IS_ENABLED(CONFIG_VSWAP_DEFAULT_ON);
+
+static int __init early_vswap(char *buf)
+{
+       return kstrtobool(buf, &vswap_enabled_early);
+}
+early_param("vswap", early_vswap);
+
+/* vswap does no IO on its own. */
+static const struct swap_ops vswap_ops = { };
+
+static int __init vswap_init(void)
+{
+       struct swap_info_struct *si;
+       unsigned long maxpages;
+       int err;
+
+       if (!IS_ENABLED(CONFIG_64BIT)) {
+               if (vswap_enabled_early)
+                       pr_warn("vswap: requires 64-bit architecture; vswap disabled, swapout falls back to direct physical swap\n");
+               return 0;
+       }
+
+       if (!vswap_enabled_early)
+               return 0;
+
+       si = alloc_swap_info();
+       if (IS_ERR(si)) {
+               pr_warn("vswap: alloc_swap_info failed (%ld); vswap disabled, swapout falls back to direct physical swap\n",
+                       PTR_ERR(si));
+               return 0;
+       }
+
+       /*
+        * Each swapped page holds a reference on its cgroup's
+        * memcg->private_id_ref, a 32-bit refcount_t, so a cgroup that swaps
+        * REFCOUNT_MAX pages saturates it and leaks the memcg until reboot.
+        * Cap the device there; that also keeps page counts inside si->max's
+        * unsigned int. Lifting it needs the memcg refcount widened, which a
+        * physical swapfile of this size needs too.
+        */
+       maxpages = min(swapfile_maximum_size,
+                      ALIGN_DOWN((unsigned long)REFCOUNT_MAX, SWAPFILE_CLUSTER));
+       /*
+        * SWP_WRITEOK enables slot allocation. SWP_SOLIDSTATE selects
+        * per-CPU cluster allocation; vswap has no si->global_cluster.
+        */
+       si->flags |= SWP_VSWAP | SWP_SOLIDSTATE | SWP_WRITEOK;
+       si->ops = &vswap_ops;
+       si->bdev = NULL;
+       si->max = maxpages;
+       si->pages = maxpages - 1;
+
+       INIT_WORK(&si->discard_work, swap_discard_work);
+       INIT_WORK(&si->reclaim_work, swap_reclaim_work);
+
+       err = setup_swap_clusters_info(si, NULL, maxpages);
+       if (err)
+               goto fail;
+
+       mutex_lock(&swapon_mutex);
+       enable_swap_info(si);
+       mutex_unlock(&swapon_mutex);
+
+       vswap_si = si;
+       pr_info("vswap: created virtual swap device (%lu pages)\n", maxpages);
+
+       /* Last: everything above must be visible before routing starts. */
+       static_branch_enable(&vswap_key);
+       return 0;
+
+fail:
+       pr_warn("vswap: setup_swap_clusters_info failed (%d); vswap disabled, swapout falls back to direct physical swap\n",
+               err);
+       spin_lock(&swap_lock);
+       si->flags = 0;
+       spin_unlock(&swap_lock);
+       return 0;
+}
+late_initcall(vswap_init);
mm/vswap.h new file +34 -0
new file mode 100644
index 000000000000..16395f357955
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Virtual swap space
+ *
+ * Copyright (C) 2026 Nhat Pham
+ */
+#ifndef _MM_VSWAP_H
+#define _MM_VSWAP_H
+
+#include <linux/jump_label.h>
+#include <linux/swap.h>
+#include "swap.h"
+
+#ifdef CONFIG_SWAP
+
+DECLARE_STATIC_KEY_FALSE(vswap_key);
+
+/*
+ * Only true once vswap_init() has published vswap_si, so callers never
+ * see the device half built.
+ */
+static inline bool vswap_is_enabled(void)
+{
+       return static_branch_unlikely(&vswap_key);
+}
+
+static inline bool is_vswap_entry(swp_entry_t entry)
+{
+       return swap_is_vswap(__swap_entry_to_info(entry));
+}
+
+#endif /* CONFIG_SWAP */
+
+#endif /* _MM_VSWAP_H */
mm/zswap.c +6 -1
index 507f2d19fd2a..73728b510ff6 100644
@@ -1018,6 +1018,12 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
        if (IS_ERR_OR_NULL(si))
                return -ENOENT;
 
+       /* Vswap entries have no physical backing to write to. */
+       if (swap_is_vswap(si)) {
+               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);
--

2.53.0-Meta

author maintainer
#3 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 8 lines · Chris Li

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

I consider this the biggest drawback of this series. This fragmentation of the code path.

This will mirror my response at [1], but I'm responding here for the record and for your convenience.

It is needed because vswap *is* a special device, with its own requirements. If you don't special case-it, you'd get undesirable behaviors.

Let's take Baoquan's patch series as an example. It treats the xswap device as just another swap device, without any special consideration for it. Which creates several problem:

1. At allocation time, cgroups that disable zswap might get an xswap slot, because you don't do any check that the device you allocating the swap slots for is xswap. At swap_writeout() time, it is *stuck* - we already do the unmapping step, so we cannot reclaim the page.

Ironically a physical swapfile backend could have bailed us out here, but it's not in that patch series yet :)

Vswap both has swapfile backend, AND allows you to bypass it if the cgroup disables zswap. Both involves a bit of swap_is_vswap() check, but I think it's worth it :)

2. Per-CPU allocation caching: since all devices share the same cache, xswap will invalidate the caching of other devices, and vice versa. It would be fine if the these devices are interchangeable, but as noted above, it's not, especially without physical swapfile as the backend option. So you're forced to taken the slow path more often.

Vswap gets around this by adding its own per-cpu allocation caching,

So by being too lazy and not carefully distinguish the swap devices, not only does xswap not work for the writeback use case, it cannot even work in deployments where some workloads (cgroup) select zswap, whereas others select disk swap. It can only work if you intend to have a single class of device - either virtual/xswap or disk swap - but not both.

Maybe instead of just grepping for swap_is_vswap() and throw your hand at the complexity, read the code and try to understand why it's necessary first, then propose simplifications if you have good ideas in minds.

Quoted 8 lines

This is questionable. A vswap device does not go through swap on.

This changes the behavior where swap devices always go through swap on/off.

I wish the swap device went through swap on to be able to start swapping.

Chris

What usecase would necessitate the need for swapon/swapoff interface? Other than just trying to shoehorn it to an existing interface?

I've expressed why I dislike the interface in [1]. Other than the sizing aspect, which we are already discussing in another thread, priority also makes zero sense. You are literally exposing an interface with only one correct answer - what's the point?

Justify your interface choice with real userspace use case, not just by conforming to the status quo.

[1]: https://lore.kernel.org/all/CAKEwX=PEEkYiNRaVhCuM4E6mxB9huPKfkDa4m62VMTzedg1oYw@mail.gmail.com/

maintainer
#4 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 8 lines · Nhat Pham
Quoted 6 lines · Chris Li

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

Quoted 5 lines
Quoted 2 lines

I consider this the biggest drawback of this series. This fragmentation of the code path.

This will mirror my response at [1], but I'm responding here for the record and for your convenience.

Thank you. Really appriciate that.

Quoted 3 lines

It is needed because vswap *is* a special device, with its own requirements. If you don't special case-it, you'd get undesirable behaviors.

Ack, that is why I am against making it a special device. That is the whole idea behind xswap. It is just normal swap device implemented via swap_ops just like ext4 is a file system implemnet on top of VFS.

Quoted 3 lines

Let's take Baoquan's patch series as an example. It treats the xswap device as just another swap device, without any special consideration for it. Which creates several problem:

That is a careful design choice. Keep in mind that design choice usually has pros and cons.

I will follow your feedback here.

Quoted 7 lines

1. At allocation time, cgroups that disable zswap might get an xswap slot, because you don't do any check that the device you allocating the swap slots for is xswap. At swap_writeout() time, it is *stuck* - we already do the unmapping step, so we cannot reclaim the page.

Ironically a physical swapfile backend could have bailed us out here, but it's not in that patch series yet :)

I am not sure I follow. Are you referring to the uncompressible pages that xswap would have to reject?

One way to address that is for xswap to just bite the bullet and store the uncompressible pages within xswap. That way it will stay out of the reclaim LRU. Zswap also stores some uncompressible pages. The last time I checked, it was unfortunately not able to serve my case but perfect for yours.

Quoted 3 lines

Vswap both has swapfile backend, AND allows you to bypass it if the cgroup disables zswap. Both involves a bit of swap_is_vswap() check, but I think it's worth it :)

If xswap needs the lower tier it can allocate for one. I don't think xswap should need to have swap_is_xswap() there. Also xswap does not have all the baggage of zswap.writeback enable interface.

Quoted 6 lines

2. Per-CPU allocation caching: since all devices share the same cache, xswap will invalidate the caching of other devices, and vice versa. It would be fine if the these devices are interchangeable, but as noted above, it's not, especially without physical swapfile as the backend option. So you're forced to taken the slow path more often.

This will be addressed by the swap tiers series if it is not delayed. This should be addressed in the core swap layer not vswap. Kairui also has some ideas to improve that. Yes, it is a problem area, but it is not specific to xswap. We are well aware of it and have plans to improve it.

Quoted 9 lines

Vswap gets around this by adding its own per-cpu allocation caching,

So by being too lazy and not carefully distinguish the swap devices, not only does xswap not work for the writeback use case, it cannot even work in deployments where some workloads (cgroup) select zswap, whereas others select disk swap. It can only work if you intend to have a single class of device - either virtual/xswap or disk swap - but not both.

Baoquan's writeback series is out. It is by no means perfect. But it is much closer to what I have in mind. That is a much better base to work on.

Quoted 5 lines

Maybe instead of just grepping for swap_is_vswap() and throw your hand at the complexity, read the code and try to understand why it's necessary first, then propose simplifications if you have good ideas in minds.

Yes, I already read your code I decide that most of the swap_is_vswap() should not be needed if taking a proper swap_ops approach. I wanted to offer you the chance to work closely with me to achieve that, but you did not follow that suggestion.

Quote from my old email:
https://lore.kernel.org/all/CACePvbX+3tO91BmRwaLqf3Xia32GCemt3W8tayErG81BYLgrzA@mail.gmail.com/

"I am happy to spend some time working with you to discuss the generic adopted version of vswap, if you are open to it. Or if you don't want to waste time on it. I can have someone else or myself come up with the generic adopted version of vswap for you to review, which I prefer less."

Anyway, Baoquan's xswap writeback patch series is out. I suggest following and improving that series instead.

Quoted 10 lines
Quoted 6 lines

This is questionable. A vswap device does not go through swap on.

This changes the behavior where swap devices always go through swap on/off.

I wish the swap device went through swap on to be able to start swapping.

What usecase would necessitate the need for swapon/swapoff interface? Other than just trying to shoehorn it to an existing interface?

I like universal interfaces. Your vswap will break the /etc/fstab. The current suggestion for xswap using sysfs will break that as well. I would like to keep the /etc/fstab interface working, including support for UUIDs for swap devices, etc.
I am very concerned that vswap will start kicking in without me explicitly enabling it. That changes the previous user-visible behavior. It breaks my mental model. Please take this feedback seriously.

It is a different design philosophy to adopt a swap device to implement VFS-like file systems for swap, making them swap file systems.
Just like all file systems have a superblock so you can probe what file system it is. You don't get a special sysfs interface for each different file system to create them.
This aligns neatly with swap ops and makes room for future flash-friendly swap file systems for example.

Quoted 7 lines

I've expressed why I dislike the interface in [1]. Other than the sizing aspect, which we are already discussing in another thread, priority also makes zero sense. You are literally exposing an interface with only one correct answer - what's the point?

Justify your interface choice with real userspace use case, not just by conforming to the status quo.

That is why I feel your patch series are really unclean. I dislike special cases, I try to avoid them as much as possible.

Chris

Quoted 2 lines

[1]: https://lore.kernel.org/all/CAKEwX=PEEkYiNRaVhCuM4E6mxB9huPKfkDa4m62VMTzedg1oYw@mail.gmail.com/

#5 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 11 lines · Chris Li
Quoted 5 lines · Nhat Pham

It is needed because vswap *is* a special device, with its own requirements. If you don't special case-it, you'd get undesirable behaviors.

Ack, that is why I am against making it a special device. That is the whole idea behind xswap. It is just normal swap device implemented via
swap_ops just like ext4 is a file system implemnet on top of VFS.

The filesystem layer is relatively clean because
it has a VFS.

Are you saying it is time we have a similar
abstraction layer on the swap side?

Signature · 1 line
All Rights Reversed.
maintainer
#6 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 14 lines · Rik van Riel
Quoted 11 lines · Chris Li
Quoted 5 lines · Nhat Pham

It is needed because vswap *is* a special device, with its own requirements. If you don't special case-it, you'd get undesirable behaviors.

Ack, that is why I am against making it a special device. That is the whole idea behind xswap. It is just normal swap device implemented via
swap_ops just like ext4 is a file system implemnet on top of VFS.

Quoted 5 lines

The filesystem layer is relatively clean because
it has a VFS.

Are you saying it is time we have a similar
abstraction layer on the swap side?

Yes, you understand me well. The swap side VFS already started as swap_ops. I give a LSF/MM talk on it as well. It is already cleaning up some ZRAM special cases in the block layer. That is what xswap is building on top of.

Chris

author maintainer
#7 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

In reply to Chris Li
Quoted 43 lines · Chris Li
Quoted 8 lines · Nhat Pham
Quoted 6 lines · Chris Li

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

Quoted 5 lines
Quoted 2 lines

I consider this the biggest drawback of this series. This fragmentation of the code path.

This will mirror my response at [1], but I'm responding here for the record and for your convenience.

Thank you. Really appriciate that.

Quoted 3 lines

It is needed because vswap *is* a special device, with its own requirements. If you don't special case-it, you'd get undesirable behaviors.

Ack, that is why I am against making it a special device. That is the whole idea behind xswap. It is just normal swap device implemented via swap_ops just like ext4 is a file system implemnet on top of VFS.

Quoted 3 lines

Let's take Baoquan's patch series as an example. It treats the xswap device as just another swap device, without any special consideration for it. Which creates several problem:

That is a careful design choice. Keep in mind that design choice usually has pros and cons.

I will follow your feedback here.

Quoted 7 lines

1. At allocation time, cgroups that disable zswap might get an xswap slot, because you don't do any check that the device you allocating the swap slots for is xswap. At swap_writeout() time, it is *stuck* - we already do the unmapping step, so we cannot reclaim the page.

Ironically a physical swapfile backend could have bailed us out here, but it's not in that patch series yet :)

Quoted 8 lines

I am not sure I follow. Are you referring to the uncompressible pages that xswap would have to reject?

One way to address that is for xswap to just bite the bullet and store the uncompressible pages within xswap. That way it will stay out of the reclaim LRU. Zswap also stores some uncompressible pages. The last time I checked, it was unfortunately not able to serve my case but perfect for yours.

Not even that. Say you have two kind of workloads in the same host:
workload enables disk swap but disable zswap (zswap.max = 0), and workload that wants zswap. Let's even ignore writeback for now.

You add 2 "swap devices" to the system: xswap and NVME swapfile.

At swap allocation time, xswap patch series does not check carefully which swap device is being used, so you might get an xswap slot for the cgroup that disables zswap. You're stuck at swap_writeout() time. You can't undo it anymore, and you don't even support the physical swapfile backend to fallback.

Quoted 8 lines
Quoted 4 lines

Vswap both has swapfile backend, AND allows you to bypass it if the cgroup disables zswap. Both involves a bit of swap_is_vswap() check, but I think it's worth it :)

If xswap needs the lower tier it can allocate for one. I don't think xswap should need to have swap_is_xswap() there. Also xswap does not have all the baggage of zswap.writeback enable interface.

But that's my point. As of now, it does not. Unless you merge the other RFC series, which brings it to roughly the same size as what I'm doing here.

Quoted 9 lines
Quoted 8 lines

2. Per-CPU allocation caching: since all devices share the same cache, xswap will invalidate the caching of other devices, and vice versa. It would be fine if the these devices are interchangeable, but as noted above, it's not, especially without physical swapfile as the backend option. So you're forced to taken the slow path more often.

Quoted 5 lines

This will be addressed by the swap tiers series if it is not delayed. This should be addressed in the core swap layer not vswap. Kairui also has some ideas to improve that. Yes, it is a problem area, but it is not specific to xswap. We are well aware of it and have plans to improve it.

Which is 2 massive patch series away. Also, I don't know how close we are to reaching a consensus on swap.tier. I defer that to memcg maintainers.

Quoted 11 lines
Quoted 10 lines

Vswap gets around this by adding its own per-cpu allocation caching,

So by being too lazy and not carefully distinguish the swap devices, not only does xswap not work for the writeback use case, it cannot even work in deployments where some workloads (cgroup) select zswap, whereas others select disk swap. It can only work if you intend to have a single class of device - either virtual/xswap or disk swap - but not both.

Quoted 3 lines

Baoquan's writeback series is out. It is by no means perfect. But it is much closer to what I have in mind. That is a much better base to work on.

It's *literally* the same design as me, from a metadata design. The only difference is:

1. It moves the metadata from a new dynamic cluster struct and shoves it into the existing physical struct.

Like, you can check patch 11 of this series. It's practically the same thing, with the only difference being ou

Quoted 31 lines
Quoted 5 lines

Maybe instead of just grepping for swap_is_vswap() and throw your hand at the complexity, read the code and try to understand why it's necessary first, then propose simplifications if you have good ideas in minds.

Yes, I already read your code I decide that most of the swap_is_vswap() should not be needed if taking a proper swap_ops approach. I wanted to offer you the chance to work closely with me to achieve that, but you did not follow that suggestion.

Quote from my old email:
https://lore.kernel.org/all/CACePvbX+3tO91BmRwaLqf3Xia32GCemt3W8tayErG81BYLgrzA@mail.gmail.com/

"I am happy to spend some time working with you to discuss the generic adopted version of vswap, if you are open to it. Or if you don't want to waste time on it. I can have someone else or myself come up with the generic adopted version of vswap for you to review, which I prefer less."

Anyway, Baoquan's xswap writeback patch series is out. I suggest following and improving that series instead.

Quoted 8 lines
Quoted 6 lines

This is questionable. A vswap device does not go through swap on.

This changes the behavior where swap devices always go through swap on/off.

I wish the swap device went through swap on to be able to start swapping.

Quoted 7 lines
Quoted 2 lines

What usecase would necessitate the need for swapon/swapoff interface? Other than just trying to shoehorn it to an existing interface?

I like universal interfaces. Your vswap will break the /etc/fstab. The current suggestion for xswap using sysfs will break that as well. I would like to keep the /etc/fstab interface working, including support for UUIDs for swap devices, etc.

"Universal interfaces" is not a use case. None of the thing you list out here is a use case. It's an interface, but you have not constructed a single use case to justify all of that.

Quoted 4 lines

I am very concerned that vswap will start kicking in without me explicitly enabling it. That changes the previous user-visible behavior. It breaks my mental model. Please take this feedback seriously.

I mean, there's a knob for it. How can it start kicking in without your enablement?

Quoted 11 lines
Quoted 8 lines

I've expressed why I dislike the interface in [1]. Other than the sizing aspect, which we are already discussing in another thread, priority also makes zero sense. You are literally exposing an interface with only one correct answer - what's the point?

Justify your interface choice with real userspace use case, not just by conforming to the status quo.

That is why I feel your patch series are really unclean. I dislike special cases, I try to avoid them as much as possible.

Again, your disliking something is not a use case.

author maintainer
#8 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 8 lines · Nhat Pham

1. It moves the metadata from a new dynamic cluster struct and shoves it into the existing physical struct.

Like, you can check patch 11 of this series. It's practically the same thing, with the only difference being ou

being our interface choice.

Sorry that got cut off. I must have accidentally deleted it.

maintainer
#9 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

In reply to Nhat Pham
Quoted 58 lines · Nhat Pham
Quoted 43 lines · Chris Li
Quoted 8 lines · Nhat Pham
Quoted 6 lines · Chris Li

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

Quoted 5 lines
Quoted 2 lines

I consider this the biggest drawback of this series. This fragmentation of the code path.

This will mirror my response at [1], but I'm responding here for the record and for your convenience.

Thank you. Really appriciate that.

Quoted 3 lines

It is needed because vswap *is* a special device, with its own requirements. If you don't special case-it, you'd get undesirable behaviors.

Ack, that is why I am against making it a special device. That is the whole idea behind xswap. It is just normal swap device implemented via swap_ops just like ext4 is a file system implemnet on top of VFS.

Quoted 3 lines

Let's take Baoquan's patch series as an example. It treats the xswap device as just another swap device, without any special consideration for it. Which creates several problem:

That is a careful design choice. Keep in mind that design choice usually has pros and cons.

I will follow your feedback here.

Quoted 7 lines

1. At allocation time, cgroups that disable zswap might get an xswap slot, because you don't do any check that the device you allocating the swap slots for is xswap. At swap_writeout() time, it is *stuck* - we already do the unmapping step, so we cannot reclaim the page.

Ironically a physical swapfile backend could have bailed us out here, but it's not in that patch series yet :)

Quoted 8 lines

I am not sure I follow. Are you referring to the uncompressible pages that xswap would have to reject?

One way to address that is for xswap to just bite the bullet and store the uncompressible pages within xswap. That way it will stay out of the reclaim LRU. Zswap also stores some uncompressible pages. The last time I checked, it was unfortunately not able to serve my case but perfect for yours.

Not even that. Say you have two kind of workloads in the same host:
workload enables disk swap but disable zswap (zswap.max = 0), and workload that wants zswap. Let's even ignore writeback for now.

Quoted 7 lines

You add 2 "swap devices" to the system: xswap and NVME swapfile.

At swap allocation time, xswap patch series does not check carefully which swap device is being used, so you might get an xswap slot for the cgroup that disables zswap. You're stuck at swap_writeout() time. You can't undo it anymore, and you don't even support the physical swapfile backend to fallback.

The xswap is to be used with the swap.tiers. So at the swap.tiers it selects xswap or SSD swap. Will that solve your problem?

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

Vswap both has swapfile backend, AND allows you to bypass it if the cgroup disables zswap. Both involves a bit of swap_is_vswap() check, but I think it's worth it :)

Quoted 7 lines
Quoted 3 lines

If xswap needs the lower tier it can allocate for one. I don't think xswap should need to have swap_is_xswap() there. Also xswap does not have all the baggage of zswap.writeback enable interface.

But that's my point. As of now, it does not. Unless you merge the other RFC series, which brings it to roughly the same size as what I'm doing here.

It is cleaner because it avoids the dual personality issue. It also paves the way to enable writingback from one swap tier to another. That is heading to the right directions. The vswap writeback only serves zswap, not others.

Quoted 17 lines
Quoted 10 lines
Quoted 9 lines

2. Per-CPU allocation caching: since all devices share the same cache, xswap will invalidate the caching of other devices, and vice versa. It would be fine if the these devices are interchangeable, but as noted above, it's not, especially without physical swapfile as the backend option. So you're forced to taken the slow path more often.

Quoted 5 lines

This will be addressed by the swap tiers series if it is not delayed. This should be addressed in the core swap layer not vswap. Kairui also has some ideas to improve that. Yes, it is a problem area, but it is not specific to xswap. We are well aware of it and have plans to improve it.

Quoted 3 lines

Which is 2 massive patch series away. Also, I don't know how close we are to reaching a consensus on swap.tier. I defer that to memcg maintainers.

The biggest hurdle is the user API. One of Johannes's biggest objections is that it lacks writeback support and perhaps more. Now the writeback RFC is available. Let's re-evaluate what is possible. The swap.tier series has been out for a year now.

In the worst case,, we can have swap.tiers using zswap.writeback to simulate the current zswap behavior. I think that should be possible.

Quoted 13 lines
Quoted 9 lines
Quoted 8 lines

Vswap gets around this by adding its own per-cpu allocation caching,

So by being too lazy and not carefully distinguish the swap devices, not only does xswap not work for the writeback use case, it cannot even work in deployments where some workloads (cgroup) select zswap, whereas others select disk swap. It can only work if you intend to have a single class of device - either virtual/xswap or disk swap - but not both.

Quoted 3 lines

Baoquan's writeback series is out. It is by no means perfect. But it is much closer to what I have in mind. That is a much better base to work on.

Quoted 8 lines

It's *literally* the same design as me, from a metadata design. The only difference is:

1. It moves the metadata from a new dynamic cluster struct and shoves it into the existing physical struct.

Like, you can check patch 11 of this series. It's practically the same thing, with the only difference being ou

If it is the same but does not have the 33 swap_is_vswap() fragmented dual personality issue, I see that is a reason to choose that path instead. What do you say?

Quoted 35 lines
Quoted 35 lines
Quoted 6 lines

Maybe instead of just grepping for swap_is_vswap() and throw your hand at the complexity, read the code and try to understand why it's necessary first, then propose simplifications if you have good ideas in minds.

Yes, I already read your code I decide that most of the swap_is_vswap() should not be needed if taking a proper swap_ops approach. I wanted to offer you the chance to work closely with me to achieve that, but you did not follow that suggestion.

Quote from my old email:
https://lore.kernel.org/all/CACePvbX+3tO91BmRwaLqf3Xia32GCemt3W8tayErG81BYLgrzA@mail.gmail.com/

"I am happy to spend some time working with you to discuss the generic adopted version of vswap, if you are open to it. Or if you don't want to waste time on it. I can have someone else or myself come up with the generic adopted version of vswap for you to review, which I prefer less."

Anyway, Baoquan's xswap writeback patch series is out. I suggest following and improving that series instead.

Quoted 10 lines
Quoted 6 lines

This is questionable. A vswap device does not go through swap on.

This changes the behavior where swap devices always go through swap on/off.

I wish the swap device went through swap on to be able to start swapping.

What usecase would necessitate the need for swapon/swapoff interface? Other than just trying to shoehorn it to an existing interface?

Quoted 8 lines
Quoted 4 lines

I like universal interfaces. Your vswap will break the /etc/fstab. The current suggestion for xswap using sysfs will break that as well. I would like to keep the /etc/fstab interface working, including support for UUIDs for swap devices, etc.

"Universal interfaces" is not a use case. None of the thing you list out here is a use case. It's an interface, but you have not constructed a single use case to justify all of that.

We don't have to go throgh the universal interface to resolve the 33 swap_is_vswap(). It seems there is an alternative now. We can take the xswap route to eventually solve all your problems.

Quoted 8 lines
Quoted 5 lines

I am very concerned that vswap will start kicking in without me explicitly enabling it. That changes the previous user-visible behavior. It breaks my mental model. Please take this feedback seriously.

I mean, there's a knob for it. How can it start kicking in without your enablement?

Please correct me if I am wrong; here is my understanding from you:

vswap is off by default because of that knob. You turn it on and it starts zswap.
Two questions here:
1) Is your knob compatible with the existing /etc/fstab where people use it to enable swap devices, including with UUIDs, etc.?
2) When you enable the knob, do some unit test and disable the knob again. Does the vswap go through the same path as swap off so no usage of vswap exists on the system?

That is the existing use case I have in mind.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

I've expressed why I dislike the interface in [1]. Other than the sizing aspect, which we are already discussing in another thread, priority also makes zero sense. You are literally exposing an interface with only one correct answer - what's the point?

Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

Justify your interface choice with real userspace use case, not just by conforming to the status quo.

That is why I feel your patch series are really unclean. I dislike special cases, I try to avoid them as much as possible.

Again, your disliking something is not a use case.

Code maintainability is also a consideration when choosing which technical solutions to move forward with, when there are alternatives to provide solutions to the same problem.

Chris

author maintainer
#10 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 62 lines · Chris Li
Quoted 60 lines · Nhat Pham
Quoted 43 lines · Chris Li
Quoted 8 lines · Nhat Pham
Quoted 6 lines · Chris Li

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

Quoted 5 lines
Quoted 2 lines

I consider this the biggest drawback of this series. This fragmentation of the code path.

This will mirror my response at [1], but I'm responding here for the record and for your convenience.

Thank you. Really appriciate that.

Quoted 3 lines

It is needed because vswap *is* a special device, with its own requirements. If you don't special case-it, you'd get undesirable behaviors.

Ack, that is why I am against making it a special device. That is the whole idea behind xswap. It is just normal swap device implemented via swap_ops just like ext4 is a file system implemnet on top of VFS.

Quoted 3 lines

Let's take Baoquan's patch series as an example. It treats the xswap device as just another swap device, without any special consideration for it. Which creates several problem:

That is a careful design choice. Keep in mind that design choice usually has pros and cons.

I will follow your feedback here.

Quoted 7 lines

1. At allocation time, cgroups that disable zswap might get an xswap slot, because you don't do any check that the device you allocating the swap slots for is xswap. At swap_writeout() time, it is *stuck* - we already do the unmapping step, so we cannot reclaim the page.

Ironically a physical swapfile backend could have bailed us out here, but it's not in that patch series yet :)

Quoted 8 lines

I am not sure I follow. Are you referring to the uncompressible pages that xswap would have to reject?

One way to address that is for xswap to just bite the bullet and store the uncompressible pages within xswap. That way it will stay out of the reclaim LRU. Zswap also stores some uncompressible pages. The last time I checked, it was unfortunately not able to serve my case but perfect for yours.

Not even that. Say you have two kind of workloads in the same host:
workload enables disk swap but disable zswap (zswap.max = 0), and workload that wants zswap. Let's even ignore writeback for now.

You add 2 "swap devices" to the system: xswap and NVME swapfile.

Quoted 8 lines
Quoted 5 lines

At swap allocation time, xswap patch series does not check carefully which swap device is being used, so you might get an xswap slot for the cgroup that disables zswap. You're stuck at swap_writeout() time. You can't undo it anymore, and you don't even support the physical swapfile backend to fallback.

The xswap is to be used with the swap.tiers. So at the swap.tiers it selects xswap or SSD swap. Will that solve your problem?

I mean, we're having that problem right now, no? :)

Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
Quoted 7 lines

Vswap both has swapfile backend, AND allows you to bypass it if the cgroup disables zswap. Both involves a bit of swap_is_vswap() check, but I think it's worth it :)

If xswap needs the lower tier it can allocate for one. I don't think xswap should need to have swap_is_xswap() there. Also xswap does not have all the baggage of zswap.writeback enable interface.

Quoted 8 lines
Quoted 3 lines

But that's my point. As of now, it does not. Unless you merge the other RFC series, which brings it to roughly the same size as what I'm doing here.

It is cleaner because it avoids the dual personality issue. It also paves the way to enable writingback from one swap tier to another. That is heading to the right directions. The vswap writeback only serves zswap, not others.

Writing back from one swap tier to another doesn't exist right now. I have not even seen a coherent design to support writeback among swap tiers. You're just delivering pie-in-the-sky.

The RFC you mentioned is not writeback between tiers. If you think it does, then maybe you should read it again, It's from a very specific swap device (xswap, with zswap backend), to a swapfile. Here is what it does: add an array to store indirection (physical swap entry) to clusters, and update that array when we need to do backend transfer.

Does that ring a bell? That's because it's the exact same mechanism as vswap (without proper attribution - not even Suggested-by). If anything, it's actually a bit less coherent, because you can set xswap to be lower priority than physical swapfile.

Vswap does not have that, because vswap is not an ordinary swap device. It's implementing the concept of virtualization (the "V" in VFS, if you want to make that analogy), made optional to reduce overhead when indirection is not needed. That gives you all the machinery you need for backend transfer: a centralized virtualized layer, where you can update the backend, without having to go and chase down all the external references - no PTE walk needed.

Quoted 5 lines

The biggest hurdle is the user API. One of Johannes's biggest objections is that it lacks writeback support and perhaps more. Now the writeback RFC is available. Let's re-evaluate what is possible. The swap.tier series has been out for a year now.

See above. But transferring between tier is still not a solved problem.

Quoted 4 lines

If it is the same but does not have the 33 swap_is_vswap() fragmented dual personality issue, I see that is a reason to choose that path instead. What do you say?

The problem is the interface and the charging question. We have put out our objections to it, and so far we have not been satisfied with the defence.

Quoted 57 lines
Quoted 36 lines
Quoted 36 lines
Quoted 7 lines

Maybe instead of just grepping for swap_is_vswap() and throw your hand at the complexity, read the code and try to understand why it's necessary first, then propose simplifications if you have good ideas in minds.

Yes, I already read your code I decide that most of the swap_is_vswap() should not be needed if taking a proper swap_ops approach. I wanted to offer you the chance to work closely with me to achieve that, but you did not follow that suggestion.

Quote from my old email:
https://lore.kernel.org/all/CACePvbX+3tO91BmRwaLqf3Xia32GCemt3W8tayErG81BYLgrzA@mail.gmail.com/

"I am happy to spend some time working with you to discuss the generic adopted version of vswap, if you are open to it. Or if you don't want to waste time on it. I can have someone else or myself come up with the generic adopted version of vswap for you to review, which I prefer less."

Anyway, Baoquan's xswap writeback patch series is out. I suggest following and improving that series instead.

Quoted 10 lines
Quoted 6 lines

This is questionable. A vswap device does not go through swap on.

This changes the behavior where swap devices always go through swap on/off.

I wish the swap device went through swap on to be able to start swapping.

What usecase would necessitate the need for swapon/swapoff interface? Other than just trying to shoehorn it to an existing interface?

Quoted 8 lines
Quoted 4 lines

I like universal interfaces. Your vswap will break the /etc/fstab. The current suggestion for xswap using sysfs will break that as well. I would like to keep the /etc/fstab interface working, including support for UUIDs for swap devices, etc.

"Universal interfaces" is not a use case. None of the thing you list out here is a use case. It's an interface, but you have not constructed a single use case to justify all of that.

We don't have to go throgh the universal interface to resolve the 33 swap_is_vswap(). It seems there is an alternative now. We can take the xswap route to eventually solve all your problems.

Quoted 8 lines
Quoted 5 lines

I am very concerned that vswap will start kicking in without me explicitly enabling it. That changes the previous user-visible behavior. It breaks my mental model. Please take this feedback seriously.

I mean, there's a knob for it. How can it start kicking in without your enablement?

Quoted 7 lines

Please correct me if I am wrong; here is my understanding from you:

vswap is off by default because of that knob. You turn it on and it starts zswap.
Two questions here:
1) Is your knob compatible with the existing /etc/fstab where people use it to enable swap devices, including with UUIDs, etc.?

If they don't turn it on, their code works as is. Their existing /etc/fstab exhibits no behavioral change.

What you're asking is us *enrolling* in that same interface. And my question is what does that interface give us? I already pointed out multiple ways where that interface's generality shoots the user in the foot.

Quoted 3 lines

2) When you enable the knob, do some unit test and disable the knob again. Does the vswap go through the same path as swap off so no usage of vswap exists on the system?

It's a boottime parameter.

Why would you care about swapoff? What use case does it serve?

Quoted 2 lines

That is the existing use case I have in mind.

You're describing an interface, again. It's still not a use case.

I can promise that it won't break /etc/fstab if vswap is off. - if it does then it's a bug and I can fix it.

Quoted 4 lines

Code maintainability is also a consideration when choosing which technical solutions to move forward with, when there are alternatives to provide solutions to the same problem.

I already pointed out how xswap's design *creates* problem, including userspace problem. You just handwaved it away with "let the users shoot themselves in the foot". I disagree with that philosophy.

author maintainer
#11 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 6 lines · Nhat Pham

Vswap does not have that, because vswap is not an ordinary swap device. It's implementing the concept of virtualization (the "V" in VFS, if you want to make that analogy), made optional to reduce overhead when indirection is not needed. That gives you all the machinery you need for backend transfer:

... for zswap/compression backend.

It's a necessary condition for non-zswap inter-tier transfer, but not sufficient. So it's not a solved problem quite there yet (and I don't know if it can become worth the squeeze, as the data becomes increasingly colder as you move down the tier).

Quoted 2 lines

layer, where you can update the backend, without having to go and chase down all the external references - no PTE walk needed.

#12 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

In reply to Chris Li
Quoted 8 lines · Chris Li
Quoted 7 lines · Nhat Pham
mm/page_io.c +0 -0
@@ -482,6 +491,11 @@ void swap_read_folio(struct swap_io_ctx *ctx,
 struct folio *folio)
         if (zswap_load(folio) != -ENOENT)
                 goto finish;
 
Quoted 8 lines

mm/page_io.c void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio) · line 494

Quoted 1 line
mm/page_io.c +1 -0
+       if (unlikely(swap_is_vswap(sis))) {

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

I consider this the biggest drawback of this series. This fragmentation of the code path.

Could we avoid that by simply always having everything go through the vswap abstraction layer?

When everything in vswap, we don't need to test for it.

Handling the details of what's behind the vswap would be handled one layer down.

Chris, do you think that would be cleaner?

What am I missing?

Signature · 1 line
All Rights Reversed.
maintainer
#13 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 16 lines · Rik van Riel
Quoted 14 lines · Chris Li

mm/page_io.c void swap_read_folio(struct swap_io_ctx *ctx, · line 495

Quoted 8 lines · Nhat Pham
mm/page_io.c +1 -0
@@ -482,6 +491,11 @@ void swap_read_folio(struct swap_io_ctx *ctx,
 struct folio *folio)
        if (zswap_load(folio) != -ENOENT)
                goto finish;
 
+       if (unlikely(swap_is_vswap(sis))) {

There are too many swap_is_vswap() in this series. It fragments the code path, making things harder to reason about. Esepcially around locks. I count 22 in this patch alone.

Quoted 5 lines
Quoted 2 lines

I consider this the biggest drawback of this series. This fragmentation of the code path.

Could we avoid that by simply always having everything go through the vswap abstraction layer?

Yes, but it will pay the price for going through the unnecessary redirection layer always. It incurs performance and meta data overhead. That was one of my previous objections to the earlier vswap version. Sorry I enjoy micro optimization too much, that is both my strength and weakness.

Quoted 3 lines

When everything in vswap, we don't need to test for it.

I've been there and done that, the result was pretty bad in those earlier series.

Quoted 4 lines

Handling the details of what's behind the vswap would be handled one layer down.

Chris, do you think that would be cleaner?

If it can wrap below the swap_ops, it is just priviate inernal dedail of implementing its own indirections. That would be much cleaner. That is what I am trying to pitch to Nhat in prevoius email but does not have following actions.

Chris

Quoted 5 lines

What am I missing?

--
All Rights Reversed.

#14 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 25 lines · Chris Li
Quoted 23 lines · Rik van Riel
Quoted 20 lines · Chris Li

mm/page_io.c void swap_read_folio(struct swap_io_ctx · line 496

Quoted 9 lines · Nhat Pham
mm/page_io.c +1 -0
@@ -482,6 +491,11 @@ void swap_read_folio(struct swap_io_ctx
 *ctx,
 struct folio *folio)
         if (zswap_load(folio) != -ENOENT)
                 goto finish;
 
+       if (unlikely(swap_is_vswap(sis))) {

There are too many swap_is_vswap() in this series. It fragments the
code path, making things harder to reason about. Esepcially around
locks. I count 22 in this patch alone.

I consider this the biggest drawback of this series. This fragmentation of the code path.

Quoted 8 lines
Quoted 2 lines

Could we avoid that by simply always having everything go through the vswap abstraction layer?

Yes, but it will pay the price for going through the unnecessary redirection layer always. It incurs performance and meta data overhead. That was one of my previous objections to the earlier vswap version. Sorry I enjoy micro optimization too much, that is both my strength and weakness.

We really only have two cases here, don't we?

Either the data is in the swap cache, and the vswap layer can directly look up the swap cache page.

Or the data is in some slower back-end, and doing a second lookup is not going to introduce noticeable overhead.

If the micro optimization come at the cost of less flexibility, and harder to maintain code, are they really worth it?

Quoted 4 lines
Quoted 4 lines

Handling the details of what's behind the vswap would be handled one layer down.

Quoted 8 lines
Quoted 1 line

Chris, do you think that would be cleaner?

If it can wrap below the swap_ops, it is just priviate inernal dedail of implementing its own indirections. That would be much cleaner. That
is what I am trying to pitch to Nhat in prevoius email but does not have following actions.

Can you sketch out the details of what you think that should look like?

What would the data structures look like?

What operations should there be at the abstraction layer, and at the swap layers below?

How should migration of data from one swap backend to another be handled?

At this point the best way to make progress would be to hash out those details.

If you are unhappy with what you have seen from others, what does your ideal design look like?

Signature · 1 line
All Rights Reversed.
maintainer
#15 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 42 lines · Rik van Riel
Quoted 25 lines · Chris Li
Quoted 23 lines · Rik van Riel
Quoted 20 lines · Chris Li

mm/page_io.c void swap_read_folio(struct swap_io_ctx · line 496

Quoted 9 lines · Nhat Pham
mm/page_io.c +1 -0
@@ -482,6 +491,11 @@ void swap_read_folio(struct swap_io_ctx
 *ctx,
 struct folio *folio)
        if (zswap_load(folio) != -ENOENT)
                goto finish;
 
+       if (unlikely(swap_is_vswap(sis))) {

There are too many swap_is_vswap() in this series. It fragments the
code path, making things harder to reason about. Esepcially around
locks. I count 22 in this patch alone.

I consider this the biggest drawback of this series. This fragmentation of the code path.

Quoted 8 lines
Quoted 2 lines

Could we avoid that by simply always having everything go through the vswap abstraction layer?

Yes, but it will pay the price for going through the unnecessary redirection layer always. It incurs performance and meta data overhead. That was one of my previous objections to the earlier vswap version. Sorry I enjoy micro optimization too much, that is both my strength and weakness.

We really only have two cases here, don't we?

Either the data is in the swap cache, and the vswap layer can directly look up the swap cache page.

Quoted 7 lines

Or the data is in some slower back-end, and doing a second lookup is not going to introduce noticeable overhead.

If the micro optimization come at the cost of less flexibility, and harder to maintain code, are they really worth it?

In this case, yes. Because there is an alternative that can both keep code complexity down, perform well, keep metadata small, and be flexible.

Quoted 25 lines
Quoted 5 lines
Quoted 5 lines

Handling the details of what's behind the vswap would be handled one layer down.

Quoted 8 lines
Quoted 1 line

Chris, do you think that would be cleaner?

If it can wrap below the swap_ops, it is just priviate inernal dedail of implementing its own indirections. That would be much cleaner. That
is what I am trying to pitch to Nhat in prevoius email but does not have following actions.

Can you sketch out the details of what you think that should look like?

What would the data structures look like?

What operations should there be at the abstraction layer, and at the swap layers below?

How should migration of data from one swap backend to another be handled?

Quoted 6 lines

At this point the best way to make progress would be to hash out those details.

If you are unhappy with what you have seen from others, what does your ideal design look like?

Those are very good questions for the people who want to take that path. I can work that person to figure those out. It will not be me just handing out all the answers.

Chris

author maintainer
#16 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

In reply to Chris Li
Quoted 18 lines · Chris Li

On Thu, Sep 24, 2026 at 8:13 AM Rik van Riel <[email protected]> wrote:

Yes, but it will pay the price for going through the unnecessary redirection layer always. It incurs performance and meta data overhead. That was one of my previous objections to the earlier vswap version. Sorry I enjoy micro optimization too much, that is both my strength and weakness.

Quoted 3 lines

When everything in vswap, we don't need to test for it.

I've been there and done that, the result was pretty bad in those earlier series.

Quoted 3 lines

Handling the details of what's behind the vswap would be handled one layer down.

Quoted 6 lines
Quoted 1 line

Chris, do you think that would be cleaner?

If it can wrap below the swap_ops, it is just priviate inernal dedail of implementing its own indirections. That would be much cleaner. That is what I am trying to pitch to Nhat in prevoius email but does not have following actions.

Registering vswap's operation as into swap_ops isn't too hard. I frankly don't see much wins to it for vswap itself, but it's not hard to do if you like it.

What I'm disagreeing is treating it as "just another swap device". The implementation shares a lot of swap device's machinery, so I have don't mind adopting it, but you can't treat it like a normal swap device, and expose it to userspace like one. You get issues with allocations internally, and externally you give userspace a vector to misconfigure with device priority.

That's why I've been insisting on what's the use case that motivates these aspects of the interface that you're interested in. A pretty design is not a real usecase, especially one that creates problems with userspace misconfigurations.

maintainer
#17 lore raw

Re: [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure

Quoted 22 lines · Nhat Pham
Quoted 20 lines · Chris Li

On Thu, Sep 24, 2026 at 8:13 AM Rik van Riel <[email protected]> wrote:

Yes, but it will pay the price for going through the unnecessary redirection layer always. It incurs performance and meta data overhead. That was one of my previous objections to the earlier vswap version. Sorry I enjoy micro optimization too much, that is both my strength and weakness.

Quoted 3 lines

When everything in vswap, we don't need to test for it.

I've been there and done that, the result was pretty bad in those earlier series.

Quoted 4 lines

Handling the details of what's behind the vswap would be handled one layer down.

Chris, do you think that would be cleaner?

Quoted 8 lines
Quoted 4 lines

If it can wrap below the swap_ops, it is just priviate inernal dedail of implementing its own indirections. That would be much cleaner. That is what I am trying to pitch to Nhat in prevoius email but does not have following actions.

Registering vswap's operation as into swap_ops isn't too hard. I frankly don't see much wins to it for vswap itself, but it's not hard to do if you like it.

I am offering these as ways to move forward with vswap. There is always the alternaive to use xswap instead.

Quoted 7 lines

What I'm disagreeing is treating it as "just another swap device". The implementation shares a lot of swap device's machinery, so I have don't mind adopting it, but you can't treat it like a normal swap device, and expose it to userspace like one. You get issues with allocations internally, and externally you give userspace a vector to misconfigure with device priority.

I'd like to hear more about this. If a user wants to shoot themselves in the foot. My philosophy is just let them. It is not worthwhile to complicate the code path. We can add a big fat warning that "Oh, you are configuring xswap with a priority other than the recommended one." But if the user really wants to do it, we should allow it.

Another use case is when users employ more than one swap device to reduce swap device lock contention. It is not a big deal when you swap out a few GB of memory. But if you swap out more than 100G of memory, the swap device lock contention really shows up in the earlier version of the swap core. The new swap allocator and swap table significantly reduce that contention. But that contention still exists. A few hundred G of memory under one lock is just a bit too much. I think there is a legitimate reason to use more than one device to reduce lock contention.

Granted, other ways exist to reduce lock contention, but they increase code complexity as well. The current swap device design is a good balance of code complexity and flexibility.

Quoted 4 lines

That's why I've been insisting on what's the use case that motivates these aspects of the interface that you're interested in. A pretty design is not a real usecase, especially one that creates problems with userspace misconfigurations.

Points taken; this isn't enough to justify the extra maintenance and complexity of vswap right now. A cleaner alternative exists with less complexity overhead.

Chris

author maintainer
#18 lore raw

PATCH v5 2/11 mm, swap: support zswap and zero-filled swap pages as vswap backends

In reply to Nhat Pham

Build the virtual swap layer on top of the swap-table infrastructure. Virtual swap entries decouple PTE swap entries from physical backing, allowing pages to be compressed by zswap (or detected as zero-filled) without pre-allocating a physical swap slot.

This patch only supports zswap and zero-page backends. If zswap_store fails, the page stays dirty in the swap cache. Physical disk backing arrives in later patches.

Zswap writeback of vswap-backed entries is also disabled: they have no physical slot to write back to yet, so the zswap shrinker (both the dynamic count path and the pool-full worker path) is skipped while vswap is enabled. Physical backing and real writeback come in later patches.

THP swapin is disabled for vswap entries for now.

vswap_alloc() only routes a swapout through vswap when vswap is enabled, either by CONFIG_VSWAP_DEFAULT_ON or by "vswap=on" on the kernel command line. It also declines the folio when zswap is off, or when the folio's cgroup is already over its zswap limit. In both cases writeout would have to find a physical slot anyway, so the indirection would buy nothing.

Anon reclaim gating needs a matching change: a vswap zswap-backed swapout consumes no physical slot, so the physical free count no longer tells reclaim whether anon is reclaimable. Add mem_cgroup_can_swap(), which answers that question and gates on the swap.max headroom instead when vswap and zswap are both on. Its callers only ever compared mem_cgroup_get_nr_swap_pages() against a threshold, so that function keeps its meaning and its physical free count.

The OVERCOMMIT_GUESS heuristic gates a single allocation on totalram_pages() + total_swap_pages. Vswap deliberately contributes to neither, so on a host with no swapfile the bound collapses to RAM alone and allocations that vswap could absorb are refused. Compression swap is backed by memory rather than by a device, so reference the bound to RAM:
add 2 * totalram_pages() when vswap and zswap are both on, for a 3x RAM ceiling plus whatever physical swap exists.

mem_cgroup_can_vswap() is added alongside, so the !CONFIG_MEMCG stub of mem_cgroup_can_swap() gets the same carve-out as the real one. Without it, get_nr_swap_pages() reads 0 under vswap and MGLRU concludes anon can never be swapped.

---
 include/linux/swap.h  |  13 +++
 include/linux/zswap.h |   4 +
 mm/memcontrol.c       |  29 +++++++
 mm/memory.c           |  11 ++-
 mm/page_io.c          |  12 ++-
 mm/shmem.c            |   4 +-
 mm/swap.h             |   1 +
 mm/swap_state.c       |   8 ++
 mm/swapfile.c         | 187 ++++++++++++++++++++++++++++++++++++++++--
 mm/util.c             |  13 ++-
 mm/vmscan.c           |  18 ++--
 mm/vswap.h            | 185 +++++++++++++++++++++++++++++++++++++++++
 mm/workingset.c       |   2 +-
 mm/zswap.c            |  68 ++++++++++++---
 14 files changed, 521 insertions(+), 34 deletions(-)
include/linux/swap.h +13 -0
index 0b341301d8fa..abf658f7861f 100644
@@ -367,6 +367,8 @@ extern void __meminit kswapd_stop(int nid);
 bool current_is_kswapd(void);
 
 #ifdef CONFIG_SWAP
+bool mem_cgroup_can_vswap(struct mem_cgroup *memcg);
+
 int add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
 		unsigned long nr_pages, sector_t start_block);
 int generic_swapfile_activate(struct swap_info_struct *, struct file *,
@@ -440,6 +442,11 @@ static inline void put_swap_device(struct swap_info_struct *si)
 }
 
 #else /* CONFIG_SWAP */
+static inline bool mem_cgroup_can_vswap(struct mem_cgroup *memcg)
+{
+	return false;
+}
+
 static inline struct swap_info_struct *get_swap_device(swp_entry_t entry)
 {
 	return NULL;
@@ -538,6 +545,7 @@ static inline void mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_p
 
 long mem_cgroup_get_folio_swap_margin(struct folio *folio);
 extern long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg);
+bool mem_cgroup_can_swap(struct mem_cgroup *memcg, long nr_pages);
 extern bool mem_cgroup_swap_full(struct folio *folio);
 #else
 static inline int mem_cgroup_try_charge_swap(struct folio *folio)
@@ -560,6 +568,11 @@ static inline long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
 	return get_nr_swap_pages();
 }
 
+static inline bool mem_cgroup_can_swap(struct mem_cgroup *memcg, long nr_pages)
+{
+	return mem_cgroup_can_vswap(memcg) || get_nr_swap_pages() >= nr_pages;
+}
+
 static inline bool mem_cgroup_swap_full(struct folio *folio)
 {
 	return vm_swap_full();
include/linux/zswap.h +4 -0
index df6cafbe95dc..0cc2cc878566 100644
@@ -6,6 +6,7 @@
 #include <linux/mm_types.h>
 
 struct lruvec;
+struct zswap_entry;
 
 extern atomic_long_t zswap_stored_pages;
 
@@ -28,6 +29,7 @@ unsigned long zswap_total_pages(void);
 bool zswap_store(struct folio *folio);
 int zswap_load(struct folio *folio);
 void zswap_invalidate(int type, pgoff_t offset, unsigned long nr_entries);
+void zswap_entry_free(struct zswap_entry *entry);
 int zswap_swapon(int type, unsigned long nr_pages);
 void zswap_swapoff(int type);
 void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg);
@@ -54,6 +56,8 @@ static inline void zswap_invalidate(int type, pgoff_t offset,
 {
 }
 
+static inline void zswap_entry_free(struct zswap_entry *entry) {}
+
 static inline int zswap_swapon(int type, unsigned long nr_pages)
 {
 	return 0;
mm/memcontrol.c +29 -0
index 791e536efaeb..63d2c9e3dbe1 100644
@@ -66,6 +66,7 @@
 #include "internal.h"
 #include "swap.h"
 #include "swap_table.h"
+#include "vswap.h"
 #include <net/sock.h>
 #include <net/ip.h>
 #include "slab.h"
@@ -6049,6 +6050,34 @@ long mem_cgroup_get_folio_swap_margin(struct folio *folio)
 	return margin;
 }
 
+/**
+ * mem_cgroup_can_swap - can @memcg swap out at least @nr_pages more pages?
+ * @memcg: the memcg to query
+ * @nr_pages: the number of pages the caller wants to swap out
+ *
+ * A vswap zswap-backed swapout needs no physical slot, so gate on the
+ * swap.max headroom rather than the physical free count.
+ *
+ * Return: true if @memcg can swap out at least @nr_pages more pages.
+ */
+bool mem_cgroup_can_swap(struct mem_cgroup *memcg, long nr_pages)
+{
+	long avail;
+
+	if (mem_cgroup_can_vswap(memcg))
+		return true;
+
+	if (!vswap_is_enabled() || !zswap_is_enabled())
+		return mem_cgroup_get_nr_swap_pages(memcg) >= nr_pages;
+
+	avail = PAGE_COUNTER_MAX;
+	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
+		avail = min_t(long, avail,
+			      READ_ONCE(memcg->swap.max) -
+			      page_counter_read(&memcg->swap));
+	return avail >= nr_pages;
+}
+
 bool mem_cgroup_swap_full(struct folio *folio)
 {
 	struct mem_cgroup *memcg;
mm/memory.c +9 -2
index 338fce99e711..73ebc59d2b03 100644
@@ -89,6 +89,7 @@
 #include "pgalloc-track.h"
 #include "internal.h"
 #include "swap.h"
+#include "vswap.h"
 
 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
@@ -4712,6 +4713,9 @@ static inline bool should_try_to_free_swap(struct swap_info_struct *si,
 {
 	if (!folio_test_swapcache(folio))
 		return false;
+	/* A vswap entry holds no physical slot, so keeping it saves no IO. */
+	if (is_vswap_entry(folio->swap))
+		return true;
 	/*
 	 * Always try to free swap cache for SWP_SYNCHRONOUS_IO devices. Swap
 	 * cache can help save some IO or memory overhead, but these devices
@@ -4868,15 +4872,18 @@ static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf)
 	if (unlikely(userfaultfd_armed(vma)))
 		return 0;
 
+	entry = softleaf_from_pte(vmf->orig_pte);
+
 	/*
 	 * A large swapped out folio could be partially or fully in zswap. We
 	 * lack handling for such cases, so fallback to swapping in order-0
 	 * folio.
+	 *
+	 * THP swapin for vswap is not supported yet either.
 	 */
-	if (!zswap_never_enabled())
+	if (is_vswap_entry(entry) || !zswap_never_enabled())
 		return 0;
 
-	entry = softleaf_from_pte(vmf->orig_pte);
 	/*
 	 * Get a list of all the (large) orders below PMD_ORDER that are enabled
 	 * and suitable for swapping THP.
mm/page_io.c +10 -2
index 5cd77bd1b12c..2e7fb335eb01 100644
@@ -162,13 +162,18 @@ static void swap_zeromap_folio_set(struct folio *folio)
 	int nr_pages = folio_nr_pages(folio);
 	struct swap_cluster_info *ci;
 	swp_entry_t entry = folio->swap;
-	unsigned int i;
+	unsigned int voff, i;
 
 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
 
 	ci = swap_cluster_get_and_lock(folio);
-	for (i = 0; i < folio_nr_pages(folio); i++) {
+	if (is_vswap_entry(folio->swap)) {
+		/* Free any prior backing (e.g. ZSWAP entry from earlier swapout) */
+		voff = swp_cluster_offset(folio->swap);
+		__vswap_release_backing(ci, voff, nr_pages);
+	}
+	for (i = 0; i < nr_pages; i++) {
 		__swap_table_set_zero(ci, swp_cluster_offset(entry));
 		entry.val++;
 	}
@@ -236,6 +241,9 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	 */
 	swap_zeromap_folio_clear(folio);
 
+	if (is_vswap_entry(folio->swap))
+		folio_release_vswap_backing(folio);
+
 	if (zswap_store(folio)) {
 		count_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);
 		goto out_unlock;
mm/shmem.c +3 -1
index b572c60f2af8..2871a1f618ec 100644
@@ -86,6 +86,7 @@ static struct vfsmount *shm_mnt __ro_after_init;
 #include <linux/uaccess.h>
 
 #include "internal.h"
+#include "vswap.h"
 
 #define VM_ACCT(size)    (PAGE_ALIGN(size) >> PAGE_SHIFT)
 
@@ -1819,7 +1820,8 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 	if ((info->flags & SHMEM_F_LOCKED) || sbinfo->noswap)
 		goto redirty;
 
-	if (!total_swap_pages)
+	/* vswap doesn't contribute to total_swap_pages */
+	if (!total_swap_pages && !(vswap_is_enabled() && zswap_is_enabled()))
 		goto redirty;
 
 	/*
mm/swap.h +1 -0
index 528a27afb335..81e47dc36a02 100644
@@ -71,6 +71,7 @@ struct swap_cluster_info_dynamic {
 	struct swap_cluster_info ci;
 	unsigned int index;		/* for cluster_index() */
 	struct rcu_head rcu;
+	atomic_long_t *virtual_table;	/* Backing pointers for vswap slots */
 };
 
 /* All on-list cluster must have a non-zero flag. */
mm/swap_state.c +8 -0
index 424a0040b4b8..54e4fefdab95 100644
@@ -27,6 +27,7 @@
 #include "internal.h"
 #include "swap_table.h"
 #include "swap.h"
+#include "vswap.h"
 
 /* Swap readahead cluster size, as a power of 2 pages. */
 static int page_cluster;
@@ -188,6 +189,13 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 	if (nr == 1)
 		return 0;
 
+	/*
+	 * Reject a vswap batch so swap_cache_alloc_folio falls back to
+	 * order 0.
+	 */
+	if (is_vswap_entry(targ_entry))
+		return -EBUSY;
+
 	is_zero = __swap_table_test_zero(ci, ci_off);
 	ci_off = round_down(ci_off, nr);
 	ci_end = ci_off + nr;
mm/swapfile.c +179 -8

320 lines not on this page · raw message

mm/util.c +12 -1
index c5ee52aede1e..bde985f242df 100644
@@ -33,6 +33,7 @@
 
 #include "internal.h"
 #include "swap.h"
+#include "vswap.h"
 
 /**
  * kfree_const - conditionally free memory
@@ -970,7 +971,17 @@ int __vm_enough_memory(const struct mm_struct *mm, long pages, int cap_sys_admin
 		return 0;
 
 	if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
-		if (pages > totalram_pages() + total_swap_pages)
+		allowed = totalram_pages() + total_swap_pages;
+		/*
+		 * Vswap is in neither term, so with no swapfile the bound
+		 * would collapse to RAM alone even though zswap can absorb
+		 * more. Compression swap is backed by memory, so budget a 3x
+		 * compression ratio, typical of most workloads. Anything that
+		 * compresses better can use OVERCOMMIT_ALWAYS.
+		 */
+		if (vswap_is_enabled() && zswap_is_enabled())
+			allowed += 2 * totalram_pages();
+		if (pages > allowed)
 			goto error;
 		return 0;
 	}
mm/vmscan.c +11 -7
index 836f50814ffa..6cf689817f2e 100644
@@ -69,6 +69,7 @@
 #include "internal.h"
 #include "page_alloc.h"
 #include "swap.h"
+#include "vswap.h"
 
 #define CREATE_TRACE_POINTS
 #include <trace/events/vmscan.h>
@@ -415,10 +416,12 @@ static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
 	if (memcg == NULL) {
 		/*
 		 * For non-memcg reclaim, is there space in any swap device?
-		 * And under GFP_NOIO, is there enough swapcached anon to make
-		 * scanning anon worthwhile?
+		 * vswap does not contribute to nr_swap_pages. And under
+		 * GFP_NOIO, is there enough swapcached anon to make scanning
+		 * anon worthwhile?
 		 */
-		if (get_nr_swap_pages() > 0 &&
+		if ((get_nr_swap_pages() > 0 ||
+		     (vswap_is_enabled() && zswap_is_enabled())) &&
 		    !reclaimable_anon_is_low(memcg, nid, sc))
 			return true;
 	} else {
@@ -426,7 +429,7 @@ static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
 		 * Is the memcg below its swap limit, and under GFP_NOIO does
 		 * it have enough swapcached anon to make scanning worthwhile?
 		 */
-		if (mem_cgroup_get_nr_swap_pages(memcg) > 0 &&
+		if (mem_cgroup_can_swap(memcg, 1) &&
 		    !reclaimable_anon_is_low(memcg, nid, sc))
 			return true;
 	}
@@ -1603,7 +1606,8 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 activate_locked:
 		/* Not a candidate for swapping, so reclaim swap space. */
 		if (folio_test_swapcache(folio) &&
-		    (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
+		    ((mem_cgroup_swap_full(folio) && !is_vswap_entry(folio->swap)) ||
+		     folio_test_mlocked(folio)))
 			folio_free_swap(folio);
 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
 		if (!folio_test_mlocked(folio)) {
@@ -2760,7 +2764,7 @@ static bool can_age_anon_pages(struct lruvec *lruvec,
 			       struct scan_control *sc)
 {
 	/* Aging the anon LRU is valuable if swap is present: */
-	if (total_swap_pages > 0)
+	if (total_swap_pages > 0 || (vswap_is_enabled() && zswap_is_enabled()))
 		return true;
 
 	/* Also valuable if anon pages can be demoted: */
@@ -2853,7 +2857,7 @@ static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
 		return 0;
 
 	if (!can_demote(pgdat->node_id, sc, memcg) &&
-	    mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
+	    !mem_cgroup_can_swap(memcg, MIN_LRU_BATCH))
 		return 0;
 
 	return swappiness;
mm/vswap.h +185 -0

199 lines not on this page · raw message

mm/workingset.c +1 -1
index 8412f4840ae3..fe80cd50f3e9 100644
@@ -523,7 +523,7 @@ bool workingset_test_recent(void *shadow, bool file, bool *workingset,
 		workingset_size += lruvec_page_state(eviction_lruvec,
 						     NR_INACTIVE_FILE);
 	}
-	if (mem_cgroup_get_nr_swap_pages(eviction_memcg) > 0) {
+	if (mem_cgroup_can_swap(eviction_memcg, 1)) {
 		workingset_size += lruvec_page_state(eviction_lruvec,
 						     NR_ACTIVE_ANON);
 		if (file) {
mm/zswap.c +56 -12

158 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#19 lore raw

PATCH v5 3/11 mm, swap: prepare the swap IO path for vswap

In reply to Nhat Pham

In preparation for adding a physical swap backend for vswap, make the swap IO path able to submit IO for a swap entry other than folio->swap.

The swap IO path derives the target device and sector from folio->swap. For a vswap folio backed by a physical slot that entry is virtual, so it identifies neither the backing device nor the sector to submit IO against.

Compute the sector from an explicit entry (swap_folio_sector becomes swap_entry_sector), thread that entry through swap_add_folio, __swap_writeout and ops->can_merge, and stash it in swap_iocb so the submit and completion paths address the IO from it rather than from folio->swap.

This lets the batching path serve both vswap entries (backed by a physical slot) and physical entries mapped directly into PTEs.

ops->can_merge changes anchor with it: swap_bdev_can_merge() compares sectors and swap_fs_can_merge() byte offsets, and both now measure from the batch head plus the accumulated length instead of from the previous folio plus its size. The two agree at every step, since a batch only grows through merges that passed the same test. The blkg comparison is unchanged and still anchors on the last folio in the batch.

All callers pass folio->swap, so there is no functional change.

---
 include/linux/swap.h     |  2 +-
 include/linux/swap_ops.h |  9 ++++---
 mm/page_io.c             | 54 +++++++++++++++++++---------------------
 mm/swap.h                |  3 ++-
 mm/swapfile.c            |  6 ++---
 mm/zswap.c               |  2 +-
 6 files changed, 38 insertions(+), 38 deletions(-)
include/linux/swap.h +1 -1
index abf658f7861f..5ab050b2457c 100644
@@ -409,7 +409,7 @@ extern int __swap_count(swp_entry_t entry);
 extern bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry);
 extern int swp_swapcount(swp_entry_t entry);
 extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
-sector_t swap_folio_sector(struct folio *folio);
+sector_t swap_entry_sector(swp_entry_t entry);
 
 /*
  * If there is an existing swap slot reference (swap entry) and the caller
include/linux/swap_ops.h +5 -4
index 57ac6c703f68..223c84548bde 100644
@@ -12,6 +12,7 @@ struct swap_iocb {
 	struct bio_vec		bvecs[SWAP_CLUSTER_MAX];
 	int			nr_bvecs;
 	int			len;
+	swp_entry_t		entry;	/* first slot in the batch; addresses the IO */
 };
 
 struct swap_io_ctx {
@@ -30,15 +31,15 @@ struct swap_io_ctx {
 struct swap_ops {
 	unsigned int		flags;
 
-	bool (*can_merge)(struct folio *folio, struct folio *prev_folio,
-			size_t prev_folio_size, int rw);
+	bool (*can_merge)(struct folio *folio, swp_entry_t phys,
+			struct swap_iocb *sio, int rw);
 	void (*submit_write)(struct swap_io_ctx *ctx);
 	void (*submit_read)(struct swap_io_ctx *ctx);
 };
 
 void swap_fs_prepare_rw(struct swap_io_ctx *ctx, int rw, struct iov_iter *iter);
-bool swap_fs_can_merge(struct folio *folio, struct folio *prev_folio,
-		size_t prev_folio_size, int rw);
+bool swap_fs_can_merge(struct folio *folio, swp_entry_t phys,
+		struct swap_iocb *sio, int rw);
 int swap_fs_activate(struct swap_info_struct *sis, const struct swap_ops *ops);
 
 #endif /* _MM_SWAP_OPS_H */
mm/page_io.c +26 -28

144 lines not on this page · raw message

mm/swap.h +2 -1
index 81e47dc36a02..df323d5e8da8 100644
@@ -320,7 +320,8 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio);
 void swap_read_submit(struct swap_io_ctx *ctx);
 void swap_write_submit(struct swap_io_ctx *ctx);
 int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio);
-void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio);
+void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio,
+		swp_entry_t phys);
 
 /* linux/mm/swap_state.c */
 extern struct address_space swap_space __read_mostly;
mm/swapfile.c +3 -3
index 67a2399cf1ae..af6a162c4450 100644
@@ -342,14 +342,14 @@ offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
 	BUG();
 }
 
-sector_t swap_folio_sector(struct folio *folio)
+sector_t swap_entry_sector(swp_entry_t entry)
 {
-	struct swap_info_struct *sis = __swap_entry_to_info(folio->swap);
+	struct swap_info_struct *sis = __swap_entry_to_info(entry);
 	struct swap_extent *se;
 	sector_t sector;
 	pgoff_t offset;
 
-	offset = swp_offset(folio->swap);
+	offset = swp_offset(entry);
 	se = offset_to_swap_extent(sis, offset);
 	sector = se->start_block + (offset - se->start_page);
 	return sector << (PAGE_SHIFT - 9);
mm/zswap.c +1 -1
index 3466c80ac188..c2430dbfc653 100644
@@ -1094,7 +1094,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	folio_set_reclaim(folio);
 
 	/* start writeback */
-	__swap_writeout(&ctx, folio);
+	__swap_writeout(&ctx, folio, folio->swap);
 	swap_write_submit(&ctx);
 
 out:
Signature · 1 line
2.53.0-Meta
author maintainer
#20 lore raw

PATCH v5 4/11 mm, swap: support physical swap as a vswap backend

In reply to Nhat Pham

Add physical swap as a backend for the virtual swap layer. When zswap declines a page, the swapout path allocates a physical slot on demand for swap out.

Each vswap entry's physical slot is tracked via a pointer-tagged swap_table entry on the physical cluster (an rmap back to the vswap entry).

Physical readahead scans a whole offset window and would trip over these rmap slots, so __swap_cache_add_check() now skips swp_tb_is_pointer() entries. Nothing is lost: a backing slot is faulted through its owning vswap entry, never through the physical offset.

swapoff reads each vswap entry back through its rmap slot before freeing the physical slot. A failed read leaves the folio not uptodate, so drop it instead of marking it dirty: dirtying would write uninitialised memory out to swap, and the loss is now reported as SIGBUS on the next fault rather than silently returning stale data.

If zswap is disabled at the host level or for the folio's cgroup, the folio still gets a physical swap slot, bypassing vswap and mapping the slot directly into the PTEs. In practice the swapfile backend is only reached when zswap declines the folio at swap_writeout() time, most often because the pool is full.

The machinery is in place, but its main consumer is not. Zswap writeback to physical swap is added in a following patch. Reclaim of physical slots backing cache-only vswap entries follows it.

---
 mm/memory.c     |  13 +-
 mm/page_io.c    |  41 ++++--
 mm/swap_state.c |   6 +-
 mm/swap_table.h |  42 +++++-
 mm/swapfile.c   | 352 +++++++++++++++++++++++++++++++++++++++++++-----
 mm/vmscan.c     |   2 +-
 mm/vswap.h      | 198 ++++++++++++++++++++++++++-
 mm/zswap.c      |   2 +-
 8 files changed, 593 insertions(+), 63 deletions(-)
mm/memory.c +8 -5
index 73ebc59d2b03..e9e05e31c4f8 100644
@@ -4713,8 +4713,11 @@ static inline bool should_try_to_free_swap(struct swap_info_struct *si,
 {
 	if (!folio_test_swapcache(folio))
 		return false;
-	/* A vswap entry holds no physical slot, so keeping it saves no IO. */
-	if (is_vswap_entry(folio->swap))
+	/*
+	 * Non-swapfile backends cannot be reused for future swapouts.
+	 * Free the swap slot unless backed by contiguous physical swap.
+	 */
+	if (!folio_phys_swap_backed(folio))
 		return true;
 	/*
 	 * Always try to free swap cache for SWP_SYNCHRONOUS_IO devices. Swap
@@ -4722,7 +4725,7 @@ static inline bool should_try_to_free_swap(struct swap_info_struct *si,
 	 * are fast, and meanwhile, swap cache pinning the slot deferring the
 	 * release of metadata or fragmentation is a more critical issue.
 	 */
-	if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
+	if (swap_entry_backend_has_flag(si, folio->swap, SWP_SYNCHRONOUS_IO))
 		return true;
 	if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
 	    folio_test_mlocked(folio))
@@ -5035,7 +5038,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 		swap_update_readahead(folio, vma, vmf->address);
 	if (!folio) {
 		/* Swapin bypasses readahead for SWP_SYNCHRONOUS_IO devices */
-		if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
+		if (swap_entry_backend_has_flag(si, entry, SWP_SYNCHRONOUS_IO))
 			folio = swapin_sync(entry, GFP_HIGHUSER_MOVABLE,
 					    thp_swapin_suitable_orders(vmf) | BIT(0),
 					    vmf, NULL, 0);
@@ -5200,7 +5203,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 			 */
 			exclusive = true;
 		} else if (exclusive && folio_test_writeback(folio) &&
-			  data_race(si->flags & SWP_STABLE_WRITES)) {
+			  swap_entry_backend_has_flag(si, entry, SWP_STABLE_WRITES)) {
 			/*
 			 * This is tricky: not all swap backends support
 			 * concurrent page modifications while under writeback.
mm/page_io.c +31 -10

77 lines not on this page · raw message

mm/swap_state.c +5 -1
index 54e4fefdab95..657622cfd7f1 100644
@@ -177,6 +177,9 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 		return -ENOENT;
 	ci_off = swp_cluster_offset(targ_entry);
 	old_tb = __swap_table_get(ci, ci_off);
+	/* Physical readahead can hit a vswap-backing rmap slot; skip it. */
+	if (swp_tb_is_pointer(old_tb))
+		return -ENOENT;
 	if (swp_tb_is_folio(old_tb))
 		return -EEXIST;
 	if (!__swp_tb_get_count(old_tb))
@@ -201,7 +204,8 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 	ci_end = ci_off + nr;
 	do {
 		old_tb = __swap_table_get(ci, ci_off);
-		if (unlikely(swp_tb_is_folio(old_tb) ||
+		if (unlikely(swp_tb_is_pointer(old_tb) ||
+			     swp_tb_is_folio(old_tb) ||
 			     !__swp_tb_get_count(old_tb) ||
 			     is_zero != __swap_table_test_zero(ci, ci_off) ||
 			     (memcg_id && *memcg_id != __swap_cgroup_get(ci, ci_off))))
mm/swap_table.h +38 -4

64 lines not on this page · raw message

mm/swapfile.c +315 -37

501 lines not on this page · raw message

mm/vmscan.c +1 -1
index 6cf689817f2e..2c9cc5c20ea9 100644
@@ -1606,7 +1606,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 activate_locked:
 		/* Not a candidate for swapping, so reclaim swap space. */
 		if (folio_test_swapcache(folio) &&
-		    ((mem_cgroup_swap_full(folio) && !is_vswap_entry(folio->swap)) ||
+		    ((mem_cgroup_swap_full(folio) && folio_phys_swap_backed(folio)) ||
 		     folio_test_mlocked(folio)))
 			folio_free_swap(folio);
 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
mm/vswap.h +194 -4

241 lines not on this page · raw message

mm/zswap.c +1 -1
index c2430dbfc653..bbfaeac00355 100644
@@ -1620,7 +1620,7 @@ bool zswap_store(struct folio *folio)
 	 */
 	if (is_vswap_entry(swp)) {
 		if (index > 0)
-			folio_release_vswap_backing(folio);
+			folio_release_non_phys_swap_backing(folio);
 	} else {
 		zswap_invalidate(swp_type(swp), swp_offset(swp), nr_pages);
 	}
Signature · 1 line
2.53.0-Meta
author maintainer
#21 lore raw

PATCH v5 5/11 mm, swap: enable THP swapin for vswap entries

In reply to Nhat Pham

Swap a large anon folio back in as a unit when its vswap entries share a contiguous run of physical swap slots on a synchronous IO device, instead of always falling back to order-0 faults.

A zswap-backed or mixed-backing batch is still refused, and the fault retries at a smaller order.

---
 mm/memory.c     |  5 +++--
 mm/swap_state.c | 17 +++++++++++++----
 mm/zswap.c      |  6 +++++-
 3 files changed, 21 insertions(+), 7 deletions(-)
mm/memory.c +3 -2
index e9e05e31c4f8..e052de3b4461 100644
@@ -4882,9 +4882,10 @@ static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf)
 	 * lack handling for such cases, so fallback to swapping in order-0
 	 * folio.
 	 *
-	 * THP swapin for vswap is not supported yet either.
+	 * Vswap entries are checked later, under the cluster lock in
+	 * __swap_cache_add_check().
 	 */
-	if (is_vswap_entry(entry) || !zswap_never_enabled())
+	if (!is_vswap_entry(entry) && !zswap_never_enabled())
 		return 0;
 
 	/*
mm/swap_state.c +13 -4
index 657622cfd7f1..2107d05ae8d5 100644
@@ -165,6 +165,9 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 	unsigned int ci_off, ci_end;
 	unsigned long old_tb;
 	bool is_zero;
+	struct swap_cluster_info_dynamic *ci_dyn;
+	enum vswap_backing_type type;
+	int ret;
 
 	lockdep_assert_held(&ci->lock);
 
@@ -193,11 +196,17 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 		return 0;
 
 	/*
-	 * Reject a vswap batch so swap_cache_alloc_folio falls back to
-	 * order 0.
+	 * For a vswap entry batch, reject if the backing is not THP-amenable
+	 * (e.g. uniformly ZSWAP, or mixed). The order-fallback loop in
+	 * swap_cache_alloc_folio will retry with a smaller order on -EBUSY.
 	 */
-	if (is_vswap_entry(targ_entry))
-		return -EBUSY;
+	if (is_vswap_entry(targ_entry)) {
+		ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+		ret = __vswap_check_backing(ci_dyn, round_down(ci_off, nr),
+					    nr, &type);
+		if (ret != nr || type == VSWAP_ZSWAP)
+			return -EBUSY;
+	}
 
 	is_zero = __swap_table_test_zero(ci, ci_off);
 	ci_off = round_down(ci_off, nr);
mm/zswap.c +5 -1
index bbfaeac00355..3e1aa295f9dd 100644
@@ -1688,9 +1688,13 @@ int zswap_load(struct folio *folio)
 	 * range on the backing device, so scan the range rather than rejecting
 	 * it outright. The caller has pinned every slot, so zswap cannot start
 	 * a store or a writeback into the range while we look.
+	 *
+	 * A vswap batch is checked when the folio enters the swap cache, and
+	 * its backing cannot change after that.
 	 */
 	if (folio_test_large(folio)) {
-		if (WARN_ON_ONCE(zswap_is_present(swp,
+		if (WARN_ON_ONCE(!swap_is_vswap(si) &&
+				 zswap_is_present(swp,
 						  folio_nr_pages(folio)))) {
 			folio_unlock(folio);
 			return -EIO;
Signature · 1 line
2.53.0-Meta
author maintainer
#22 lore raw

PATCH v5 6/11 mm, swap: write back vswap zswap entries to physical swap

In reply to Nhat Pham

Add support for writing back zswap-backed vswap entries to physical swap. The mechanism mirrors the existing zswap writeback path, except the backing physical slot is allocated on demand at writeback time rather than already being pinned by the PTE.

The zswap shrinker no longer skips vswap entries, unless we are out of physical swap space.

---
 mm/zswap.c | 67 +++++++++++++++++++++++++++++++++++++-----------------
 1 file changed, 46 insertions(+), 21 deletions(-)
mm/zswap.c +46 -21
index 3e1aa295f9dd..56315298c291 100644
@@ -1025,12 +1025,13 @@ static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio)
 static int zswap_writeback_entry(struct zswap_entry *entry,
 				 swp_entry_t swpentry)
 {
-	struct xarray *tree;
 	pgoff_t offset = swp_offset(swpentry);
 	struct folio *folio;
 	struct mempolicy *mpol;
 	struct swap_info_struct *si;
 	struct swap_io_ctx ctx = {};
+	swp_entry_t phys = {};
+	bool is_vswap;
 	int ret = 0;
 
 	/* try to allocate swap cache folio */
@@ -1038,12 +1039,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	if (IS_ERR_OR_NULL(si))
 		return -ENOENT;
 
-	/* Vswap entries have no physical backing to write to. */
-	if (swap_is_vswap(si)) {
-		put_swap_device(si);
-		return -EINVAL;
-	}
-
+	is_vswap = swap_is_vswap(si);
 	mpol = get_task_policy(current);
 	folio = swap_cache_alloc_folio(swpentry, GFP_KERNEL, BIT(0), NULL, mpol,
 				       NO_INTERLEAVE_INDEX);
@@ -1062,24 +1058,44 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	/*
 	 * folio is locked, and the swapcache is now secured against
 	 * concurrent swapping to and from the slot, and concurrent
-	 * swapoff so we can safely dereference the zswap tree here.
+	 * swapoff so we can safely dereference the zswap tree (or vswap
+	 * vtable) here.
 	 * Verify that the swap entry hasn't been invalidated and recycled
 	 * behind our backs, to avoid overwriting a new swap folio with
 	 * old compressed data. Only when this is successful can the entry
 	 * be dereferenced.
 	 */
-	tree = swap_zswap_tree(swpentry);
-	if (entry != xa_load(tree, offset)) {
+	if (entry != zswap_entry_load(swpentry)) {
 		ret = -ENOMEM;
 		goto out;
 	}
 
+	if (is_vswap) {
+		/*
+		 * Allocate physical backing before decompress so a failure
+		 * wastes no work.
+		 */
+		phys = folio_realloc_swap(folio);
+		if (!phys.val) {
+			ret = -ENOMEM;
+			goto out;
+		}
+	}
+
 	if (!zswap_decompress(entry, folio)) {
 		ret = -EIO;
+		/*
+		 * The phys allocation above took the entry out of the vtable.
+		 * Restore the zswap entry to the vtable, which also frees the
+		 * allocated physical swap space.
+		 */
+		if (is_vswap)
+			vswap_zswap_store(swpentry, entry);
 		goto out;
 	}
 
-	xa_erase(tree, offset);
+	if (!is_vswap)
+		xa_erase(swap_zswap_tree(swpentry), offset);
 
 	count_vm_event(ZSWPWB);
 	if (entry->objcg)
@@ -1094,7 +1110,10 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	folio_set_reclaim(folio);
 
 	/* start writeback */
-	__swap_writeout(&ctx, folio, folio->swap);
+	if (is_vswap)
+		__swap_writeout(&ctx, folio, phys);
+	else
+		__swap_writeout(&ctx, folio, folio->swap);
 	swap_write_submit(&ctx);
 
 out:
@@ -1109,6 +1128,15 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 /*********************************
 * shrinker functions
 **********************************/
+/*
+ * vswap zswap entries get a physical slot allocated on demand at writeback
+ * time. Skip the shrinker when none is available.
+ */
+static bool zswap_writeback_possible(void)
+{
+	return !vswap_is_enabled() || get_nr_swap_pages() > 0;
+}
+
 /*
  * The dynamic shrinker is modulated by the following factors:
  *
@@ -1246,7 +1274,7 @@ static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
 	if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
 		return 0;
 
-	if (vswap_is_enabled())
+	if (!zswap_writeback_possible())
 		return 0;
 
 	/*
@@ -1332,7 +1360,8 @@ static struct shrinker *zswap_alloc_shrinker(void)
  * were scanned but none could be written back, or -ENOENT if @memcg has
  * writeback disabled, is a zombie cgroup, or has empty zswap LRUs.
  *
- * Also returns -ENOENT when vswap is enabled.
+ * Also returns -ENOENT when vswap is enabled and there is no physical
+ * swap to write back to.
  */
 static int shrink_memcg(struct mem_cgroup *memcg)
 {
@@ -1341,7 +1370,7 @@ static int shrink_memcg(struct mem_cgroup *memcg)
 	if (!mem_cgroup_zswap_writeback_enabled(memcg))
 		return -ENOENT;
 
-	if (vswap_is_enabled())
+	if (!zswap_writeback_possible())
 		return -ENOENT;
 
 	/*
@@ -1372,11 +1401,7 @@ static void shrink_worker(struct work_struct *w)
 	int ret, failures = 0, attempts = 0;
 	unsigned long thr;
 
-	/*
-	 * When vswap is enabled, zswap entries are almost all vswap backed,
-	 * with no slot to write back to.
-	 */
-	if (vswap_is_enabled())
+	if (!zswap_writeback_possible())
 		return;
 
 	/* Reclaim down to the accept threshold */
@@ -1457,7 +1482,7 @@ static void shrink_worker(struct work_struct *w)
 			break;
 resched:
 		cond_resched();
-	} while (zswap_total_pages() > thr);
+	} while (zswap_total_pages() > thr && zswap_writeback_possible());
 }
 
 /*********************************
Signature · 1 line
2.53.0-Meta
author maintainer
#23 lore raw

PATCH v5 7/11 mm, swap: reclaim physical slots backing cache-only vswap entries

In reply to Nhat Pham

When a vswap entry's swap_count drops to 0 while its folio is still in the swap cache, the entry is cache-only and its physical slot is redundant. swap_put_entries_direct() tries to reclaim it at put time, but folio_put_swap() does not, and even the direct route can come back empty:
the folio may be under the writeback that allocated the slot, its trylock may be lost, it may still be mapped, or swap_only_has_cache() may be false on a partial run. Nothing retried afterwards, so the slot stayed pinned.

Reclaim such slots from the physical reclaim scanner, once swap is more than half used (vm_swap_full()), to free physical capacity for new allocations. Reclaim goes through folio_free_swap(), which ends in folio_set_dirty(), so a reclaimed slot costs a re-swapout if the folio is dropped again.

---
 mm/swap_table.h |  12 +++--
 mm/swapfile.c   | 117 ++++++++++++++++++++++++++++++++++++++++++++++++
 mm/vswap.h      |  31 +++++++++++++
 3 files changed, 156 insertions(+), 4 deletions(-)
mm/swap_table.h +8 -4
index 7d094694ec37..79f06642a553 100644
@@ -31,7 +31,7 @@ struct swap_memcg_table {
  * NULL:     |---------------- 0 ---------------| - Free slot
  * Shadow:   |SWAP_COUNT|Z|---- SHADOW_VAL ---|1| - Swapped out slot
  * PFN:      |SWAP_COUNT|Z|------ PFN -------|10| - Cached slot
- * Pointer:  |-------- vswap offset --------|100| - vswap rmap
+ * Pointer:  |C|------- vswap offset -------|100| - vswap rmap
  * Bad:      |------------- 1 -------------|1000| - Bad slot
  *
  * COUNT is `SWP_TB_COUNT_BITS` long, Z is the `SWP_TB_ZERO_FLAG` bit,
@@ -399,14 +399,18 @@ static inline unsigned short __swap_cgroup_clear(struct swap_cluster_info *ci,
  * On physical clusters, a Pointer-tagged entry stores the offset of the
  * vswap entry that owns this physical slot (the reverse map). Only the
  * offset is stored; the swap type is implicit (always vswap_si->type,
- * since there is exactly one vswap device).
+ * since there is exactly one vswap device). The top bit is reserved as
+ * a cache-only flag, set when vswap swap_count drops to 0 but the folio
+ * is still in swap cache.
  *
- *   Pointer:  |---- vswap offset ----|100|
+ *   Pointer:  |C|---- vswap offset ----|100|
+ *              C = SWP_RMAP_CACHE_ONLY (the top bit)
  */
 #define SWP_TB_PTR_MARK_BITS	3
 #define SWP_TB_PTR_MARK		0b100UL
 #define SWP_TB_PTR_MARK_MASK	((1UL << SWP_TB_PTR_MARK_BITS) - 1)
-#define SWP_RMAP_ENTRY_MASK	(~SWP_TB_PTR_MARK_MASK)
+#define SWP_RMAP_CACHE_ONLY	(1UL << (BITS_PER_LONG - 1))
+#define SWP_RMAP_ENTRY_MASK	(~(SWP_RMAP_CACHE_ONLY | SWP_TB_PTR_MARK_MASK))
 
 static inline bool swp_tb_is_pointer(unsigned long swp_tb)
 {
mm/swapfile.c +117 -0

159 lines not on this page · raw message

mm/vswap.h +31 -0
index 6f952b2591d1..b79866d5999c 100644
@@ -44,6 +44,37 @@ static inline bool is_vswap_entry(swp_entry_t entry)
 	return swap_is_vswap(__swap_entry_to_info(entry));
 }
 
+/*
+ * Rmap cache-only helpers for physical cluster Pointer-tagged entries.
+ * SWP_RMAP_CACHE_ONLY records, inline on the physical swap_table entry,
+ * that the backing vswap entry has swap_count == 0 (swap-cache-only, so
+ * reclaimable). The physical reclaim scanner reads it directly instead of
+ * chasing the rmap into the vswap layer and paying the cluster-lookup
+ * indirection.
+ *
+ * Callers hold the vswap cluster lock, not the physical one. The rmap is
+ * only touched while the vtable holds the slot as SWAPFILE, and that
+ * window is opened and closed under the vswap cluster lock, so the
+ * allocator has finished writing the entry by then.
+ */
+static inline void swap_rmap_mark_cache_only(struct swap_cluster_info *ci,
+					     unsigned int off)
+{
+	atomic_long_t *table;
+
+	table = rcu_dereference_protected(ci->table, true);
+	atomic_long_or(SWP_RMAP_CACHE_ONLY, &table[off]);
+}
+
+static inline void swap_rmap_clear_cache_only(struct swap_cluster_info *ci,
+					      unsigned int off)
+{
+	atomic_long_t *table;
+
+	table = rcu_dereference_protected(ci->table, true);
+	atomic_long_and(~SWP_RMAP_CACHE_ONLY, &table[off]);
+}
+
 /*
  * Virtual table entry encoding for vswap clusters.
  *
Signature · 1 line
2.53.0-Meta
author maintainer
#24 lore raw

PATCH v5 8/11 mm, swap: only charge physical swap entries

In reply to Nhat Pham

Zswap-backed and zero-filled pages occupy no swap space, but were charged against memcg->swap as though they did.

Charge memcg->swap when a vswap entry acquires physical backing rather than when it is allocated.

This changes what the counter means and when the charge can fail:

* memory.swap.current counts only on-disk swap usage, not zswap-backed or zero-filled pages.
* A cgroup can reclaim its anon memory even with memory.swap.max set to 0, provided zswap is allowed for it.
* The charge can fail at writeback rather than at allocation. swap_writeout() returns AOP_WRITEPAGE_ACTIVATE and zswap_writeback_entry() returns -ENOMEM for a cgroup at its limit.
* The zswap shrinker skips such a cgroup rather than walking its LRUs.

Also refactor the swap memcg operations into separate get, record, charge, uncharge and put helpers, since recording the owner and charging it no longer happen at the same time.

Direct-mapped physical swap charging is unchanged. So is cgroup v1 memsw
accounting: the folio's memsw charge is retained across swapout regardless of backing, and released when the entry is freed.

---
 .../admin-guide/cgroup-v1/memcg_test.rst      |   2 +-
 Documentation/admin-guide/cgroup-v2.rst       |  46 +++---
 include/linux/memcontrol.h                    |   6 +
 include/linux/swap.h                          |  61 ++++++-
 mm/memcontrol-v1.c                            |  10 +-
 mm/memcontrol.c                               | 152 ++++++++++--------
 mm/swapfile.c                                 | 128 +++++++++++++--
 mm/zswap.c                                    |  29 ++--
 8 files changed, 312 insertions(+), 122 deletions(-)
Documentation/admin-guide/cgroup-v1/memcg_test.rst +1 -1
index d9951c319ef5..cd565626c435 100644
@@ -43,7 +43,7 @@ Please note that implementation details can be changed.
 	mem_cgroup_uncharge()
 	  Called when a page's refcount goes down to 0.
 
-	mem_cgroup_uncharge_swap()
+	mem_cgroup_swap_uncharge()
 	  Called when swp_entry's refcnt goes down to 0. A charge against swap
 	  disappears.
 
Documentation/admin-guide/cgroup-v2.rst +25 -21

79 lines not on this page · raw message

include/linux/memcontrol.h +6 -0
index 46bf724cae7a..4add06affefa 100644
@@ -1933,6 +1933,7 @@ static inline void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_ZSWAP)
 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg);
+bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush);
 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size);
 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size);
 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg);
@@ -1941,6 +1942,11 @@ static inline bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
 {
 	return true;
 }
+
+static inline bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
+{
+	return true;
+}
 static inline void obj_cgroup_charge_zswap(struct obj_cgroup *objcg,
 					   size_t size)
 {
include/linux/swap.h +53 -8

89 lines not on this page · raw message

mm/memcontrol-v1.c +9 -1
index bf2c7d53b01b..3e06a8bdf46e 100644
@@ -341,6 +341,7 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
 void memcg1_swapin(struct folio *folio)
 {
 	struct swap_cluster_info *ci;
+	struct mem_cgroup *memcg;
 	unsigned long nr_pages;
 	unsigned short id;
 
@@ -372,7 +373,14 @@ void memcg1_swapin(struct folio *folio)
 	id = __swap_cgroup_clear(ci, swp_cluster_offset(folio->swap),
 				 nr_pages);
 	swap_cluster_unlock(ci);
-	mem_cgroup_uncharge_swap(id, nr_pages);
+
+	rcu_read_lock();
+	memcg = mem_cgroup_from_private_id(id);
+	if (memcg) {
+		mem_cgroup_swap_uncharge(memcg, nr_pages);
+		mem_cgroup_swap_put(memcg, nr_pages);
+	}
+	rcu_read_unlock();
 }
 #endif
 
mm/memcontrol.c +86 -66

237 lines not on this page · raw message

mm/swapfile.c +114 -14

222 lines not on this page · raw message

mm/zswap.c +18 -11
index 56315298c291..aac09970c4d1 100644
@@ -1130,11 +1130,17 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 **********************************/
 /*
  * vswap zswap entries get a physical slot allocated on demand at writeback
- * time. Skip the shrinker when none is available.
+ * time, and that slot is charged to @memcg. Skip the shrinker when either
+ * the device or the cgroup has no room left. @memcg may be NULL to check
+ * the device alone.
  */
-static bool zswap_writeback_possible(void)
+static bool zswap_writeback_possible(struct mem_cgroup *memcg)
 {
-	return !vswap_is_enabled() || get_nr_swap_pages() > 0;
+	if (!vswap_is_enabled())
+		return true;
+	if (!memcg)
+		return get_nr_swap_pages() > 0;
+	return mem_cgroup_get_nr_swap_pages(memcg) > 0;
 }
 
 /*
@@ -1199,9 +1205,10 @@ static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_o
 	 *
 	 *    Temporary failures, where the same entry should be tried
 	 *    again immediately, almost never happen for this shrinker.
-	 *    We don't do any trylocking; -ENOMEM comes closest,
-	 *    but that's extremely rare and doesn't happen spuriously
-	 *    either. Don't bother distinguishing this case.
+	 *    We don't do any trylocking; -ENOMEM comes closest, but
+	 *    zswap_writeback_possible() keeps the shrinker off cgroups
+	 *    with no physical swap headroom, and it doesn't happen
+	 *    spuriously either. Don't bother distinguishing this case.
 	 */
 	list_move_tail(item, &l->list);
 
@@ -1274,7 +1281,7 @@ static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
 	if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
 		return 0;
 
-	if (!zswap_writeback_possible())
+	if (!zswap_writeback_possible(memcg))
 		return 0;
 
 	/*
@@ -1361,7 +1368,7 @@ static struct shrinker *zswap_alloc_shrinker(void)
  * writeback disabled, is a zombie cgroup, or has empty zswap LRUs.
  *
  * Also returns -ENOENT when vswap is enabled and there is no physical
- * swap to write back to.
+ * swap for @memcg to write back to.
  */
 static int shrink_memcg(struct mem_cgroup *memcg)
 {
@@ -1370,7 +1377,7 @@ static int shrink_memcg(struct mem_cgroup *memcg)
 	if (!mem_cgroup_zswap_writeback_enabled(memcg))
 		return -ENOENT;
 
-	if (!zswap_writeback_possible())
+	if (!zswap_writeback_possible(memcg))
 		return -ENOENT;
 
 	/*
@@ -1401,7 +1408,7 @@ static void shrink_worker(struct work_struct *w)
 	int ret, failures = 0, attempts = 0;
 	unsigned long thr;
 
-	if (!zswap_writeback_possible())
+	if (!zswap_writeback_possible(NULL))
 		return;
 
 	/* Reclaim down to the accept threshold */
@@ -1482,7 +1489,7 @@ static void shrink_worker(struct work_struct *w)
 			break;
 resched:
 		cond_resched();
-	} while (zswap_total_pages() > thr && zswap_writeback_possible());
+	} while (zswap_total_pages() > thr && zswap_writeback_possible(NULL));
 }
 
 /*********************************
Signature · 1 line
2.53.0-Meta
author maintainer
#25 lore raw

PATCH v5 9/11 mm, swap: add debugfs counters for vswap

In reply to Nhat Pham

Add /sys/kernel/debug/vswap/ with two counters:

* used: virtual swap slots (pages) currently allocated
* alloc_reject: cumulative pages that failed to get a vswap slot

---
 mm/swapfile.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
mm/swapfile.c +25 -0
index 3c3fc3b87b9b..cf07d87d2301 100644
@@ -7,6 +7,7 @@
  */
 
 #include <linux/blkdev.h>
+#include <linux/debugfs.h>
 #include <linux/mm.h>
 #include <linux/sched/mm.h>
 #include <linux/sched/task.h>
@@ -142,6 +143,7 @@ static DEFINE_PER_CPU(struct percpu_vswap_cluster, percpu_vswap_cluster) = {
 	.lock = INIT_LOCAL_LOCK(),
 };
 
+static atomic_long_t vswap_alloc_reject = ATOMIC_LONG_INIT(0);
 static void vswap_mark_cache_only(struct swap_cluster_info *ci,
 				  unsigned int ci_off);
 static void vswap_clear_cache_only(struct swap_cluster_info *ci,
@@ -1996,6 +1998,7 @@ static bool vswap_alloc(struct folio *folio)
 
 	this_cpu_write(percpu_vswap_cluster.offset[order], SWAP_ENTRY_INVALID);
 	local_unlock(&percpu_vswap_cluster.lock);
+	atomic_long_add(folio_nr_pages(folio), &vswap_alloc_reject);
 	return false;
 }
 
@@ -4827,9 +4830,25 @@ early_param("vswap", early_vswap);
 /* vswap does no IO on its own. */
 static const struct swap_ops vswap_ops = { };
 
+static int vswap_used_get(void *data, u64 *val)
+{
+	*val = swap_usage_in_pages(vswap_si);
+	return 0;
+}
+DEFINE_DEBUGFS_ATTRIBUTE(vswap_used_fops, vswap_used_get, NULL, "%llu\n");
+
+static int vswap_alloc_reject_get(void *data, u64 *val)
+{
+	*val = atomic_long_read(&vswap_alloc_reject);
+	return 0;
+}
+DEFINE_DEBUGFS_ATTRIBUTE(vswap_alloc_reject_fops, vswap_alloc_reject_get, NULL,
+			 "%llu\n");
+
 static int __init vswap_init(void)
 {
 	struct swap_info_struct *si;
+	struct dentry *root;
 	unsigned long maxpages;
 	int err;
 
@@ -4881,6 +4900,12 @@ static int __init vswap_init(void)
 	mutex_unlock(&swapon_mutex);
 
 	vswap_si = si;
+
+	root = debugfs_create_dir("vswap", NULL);
+	debugfs_create_file("used", 0444, root, NULL, &vswap_used_fops);
+	debugfs_create_file("alloc_reject", 0444, root, NULL,
+			    &vswap_alloc_reject_fops);
+
 	pr_info("vswap: created virtual swap device (%lu pages)\n", maxpages);
 
 	/* Last: everything above must be visible before routing starts. */
Signature · 1 line
2.53.0-Meta
author maintainer
#26 lore raw

PATCH v5 10/11 mm, swap: defer memcg_table allocation for physical swap clusters

In reply to Nhat Pham

Stop allocating a memcg table for every physical swap cluster that only ever holds vswap backings. The table costs SWAPFILE_CLUSTER * sizeof(unsigned short) per cluster, 1 KB per 2 MB of swap on a 64-bit kernel with 4 KB pages. On a vswap-heavy workload, where zswap writeback is the only consumer of physical swap, that is the common case.

Such clusters never have their memcg_table read or written: vswap-layer charging records on the vswap cluster's table, not the physical one.

Allocate eagerly only where the table is known to be needed: every vswap cluster, and, when vswap is off, every physical cluster, since none of its slots is then a vswap backing. A physical cluster otherwise allocates on its first direct-use slot, and skips entirely if it only holds vswap backings. Hibernation slots have no folio and record no cgroup, so they do not trigger it. That deferred allocation is on the allocator's fast path and can fail; the allocation it serves then fails too, and the caller falls back to another cluster.

---
 mm/swapfile.c | 83 +++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 64 insertions(+), 19 deletions(-)
mm/swapfile.c +64 -19
index cf07d87d2301..39d1840b0d36 100644
@@ -472,7 +472,8 @@ static void swap_cluster_free_table(struct swap_cluster_info *ci)
 	swap_cluster_free_count_table(table);
 }
 
-static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp)
+static int swap_cluster_alloc_table(struct swap_info_struct *si,
+				    struct swap_cluster_info *ci, gfp_t gfp)
 {
 	struct swap_table *table = NULL;
 	struct folio *folio;
@@ -493,7 +494,14 @@ static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp)
 		return -ENOMEM;
 
 #ifdef CONFIG_MEMCG
-	if (!mem_cgroup_disabled()) {
+	/*
+	 * A physical cluster under vswap may hold only vswap backings, which
+	 * record their memcg on the vswap cluster's table, not this one. Such
+	 * clusters defer memcg_table allocation until they hand out a slot
+	 * that maps directly into the PTEs.
+	 */
+	if ((!vswap_is_enabled() || swap_is_vswap(si)) &&
+	    !mem_cgroup_disabled()) {
 		VM_WARN_ON_ONCE(ci->memcg_table);
 		ci->memcg_table = kzalloc_obj(*ci->memcg_table, gfp);
 		if (!ci->memcg_table) {
@@ -571,8 +579,8 @@ swap_cluster_populate(struct swap_info_struct *si,
 		lockdep_assert_held(&si->global_cluster_lock);
 	lockdep_assert_held(&ci->lock);
 
-	if (!swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC |
-					  __GFP_NOWARN))
+	if (!swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
+					      __GFP_NOWARN))
 		return ci;
 
 	/*
@@ -585,8 +593,8 @@ swap_cluster_populate(struct swap_info_struct *si,
 		spin_unlock(&si->global_cluster_lock);
 	local_unlock(&percpu_swap_cluster.lock);
 
-	ret = swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC |
-					   GFP_KERNEL);
+	ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
+					       GFP_KERNEL);
 
 	/*
 	 * Back to atomic context. We might have migrated to a new CPU with a
@@ -863,7 +871,7 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si,
 
 	ci = cluster_info + idx;
 	/* Need to allocate swap table first for initial bad slot marking. */
-	if (!ci->count && swap_cluster_alloc_table(ci, GFP_KERNEL))
+	if (!ci->count && swap_cluster_alloc_table(si, ci, GFP_KERNEL))
 		return -ENOMEM;
 	spin_lock(&ci->lock);
 	/* Check for duplicated bad swap slots. */
@@ -1086,7 +1094,9 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 /* Try use a new cluster for current CPU and allocate from it. */
 static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 					    struct swap_cluster_info *ci,
-					    struct folio *folio, unsigned long offset)
+					    struct folio *folio,
+					    unsigned long offset,
+					    bool *nomem)
 {
 	unsigned int next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 	unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);
@@ -1115,6 +1125,23 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 			if (!ret)
 				continue;
 		}
+#ifdef CONFIG_MEMCG
+		/*
+		 * Lazy-allocate memcg_table on the first direct-use slot of a
+		 * physical cluster.
+		 */
+		if (vswap_is_enabled() && folio &&
+		    !folio_test_swapcache(folio) && !mem_cgroup_disabled() &&
+		    !ci->memcg_table) {
+			ci->memcg_table = kzalloc_obj(*ci->memcg_table,
+						      GFP_ATOMIC | __GFP_NOWARN);
+			if (!ci->memcg_table) {
+				if (nomem)
+					*nomem = true;
+				goto out;
+			}
+		}
+#endif
 		if (!__swap_cluster_alloc_entries(si, ci, folio, offset % SWAPFILE_CLUSTER))
 			break;
 		found = offset;
@@ -1124,7 +1151,15 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 		break;
 	}
 out:
-	relocate_cluster(si, ci);
+	/*
+	 * On a discard-capable device, relocating a cluster whose memcg_table
+	 * allocation failed queues a discard for slots that were never used,
+	 * which folio_alloc_phys_swap() reads as progress and retries on.
+	 */
+	if (nomem && *nomem && !ci->count)
+		__free_cluster(si, ci);
+	else
+		relocate_cluster(si, ci);
 	swap_cluster_unlock(ci);
 	if (swap_is_vswap(si)) {
 		this_cpu_write(percpu_vswap_cluster.offset[order], next);
@@ -1145,7 +1180,13 @@ static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,
 					 bool scan_all)
 {
 	unsigned int found = SWAP_ENTRY_INVALID;
+	bool nomem = false;
 
+	/*
+	 * In rare cases alloc_swap_scan_cluster() can fail due to
+	 * memcg_table allocation failure. Short-circuit to avoid looping
+	 * over the list indefinitely.
+	 */
 	do {
 		struct swap_cluster_info *ci = isolate_lock_cluster(si, list);
 		unsigned long offset;
@@ -1153,10 +1194,10 @@ static unsigned int 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, &nomem);
 		if (found)
 			break;
-	} while (scan_all);
+	} while (scan_all && !nomem);
 
 	return found;
 }
@@ -1177,7 +1218,8 @@ static unsigned int vswap_alloc_cluster(struct swap_info_struct *si,
 	spin_lock_init(&ci_dyn->ci.lock);
 	INIT_LIST_HEAD(&ci_dyn->ci.list);
 
-	if (swap_cluster_alloc_table(&ci_dyn->ci, GFP_ATOMIC | __GFP_NOWARN)) {
+	if (swap_cluster_alloc_table(si, &ci_dyn->ci,
+				     GFP_ATOMIC | __GFP_NOWARN)) {
 		kfree(ci_dyn);
 		return SWAP_ENTRY_INVALID;
 	}
@@ -1203,7 +1245,7 @@ static unsigned int vswap_alloc_cluster(struct swap_info_struct *si,
 	}
 
 	offset = cluster_offset(si, ci);
-	return alloc_swap_scan_cluster(si, ci, folio, offset);
+	return alloc_swap_scan_cluster(si, ci, folio, offset, NULL);
 }
 
 static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
@@ -1310,7 +1352,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,
+							NULL);
 		} else {
 			swap_cluster_unlock(ci);
 		}
@@ -1354,7 +1397,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	if (order < PMD_ORDER) {
 		/*
 		 * Scan only one fragment cluster is good enough. Order 0
-		 * allocation will surely success, and large allocation
+		 * allocation rarely fails, and large allocation
 		 * failure is not critical. Scanning one cluster still
 		 * keeps the list rotated and reclaimed (for clean swap cache).
 		 */
@@ -1369,7 +1412,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	/* Order 0 stealing from higher order */
 	for (int o = 1; o < SWAP_NR_ORDERS; o++) {
 		/*
-		 * Clusters here have at least one usable slots and can't fail order 0
+		 * Clusters here have at least one usable slots and rarely 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);
@@ -1590,7 +1633,7 @@ static swp_entry_t swap_alloc_fast(struct folio *folio)
 	if (ci && 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, NULL);
 	} else if (ci) {
 		swap_cluster_unlock(ci);
 	}
@@ -1981,7 +2024,8 @@ static bool vswap_alloc(struct folio *folio)
 		if (ci && cluster_is_usable(ci, order)) {
 			if (cluster_is_empty(ci))
 				offset = cluster_offset(vswap_si, ci);
-			alloc_swap_scan_cluster(vswap_si, ci, folio, offset);
+			alloc_swap_scan_cluster(vswap_si, ci, folio, offset,
+						NULL);
 		} else if (ci) {
 			swap_cluster_unlock(ci);
 		}
@@ -2860,7 +2904,8 @@ 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, NULL);
 		else
 			swap_cluster_unlock(ci);
 	}
Signature · 1 line
2.53.0-Meta
author maintainer
#27 lore raw

RFC PATCH v5 11/11 mm, swap: back vswap clusters with a VM_SPARSE array

In reply to Nhat Pham

vswap keeps its cluster_info in an xarray of individually allocated clusters. Replace it with the VM_SPARSE vmalloc array Baoquan He designed for xswap: one reservation at init, mapped a page of clusters at a time as the device grows. That drops the per-cluster allocation and the xarray nodes, and it simplifies access, because the index gives the address. A lookup becomes arithmetic instead of an xa_load() that can return NULL, and no cluster needs an RCU grace period to be freed, so the NULL arm goes away in every caller along with the index and rcu_head fields, the kfree_rcu(), CLUSTER_FLAG_DEAD and __vswap_cluster_lock(). Only the grow side is ported; there is no shrink.

That leaves swap_cluster_info_dynamic wrapping swap_cluster_info for a single pointer, so move the virtual table into swap_cluster_info and delete the wrapper. Both cluster arrays then have the same element type and merge into si->cluster_info, which restores cluster_index() to upstream's subtraction and leaves __swap_offset_to_cluster() a plain array index. A vswap cluster ends up smaller, having lost the index and rcu_head; a physical cluster grows by the one pointer it never uses.

A cluster is no longer destroyed when it empties. There is nothing left to free, since it is now an element of a fixed array, so it goes onto si->free_clusters like a physical device's cluster and waits to be reused.

Its virtual table is still freed, and that is the bulk of it:
SWAPFILE_CLUSTER pointers, a full page at the usual layout, against a few dozen bytes for the cluster itself. An emptied cluster gives back almost all of what it held; only the mapping stays.

Most of this is Baoquan's code, adapted to vswap's existing cluster layer rather than to a new device type, so I am keeping his attributions from the original posting.

---
 include/linux/swap.h |   5 +-
 mm/swap.h            |  61 +-------
 mm/swap_state.c      |  19 +--
 mm/swap_table.h      |   9 --
 mm/swapfile.c        | 353 ++++++++++++++++++++++++++++---------------
 mm/vswap.h           |  96 +++++-------
 6 files changed, 280 insertions(+), 263 deletions(-)
include/linux/swap.h +4 -1
index cd22db50b44c..dffdec14c407 100644
@@ -164,6 +164,7 @@ static inline void mm_account_reclaimed_pages(unsigned long pages)
 
 struct address_space;
 struct sysinfo;
+struct vm_struct;
 struct zone;
 
 /*
@@ -271,7 +272,9 @@ struct swap_info_struct {
 	struct list_head discard_clusters; /* discard clusters list */
 	struct plist_node avail_list;   /* entry in swap_avail_head */
 	const struct swap_ops *ops;
-	struct xarray cluster_info_pool; /* Xarray for vswap dynamic cluster info */
+	struct vm_struct *cluster_info_area; /* Vswap cluster array reservation */
+	unsigned int nr_mapped_clusters; /* Mapped prefix of cluster_info */
+	struct mutex cluster_grow_lock;	/* Serialize growth of the array */
 };
 
 static inline bool swap_is_vswap(struct swap_info_struct *si)
mm/swap.h +4 -57

106 lines not on this page · raw message

mm/swap_state.c +5 -14
index 2107d05ae8d5..627fee08593c 100644
@@ -165,7 +165,6 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 	unsigned int ci_off, ci_end;
 	unsigned long old_tb;
 	bool is_zero;
-	struct swap_cluster_info_dynamic *ci_dyn;
 	enum vswap_backing_type type;
 	int ret;
 
@@ -201,8 +200,7 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 	 * swap_cache_alloc_folio will retry with a smaller order on -EBUSY.
 	 */
 	if (is_vswap_entry(targ_entry)) {
-		ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
-		ret = __vswap_check_backing(ci_dyn, round_down(ci_off, nr),
+		ret = __vswap_check_backing(ci, round_down(ci_off, nr),
 					    nr, &type);
 		if (ret != nr || type == VSWAP_ZSWAP)
 			return -EBUSY;
@@ -451,12 +449,9 @@ static struct folio *__swap_cache_alloc(swp_entry_t targ_entry, gfp_t gfp,
 	entry.val = round_down(targ_entry.val, nr_pages);
 
 	/* Check if the slot and range are available, skip allocation if not */
-	err = -ENOENT;
 	ci = swap_cluster_lock(si, offset);
-	if (ci) {
-		err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
-		swap_cluster_unlock(ci);
-	}
+	err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL);
+	swap_cluster_unlock(ci);
 	if (unlikely(err))
 		return ERR_PTR(err);
 
@@ -477,13 +472,10 @@ static struct folio *__swap_cache_alloc(swp_entry_t targ_entry, gfp_t gfp,
 		return ERR_PTR(-ENOMEM);
 
 	/* Double check the range is still not in conflict */
-	err = -ENOENT;
 	ci = swap_cluster_lock(si, offset);
-	if (ci)
-		err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
+	err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
 	if (unlikely(err)) {
-		if (ci)
-			swap_cluster_unlock(ci);
+		swap_cluster_unlock(ci);
 		folio_put(folio);
 		return ERR_PTR(err);
 	}
@@ -495,7 +487,6 @@ static struct folio *__swap_cache_alloc(swp_entry_t targ_entry, gfp_t gfp,
 
 	if (mem_cgroup_swapin_charge_folio(folio, memcg_id,
 					   vmf ? vmf->vma->vm_mm : NULL, gfp)) {
-		/* The folio pins the cluster */
 		spin_lock(&ci->lock);
 		__swap_cache_do_del_folio(ci, folio, entry, shadow);
 		spin_unlock(&ci->lock);
mm/swap_table.h +0 -9
index 79f06642a553..7d005a943881 100644
@@ -266,11 +266,6 @@ static inline unsigned long swap_table_get(struct swap_cluster_info *ci,
 	return swp_tb;
 }
 
-/*
- * Resolve @entry's cluster and read its slot, both under RCU. A vswap
- * cluster is allocated on demand and freed by kfree_rcu(), so a caller
- * starting from an entry cannot resolve it beforehand.
- */
 static inline unsigned long swap_table_lookup(swp_entry_t entry)
 {
 	struct swap_cluster_info *ci;
@@ -279,10 +274,6 @@ static inline unsigned long swap_table_lookup(swp_entry_t entry)
 
 	rcu_read_lock();
 	ci = __swap_entry_to_cluster(entry);
-	if (!ci) {
-		rcu_read_unlock();
-		return null_to_swp_tb();
-	}
 	table = rcu_dereference(ci->table);
 	swp_tb = table ? atomic_long_read(&table[swp_cluster_offset(entry)])
 		       : null_to_swp_tb();
mm/swapfile.c +228 -125

615 lines not on this page · raw message

mm/vswap.h +39 -57

201 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#28 lore raw
In reply to Nhat Pham
Quoted 11 lines · Nhat Pham

Patch 11 is an RFC. It swaps vswap's cluster xarray for the VM_SPARSE vmalloc array Baoquan He designed for xswap, to show that the data structure and the device model are separable: moving to his is one self-contained patch that adds no userspace interface. Note that per Baoquan's commentary (see [5]), I have skipped shrink for now, only freeing vtable when the cluster becomes free to minimize metadata overhead while keeping the skeleton in the free list. I have not done performance testing on this patch yet (the number is from the old design), but I have run a suite of simple stress tests.

Quoted 2 lines

It is adapted almost entirely from Baoquan's code (see [6]), so I have kept Baoquan's Co-developed-by and Signed-off-by tag.

To clarify a bit on the motivation of this exercise: Kairui and Baoquan raised the concerns (for e.g in [1]) that if we were to go with the xarray as a data structure first, switching it to the VM_SPARSE vmalloc array would be difficult. I want to check this claim by prototyping such a conversion. It is fairly straightforward and simple to me. So it is not a valid concern to block the landing of vswap.

If we are to actually switch to such a data structure, Baoquan should be the one driving this, by showing that there are performance wins to the switch :) It is his proposal, so the onus is on him to drive it to completion. I'm happy to assist with the reviewing and testing!

[1]: https://lore.kernel.org/all/CAMgjq7AHRzBsbmGOx0s=TQFBwcn=DEU1naR443sO6x+pJd6hAg@mail.gmail.com/

syzbot Tested-by [email protected] on the v5 series
#29 lore raw
In reply to Nhat Pham
syzbot ci has tested the following series

syzbot ci has tested the following series

[v5] Virtual Swap Space (Swap Table Edition)
https://lore.kernel.org/all/[email protected]
* [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure
* [PATCH v5 02/11] mm, swap: support zswap and zero-filled swap pages as vswap backends
* [PATCH v5 03/11] mm, swap: prepare the swap IO path for vswap
* [PATCH v5 04/11] mm, swap: support physical swap as a vswap backend
* [PATCH v5 05/11] mm, swap: enable THP swapin for vswap entries
* [PATCH v5 06/11] mm, swap: write back vswap zswap entries to physical swap
* [PATCH v5 07/11] mm, swap: reclaim physical slots backing cache-only vswap entries
* [PATCH v5 08/11] mm, swap: only charge physical swap entries
* [PATCH v5 09/11] mm, swap: add debugfs counters for vswap
* [PATCH v5 10/11] mm, swap: defer memcg_table allocation for physical swap clusters
* [RFC PATCH v5 11/11] mm, swap: back vswap clusters with a VM_SPARSE array

and found the following issue:

KASAN: null-ptr-deref Read in swap_entry_backend_has_flag

Full report is available here:
https://ci.syzbot.org/series/713f2473-328a-4c16-8bce-63005d15a338

***

KASAN: null-ptr-deref Read in swap_entry_backend_has_flag
tree:      linux-next
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/next/linux-next
base:      27e4e1835109ef599d72abe6c09711e0b1916033
arch:      amd64
compiler:  Debian clang version 22.1.8 (++20260613092233+e80beda6e255-1~exp1~20260613092250.77), Debian LLD 22.1.8
config:    https://ci.syzbot.org/builds/26b06329-3b1c-4c73-8ee3-64c53b995186/config
syz repro: https://ci.syzbot.org/findings/f743742b-1934-4b4e-a590-9a36592da902/syz_repro

==================================================================

BUG: KASAN: null-ptr-deref in instrument_atomic_read include/linux/instrumented.h:82 [inline]
BUG: KASAN: null-ptr-deref in atomic_long_read include/linux/atomic/atomic-instrumented.h:3188 [inline]
BUG: KASAN: null-ptr-deref in __vtable_get mm/vswap.h:163 [inline]
BUG: KASAN: null-ptr-deref in vswap_to_phys mm/vswap.h:202 [inline]
BUG: KASAN: null-ptr-deref in swap_entry_backend_has_flag+0xea/0x210 mm/vswap.h:409
Read of size 8 at addr 0000000000000e00 by task syz.1.38/5916

CPU: 1 UID: 0 PID: 5916 Comm: syz.1.38 Not tainted syzkaller #0 PREEMPT(full) 
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
Call Trace:
 <TASK>
 dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
 kasan_report+0x117/0x150 mm/kasan/report.c:595
 check_region_inline mm/kasan/generic.c:-1 [inline]
 kasan_check_range+0x264/0x2c0 mm/kasan/generic.c:200
 instrument_atomic_read include/linux/instrumented.h:82 [inline]
 atomic_long_read include/linux/atomic/atomic-instrumented.h:3188 [inline]
 __vtable_get mm/vswap.h:163 [inline]
 vswap_to_phys mm/vswap.h:202 [inline]
 swap_entry_backend_has_flag+0xea/0x210 mm/vswap.h:409
 do_swap_page+0x767/0x5a20 mm/memory.c:5042
 __collapse_huge_page_swapin mm/khugepaged.c:1152 [inline]
 collapse_huge_page mm/khugepaged.c:1271 [inline]
 mthp_collapse mm/khugepaged.c:1469 [inline]
 collapse_run_pmd+0xaf1/0x5d90 mm/khugepaged.c:2811
 madvise_collapse mm/madvise.c:1026 [inline]
 madvise_vma_behavior+0x17cf/0x4d80 mm/madvise.c:1548
 madvise_walk_vmas+0x576/0xb00 mm/madvise.c:1896
 madvise_do_behavior+0x385/0x540 mm/madvise.c:2091
 do_madvise+0x26f/0x330 mm/madvise.c:2189
 __do_sys_madvise mm/madvise.c:2198 [inline]
 __se_sys_madvise mm/madvise.c:2196 [inline]
 __x64_sys_madvise+0xa6/0xc0 mm/madvise.c:2196
 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
 do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f7b5939e159
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f7b5a1ff028 EFLAGS: 00000246 ORIG_RAX: 000000000000001c
RAX: ffffffffffffffda RBX: 00007f7b59625fa0 RCX: 00007f7b5939e159
RDX: 0000000000000019 RSI: 0000000000c00000 RDI: 0000200000000000
RBP: 00007f7b5943506b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f7b59626038 R14: 00007f7b59625fa0 R15: 00007ffe5f2d8d38
 </TASK>
==================================================================

***

If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:

---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].

To test a fix for this bug, please reply with #syz test (on a separate line) and attach the patch to the email.

Notes:
- The patch will be applied on top of the tested series (as an incremental fix).
- To test a new version of the whole series, please send it directly to [email protected].
- Arguments like custom git repos and branches are not supported.

author maintainer
#30 lore raw
Quoted 18 lines · syzbot ci

syzbot ci has tested the following series

[v5] Virtual Swap Space (Swap Table Edition)
https://lore.kernel.org/all/[email protected]
* [PATCH v5 01/11] mm, swap: add virtual swap device infrastructure
* [PATCH v5 02/11] mm, swap: support zswap and zero-filled swap pages as vswap backends
* [PATCH v5 03/11] mm, swap: prepare the swap IO path for vswap
* [PATCH v5 04/11] mm, swap: support physical swap as a vswap backend
* [PATCH v5 05/11] mm, swap: enable THP swapin for vswap entries
* [PATCH v5 06/11] mm, swap: write back vswap zswap entries to physical swap
* [PATCH v5 07/11] mm, swap: reclaim physical slots backing cache-only vswap entries
* [PATCH v5 08/11] mm, swap: only charge physical swap entries
* [PATCH v5 09/11] mm, swap: add debugfs counters for vswap
* [PATCH v5 10/11] mm, swap: defer memcg_table allocation for physical swap clusters
* [RFC PATCH v5 11/11] mm, swap: back vswap clusters with a VM_SPARSE array

and found the following issue:

Quoted 8 lines
KASAN: null-ptr-deref Read in swap_entry_backend_has_flag

Full report is available here:
https://ci.syzbot.org/series/713f2473-328a-4c16-8bce-63005d15a338

***

KASAN: null-ptr-deref Read in swap_entry_backend_has_flag

Ah I think the bug is in the RFC patch (the one that does the conversion). I was too overzealous in deleting checks :)

The skeleton (cluster struct) itself is no longer freed (I just put it back on the free list). But I do free the vtable when there is no slot used in that cluster. It's one invariant replaced with another - "cluster freeable, but if cluster exists then vtable exists" becomes "cluster is never freed but the vtable inside it might be freed", so I should change the check rather than just deleting the check.

Should be easily fixable.

Tested-by on the v5 series
#31 lore raw
In reply to Nhat Pham
Quoted 345 lines · Nhat Pham

Changelog:
* v4 [v4] -> v5
* OVERCOMMIT_GUESS now allows for 3xRAM margin when vswap is enabled, to take into account swapfile-less zswap usage (proposed by Johannes Weiner).
* Limit vswap swapfile size to 8TB and drop the last patch, to avoid memcg private id refcnt saturation.
* More assorted cleanups and fixes: anon swappability check, etc.
* RFC: Replace the xarray with a new data structure (vmalloc array) (new patch 11).
* Rebased onto mm-unstable.
* v3 [v3] -> v4
* Replaced the runtime sysctl with a cmdline param, and remove CONFIG_VSWAP (suggested by Johannes Weiner). CONFIG_VSWAP_DEFAULT_ON now only gives the default value of the vswap cmdline parameter.
* Refactor swap-related memcg operations into composable building
blocks: reference acquisitions, charging, etc. (patch 8, suggested by Johannes Weiner).
* Fixed vtable UAF bug reported by syzbot and Kunwu.
* Rebased onto mm-unstable (minimal merge conflicts).
* Re-run benchmarks (no signal change).
* v2 [v2] -> v3:
* Rebased onto current mm-unstable.
* Add a runtime vm.vswap_enabled sysctl and CONFIG_VSWAP_DEFAULT_ON to gate vswap allocation.
* More cleanups and small bug fixes.
* Split THP swapin enablement into its own patch (patch 5).
* Add production workload benchmark results, and drop RFC tag.
* v1 [v1] -> v2:
* Rebased to a newer mm-unstable tip.
* Fix a bunch of assorted issues (incorrect zswap store failure rollback, vswap_init() failure handling, rmap-encoding collision, etc.) and clean up the code (rename a bunch of functions to more closely follow existing patterns, etc.).
* Some more code clean up and simplification: some renamings to more closely follow existing patterns, move vswap backing check to __swap_cache_add_check, store zero state in the swap_table for vswap entries, etc.. Many of these are proposed by Kairui Song in [1].
* Defer memcg_table allocation on physical clusters until the first vswap-backing slot installs. Saves ~512 bytes per physical cluster that only serves vswap-backing slots (this is the new patch 8).
* Widen swap_info_struct->max and ->pages (and the swapoff unuse-path index) so vswap supports ~8 PB of swap space (this is the new patch 9).
* Split the physical-swap-backend patch into three for reviewability:
the core backend (patch 3), zswap writeback to physical swap (patch 4), and reclaim of cache-only physical slots (patch 5). No functional change.
* Add kerneldoc for the vswap API.
* Add some benchmark numbers for zswap case.

Patch 11 is an RFC. It swaps vswap's cluster xarray for the VM_SPARSE vmalloc array Baoquan He designed for xswap, to show that the data structure and the device model are separable: moving to his is one self-contained patch that adds no userspace interface. Note that per Baoquan's commentary (see [5]), I have skipped shrink for now, only freeing vtable when the cluster becomes free to minimize metadata overhead while keeping the skeleton in the free list. I have not done performance testing on this patch yet (the number is from the old design), but I have run a suite of simple stress tests.

It is adapted almost entirely from Baoquan's code (see [6]), so I have kept Baoquan's Co-developed-by and Signed-off-by tag.

I. Context and Motivation
=========================

Currently, when an anon page is swapped out, a slot in a backing swap device is allocated and stored in the page table entries that refer to the original page. This slot is also used as the "key" to find the swapped out content, as well as the index to swap data structures, such as the swap cache, or the swap cgroup mapping. Tying a swap entry to its backing slot in this way is performant and efficient when swap is purely just disk space, and swapoff is rare.

However, the advent of many swap optimizations has exposed major drawbacks of this design. The first problem is that we occupy a physical slot in the swap space, even for pages that are NEVER expected to hit the disk: pages compressed and stored in the zswap pool, zero-filled pages, or pages rejected by both of these optimizations when zswap writeback is disabled. This is arguably the central shortcoming of zswap:
* Resource-wise, it is hugely wasteful in terms of disk usage. At Meta, we size swapfile in the order of 25-50% of host RAM, depending on flash availability. This is a lot of flash for a fleet of our size, and with universal zswap enablement, most of this is wasted for zswap entries.

* In deployments when no disk space can be afforded for swap (such as mobile and embedded devices), users cannot adopt zswap, and are forced to use zram. This is confusing for users, and creates extra burdens for developers, having to develop and maintain similar features for two separate swap backends (writeback, cgroup charging, THP support, etc.). For instance, see the discussion in [2].

* Tying zswap (and more generally, other in-memory swap backends) to the current physical swapfile infrastructure makes zswap implicitly statically sized. This does not make sense, as unlike disk swap, in which we consume a limited resource (disk space or swapfile space) to save another resource (memory), zswap consumes the same resource it is saving (memory). The more we zswap, the more memory we have available, not less. We are not rationing a limited resource when we limit the size of the zswap pool, but rather we are capping the resource (memory) saving potential of zswap. Under memory pressure, using more zswap is almost always better than the alternative (disk IOs, or even worse, OOMs), and dynamically sizing the zswap pool on demand allows the system to flexibly respond to these precarious scenarios.

* Operationally, static provisioning the swapfile for zswap poses significant challenges, because the sysadmin has to prescribe how much swap is needed a priori, for each combination of (memory size x disk space x workload usage). It is even more complicated when we take into account the variance of memory compression, which changes the reclaim dynamics (and as a result, swap space size requirement). The problem is further exacerbated for users who rely on swap utilization (and exhaustion) as an OOM signal.

All of these factors make it very difficult to configure the swapfile for zswap: too small of a swapfile and we risk preventable OOMs and limit the memory saving potentials of zswap; too big of a swapfile and we waste disk space and memory due to swap metadata overhead. This dilemma becomes more drastic in high memory systems, which can have up to TBs worth of memory.

Swap virtualization is the answer to these issues, with three properties:

1. Decoupled backends. For zswap in particular, this means we eliminate the unused storage space, and allows zswap to be used in systems that do not have enough storage capacity for physical swap (without having to resort to silly hacks). Zero-filled swap pages and swap-cache-only folios also benefit here.

2. Dynamic swap space. Since virtual swap is not tied to any physical resource, we can make it effectively infinite and dynamically grow it on demand.
This massively simplifies operational provisioning, and increases the utilization of compressed swap backends (zswap). Dynamicity also reduces overhead on unused swap capacity.

3. Efficient backend transfer. The virtualization scheme should not introduce PTE/rmap walking overhead for backend transfer. This is crucial for systems that want to support multiple swap backends in a tiering fashion (for e.g zswap -> disk swap).

For more historical contexts and references, please take a look at the cover letter of the older vswap submissions ([3] and [v2]).

II. Design
==========

When vswap is enabled (via vswap=on cmdline parameter), a special vswap device is allocated at boot time. Anon pages that can be zswapped will obtain a vswap slot at swap allocation time.

These swap entries can subsequently acquire backend on-demand, such as a zswap entry, or a slot on a physical swap device (as a fallback option or at zswap writeback time).

We repurpose much of the existing swap_table infrastructure and swapfile allocator for this new vswap device, with two notable differences:
* Clusters are dynamically allocated on demand and managed through an xarray. This in turn allows us to avoid static provisioning and let swap space grow dynamically.

* Each cluster of this new vswap device has a virtual_table that stores the backend information of the entries in the cluster (see below).

Diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +---------------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)          |
                       | +----------------------------+  |
                       | | swap_table                 |  |
                       | |   PFN / Shadow             |  |
                       | | memcg_table                |  |
                       | | count,flags,order          |  |
                       | | lock, list                 |  |
                       | +----------------------------+  |
                       |                                 |
                       | virtual_table                   |
                       | +----------------------------+  |
                       | | NONE                       |  |
                       | | SWAPFILE(swp_entry_t)      |  |
                       | | ZSWAP(struct zswap_entry*) |  |
                       | +----------------------------+  |
                       +---------------------------------+
                              |
                              | SWAPFILE resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate the backend type:

  NONE:     |----- 0000 ------|000|  free / unbacked
  ZSWAP:    |--- zswap_entry* |001|  compressed in zswap
  SWAPFILE: |- type:5,off:56 -|010|  on a physical swapfile

Other design highlights:

* Note that for the vswap device, we have merged the zswap xarray tree with the swapfile-level clusters. This means that for zswap only users, we have negligible extra space overhead.

* Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens.

* Backend transitions in the virtual_table are synchronized through the swap cache and the folio lock - the same mechanism that already serializes ordinary swap operations (swapin, swapout, zswap writeback, swap cache reclaim). IOW, we can only assume that the backend of a vswap entry is stable through swap cache/folio lock. Looking at the backend without this should be done at best for optimization purposes, as there is no guarantee that the backend will not change under the observer.

* Pointer-tagged swap_table entries on physical clusters provide the rmap (physical -> virtual) lookup.

* Virtual swap slots not backed by physical swap are not charged to memcg swap counters - only physical backing is charged (I made the case for this in [4]).

III. Benchmarks
===============

Note that the goal is not to match vswap performance with baseline on every single case yet - running with vswap off is still supported. We can optimize further once we have landed this new feature.

A. Production Workload: Instagram
=================================

To test vswap's stability and performance, I ran an A/B experiment on Instagram (django) workload, with zswap as the swap backend. On these hosts, the swapfiles' size is 50% of RAM.

Compared to baseline, vswap gives:

* On par request throughput.
* Lower request serving latency (by about 1-3%).
* Lower memory pressure in the system service cgroups running alongside the workload. PSI-based proactive reclaimer can therefore recover more from them, lowering their overall memory footprint, allowing the main workload to expand.
* Elimination of swapfile footprint for all zswap users in the host.

B. Semi-synthetic Workloads (memhog, usemem, kernel build)
==========================================================

All values are mean +/- standard deviation across rounds.

Test system: x86_64, 52 cores, 64 GB swapfile for all 3 benchmarks. Swap backend: zswap (zstd) with the traditional active/inactive LRU. We focus on zswap here because it is the motivating use case for vswap.

For each benchmark, we test 3 kernels:
* Baseline: mm-unstable, no vswap patches.
* VSS off: vswap series applied, vswap=off, to verify that there is no regression to existing swap paths when we disable vswap.
* VSS on: vswap series applied, vswap=on.

1. Memhog: single-threaded, 48GB allocation on a host with 16GB RAM, 20 rounds.

Baseline VSS off VSS on

   real (s)        124.05 +/- 11.64   122.31 +/- 10.29   118.57 +/- 15.68
   sys (s)         106.75 +/- 10.86   105.01 +/- 9.64    101.34 +/- 13.97
   user (s)        10.81 +/- 0.11     10.85 +/- 0.09     10.79 +/- 0.09
   delta real              -              -1.4%              -4.4%
   delta sys               -              -1.6%              -5.1%

Dropping the best and the worst round to reduce variance:

memhog Baseline VSS off VSS on

   real (s)        123.75 +/- 10.39   122.04 +/- 9.10    116.06 +/- 8.22
   sys (s)         106.80 +/- 10.21   104.99 +/- 8.86    99.29 +/- 8.27
   user (s)        10.82 +/- 0.11     10.85 +/- 0.08     10.79 +/- 0.10
   delta real              -              -1.4%              -6.2%
   delta sys               -              -1.7%              -7.0%

2. Usemem single-threaded: 56GB allocation on a host with 32GB RAM, 16 rounds.

Baseline VSS off VSS on

   real (s)        178.75 +/- 6.47    178.95 +/- 6.56    175.97 +/- 7.74
   sys (s)         127.03 +/- 6.56    128.08 +/- 6.59    124.71 +/- 7.90
   tput (KB/s)     386662 +/- 14648   386264 +/- 15150   390443 +/- 17532
   free (ms)       7669 +/- 146       7678 +/- 136       6439 +/- 111
   delta real              -              +0.1%              -1.6%
   delta sys               -              +0.8%              -1.8%
   delta tput              -              -0.1%              +1.0%
   delta free              -              +0.1%             -16.0%

3. Kernel build: 52 workers (one per processor), memory.max=3GB, 10 rounds.

Baseline VSS off VSS on

   real (s)        165.58 +/- 0.45    165.83 +/- 0.49    166.01 +/- 0.58
   sys (s)         694.24 +/- 26.13   710.76 +/- 19.83   705.06 +/- 21.40
   user (s)       5132.62 +/- 1.12   5133.69 +/- 1.57   5134.68 +/- 1.68
   delta real              -              +0.2%              +0.3%
   delta sys               -              +2.4%              +1.6%
   delta user              -              +0.0%              +0.0%
Quoted 2 lines

For zswap backend, vswap outperforms baseline on usemem freeing, and is on par with baseline on the rest.

I have been using versions of this series consistently since about August and occasionally before with no apparent issues, so I think it's time for

Quoted 59 lines

IV. References
==============

[v1]: https://lore.kernel.org/all/[email protected]/
[v2]: https://lore.kernel.org/all/[email protected]/
[v3]: https://lore.kernel.org/all/[email protected]/
[v4]: https://lore.kernel.org/all/[email protected]/
[1]: https://lore.kernel.org/all/CAMgjq7BhOn48xEyC=2j837R7qddfjeBVHMiRqdx8no4ZEBpBLg@mail.gmail.com/
[2]: https://lore.kernel.org/all/[email protected]/
[3]: https://lore.kernel.org/all/[email protected]/
[4]: https://lore.kernel.org/linux-mm/CAKEwX=P4syV38jAVCWq198r2OHXXc=xA-fx1dk6+qYef6yzxWQ@mail.gmail.com/
[5]: https://lore.kernel.org/all/aqjpYHbZ14A8xRtK@fedora/
[6]: https://lore.kernel.org/all/[email protected]/

Nhat Pham (11):
mm, swap: add virtual swap device infrastructure
mm, swap: support zswap and zero-filled swap pages as vswap backends mm, swap: prepare the swap IO path for vswap
mm, swap: support physical swap as a vswap backend
mm, swap: enable THP swapin for vswap entries
mm, swap: write back vswap zswap entries to physical swap mm, swap: reclaim physical slots backing cache-only vswap entries mm, swap: only charge physical swap entries
mm, swap: add debugfs counters for vswap
mm, swap: defer memcg_table allocation for physical swap clusters mm, swap: back vswap clusters with a VM_SPARSE array

 .../admin-guide/cgroup-v1/memcg_test.rst      |    2 +-
 Documentation/admin-guide/cgroup-v2.rst       |   46 +-
 .../admin-guide/kernel-parameters.txt         |    7 +
 MAINTAINERS                                   |    1 +
 include/linux/memcontrol.h                    |    6 +
 include/linux/swap.h                          |   88 +-
 include/linux/swap_ops.h                      |    9 +-
 include/linux/zswap.h                         |    4 +
 mm/Kconfig                                    |   20 +
 mm/memcontrol-v1.c                            |   10 +-
 mm/memcontrol.c                               |  147 +-
 mm/memory.c                                   |   21 +-
 mm/page_io.c                                  |  101 +-
 mm/shmem.c                                    |    4 +-
 mm/swap.h                                     |   28 +-
 mm/swap_state.c                               |   50 +-
 mm/swap_table.h                               |   64 +-
 mm/swapfile.c                                 | 1254 +++++++++++++++--
 mm/util.c                                     |   13 +-
 mm/vmscan.c                                   |   18 +-
 mm/vswap.h                                    |  422 ++++++
 mm/workingset.c                               |    2 +-
 mm/zswap.c                                    |  132 +-
 23 files changed, 2180 insertions(+), 269 deletions(-)
 create mode 100644 mm/vswap.h

base-commit: 27e4e1835109ef599d72abe6c09711e0b1916033

Signature · 1 line
2.53.0-Meta