Skip to contentSkip to conversation

Virtual Swap Space (Swap Table Edition)

PATCH In review Nhat Pham 4 participants 26 messages Oct 21 – Oct 27

Subsystems (10)
lore
Share & tools
lore

Nhat Pham

author maintainer
#0 lore raw

v6 cover Virtual Swap Space (Swap Table Edition)

Changelog:
* v5 [v5] -> v6
* Added a new cgroup memory.stats counter for vswap slots (patch 11).
* Fixed some small bugs: incorrect swap-allocation failure classification, nofs check in phys swap fallback path, etc.
* Rebased onto a newer mm-unstable.
* 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 12 is an RFC. It replaces vswap's cluster xarray with the VM_SPARSE vmalloc array Baoquan He designed for xswap [6]. This changes descriptor storage without adding a userspace interface. The array grows on demand but does not shrink [5]. Empty clusters release their per-cluster tables and return to the free list for reuse.

The benchmark results below are from the xarray design. I have not benchmarked the VM_SPARSE version, 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 eligible for zswap are first allocated virtual slots; physical slots are used if virtual allocation fails.

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 |
| Vswap - vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Vswap(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|  no separate backend
  ZSWAP:    |--- zswap_entry* |001|  compressed in zswap
  SWAPFILE: |- type:5,off:56 -|010|  on a physical swapfile

Zero-filled pages use the swap_table zero flag; cache folios use its PFN entries.

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.

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

* Virtual swap entries count towards memory.swap.current only when backed by physical swap slots [4]. In cgroup v1, vswap entries are still accounted towards the memsw counter.

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]/
[v5]: 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 (12):
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: add vmstat and memcg counters for vswap
mm, swap: back vswap clusters with a VM_SPARSE array

 .../admin-guide/cgroup-v1/memcg_test.rst      |    2 +-
 .../admin-guide/cgroup-v1/memory.rst          |    3 +-
 Documentation/admin-guide/cgroup-v2.rst       |   54 +-
 .../admin-guide/kernel-parameters.txt         |    7 +
 MAINTAINERS                                   |    1 +
 include/linux/memcontrol.h                    |    7 +
 include/linux/swap.h                          |  101 +-
 include/linux/swap_ops.h                      |   10 +-
 include/linux/vmstat.h                        |    3 +
 include/linux/zswap.h                         |    4 +
 mm/Kconfig                                    |   20 +
 mm/memcontrol-v1.c                            |   13 +-
 mm/memcontrol.c                               |  208 ++-
 mm/memory.c                                   |   21 +-
 mm/page_io.c                                  |  104 +-
 mm/shmem.c                                    |    4 +-
 mm/swap.h                                     |   28 +-
 mm/swap_state.c                               |   62 +-
 mm/swap_table.h                               |   64 +-
 mm/swapfile.c                                 | 1241 +++++++++++++++--
 mm/util.c                                     |   13 +-
 mm/vmscan.c                                   |   41 +-
 mm/vmstat.c                                   |    6 +
 mm/vswap.h                                    |  438 ++++++
 mm/workingset.c                               |    2 +-
 mm/zswap.c                                    |  127 +-
 26 files changed, 2291 insertions(+), 293 deletions(-)
 create mode 100644 mm/vswap.h

base-commit: 4dbe24720eb3811563cd56b35d87ddf3f9beed2a

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

PATCH v6 1/12 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.

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. 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 objcg->private_id_ref, a 32-bit refcount_t, so a cgroup that swaps past that saturates it and leaks the objcg until reboot. The limit is not specific to vswap, a physical swapfile that large hits it too.

---
 .../admin-guide/kernel-parameters.txt         |   7 +
 MAINTAINERS                                   |   1 +
 include/linux/swap.h                          |   9 +
 mm/Kconfig                                    |  20 ++
 mm/page_io.c                                  |  12 +
 mm/swap.h                                     |  77 ++++-
 mm/swap_state.c                               |  43 +--
 mm/swap_table.h                               |  27 ++
 mm/swapfile.c                                 | 273 ++++++++++++++++--
 mm/vswap.h                                    |  34 +++
 mm/zswap.c                                    |   6 +
 11 files changed, 465 insertions(+), 44 deletions(-)
 create mode 100644 mm/vswap.h
Documentation/admin-guide/kernel-parameters.txt +7 -0
index e75344f4e0cd..5482a133a566 100644
@@ -8395,6 +8395,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 6f1f35a017a6..4d11f2b3a2db 100644
@@ -17431,6 +17431,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 4f686709d71f..81b9f3569c23 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.
@@ -434,6 +441,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 acefc994d9a8..6cb5297658f5 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 +12 -0
index c6824fcd483e..e9998fc6cf06 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,12 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
+	/* A vswap folio has no physical slot to write to. */
+	if (is_vswap_entry(folio->swap)) {
+		folio_mark_dirty(folio);
+		return AOP_WRITEPAGE_ACTIVATE;
+	}
+
 	__swap_writeout(ctx, folio);
 	return 0;
 out_unlock:
@@ -486,6 +493,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 +23 -20

118 lines not on this page · raw message

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 +252 -21

466 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 572075bb1c1c..b75c513da299 100644
@@ -1069,6 +1069,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
author maintainer
#2 lore raw

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

In reply to Nhat Pham

This patch adds support for zswap and zero-filled swap backends for vswap.

This allows users to use zswap without a physical backing swapfile.

If zswap_store fails, the page stays dirty in the swap cache. Zswap writeback of vswap-backed entries is also disabled: they have no physical slot to write back to yet, so the zswap shrinker is skipped while vswap is enabled.

THP swapin is disabled for vswap entries for now.

We also need to change the reclaim and overcommit logic to accommodate physical swapfile-less swapping:

* 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: within the cgroup's swap.max headroom, either zswap will take the folio or a physical slot is free.

* 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.

---
 include/linux/memcontrol.h |   6 ++
 include/linux/swap.h       |  13 +++
 include/linux/zswap.h      |   4 +
 mm/memcontrol.c            |  58 ++++++++----
 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 +++++++++++---
 15 files changed, 537 insertions(+), 53 deletions(-)
include/linux/memcontrol.h +6 -0
index 74110a324f9e..b9072a3c9a2a 100644
@@ -1944,6 +1944,7 @@ static inline void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_ZSWAP)
 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg);
+bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush);
 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size);
 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size);
 bool mem_cgroup_zswap_writeback_enabled(const struct mem_cgroup *memcg);
@@ -1952,6 +1953,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 +13 -0
index 81b9f3569c23..1479914d545d 100644
@@ -370,6 +370,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 *,
@@ -448,6 +450,11 @@ static inline void put_swap_device(struct swap_info_struct *si)
 
 #else /* CONFIG_SWAP */
 static inline void swap_writeback_dropbehind_folio(struct folio *folio) {}
+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;
@@ -546,6 +553,7 @@ static inline void mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_p
 
 long mem_cgroup_get_folio_swap_margin(const struct folio *folio);
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg);
+bool mem_cgroup_can_swap(struct mem_cgroup *memcg, long nr_pages);
 bool mem_cgroup_swap_full(const struct folio *folio);
 #else
 static inline int mem_cgroup_try_charge_swap(struct folio *folio)
@@ -568,6 +576,11 @@ static inline long mem_cgroup_get_nr_swap_pages(const 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(const 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 +39 -19

89 lines not on this page · raw message

mm/memory.c +9 -2
index 976cd03954e3..e9b8855a7f11 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.
@@ -4715,6 +4716,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
@@ -4871,15 +4875,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 e9998fc6cf06..f849c285ba22 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 fd0953d55fd6..510ab181cc3a 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)
 
@@ -1822,7 +1823,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 f3773e376496..d0e7c991a4c0 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 e1db48ee5a21..a6bb650f5885 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;
@@ -197,6 +198,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

324 lines not on this page · raw message

mm/util.c +12 -1
index 7f374bb8bf36..7bf6b5b5a6d5 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 daa7e37c2236..4c5f0f97c1c7 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;
 	}
@@ -1632,7 +1635,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)) {
@@ -2801,7 +2805,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: */
@@ -2894,7 +2898,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 1504f91cdca5..39fa664daf98 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
#3 lore raw

PATCH v6 3/12 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.

Carry reclaim's NOFS restriction in the I/O context. A subsequent patch uses it when zswap_store() fails and writeout falls back to physical swap.

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 | 10 +++++---
 mm/page_io.c             | 54 +++++++++++++++++++---------------------
 mm/swap.h                |  3 ++-
 mm/swapfile.c            |  6 ++---
 mm/vmscan.c              |  4 ++-
 mm/zswap.c               |  2 +-
 7 files changed, 42 insertions(+), 39 deletions(-)
include/linux/swap.h +1 -1
index 1479914d545d..4066d99f896e 100644
@@ -414,7 +414,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 +6 -4
index 57ac6c703f68..1c65e346e127 100644
@@ -12,11 +12,13 @@ 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 {
 	struct swap_iocb	*sio;
 	struct swap_info_struct	*sis;
+	bool			nofs;
 };
 
 /*
@@ -30,15 +32,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 d0e7c991a4c0..b0a092b47fce 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 81ac45b4856e..69fac2d905a4 100644
@@ -341,14 +341,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/vmscan.c +3 -1
index 4c5f0f97c1c7..b9c5e92757f3 100644
@@ -1172,7 +1172,9 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 	unsigned int nr_reclaimed = 0, nr_demoted = 0;
 	unsigned int pgactivate = 0;
 	bool do_demote_pass;
-	struct swap_io_ctx ctx = {};
+	struct swap_io_ctx ctx = {
+		.nofs = !(sc->gfp_mask & __GFP_FS),
+	};
 
 	folio_batch_init(&free_folios);
 	memset(stat, 0, sizeof(*stat));
mm/zswap.c +1 -1
index 1ba191cbc26f..73c6b82aa593 100644
@@ -1159,7 +1159,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	folio_put(folio);
 
 	/* start writeback */
-	__swap_writeout(&ctx, folio);
+	__swap_writeout(&ctx, folio, folio->swap);
 	swap_write_submit(&ctx);
 
 	return 0;
Signature · 1 line
2.53.0-Meta
author maintainer
#4 lore raw

PATCH v6 4/12 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 vswap-tagged swap_table entry on the physical cluster (an rmap back to the vswap entry).

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 the folio's cgroup is at its zswap limit, 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.

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    |  40 +++++-
 mm/swap_state.c |   6 +-
 mm/swap_table.h |  42 +++++-
 mm/swapfile.c   | 352 +++++++++++++++++++++++++++++++++++++++++++-----
 mm/vmscan.c     |  21 ++-
 mm/vswap.h      | 198 ++++++++++++++++++++++++++-
 mm/zswap.c      |   2 +-
 8 files changed, 609 insertions(+), 65 deletions(-)
mm/memory.c +8 -5
index e9b8855a7f11..9f651d247eef 100644
@@ -4716,8 +4716,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
@@ -4725,7 +4728,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))
@@ -5066,7 +5069,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);
@@ -5230,7 +5233,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 +33 -7
index 61bb5c6e9759..ed8c037e4aa0 100644
@@ -209,6 +209,7 @@ static void swap_zeromap_folio_clear(struct folio *folio)
  */
 int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 {
+	swp_entry_t phys = folio->swap;
 	int ret = 0;
 
 	if (folio_free_swap(folio))
@@ -241,8 +242,14 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	 */
 	swap_zeromap_folio_clear(folio);
 
+	/*
+	 * For vswap: release stale non-swapfile backings (e.g. ZSWAP from a
+	 * previous swapout cycle) so zswap_store or folio_realloc_swap
+	 * starts on clean slots. Contiguous PHYS backing is preserved for
+	 * reuse by folio_realloc_swap.
+	 */
 	if (is_vswap_entry(folio->swap))
-		folio_release_vswap_backing(folio);
+		folio_release_non_phys_swap_backing(folio);
 
 	if (zswap_store(folio)) {
 		count_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);
@@ -257,13 +264,21 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
-	/* A vswap folio has no physical slot to write to. */
 	if (is_vswap_entry(folio->swap)) {
+		phys = folio_realloc_swap(folio);
+		if (!phys.val) {
+			folio_mark_dirty(folio);
+			return AOP_WRITEPAGE_ACTIVATE;
+		}
+	}
+
+	if (ctx->nofs &&
+	    (__swap_entry_to_info(phys)->ops->flags & SWAP_OPS_F_REQUIRE_NOFS)) {
 		folio_mark_dirty(folio);
 		return AOP_WRITEPAGE_ACTIVATE;
 	}
 
-	__swap_writeout(ctx, folio, folio->swap);
+	__swap_writeout(ctx, folio, phys);
 	return 0;
 out_unlock:
 	folio_unlock(folio);
@@ -477,6 +492,7 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	bool workingset = folio_test_workingset(folio);
 	unsigned long pflags;
 	bool in_thrashing;
+	swp_entry_t phys;
 
 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio) && !synchronous, folio);
 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
@@ -501,14 +517,24 @@ 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;
+	/*
+	 * Resolve the physical slot to read from. A vswap entry keeps
+	 * folio->swap virtual, so map it to its physical backing; a folio with
+	 * no backing has nothing to read.
+	 */
+	if (swap_is_vswap(sis)) {
+		phys = vswap_to_phys(folio->swap);
+		if (!phys.val) {
+			folio_unlock(folio);
+			goto finish;
+		}
+	} else {
+		phys = folio->swap;
 	}
 
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
-	swap_add_folio(ctx, folio, folio->swap, READ);
+	swap_add_folio(ctx, folio, phys, READ);
 
 finish:
 	if (workingset) {
mm/swap_state.c +5 -1
index a6bb650f5885..3900975c675f 100644
@@ -186,6 +186,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_vswap(old_tb))
+		return -ENOENT;
 	if (swp_tb_is_folio(old_tb))
 		return -EEXIST;
 	if (!__swp_tb_get_count(old_tb))
@@ -210,7 +213,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_vswap(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 +15 -6
index b9c5e92757f3..70044688a7cb 100644
@@ -1145,17 +1145,26 @@ static unsigned int demote_folio_list(struct list_head *demote_folios,
 
 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
 {
+	swp_entry_t entry;
+
 	if (gfp_mask & __GFP_FS)
 		return true;
 	/*
 	 * We can "enter_fs" for swap-cache with only __GFP_IO unless backed by
 	 * a swapfile that requires GFP_NOFS I/O.
 	 */
-	if (folio_test_swapcache(folio) && (gfp_mask & __GFP_IO) &&
-	    !(__swap_entry_to_info(folio->swap)->ops->flags &
-			SWAP_OPS_F_REQUIRE_NOFS))
-		return true;
-	return false;
+	if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
+		return false;
+
+	entry = folio->swap;
+	if (is_vswap_entry(entry)) {
+		entry = vswap_to_phys(entry);
+		if (!entry.val)
+			return true;
+	}
+
+	return !(__swap_entry_to_info(entry)->ops->flags &
+		 SWAP_OPS_F_REQUIRE_NOFS);
 }
 
 /*
@@ -1637,7 +1646,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 73c6b82aa593..24c4e7a73d56 100644
@@ -1685,7 +1685,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
#5 lore raw

Re: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] mm: try_to_unuse() dirties unmapped vswap folios rejected by pageout() - [High] mm: try_to_unuse()…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] mm: try_to_unuse() dirties unmapped vswap folios rejected by pageout()
- [High] mm: try_to_unuse() leaks vswap folios and slots when swap count is zero
- [High] mm: large vswap folios declined by zswap fail swapout without splitting --

commit f1735375be4432e3cb8facdcc6b588e080aeb34c
Author: Nhat Pham <[email protected]>

mm, swap: support physical swap as a vswap backend

This commit adds physical swapfile support as a backend for virtual swap entries when zswap declines a folio during swap_writeout(), tracking the reverse mapping via vswap-tagged swap_table entries on the physical cluster. During swapoff, try_to_unuse() reads vswap-backed physical slots into the swap cache and releases their physical backing slots before walking process and shmem mappings.

Quoted 12 lines
mm/page_io.c +1 -0
index 61bb5c6e97595..ed8c037e4aa08 100644
@@ -209,6 +209,7 @@ static void swap_zeromap_folio_clear(struct folio *folio)
  */
 int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 {
+	swp_entry_t phys = folio->swap;
 	int ret = 0;
 
 	if (folio_free_swap(folio))

[ ... ]

mm/page_io.c int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio) · line 273

Quoted 12 lines
mm/page_io.c +6 -1
@@ -257,13 +264,21 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
-	/* A vswap folio has no physical slot to write to. */
 	if (is_vswap_entry(folio->swap)) {
+		phys = folio_realloc_swap(folio);
+		if (!phys.val) {
+			folio_mark_dirty(folio);
+			return AOP_WRITEPAGE_ACTIVATE;
+		}
+	}

[Severity: High]
What happens here when a large folio (order > 0) with a virtual swap entry is declined by zswap_store() and the underlying physical swap cannot satisfy a high-order allocation?

During reclaim in shrink_folio_list() or shmem_writeout(), folio_alloc_swap() allocates from vswap_si via vswap_alloc() -> cluster_alloc_swap_entry():

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

Because swap_is_vswap(vswap_si) is true, vswap_alloc() succeeds for order > 0 folios even when the physical swap devices are regular swapfiles without SWP_BLKDEV or have fragmented high-order clusters. As a result, folio_alloc_swap() returns 0 instead of -E2BIG, bypassing the split_folio_to_list() fallback in both shrink_folio_list() and shmem_writeout().

Later in swap_writeout(), if zswap_store() declines the large folio, folio_realloc_swap() -> folio_alloc_phys_swap() attempts to allocate a contiguous physical swap range of folio_order(folio), which always fails on non-SWP_BLKDEV swapfiles and fails when high-order physical clusters are unavailable. swap_writeout() then marks the folio dirty and returns AOP_WRITEPAGE_ACTIVATE without splitting it.

On subsequent reclaim passes, an anonymous large folio is already in the swap cache with PTEs referencing its vswap slots, so shrink_folio_list() skips the !folio_test_swapcache(folio) block where split_folio_to_list() is called:

mm/vmscan.c:shrink_folio_list() {
	if (folio_test_anon(folio) && folio_test_swapbacked(folio) &&
			!folio_test_swapcache(folio)) {
		...
		ret = folio_alloc_swap(folio);
		if (ret) {
			...
			if (split_folio_to_list(folio, folio_list))
				goto activate_locked;
}

For a large shmem folio, shmem_writeout() removes the unsplit folio from the swap cache on AOP_WRITEPAGE_ACTIVATE without reaching its -E2BIG split path, repeating the same vswap_alloc() success and folio_realloc_swap() failure on every pass.

Can this cause large vswap folios declined by zswap to never split or swap out?

Quoted 4 lines
mm/swapfile.c +0 -0
index 69fac2d905a4f..be66ac79313ce 100644

[ ... ]

Quoted 78 lines
mm/swapfile.c +61 -2
@@ -3087,19 +3287,95 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 
 static int try_to_unuse(unsigned int type)
 {
+	struct mempolicy *mpol = get_task_policy(current);
 	struct mm_struct *prev_mm;
 	struct mm_struct *mm;
 	struct list_head *p;
 	int retval = 0;
 	struct swap_info_struct *si = swap_info[type];
 	struct folio *folio;
-	swp_entry_t entry;
-	unsigned int i;
+	struct swap_io_ctx ctx;
+	swp_entry_t entry, vswap_entry, phys;
+	unsigned long swp_tb;
+	unsigned int i, j;
 
 	if (!swap_usage_in_pages(si))
 		goto success;
 
 retry:
+	/*
+	 * Free vswap-backing slots (Vswap-tagged) first. Walk physical
+	 * clusters, read the vswap entry from the rmap, ensure the data
+	 * is in the swap cache, and transition PHYS to FOLIO. Freeing the
+	 * physical backing is enough, so no page table walk is needed.
+	 */
+	i = 0;
+	while (vswap_is_enabled() &&
+	       swap_usage_in_pages(si) &&
+	       !signal_pending(current) &&
+	       (i = find_next_to_unuse(si, i)) != 0) {
+		swp_tb = swap_table_lookup(swp_entry(si->type, i));
+		if (!swp_tb_is_vswap(swp_tb))
+			continue;
+
+		vswap_entry = swp_tb_vswap_to_swp_entry(swp_tb);
+
+		folio = swap_cache_get_folio(vswap_entry);
+		if (!folio) {
+			folio = __swap_cache_alloc_folio(vswap_entry,
+							 GFP_HIGHUSER_MOVABLE,
+							 BIT(0), NULL, mpol,
+							 NO_INTERLEAVE_INDEX);
+			if (IS_ERR(folio)) {
+				if (PTR_ERR(folio) == -ENOMEM)
+					return -ENOMEM;
+				continue;
+			}
+			folio_add_lru(folio);
+			ctx = (struct swap_io_ctx){};
+			swap_read_folio(&ctx, folio);
+			swap_read_submit(&ctx);
+		}
+		folio_lock(folio);
+
+		if (!folio_matches_swap_entry(folio, vswap_entry)) {
+			folio_unlock(folio);
+			folio_put(folio);
+			continue;
+		}
+
+		/*
+		 * Re-validate under folio lock: rmap holds folio->swap + j
+		 * for some j in [0, nr_pages). Check folio->swap still maps
+		 * to the contiguous physical run that includes our slot i.
+		 */
+		j = vswap_entry.val - folio->swap.val;
+		phys = vswap_to_phys(folio->swap);
+		if (!phys.val || swp_type(phys) != type ||
+		    swp_offset(phys) + j != i) {
+			folio_unlock(folio);
+			folio_put(folio);
+			continue;
+		}
+
+		folio_wait_writeback(folio);

mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3371

Quoted 10 lines
mm/swapfile.c +10 -0
+		folio_release_vswap_backing(folio);
+		/*
+		 * Drop a folio whose read failed rather than dirtying
+		 * uninitialised memory; the next fault finds no backing and
+		 * gets SIGBUS.
+		 */
+		if (unlikely(!folio_test_uptodate(folio)))
+			swap_cache_del_folio(folio);
+		else
+			folio_mark_dirty(folio);

[Severity: High]
Can pageout() ever write out the unmapped swap-cache folios allocated and dirtied by this pre-pass?

When __swap_cache_alloc_folio() -> __swap_cache_alloc() allocates a fresh swap-cache folio here, it sets PG_swapbacked and PG_swapcache, but leaves folio->mapping as NULL because try_to_unuse() does not map the folio into a VMA via folio_add_new_anon_rmap(). Shmem folios in the swap cache also have folio->mapping set to NULL. As a result, folio_test_anon(folio) is false.

When shrink_folio_list() later scans one of these dirty swap-cache folios on
the LRU, folio_mapping(folio) returns &swap_space and shrink_folio_list()
calls pageout():

mm/vmscan.c:pageout() {
	if (folio_ref_count(folio) != 1 + folio_nr_pages(folio) || !mapping)
		return PAGE_KEEP;
	if (!shmem_mapping(mapping) && !folio_test_anon(folio))
		return PAGE_ACTIVATE;
	if (!folio_clear_dirty_for_io(folio))
		return PAGE_CLEAN;
}

Because mapping is &swap_space (!shmem_mapping(mapping)) and folio_test_anon(folio) is false, pageout() unconditionally returns PAGE_ACTIVATE before reaching swap_writeout(). Wouldn't this prevent reclaim from ever writing these dirtied vswap folios out to zswap or another swap device until they are faulted in?

mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3345

Quoted 3 lines
mm/swapfile.c +3 -0
+		folio_unlock(folio);
+		folio_put(folio);
+	}

[Severity: High]
Does this pre-pass leak the folio, its vswap slot, and its memcg swap charge if the vswap entry's swap count is 0 (or drops to 0 concurrently)?

There are two ways the vswap entry can have swap_count == 0 when reaching folio_release_vswap_backing(folio):

1. While try_to_unuse() holds the folio lock (during swap_read_folio() IO or before folio_unlock()), the owning process exits or zaps the swap PTE via zap_nonpresent_ptes() -> free_swap_and_cache_nr() -> swap_put_entries_cluster(). That path decrements the vswap slot's swap count to 0 and calls __try_to_reclaim_swap(), which fails folio_trylock() and bails out expecting the folio lock holder to clean up.

2. A prior read fault in do_swap_page() mapped the folio, decremented the vswap entry's swap count to 0 via folio_put_swap(), and left the folio in the swap cache because should_try_to_free_swap() saw folio_phys_swap_backed(folio) == true.

After folio_release_vswap_backing(folio) frees the physical slot, folio_phys_swap_backed(folio) becomes false, and try_to_unuse() marks the folio dirty without calling folio_free_swap(folio) (unlike the post-pass at the end of try_to_unuse()).

In the first case, the unlocked folio is unmapped, has folio->mapping == NULL (!folio_test_anon(folio)), has swap_count == 0, and is no longer physically backed. pageout() rejects it with PAGE_ACTIVATE before reaching swap_writeout() -> folio_free_swap(), and the activate_locked path in shrink_folio_list() also skips folio_free_swap() because folio_phys_swap_backed(folio) is now false:

mm/vmscan.c:shrink_folio_list() {
activate_locked:

	/* Not a candidate for swapping, so reclaim swap space. */
	if (folio_test_swapcache(folio) &&
	    ((mem_cgroup_swap_full(folio) && folio_phys_swap_backed(folio)) ||
	     folio_test_mlocked(folio)))
		folio_free_swap(folio);
}

Should try_to_unuse() check or call folio_free_swap(folio) when releasing the vswap backing here?

mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3379

Quoted 5 lines
mm/swapfile.c +3 -0
+	if (!swap_usage_in_pages(si))
+		goto success;
+
 	retval = shmem_unuse(type);

[ ... ]

完美 (Wait: oops, don't write any extra text after the report! Let's make sure the final output has only the report and ends with a blank line.) Let's review the whole text and output it cleanly.commit f1735375be4432e3cb8facdcc6b588e080aeb34c
Author: Nhat Pham <[email protected]>

mm, swap: support physical swap as a vswap backend

This commit adds physical swapfile support as a backend for virtual swap entries when zswap declines a folio during swap_writeout(), tracking the reverse mapping via vswap-tagged swap_table entries on the physical cluster. During swapoff, try_to_unuse() reads vswap-backed physical slots into the swap cache and releases their physical backing slots before walking process and shmem mappings.

Quoted 12 lines
mm/page_io.c +1 -0
index 61bb5c6e97595..ed8c037e4aa08 100644
@@ -209,6 +209,7 @@ static void swap_zeromap_folio_clear(struct folio *folio)
  */
 int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 {
+	swp_entry_t phys = folio->swap;
 	int ret = 0;
 
 	if (folio_free_swap(folio))

[ ... ]

mm/page_io.c int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio) · line 273

Quoted 12 lines
mm/page_io.c +6 -1
@@ -257,13 +264,21 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
-	/* A vswap folio has no physical slot to write to. */
 	if (is_vswap_entry(folio->swap)) {
+		phys = folio_realloc_swap(folio);
+		if (!phys.val) {
+			folio_mark_dirty(folio);
+			return AOP_WRITEPAGE_ACTIVATE;
+		}
+	}

[Severity: High]
What happens here when a large folio (order > 0) with a virtual swap entry is declined by zswap_store() and the underlying physical swap cannot satisfy a high-order allocation?

During reclaim in shrink_folio_list() or shmem_writeout(), folio_alloc_swap() allocates from vswap_si via vswap_alloc() -> cluster_alloc_swap_entry():

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

Because swap_is_vswap(vswap_si) is true, vswap_alloc() succeeds for order > 0 folios even when the physical swap devices are regular swapfiles without SWP_BLKDEV or have fragmented high-order clusters. As a result, folio_alloc_swap() returns 0 instead of -E2BIG, bypassing the split_folio_to_list() fallback in both shrink_folio_list() and shmem_writeout().

Later in swap_writeout(), if zswap_store() declines the large folio, folio_realloc_swap() -> folio_alloc_phys_swap() attempts to allocate a contiguous physical swap range of folio_order(folio), which always fails on non-SWP_BLKDEV swapfiles and fails when high-order physical clusters are unavailable. swap_writeout() then marks the folio dirty and returns AOP_WRITEPAGE_ACTIVATE without splitting it.

On subsequent reclaim passes, an anonymous large folio is already in the swap cache with PTEs referencing its vswap slots, so shrink_folio_list() skips the !folio_test_swapcache(folio) block where split_folio_to_list() is called:

mm/vmscan.c:shrink_folio_list() {
	if (folio_test_anon(folio) && folio_test_swapbacked(folio) &&
			!folio_test_swapcache(folio)) {
		...
		ret = folio_alloc_swap(folio);
		if (ret) {
			...
			if (split_folio_to_list(folio, folio_list))
				goto activate_locked;
}

For a large shmem folio, shmem_writeout() removes the unsplit folio from the swap cache on AOP_WRITEPAGE_ACTIVATE without reaching its -E2BIG split path, repeating the same vswap_alloc() success and folio_realloc_swap() failure on every pass.

Can this cause large vswap folios declined by zswap to never split or swap out?

Quoted 4 lines
mm/swapfile.c +0 -0
index 69fac2d905a4f..be66ac79313ce 100644

[ ... ]

Quoted 78 lines
mm/swapfile.c +61 -2
@@ -3087,19 +3287,95 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 
 static int try_to_unuse(unsigned int type)
 {
+	struct mempolicy *mpol = get_task_policy(current);
 	struct mm_struct *prev_mm;
 	struct mm_struct *mm;
 	struct list_head *p;
 	int retval = 0;
 	struct swap_info_struct *si = swap_info[type];
 	struct folio *folio;
-	swp_entry_t entry;
-	unsigned int i;
+	struct swap_io_ctx ctx;
+	swp_entry_t entry, vswap_entry, phys;
+	unsigned long swp_tb;
+	unsigned int i, j;
 
 	if (!swap_usage_in_pages(si))
 		goto success;
 
 retry:
+	/*
+	 * Free vswap-backing slots (Vswap-tagged) first. Walk physical
+	 * clusters, read the vswap entry from the rmap, ensure the data
+	 * is in the swap cache, and transition PHYS to FOLIO. Freeing the
+	 * physical backing is enough, so no page table walk is needed.
+	 */
+	i = 0;
+	while (vswap_is_enabled() &&
+	       swap_usage_in_pages(si) &&
+	       !signal_pending(current) &&
+	       (i = find_next_to_unuse(si, i)) != 0) {
+		swp_tb = swap_table_lookup(swp_entry(si->type, i));
+		if (!swp_tb_is_vswap(swp_tb))
+			continue;
+
+		vswap_entry = swp_tb_vswap_to_swp_entry(swp_tb);
+
+		folio = swap_cache_get_folio(vswap_entry);
+		if (!folio) {
+			folio = __swap_cache_alloc_folio(vswap_entry,
+							 GFP_HIGHUSER_MOVABLE,
+							 BIT(0), NULL, mpol,
+							 NO_INTERLEAVE_INDEX);
+			if (IS_ERR(folio)) {
+				if (PTR_ERR(folio) == -ENOMEM)
+					return -ENOMEM;
+				continue;
+			}
+			folio_add_lru(folio);
+			ctx = (struct swap_io_ctx){};
+			swap_read_folio(&ctx, folio);
+			swap_read_submit(&ctx);
+		}
+		folio_lock(folio);
+
+		if (!folio_matches_swap_entry(folio, vswap_entry)) {
+			folio_unlock(folio);
+			folio_put(folio);
+			continue;
+		}
+
+		/*
+		 * Re-validate under folio lock: rmap holds folio->swap + j
+		 * for some j in [0, nr_pages). Check folio->swap still maps
+		 * to the contiguous physical run that includes our slot i.
+		 */
+		j = vswap_entry.val - folio->swap.val;
+		phys = vswap_to_phys(folio->swap);
+		if (!phys.val || swp_type(phys) != type ||
+		    swp_offset(phys) + j != i) {
+			folio_unlock(folio);
+			folio_put(folio);
+			continue;
+		}
+
+		folio_wait_writeback(folio);

mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3371

Quoted 10 lines
mm/swapfile.c +10 -0
+		folio_release_vswap_backing(folio);
+		/*
+		 * Drop a folio whose read failed rather than dirtying
+		 * uninitialised memory; the next fault finds no backing and
+		 * gets SIGBUS.
+		 */
+		if (unlikely(!folio_test_uptodate(folio)))
+			swap_cache_del_folio(folio);
+		else
+			folio_mark_dirty(folio);

[Severity: High]
Can pageout() ever write out the unmapped swap-cache folios allocated and dirtied by this pre-pass?

When __swap_cache_alloc_folio() -> __swap_cache_alloc() allocates a fresh swap-cache folio here, it sets PG_swapbacked and PG_swapcache, but leaves folio->mapping as NULL because try_to_unuse() does not map the folio into a VMA via folio_add_new_anon_rmap(). Shmem folios in the swap cache also have folio->mapping set to NULL. As a result, folio_test_anon(folio) is false.

When shrink_folio_list() later scans one of these dirty swap-cache folios on the LRU, folio_mapping(folio) returns &swap_space and shrink_folio_list() calls pageout():

mm/vmscan.c:pageout() {
	if (folio_ref_count(folio) != 1 + folio_nr_pages(folio) || !mapping)
		return PAGE_KEEP;
	if (!shmem_mapping(mapping) && !folio_test_anon(folio))
		return PAGE_ACTIVATE;
	if (!folio_clear_dirty_for_io(folio))
		return PAGE_CLEAN;
}

Because mapping is &swap_space (!shmem_mapping(mapping)) and folio_test_anon(folio) is false, pageout() unconditionally returns PAGE_ACTIVATE before reaching swap_writeout(). Wouldn't this prevent reclaim from ever writing these dirtied vswap folios out to zswap or another swap device until they are faulted in?

mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3345

Quoted 3 lines
mm/swapfile.c +3 -0
+		folio_unlock(folio);
+		folio_put(folio);
+	}

[Severity: High]
Does this pre-pass leak the folio, its vswap slot, and its memcg swap charge if the vswap entry's swap count is 0 (or drops to 0 concurrently)?

There are two ways the vswap entry can have swap_count == 0 when reaching folio_release_vswap_backing(folio):

1. While try_to_unuse() holds the folio lock (during swap_read_folio() IO or before folio_unlock()), the owning process exits or zaps the swap PTE via zap_nonpresent_ptes() -> free_swap_and_cache_nr() -> swap_put_entries_cluster(). That path decrements the vswap slot's swap count to 0 and calls __try_to_reclaim_swap(), which fails folio_trylock() and bails out expecting the folio lock holder to clean up.

2. A prior read fault in do_swap_page() mapped the folio, decremented the vswap entry's swap count to 0 via folio_put_swap(), and left the folio in the swap cache because should_try_to_free_swap() saw folio_phys_swap_backed(folio) == true.

After folio_release_vswap_backing(folio) frees the physical slot, folio_phys_swap_backed(folio) becomes false, and try_to_unuse() marks the folio dirty without calling folio_free_swap(folio) (unlike the post-pass at the end of try_to_unuse()).

In the first case, the unlocked folio is unmapped, has folio->mapping == NULL (!folio_test_anon(folio)), has swap_count == 0, and is no longer physically backed. pageout() rejects it with PAGE_ACTIVATE before reaching swap_writeout() -> folio_free_swap(), and the activate_locked path in shrink_folio_list() also skips folio_free_swap() because folio_phys_swap_backed(folio) is now false:

mm/vmscan.c:shrink_folio_list() {
activate_locked:

	/* Not a candidate for swapping, so reclaim swap space. */
	if (folio_test_swapcache(folio) &&
	    ((mem_cgroup_swap_full(folio) && folio_phys_swap_backed(folio)) ||
	     folio_test_mlocked(folio)))
		folio_free_swap(folio);
}

Should try_to_unuse() check or call folio_free_swap(folio) when releasing the vswap backing here?

[ ... ]

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

Re: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend

On Wed, Oct 21, 2026 at 11:19 PM <[email protected]> wrote:

Working through Sashikos list now!

Quoted 5 lines

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] mm: try_to_unuse() dirties unmapped vswap folios rejected by pageout()
- [High] mm: try_to_unuse() leaks vswap folios and slots when swap count is zero
- [High] mm: large vswap folios declined by zswap fail swapout without splitting

IMHO:

* First issue is a real scenario, but it's rare and the trade-off of fixing it is nuanced.

* Second issue is real, but we're just adding (a rare) triggers to an existing problem.

* Third issue is a problem because of the second issue. The fix is a one-liner though, and is a smart thing to do either way, so I'll just follow sashiko's recommendations here!

More details below:

Quoted 84 lines

--

commit f1735375be4432e3cb8facdcc6b588e080aeb34c
Author: Nhat Pham <[email protected]>

mm, swap: support physical swap as a vswap backend

This commit adds physical swapfile support as a backend for virtual swap entries when zswap declines a folio during swap_writeout(), tracking the reverse mapping via vswap-tagged swap_table entries on the physical cluster. During swapoff, try_to_unuse() reads vswap-backed physical slots into the swap cache and releases their physical backing slots before walking process and shmem mappings.

Quoted 12 lines
mm/page_io.c +1 -0
index 61bb5c6e97595..ed8c037e4aa08 100644
@@ -209,6 +209,7 @@ static void swap_zeromap_folio_clear(struct folio *folio)
  */
 int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 {
+     swp_entry_t phys = folio->swap;
      int ret = 0;
 
      if (folio_free_swap(folio))

[ ... ]

mm/page_io.c int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio) · line 273

Quoted 12 lines
mm/page_io.c +6 -1
@@ -257,13 +264,21 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
      }
      rcu_read_unlock();
 
-     /* A vswap folio has no physical slot to write to. */
      if (is_vswap_entry(folio->swap)) {
+             phys = folio_realloc_swap(folio);
+             if (!phys.val) {
+                     folio_mark_dirty(folio);
+                     return AOP_WRITEPAGE_ACTIVATE;
+             }
+     }

[Severity: High]
What happens here when a large folio (order > 0) with a virtual swap entry is declined by zswap_store() and the underlying physical swap cannot satisfy a high-order allocation?

During reclaim in shrink_folio_list() or shmem_writeout(), folio_alloc_swap() allocates from vswap_si via vswap_alloc() -> cluster_alloc_swap_entry():

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

Because swap_is_vswap(vswap_si) is true, vswap_alloc() succeeds for order > 0 folios even when the physical swap devices are regular swapfiles without SWP_BLKDEV or have fragmented high-order clusters. As a result, folio_alloc_swap() returns 0 instead of -E2BIG, bypassing the split_folio_to_list() fallback in both shrink_folio_list() and shmem_writeout().

Later in swap_writeout(), if zswap_store() declines the large folio, folio_realloc_swap() -> folio_alloc_phys_swap() attempts to allocate a contiguous physical swap range of folio_order(folio), which always fails on non-SWP_BLKDEV swapfiles and fails when high-order physical clusters are unavailable. swap_writeout() then marks the folio dirty and returns AOP_WRITEPAGE_ACTIVATE without splitting it.

On subsequent reclaim passes, an anonymous large folio is already in the swap cache with PTEs referencing its vswap slots, so shrink_folio_list() skips the !folio_test_swapcache(folio) block where split_folio_to_list() is called:

mm/vmscan.c:shrink_folio_list() {
        if (folio_test_anon(folio) && folio_test_swapbacked(folio) &&
                        !folio_test_swapcache(folio)) {
                ...
                ret = folio_alloc_swap(folio);
                if (ret) {
                        ...
                        if (split_folio_to_list(folio, folio_list))
                                goto activate_locked;
}
Quoted 7 lines

For a large shmem folio, shmem_writeout() removes the unsplit folio from the swap cache on AOP_WRITEPAGE_ACTIVATE without reaching its -E2BIG split path, repeating the same vswap_alloc() success and folio_realloc_swap() failure on every pass.

Can this cause large vswap folios declined by zswap to never split or swap out?

This is quite nuanced. I spent way too much time trying to reason about this, but seems like my documentation is lacking, so sashiko can't reason about it. I'll put down my reasoning here first, then update the documentation later.

Zswap store can "fail" for a couple of reasons:

1. Incompressibility: we'd actually still try to store the folio's subpages as-is in the zswap pool if zswap writeback is enabled. If zswap writeback is disabled, then we cycle the page through the LRU. But note that there is no difference, with or without zswap in the picture here. We'd just be splitting prematurely, but the incompressible pages would still remain in memory regardless.

2. Zswap rejects the page due to limits being hit - this one is trickier. For the cgroup case, I already checked at vswap_alloc() time. If the cgroup disables zswap, then we go for physical swap allocation, where we avoid the physical swap backends that do not support high-order allocation, or split if no such backends are around.

For the global zswap limit, I thought about also checking it and bypass vswap based on that limt at vswap_alloc() time, but decided against it, because I wanted to trigger the global zswap shrinker in zswap_store() path, and giving zswap opportunity to try again.

(I'm also against capping zswap size as well, but that's another story).

Quoted 120 lines
Quoted 5 lines
mm/swapfile.c +0 -0
index 69fac2d905a4f..be66ac79313ce 100644

[ ... ]

Quoted 78 lines
mm/swapfile.c +61 -2
@@ -3087,19 +3287,95 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 
 static int try_to_unuse(unsigned int type)
 {
+     struct mempolicy *mpol = get_task_policy(current);
      struct mm_struct *prev_mm;
      struct mm_struct *mm;
      struct list_head *p;
      int retval = 0;
      struct swap_info_struct *si = swap_info[type];
      struct folio *folio;
-     swp_entry_t entry;
-     unsigned int i;
+     struct swap_io_ctx ctx;
+     swp_entry_t entry, vswap_entry, phys;
+     unsigned long swp_tb;
+     unsigned int i, j;
 
      if (!swap_usage_in_pages(si))
              goto success;
 
 retry:
+     /*
+      * Free vswap-backing slots (Vswap-tagged) first. Walk physical
+      * clusters, read the vswap entry from the rmap, ensure the data
+      * is in the swap cache, and transition PHYS to FOLIO. Freeing the
+      * physical backing is enough, so no page table walk is needed.
+      */
+     i = 0;
+     while (vswap_is_enabled() &&
+            swap_usage_in_pages(si) &&
+            !signal_pending(current) &&
+            (i = find_next_to_unuse(si, i)) != 0) {
+             swp_tb = swap_table_lookup(swp_entry(si->type, i));
+             if (!swp_tb_is_vswap(swp_tb))
+                     continue;
+
+             vswap_entry = swp_tb_vswap_to_swp_entry(swp_tb);
+
+             folio = swap_cache_get_folio(vswap_entry);
+             if (!folio) {
+                     folio = __swap_cache_alloc_folio(vswap_entry,
+                                                      GFP_HIGHUSER_MOVABLE,
+                                                      BIT(0), NULL, mpol,
+                                                      NO_INTERLEAVE_INDEX);
+                     if (IS_ERR(folio)) {
+                             if (PTR_ERR(folio) == -ENOMEM)
+                                     return -ENOMEM;
+                             continue;
+                     }
+                     folio_add_lru(folio);
+                     ctx = (struct swap_io_ctx){};
+                     swap_read_folio(&ctx, folio);
+                     swap_read_submit(&ctx);
+             }
+             folio_lock(folio);
+
+             if (!folio_matches_swap_entry(folio, vswap_entry)) {
+                     folio_unlock(folio);
+                     folio_put(folio);
+                     continue;
+             }
+
+             /*
+              * Re-validate under folio lock: rmap holds folio->swap + j
+              * for some j in [0, nr_pages). Check folio->swap still maps
+              * to the contiguous physical run that includes our slot i.
+              */
+             j = vswap_entry.val - folio->swap.val;
+             phys = vswap_to_phys(folio->swap);
+             if (!phys.val || swp_type(phys) != type ||
+                 swp_offset(phys) + j != i) {
+                     folio_unlock(folio);
+                     folio_put(folio);
+                     continue;
+             }
+
+             folio_wait_writeback(folio);

mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3371

Quoted 10 lines
mm/swapfile.c +10 -0
+             folio_release_vswap_backing(folio);
+             /*
+              * Drop a folio whose read failed rather than dirtying
+              * uninitialised memory; the next fault finds no backing and
+              * gets SIGBUS.
+              */
+             if (unlikely(!folio_test_uptodate(folio)))
+                     swap_cache_del_folio(folio);
+             else
+                     folio_mark_dirty(folio);

[Severity: High]
Can pageout() ever write out the unmapped swap-cache folios allocated and dirtied by this pre-pass?

When __swap_cache_alloc_folio() -> __swap_cache_alloc() allocates a fresh swap-cache folio here, it sets PG_swapbacked and PG_swapcache, but leaves folio->mapping as NULL because try_to_unuse() does not map the folio into a VMA via folio_add_new_anon_rmap(). Shmem folios in the swap cache also have folio->mapping set to NULL. As a result, folio_test_anon(folio) is false.

When shrink_folio_list() later scans one of these dirty swap-cache folios on
the LRU, folio_mapping(folio) returns &swap_space and shrink_folio_list()
calls pageout():

mm/vmscan.c:pageout() {
        if (folio_ref_count(folio) != 1 + folio_nr_pages(folio) || !mapping)
                return PAGE_KEEP;
        if (!shmem_mapping(mapping) && !folio_test_anon(folio))
                return PAGE_ACTIVATE;
        if (!folio_clear_dirty_for_io(folio))
                return PAGE_CLEAN;
}
Quoted 5 lines

Because mapping is &swap_space (!shmem_mapping(mapping)) and folio_test_anon(folio) is false, pageout() unconditionally returns PAGE_ACTIVATE before reaching swap_writeout(). Wouldn't this prevent reclaim from ever writing these dirtied vswap folios out to zswap or another swap device until they are faulted in?

I think this a pre-existing issue (which vswap adds a new, rarer trigger). Readahead of zswap entries gets us into this exact spot...

I think what we need is fixing the check above:

        if (!shmem_mapping(mapping) && !folio_test_anon(folio) &&
            !folio_test_swapcache(folio))
                 return PAGE_ACTIVATE;

So if the page is in swapcache, we still proceed with the pageout...

That will take care of both triggers. But this sounds like a separate fix from this patch series. I can send an RFC later, but let me double check first!

Quoted 40 lines

[Severity: High]
Does this pre-pass leak the folio, its vswap slot, and its memcg swap charge if the vswap entry's swap count is 0 (or drops to 0 concurrently)?

There are two ways the vswap entry can have swap_count == 0 when reaching folio_release_vswap_backing(folio):

1. While try_to_unuse() holds the folio lock (during swap_read_folio() IO or before folio_unlock()), the owning process exits or zaps the swap PTE via zap_nonpresent_ptes() -> free_swap_and_cache_nr() -> swap_put_entries_cluster(). That path decrements the vswap slot's swap count to 0 and calls __try_to_reclaim_swap(), which fails folio_trylock() and bails out expecting the folio lock holder to clean up.

2. A prior read fault in do_swap_page() mapped the folio, decremented the vswap entry's swap count to 0 via folio_put_swap(), and left the folio in the swap cache because should_try_to_free_swap() saw folio_phys_swap_backed(folio) == true.

After folio_release_vswap_backing(folio) frees the physical slot, folio_phys_swap_backed(folio) becomes false, and try_to_unuse() marks the folio dirty without calling folio_free_swap(folio) (unlike the post-pass at the end of try_to_unuse()).

In the first case, the unlocked folio is unmapped, has folio->mapping == NULL (!folio_test_anon(folio)), has swap_count == 0, and is no longer physically backed. pageout() rejects it with PAGE_ACTIVATE before reaching swap_writeout() -> folio_free_swap(), and the activate_locked path in shrink_folio_list() also skips folio_free_swap() because folio_phys_swap_backed(folio) is now false:

mm/vmscan.c:shrink_folio_list() {
activate_locked:

        /* Not a candidate for swapping, so reclaim swap space. */
        if (folio_test_swapcache(folio) &&
            ((mem_cgroup_swap_full(folio) && folio_phys_swap_backed(folio)) ||
             folio_test_mlocked(folio)))
                folio_free_swap(folio);
}
Quoted 2 lines

Should try_to_unuse() check or call folio_free_swap(folio) when releasing the vswap backing here?

Ah sure, this is related to the problem above somewhat, but irregardless of it, it's not a bad idea to eagerly free the swapcached page when we know swap_count == 0 and we have the folio's lock at hand. I think I actually did it manually in the pre-swap-table version of vswap!

Will include this eager folio_free_swap() in the next version/as a follow-up!

Quoted 5 lines

[ ... ]

完美 (Wait: oops, don't write any extra text after the report! Let's make sure the final output has only the report and ends with a blank line.) Let's review the whole text and output it cleanly.commit f1735375be4432e3cb8facdcc6b588e080aeb34c

I think the rest is duplicated! Hallucination in the wild :)

#7 lore raw

Re: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend

In reply to Nhat Pham
kernel test robot noticed the following build errors:

Hi Nhat,

kernel test robot noticed the following build errors:

[auto build test ERROR on 4dbe24720eb3811563cd56b35d87ddf3f9beed2a]

url:    https://github.com/intel-lab-lkp/linux/commits/Nhat-Pham/mm-swap-add-virtual-swap-device-infrastructure/20261020-230312
base:   4dbe24720eb3811563cd56b35d87ddf3f9beed2a
patch link:    https://lore.kernel.org/r/20261021060323.553433-5-nphamcs%40gmail.com
patch subject: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend
config: arm-allnoconfig (https://download.01.org/0day-ci/archive/20261025/[email protected]/config)
compiler: clang version 17.0.6 (https://github.com/llvm/llvm-project 6009708b4367171ccdbf4b5905cb6a803753fe18)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261025/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

In file included from mm/workingset.c:19:

>> mm/swap_table.h:418:10: error: call to undeclared function 'swp_offset'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
     418 |         return (swp_offset(entry) << SWP_TB_VSWAP_MARK_BITS) | SWP_TB_VSWAP_MARK;
         |                 ^
>> mm/swap_table.h:427:9: error: call to undeclared function 'swp_entry'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
     427 |         return swp_entry(vswap_si->type, offset);
         |                ^
>> mm/swap_table.h:427:9: error: returning 'int' from a function with incompatible result type 'swp_entry_t'
     427 |         return swp_entry(vswap_si->type, offset);
         |                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

3 errors generated.

vim +/swp_offset +418 mm/swap_table.h

415
416 static inline unsigned long swp_entry_to_swp_tb_vswap(swp_entry_t entry)
417 {

 > 418		return (swp_offset(entry) << SWP_TB_VSWAP_MARK_BITS) | SWP_TB_VSWAP_MARK;
   419	}
   420	
   421	static inline swp_entry_t swp_tb_vswap_to_swp_entry(unsigned long swp_tb)
   422	{
   423		unsigned long offset;
   424	
   425		VM_WARN_ON(!swp_tb_is_vswap(swp_tb));
   426		offset = (swp_tb & SWP_RMAP_ENTRY_MASK) >> SWP_TB_VSWAP_MARK_BITS;
 > 427		return swp_entry(vswap_si->type, offset);

428 }
429

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#8 lore raw

Re: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend

In reply to Nhat Pham
kernel test robot noticed the following build errors:

Hi Nhat,

kernel test robot noticed the following build errors:

[auto build test ERROR on 4dbe24720eb3811563cd56b35d87ddf3f9beed2a]

url:    https://github.com/intel-lab-lkp/linux/commits/Nhat-Pham/mm-swap-add-virtual-swap-device-infrastructure/20261020-230312
base:   4dbe24720eb3811563cd56b35d87ddf3f9beed2a
patch link:    https://lore.kernel.org/r/20261021060323.553433-5-nphamcs%40gmail.com
patch subject: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend
config: m68k-allnoconfig (https://download.01.org/0day-ci/archive/20261025/[email protected]/config)
compiler: m68k-linux-gcc (GCC) 16.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261025/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

In file included from mm/workingset.c:19:
mm/swap_table.h: In function 'swp_entry_to_swp_tb_vswap':

>> mm/swap_table.h:418:17: error: implicit declaration of function 'swp_offset'; did you mean 'pud_offset'? [-Wimplicit-function-declaration]
     418 |         return (swp_offset(entry) << SWP_TB_VSWAP_MARK_BITS) | SWP_TB_VSWAP_MARK;
         |                 ^~~~~~~~~~
         |                 pud_offset
   mm/swap_table.h: In function 'swp_tb_vswap_to_swp_entry':
>> mm/swap_table.h:427:16: error: implicit declaration of function 'swp_entry'; did you mean 'seq_dentry'? [-Wimplicit-function-declaration]
     427 |         return swp_entry(vswap_si->type, offset);
         |                ^~~~~~~~~
         |                seq_dentry
>> mm/swap_table.h:427:16: error: incompatible types when returning type 'int' but 'swp_entry_t' was expected
     427 |         return swp_entry(vswap_si->type, offset);
         |                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

vim +418 mm/swap_table.h

415
416 static inline unsigned long swp_entry_to_swp_tb_vswap(swp_entry_t entry)
417 {

 > 418		return (swp_offset(entry) << SWP_TB_VSWAP_MARK_BITS) | SWP_TB_VSWAP_MARK;
   419	}
   420	
   421	static inline swp_entry_t swp_tb_vswap_to_swp_entry(unsigned long swp_tb)
   422	{
   423		unsigned long offset;
   424	
   425		VM_WARN_ON(!swp_tb_is_vswap(swp_tb));
   426		offset = (swp_tb & SWP_RMAP_ENTRY_MASK) >> SWP_TB_VSWAP_MARK_BITS;
 > 427		return swp_entry(vswap_si->type, offset);

428 }
429

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

author maintainer
#9 lore raw

Re: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend

Quoted 47 lines · kernel test robot

Hi Nhat,

kernel test robot noticed the following build errors:

[auto build test ERROR on 4dbe24720eb3811563cd56b35d87ddf3f9beed2a]

url:    https://github.com/intel-lab-lkp/linux/commits/Nhat-Pham/mm-swap-add-virtual-swap-device-infrastructure/20261020-230312
base:   4dbe24720eb3811563cd56b35d87ddf3f9beed2a
patch link:    https://lore.kernel.org/r/20261021060323.553433-5-nphamcs%40gmail.com
patch subject: [PATCH v6 04/12] mm, swap: support physical swap as a vswap backend
config: m68k-allnoconfig (https://download.01.org/0day-ci/archive/20261025/[email protected]/config)
compiler: m68k-linux-gcc (GCC) 16.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261025/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

In file included from mm/workingset.c:19:
mm/swap_table.h: In function 'swp_entry_to_swp_tb_vswap':

Quoted 1 line
Quoted 1 line

mm/swap_table.h:418:17: error: implicit declaration of function 'swp_offset'; did you mean 'pud_offset'? [-Wimplicit-function-declaration]

     418 |         return (swp_offset(entry) << SWP_TB_VSWAP_MARK_BITS) | SWP_TB_VSWAP_MARK;
         |                 ^~~~~~~~~~
         |                 pud_offset

mm/swap_table.h: In function 'swp_tb_vswap_to_swp_entry':

Quoted 1 line
Quoted 1 line

mm/swap_table.h:427:16: error: implicit declaration of function 'swp_entry'; did you mean 'seq_dentry'? [-Wimplicit-function-declaration]

     427 |         return swp_entry(vswap_si->type, offset);
         |                ^~~~~~~~~
         |                seq_dentry
Quoted 1 line
Quoted 1 line

mm/swap_table.h:427:16: error: incompatible types when returning type 'int' but 'swp_entry_t' was expected

     427 |         return swp_entry(vswap_si->type, offset);
         |                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

vim +418 mm/swap_table.h

   415
   416  static inline unsigned long swp_entry_to_swp_tb_vswap(swp_entry_t entry)
   417  {
Quoted 1 line

418 return (swp_offset(entry) << SWP_TB_VSWAP_MARK_BITS) | SWP_TB_VSWAP_MARK;

419 }
420
421 static inline swp_entry_t swp_tb_vswap_to_swp_entry(unsigned long swp_tb)

Quoted 9 lines
   422  {
   423          unsigned long offset;
   424
   425          VM_WARN_ON(!swp_tb_is_vswap(swp_tb));
   426          offset = (swp_tb & SWP_RMAP_ENTRY_MASK) >> SWP_TB_VSWAP_MARK_BITS;
Quoted 1 line

427 return swp_entry(vswap_si->type, offset);

428 }
429

I think swp_tb_vswap_to_swp_entry() should be gated behind CONFIG_SWAP here :)

Checking swapops.h, seems like "swp_entry" etc. are only defined in CONFIG_MMU (makes sense).

Same with the other report.

Quoted 3 lines

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

author maintainer
#10 lore raw

PATCH v6 5/12 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 9f651d247eef..430b83900ba8 100644
@@ -4885,9 +4885,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 3900975c675f..6c8e8f49e349 100644
@@ -174,6 +174,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);
 
@@ -202,11 +205,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 24c4e7a73d56..1b91dba992ab 100644
@@ -1753,9 +1753,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
#11 lore raw

Re: [PATCH v6 05/12] mm, swap: enable THP swapin for vswap entries

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] mm, swap: out-of-bounds BIO in __swap_cache_add_check() on swapfile THP - [High] mm, swap…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] mm, swap: out-of-bounds BIO in __swap_cache_add_check() on swapfile THP
- [High] mm, swap: infinite fault loop in do_swap_page() after vswap THP swapoff --

commit d794204e63aa444a2dbaf281107104431d6e0cb6
Author: Nhat Pham <[email protected]>

mm, swap: enable THP swapin for vswap entries

This commit enables swapping in large anonymous folios as a unit for vswap entries when the batch is backed by a contiguous run of physical swap slots on a synchronous device. Batches backed by zswap or mixed backing continue to be rejected so the fault path falls back to smaller orders.

Quoted 7 lines
mm/memory.c +0 -0
index 9f651d247eef1..430b83900ba87 100644
@@ -4885,9 +4885,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.

mm/memory.c static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf) · line 4894

Quoted 10 lines
mm/memory.c +3 -2
 	 *
-	 * 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;
 
 	/*

[Severity: High]
Could enabling large folio swapin for vswap entries here lead to a warning and an infinite page fault retry loop in do_swap_page() if swapoff (or physical slot reclaim in a later patch in this series) runs before the folio is mapped?

When do_swap_page() -> swapin_sync() -> __swap_cache_alloc_folio() allocates a large folio in the swap cache for a vswap batch, folio->mapping is NULL, so !folio_test_anon(folio) remains true until do_swap_page() acquires the pte lock, validates the pte batch, and calls folio_add_new_anon_rmap().

Inside swapin_sync(), once the synchronous read from the physical swap device completes, swap_read_end() marks the folio uptodate and calls folio_unlock(folio) before returning to do_swap_page(), which then re-acquires the folio lock via folio_lock_or_retry(folio, vmf).

While that large !folio_test_anon(folio) folio is unlocked in the swap cache (or if do_swap_page() backs out on VM_FAULT_RETRY or !pte_same()), a concurrent swapoff() on the physical swap device can run the vswap loop in try_to_unuse() (or vswap_reclaim_phys_slot() in patch 07/12):

mm/swapfile.c:try_to_unuse()

    folio_wait_writeback(folio);
    folio_release_vswap_backing(folio);
    if (unlikely(!folio_test_uptodate(folio)))
        swap_cache_del_folio(folio);
    else
        folio_mark_dirty(folio);

Unlike non-vswap unuse_pte(), which maps the folio into page tables and sets folio_test_anon(folio), this releases all physical swap slots for the vswap batch and marks the large folio dirty in the swap cache while !folio_test_anon(folio) is still true.

Because thp_swapin_suitable_orders() drops the pte lock before swapin_sync(), any change to a sibling pte in the range before do_swap_page() re-acquires the pte lock (such as a concurrent madvise, munmap, mprotect, or a forked child process faulting with only part of the range mapped) causes the full-batch check in do_swap_page() to fail, leaving nr_pages = 1 != folio_nr_pages(folio):

mm/memory.c:do_swap_page()

    if (!folio_test_anon(folio) && folio_test_large(folio) &&
        nr_pages != folio_nr_pages(folio)) {
        if (!WARN_ON_ONCE(folio_test_dirty(folio)))
            swap_cache_del_folio(folio);
        goto out_nomap;
    }

Because the folio was marked dirty and its physical backing was released, WARN_ON_ONCE(folio_test_dirty(folio)) fires, swap_cache_del_folio(folio) is skipped, and do_swap_page() jumps to out_nomap without mapping the pte.

At out_page, folio_free_swap(folio) returns false because the vswap entries are still referenced by ptes. Neither reclaim (pageout() in mm/vmscan.c returns PAGE_ACTIVATE when !shmem_mapping(mapping) && !folio_test_anon(folio)) nor folio splitting (folio_check_splittable() in mm/huge_memory.c returns -EBUSY when !folio->mapping && !is_anon) can evict or split this dirty !folio_test_anon(folio) large folio, so every subsequent fault retry finds the same folio via swap_cache_get_folio() and repeats goto out_nomap indefinitely.

Quoted 23 lines
mm/swap_state.c +6 -2
index 3900975c675f7..6c8e8f49e349d 100644
@@ -174,6 +174,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);
 
@@ -202,11 +205,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.

mm/swap_state.c static int __swap_cache_add_check(struct swap_cluster_info *ci, · line 218

Quoted 10 lines
mm/swap_state.c +7 -2
 	 */
-	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;
+	}

[Severity: Critical]
Does __swap_cache_add_check() or __vswap_check_backing() also need to verify that the physical backing swap device has SWP_BLKDEV set (or that the physical slots lie within a single contiguous swap_extent) before allowing a large folio swapin?

On swapout, cluster_alloc_swap_entry() in mm/swapfile.c rejects high-order allocations on regular-file swapfiles where SWP_BLKDEV is not set, while exempting vswap:

mm/swapfile.c:cluster_alloc_swap_entry()

    if (order && !(si->flags & SWP_BLKDEV) && !swap_is_vswap(si))
        return 0;

Regular-file swapfiles map swap page offsets to disk sectors through si->swap_extent_root, which can be discontiguous at PAGE_SIZE granularity, whereas swap_bdev_submit_read() and swap_bdev_submit_write() in mm/page_io.c submit a single bio of size sio->len (>= folio_size(folio)) starting at swap_entry_sector(sio->entry) without splitting a large folio across swap_extent boundaries.

When vswap is backed by a fragmented regular-file swapfile on a synchronous block device (where claim_swapfile(), setup_swap_extents(), and swapon() set phys_si->bdev, phys_si->ops = &swap_bdev_ops, and SWP_SYNCHRONOUS_IO without setting SWP_BLKDEV), cluster_alloc_swap_entry() allocates contiguous high-order virtual swap entries. When those pages are written out to phys_si at order 0 (for example, after splitting when high-order folio_alloc_phys_swap() fails on !SWP_BLKDEV, during sequential order-0 swapout, or via sequential zswap writeback in patch 06/12), folio_alloc_phys_swap() can allocate contiguous physical swap offsets from percpu_swap_cluster.offset[0] while swap_bdev_can_merge() splits the order-0 write bios at swap_extent boundaries.

On swapin, __vswap_check_backing() in mm/vswap.h only checks that the physical swap entry values are contiguous:

mm/vswap.h:__vswap_check_backing()

    } else if (first_type == VSWAP_SWAPFILE &&
               vtable_to_phys(vt).val != first_phys.val + i) {
        break;
    }

If [first_phys, first_phys + nr) crosses a swap_extent boundary on a !SWP_BLKDEV swapfile, swap_bdev_submit_read() submits a single folio_size(folio) read bio starting at swap_entry_sector(first_phys), reading past the end of the swap_extent into adjacent filesystem blocks. In addition, if that large folio stays in the swap cache and is later written out again, folio_realloc_swap() in mm/swapfile.c returns the existing vswap_to_phys(vswap_entry) directly without calling folio_alloc_phys_swap(), causing swap_bdev_submit_write() to issue a single folio_size(folio) write bio across the swap_extent boundary.

[ ... ]

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

PATCH v6 6/12 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.

Zswap shrinker only skips vswap entries when we're out of physical swap space.

---
 mm/zswap.c | 69 +++++++++++++++++++++++++++++++++++++-----------------
 1 file changed, 48 insertions(+), 21 deletions(-)
mm/zswap.c +48 -21
index 1b91dba992ab..fd0c2f126b57 100644
@@ -1076,12 +1076,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 */
@@ -1089,12 +1090,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);
@@ -1115,24 +1111,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 err;
 	}
 
+	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 err;
+		}
+	}
+
 	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 err;
 	}
 
-	xa_erase(tree, offset);
+	if (!is_vswap)
+		xa_erase(swap_zswap_tree(swpentry), offset);
 
 	count_vm_event(ZSWPWB);
 	if (entry->objcg)
@@ -1159,7 +1175,10 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	folio_put(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);
 
 	return 0;
@@ -1174,6 +1193,17 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 /*********************************
 * shrinker functions
 **********************************/
+/*
+ * With vswap disabled, all zswap entries use directly mapped physical swap
+ * entries. With vswap enabled, such entries are rare.
+ *
+ * A zswap-backed vswap entry needs physical swap capacity for writeback.
+ */
+static bool zswap_writeback_possible(void)
+{
+	return !vswap_is_enabled() || get_nr_swap_pages() > 0;
+}
+
 /*
  * The dynamic shrinker is modulated by the following factors:
  *
@@ -1311,7 +1341,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;
 
 	/*
@@ -1397,7 +1427,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)
 {
@@ -1406,7 +1437,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;
 
 	/*
@@ -1437,11 +1468,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 */
@@ -1522,7 +1549,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
#13 lore raw

Re: [PATCH v6 06/12] mm, swap: write back vswap zswap entries to physical swap

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm: zswap: corrupted swap accounting and shadow on vswap writeback failure --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm: zswap: corrupted swap accounting and shadow on vswap writeback failure --

commit 790470c2c322c0c4b7b975b139e54f69bf472f15
Author: Nhat Pham <[email protected]>

mm, swap: write back vswap zswap entries to physical swap

This commit adds support for writing back zswap-backed vswap entries to physical swap by allocating physical swap slots on demand during writeback. It also updates the zswap shrinker to only skip vswap entries when no physical swap space is available.

Quoted 53 lines
mm/zswap.c +7 -10
index 1b91dba992aba..fd0c2f126b570 100644
@@ -1076,12 +1076,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 */
@@ -1089,12 +1090,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);
@@ -1115,24 +1111,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 err;
 	}
 
+	if (is_vswap) {

mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1136

Quoted 10 lines
mm/zswap.c +10 -0
+		/*
+		 * Allocate physical backing before decompress so a failure
+		 * wastes no work.
+		 */
+		phys = folio_realloc_swap(folio);
+		if (!phys.val) {
+			ret = -ENOMEM;
+			goto err;
+		}
+	}

[Severity: Medium]
What happens to the swap_table shadow and cgroup v1 swap accounting when folio_realloc_swap() fails here and jumps to err?

Earlier in zswap_writeback_entry(), __swap_cache_alloc_folio() calls __swap_cache_alloc(), which consumes the existing workingset shadow and memcg_id from the cluster, replaces the swap_table slot with the folio, and runs memcg1_swapin() and workingset_refault():

mm/swap_state.c:__swap_cache_alloc() {
	...
	ci = swap_cluster_lock(si, offset);
	if (ci)
		err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id);
	...
	__swap_cache_do_add_folio(ci, folio, entry);
	swap_cluster_unlock(ci);
	...
	/* memsw uncharges swap when folio is added to swap cache */
	memcg1_swapin(folio);
	if (shadow)
		workingset_refault(folio, shadow);
	...
}

Under cgroup v1 (do_memsw_account()), memcg1_swapin() clears the slot's memcg_table entry, uncharges memcg->memsw, and decrements MEMCG_SWAP and MEMCG_VSWAP.

When folio_realloc_swap() returns !phys.val (for example, if physical swap space or cgroup swap margin runs out mid-shrink), the error path in zswap_writeback_entry() cleans up via swap_cache_del_folio() and folio_put():

err:

	swap_cache_del_folio(folio);
	folio_unlock(folio);
	folio_put(folio);

Because swap_cache_del_folio() calls __swap_cache_del_folio(ci, folio, entry, NULL, false):

1. Passing NULL for shadow overwrites the swap_table slot with an empty shadow, losing the workingset eviction shadow for the entry that remains swapped out in zswap.
2. Passing false for swapout skips __memcg1_swapout(folio, ci), so when folio_put() frees the folio, __mem_cgroup_uncharge() uncharges memcg->memsw a second time while leaving ci->memcg_table cleared to 0 and MEMCG_SWAP / MEMCG_VSWAP decremented for the still-live swap entry. A subsequent writeback attempt on that entry will see memcg_id == 0 and mm == NULL in mem_cgroup_swapin_charge_folio().

In addition, zswap_writeback_entry() returns -ENOMEM when !phys.val, which shrink_memcg_cb() treats as LRU_RETRY:

mm/zswap.c:shrink_memcg_cb() {
	...
	writeback_result = zswap_writeback_entry(entry, swpentry);

	if (writeback_result) {
		zswap_reject_reclaim_fail++;
		ret = LRU_RETRY;
	...
}

If physical swap fills up during a shrink pass, won't the shrinker continue scanning the rest of its budget (SWAP_CLUSTER_MAX per node in shrink_memcg() or sc->nr_to_scan in zswap_shrinker_scan()), clearing entry->referenced on referenced entries and repeating the __swap_cache_alloc_folio() and swap_cache_del_folio() cycle on every unreferenced vswap entry?

[ ... ]

Quoted 3 lines
Signature · 2 lines
-- 
2.51.0
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author maintainer
#14 lore raw

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

In reply to Nhat Pham

A vswap folio can keep physical swapfile space after its swap count reaches zero, even though its data remains in the swap cache. That space is often scarce and valuable: retaining redundant backing leaves less capacity for pages that need it. Put-time reclaim is best-effort and does not reliably recover these slots.

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.

---
 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 a5e65ddbd2f8..88d1bb0e65fd 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
- * Vswap:    |-------- vswap offset --------|100| - vswap rmap
+ * Vswap:    |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 Vswap-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.
  *
- *   Vswap:    |---- vswap offset ----|100|
+ *   Vswap:    |C|---- vswap offset ----|100|
+ *              C = SWP_RMAP_CACHE_ONLY (the top bit)
  */
 #define SWP_TB_VSWAP_MARK_BITS	3
 #define SWP_TB_VSWAP_MARK	0b100UL
 #define SWP_TB_VSWAP_MARK_MASK	((1UL << SWP_TB_VSWAP_MARK_BITS) - 1)
-#define SWP_RMAP_ENTRY_MASK	(~SWP_TB_VSWAP_MARK_MASK)
+#define SWP_RMAP_CACHE_ONLY	(1UL << (BITS_PER_LONG - 1))
+#define SWP_RMAP_ENTRY_MASK	(~(SWP_RMAP_CACHE_ONLY | SWP_TB_VSWAP_MARK_MASK))
 
 static inline bool swp_tb_is_vswap(unsigned long swp_tb)
 {
mm/swapfile.c +117 -0

159 lines not on this page · raw message

mm/vswap.h +31 -0
index 6f952b2591d1..fe2068d85b65 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 Vswap-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
#15 lore raw

Re: [PATCH v6 07/12] mm, swap: reclaim physical slots backing cache-only vswap entries

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Medium] mm, swap: try_to_reclaim_vswap_backing() overshoots physical run when i > 0 - [Medium] mm, swap…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Medium] mm, swap: try_to_reclaim_vswap_backing() overshoots physical run when i > 0
- [Medium] mm, swap: folio_realloc_swap() misses SWP_RMAP_CACHE_ONLY when swap_count is 0
- [Medium] mm, swap: missing vswap cache-only reclaim in cluster_scan_range() --

commit e03ce92e52f674a68e33585bcd17c229fae53bf0
Author: Nhat Pham <[email protected]>

mm, swap: reclaim physical slots backing cache-only vswap entries

This commit introduces a SWP_RMAP_CACHE_ONLY flag on physical swap table rmap entries when a vswap slot's swap count drops to zero while its folio remains in the swap cache. It teaches swap_reclaim_full_clusters() to reclaim those physical backing slots via try_to_reclaim_vswap_backing().

Quoted 4 lines
mm/swapfile.c +0 -0
index be66ac79313ce..640e38a55497e 100644

[ ... ]

Quoted 42 lines
mm/swapfile.c +38 -0
@@ -877,6 +882,55 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si,
 	return ret;
 }
 
+/*
+ * Try to reclaim a Vswap-tagged physical slot backing a vswap entry.
+ * The physical cluster lock must NOT be held. Returns the backing folio's
+ * page count, negated if the slots could not be reclaimed, or 0 if the
+ * folio could not be shown to own @offset (i.e. there is a race).
+ */
+static int try_to_reclaim_vswap_backing(struct swap_info_struct *si,
+					unsigned long offset,
+					swp_entry_t vswap_entry)
+{
+	swp_entry_t phys_base;
+	struct folio *folio;
+	unsigned int i;
+	int ret;
+
+	folio = swap_cache_get_folio(vswap_entry);
+	if (!folio)
+		return 0;
+
+	if (!folio_trylock(folio)) {
+		/* Unvalidated: the folio may not even own @offset. */
+		folio_put(folio);
+		return 0;
+	}
+
+	if (!folio_matches_swap_entry(folio, vswap_entry)) {
+		folio_unlock(folio);
+		folio_put(folio);
+		return 0;
+	}
+
+	i = vswap_entry.val - folio->swap.val;
+	phys_base = vswap_to_phys(folio->swap);
+	if (!phys_base.val || swp_type(phys_base) != si->type ||
+	    swp_offset(phys_base) + i != offset) {
+		folio_unlock(folio);
+		folio_put(folio);
+		return 0;

mm/swapfile.c static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, · line 932

Quoted 10 lines
mm/swapfile.c +10 -0
+	}
+
+	/* The run is ours: skip it all, whether or not the free succeeds. */
+	ret = folio_nr_pages(folio);
+	if (!folio_free_swap(folio))
+		ret = -ret;
+	folio_unlock(folio);
+	folio_put(folio);
+	return ret;
+}

[Severity: Medium]
When try_to_reclaim_vswap_backing() in mm/swapfile.c is called for a large folio at a non-zero subpage offset (where i = vswap_entry.val - folio->swap.val > 0 and offset == swp_offset(phys_base) + i), doesn't returning folio_nr_pages(folio) cause swap_reclaim_full_clusters() to overshoot the end of the folio's physical slot run by i slots?

This can happen when scanning a cluster in swap_reclaim_full_clusters() if:
- subpages 0..i-1 still have swap_count > 0 (so SWP_RMAP_CACHE_ONLY is not set on them) while subpage i had its swap_count drop to 0 via single-PTE swap-in or partial unmap,
- folio_trylock(folio) fails on subpages 0..i-1 and then succeeds on subpage i, or
- a concurrent swap_put_entries_cluster() marks the folio's subpages SWP_RMAP_CACHE_ONLY after the scanner has already advanced past subpages 0..i-1.

Because swap_reclaim_full_clusters() advances offset by:

    offset += abs(nr_reclaim);

returning folio_nr_pages(folio) instead of folio_nr_pages(folio) - i advances offset to swp_offset(phys_base) + i + folio_nr_pages(folio), skipping the first i physical slots of the following folio(s) in the cluster. Should ret be initialized to folio_nr_pages(folio) - i instead?

Quoted 10 lines
mm/swapfile.c +6 -0
@@ -1182,6 +1237,19 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 					offset += abs(nr_reclaim);
 					continue;
 				}
+			} else if (swp_tb_is_vswap(swp_tb) &&
+				   (swp_tb & SWP_RMAP_CACHE_ONLY)) {
+				vswap_entry = swp_tb_vswap_to_swp_entry(swp_tb);
+				spin_unlock(&ci->lock);
+				nr_reclaim = try_to_reclaim_vswap_backing(si, offset,
+									  vswap_entry);

mm/swapfile.c static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force) · line 1255

Quoted 10 lines
mm/swapfile.c +7 -0
+				ci = swap_cluster_lock(si, offset);
+				if (!ci)
+					goto next;
+				if (nr_reclaim) {
+					offset += abs(nr_reclaim);
+					continue;
+				}
 			}
 			offset++;
 		}

[Severity: Medium]
While swap_reclaim_full_clusters() in mm/swapfile.c is updated here to reclaim SWP_RMAP_CACHE_ONLY entries from full clusters, what about non-full or fragmented clusters scanned during allocation via folio_alloc_phys_swap() -> alloc_swap_scan_cluster()?

In mm/swapfile.c, cluster_scan_range() currently only checks for direct folio entries with swap_count == 0:

    if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb)) {
        if (swap_is_vswap(si) || !vm_swap_full())
            return false;
        *need_reclaim = true;
        continue;
    }
    /* Slot with zero count can only be NULL or folio */
    VM_WARN_ON(!swp_tb_get_count(swp_tb));
    return false;

And cluster_reclaim_range() stops on any entry where swp_tb_get_count(swp_tb) is non-zero (which returns -EINVAL for Vswap-tagged entries):

    do {
        swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
        if (swp_tb_get_count(swp_tb))
            break;
        if (swp_tb_is_folio(swp_tb))
            if (__try_to_reclaim_swap(si, offset, TTRS_ANYWAY) < 0)
                break;
    } while (++offset < end);

If a physical cluster has some free slots (ci->count < SWAPFILE_CLUSTER, so it sits on percpu_swap_cluster, global_cluster, si->nonfull_clusters[order], or si->frag_clusters[order] rather than si->full_clusters), won't SWP_RMAP_CACHE_ONLY slots in that cluster prevent cluster_scan_range() and cluster_reclaim_range() from reclaiming them when vm_swap_full() is true, causing high-order physical swap allocations to fail prematurely?

[ ... ]

Quoted 9 lines
mm/swapfile.c +2 -0
@@ -1752,6 +1820,8 @@ static void swap_put_entries_cluster(struct swap_info_struct *si,
 			}
 			/* count will be 0 after put, slot can be reclaimed */
 			need_reclaim = true;
+			if (swap_is_vswap(si))
+				vswap_mark_cache_only(ci, ci_off);
 		}
 		/*
 		 * A count != 1 or cached slot can't be freed. Put its swap

[ ... ]

Quoted 11 lines
mm/swapfile.c +7 -0
@@ -2008,6 +2080,51 @@ int folio_alloc_swap(struct folio *folio)
 	return order ? -E2BIG : -ENOMEM;
 }
 
+static void vswap_mark_cache_only(struct swap_cluster_info *ci,
+				  unsigned int ci_off)
+{
+	struct swap_cluster_info_dynamic *ci_dyn;
+	struct swap_cluster_info *pci;
+	swp_entry_t phys;
+	unsigned long vt;

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

Quoted 10 lines
mm/swapfile.c +10 -0
+
+	ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+	vt = __vtable_get(ci_dyn, ci_off);
+
+	if (vtable_type(vt) == VSWAP_SWAPFILE) {
+		phys = vtable_to_phys(vt);
+		pci = __swap_entry_to_cluster(phys);
+		swap_rmap_mark_cache_only(pci, swp_cluster_offset(phys));
+	}
+}

[Severity: Medium]
Can physical swap slots remain unmarked with SWP_RMAP_CACHE_ONLY if a vswap slot already has swap_count == 0 when folio_realloc_swap() in mm/swapfile.c installs its physical backing?

In folio_realloc_swap(), folio_alloc_phys_swap() -> __swap_cluster_alloc_entries() initializes the physical swap_table entries with swp_entry_to_swp_tb_vswap(v) (with SWP_RMAP_CACHE_ONLY clear), and then folio_realloc_swap() writes VSWAP_SWAPFILE into virtual_table under ci->lock:

    for (i = 0; i < nr; i++) {
        pe.val = phys_entry.val + i;
        __vtable_set(ci_dyn, voff + i, vtable_mk_phys(pe));
    }

However, vswap_mark_cache_only() only sets SWP_RMAP_CACHE_ONLY during swap_put_entries_cluster() when swap_count transitions from 1 to 0 and vtable_type(vt) is already VSWAP_SWAPFILE. A vswap slot can already have swap_count == 0 when folio_realloc_swap() installs VSWAP_SWAPFILE in two cases:

1. During swap_writeout() or zswap_writeback_entry(), the folio is locked while virtual_table is still VSWAP_NONE or VSWAP_ZSWAP. A concurrent PTE zap (such as munmap() or MADV_DONTNEED calling free_swap_and_cache_nr() -> swap_put_entries_direct() -> swap_put_entries_cluster()) can drop the vswap slot's swap_count from 1 to 0 before folio_realloc_swap() sets VSWAP_SWAPFILE. At that point vswap_mark_cache_only() sees vtable_type(vt) != VSWAP_SWAPFILE, and __try_to_reclaim_swap() cannot lock the folio.
2. When swapping out a partially unmapped large folio (mTHP), some subpages may already have swap_count == 0 while other subpages have swap_count > 0.

Since swap_count is already 0, swap_put_entries_cluster() will not run on those slots again. Should folio_realloc_swap() check whether __swp_tb_get_count(__swap_table_get(ci, voff + i)) == 0 while holding ci->lock and mark the corresponding physical rmap entry with SWP_RMAP_CACHE_ONLY?

[ ... ]

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

PATCH v6 8/12 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, the memcg's swap cgroup counter, as though they did.

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

With vswap enabled, this changes what the counter means and when the charge can fail:

* Virtual swap entries count towards memory.swap.current only when backed by physical swap slots.
* 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. In cgroup v1, vswap entries are still accounted against the memsw counter.

---
 .../admin-guide/cgroup-v1/memcg_test.rst      |   2 +-
 .../admin-guide/cgroup-v1/memory.rst          |   2 +-
 Documentation/admin-guide/cgroup-v2.rst       |  51 +++---
 include/linux/swap.h                          |  73 ++++++++-
 mm/memcontrol-v1.c                            |   9 +-
 mm/memcontrol.c                               | 148 ++++++++++++------
 mm/swapfile.c                                 | 114 ++++++++++++--
 mm/zswap.c                                    |  22 ++-
 8 files changed, 316 insertions(+), 105 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-v1/memory.rst +1 -1
index 7d2a44af52c9..2a67356d25a0 100644
@@ -553,7 +553,7 @@ memory.stat file includes following statistics:
     pgpgout         # of uncharging events to the memory cgroup. The uncharging
                     event happens each time a page is unaccounted from the
                     cgroup.
-    swap            # of bytes of swap usage
+    swap            # of bytes of physical swap usage
     swapcached      # of bytes of swap cached in memory
     dirty           # of bytes that are waiting to get written back to the disk.
     writeback       # of bytes of file/anon cache that are queued for syncing to
Documentation/admin-guide/cgroup-v2.rst +27 -24

97 lines not on this page · raw message

include/linux/swap.h +65 -8

101 lines not on this page · raw message

mm/memcontrol-v1.c +7 -2
index b7f286888507..4e4946728db5 100644
@@ -15,6 +15,7 @@
 #include "internal.h"
 #include "swap.h"
 #include "swap_table.h"
+#include "vswap.h"
 #include "memcontrol-v1.h"
 
 /* for OOM */
@@ -299,7 +300,8 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
 	 */
 	nr_entries = folio_nr_pages(folio);
 	private_id = mem_cgroup_private_id_get(memcg, nr_entries);
-	mod_memcg_state(memcg, MEMCG_SWAP, nr_entries);
+	if (!is_vswap_entry(folio->swap))
+		mod_memcg_state(memcg, MEMCG_SWAP, nr_entries);
 
 	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_entries, private_id);
 
@@ -371,7 +373,10 @@ 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);
+	if (!id)
+		return;
+	mem_cgroup_swap_uncharge(id, nr_pages);
+	mem_cgroup_swap_put(id, nr_pages, is_vswap_entry(folio->swap));
 }
 #endif
 
mm/memcontrol.c +102 -46

190 lines not on this page · raw message

mm/swapfile.c +99 -15

212 lines not on this page · raw message

mm/zswap.c +14 -8
index fd0c2f126b57..22baac2662d2 100644
@@ -1197,11 +1197,17 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
  * With vswap disabled, all zswap entries use directly mapped physical swap
  * entries. With vswap enabled, such entries are rare.
  *
- * A zswap-backed vswap entry needs physical swap capacity for writeback.
+ * A zswap-backed vswap entry needs physical swap capacity for writeback
+ * and cgroup swap margin where applicable. @memcg may be NULL to check
+ * device capacity 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;
 }
 
 /*
@@ -1341,7 +1347,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;
 
 	/*
@@ -1428,7 +1434,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)
 {
@@ -1437,7 +1443,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;
 
 	/*
@@ -1468,7 +1474,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 */
@@ -1549,7 +1555,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
#17 lore raw

Re: [PATCH v6 08/12] mm, swap: only charge physical swap entries

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] mm, swap: folio_realloc_swap() allocates physical swap before charging memcg - [Medium] mm…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] mm, swap: folio_realloc_swap() allocates physical swap before charging memcg
- [Medium] mm: memcontrol-v1: __memcg1_swapout() omits physical vswap from MEMCG_SWAP --

commit c922e31fae8f71fd3ae6707b90202f40d4d0babb
Author: Nhat Pham <[email protected]>

mm, swap: only charge physical swap entries

This commit changes swap memcg accounting so that virtual swap entries are charged against a memcg's swap counter only when physical swap backing is allocated rather than when the virtual swap entry is first allocated. It also splits the swap memcg helpers into separate get, record, charge, uncharge, and put operations.

Quoted 13 lines
Documentation/admin-guide/cgroup-v1/memory.rst +1 -1
index 7d2a44af52c93..2a67356d25a0d 100644
@@ -553,7 +553,7 @@ memory.stat file includes following statistics:
     pgpgout         # of uncharging events to the memory cgroup. The uncharging
                     event happens each time a page is unaccounted from the
                     cgroup.
-    swap            # of bytes of swap usage
+    swap            # of bytes of physical swap usage
     swapcached      # of bytes of swap cached in memory
     dirty           # of bytes that are waiting to get written back to the disk.
     writeback       # of bytes of file/anon cache that are queued for syncing to

[ ... ]

Quoted 13 lines
mm/memcontrol-v1.c +1 -0
index b7f2868885071..4e4946728db5a 100644
@@ -15,6 +15,7 @@
 #include "internal.h"
 #include "swap.h"
 #include "swap_table.h"
+#include "vswap.h"
 #include "memcontrol-v1.h"
 
 /* for OOM */

mm/memcontrol-v1.c void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci) · line 306

Quoted 8 lines
mm/memcontrol-v1.c +2 -1
@@ -299,7 +300,8 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
 	 */
 	nr_entries = folio_nr_pages(folio);
 	private_id = mem_cgroup_private_id_get(memcg, nr_entries);
-	mod_memcg_state(memcg, MEMCG_SWAP, nr_entries);
+	if (!is_vswap_entry(folio->swap))
+		mod_memcg_state(memcg, MEMCG_SWAP, nr_entries);
 
 	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_entries, private_id);

[Severity: Medium] Documentation/admin-guide/cgroup-v1/memory.rst is updated above to describe the swap counter in memory.stat as bytes of physical swap usage.

On cgroup v1 (where do_memsw_account() is true) with vswap and zswap enabled, mem_cgroup_may_zswap() returns true when !cgroup_subsys_on_dfl(memory_cgrp_subsys), so folio_may_vswap() returns true and folio_alloc_swap() allocates virtual swap entries via vswap_alloc() where is_vswap_entry(folio->swap) is true.

When a vswap folio acquires physical swapfile backing via folio_realloc_swap() -- either in swap_writeout() when zswap_store() rejects the folio or in zswap_writeback_entry() when zswap writes an entry back to disk -- folio->swap remains a virtual swap entry while the physical slot is recorded in the cluster's virtual_table:

  folio_realloc_swap()
    __vtable_set(ci_dyn, voff + i, vtable_mk_phys(pe));

In folio_realloc_swap(), __mem_cgroup_swap_charge() returns 0 early because do_memsw_account() is true (and memcg_id in ci->memcg_table is 0 while the folio is still in the swap cache on cgroup v1).

When writeback completes and the folio is removed from the swap cache via __swap_cache_del_folio() -> __memcg1_swapout(), __memcg1_swapout() checks !is_vswap_entry(folio->swap) (and the subsequent commit "mm, swap: add vmstat and memcg counters for vswap" branches on is_vswap_entry(folio->swap) between the vswap and swap counters) and skips incrementing the swap state counter even when the vswap entry is backed by physical swap. Likewise, __mem_cgroup_swap_uncharge() and __mem_cgroup_swap_put() never decrement the swap state counter for vswap entries on cgroup v1.

Does this cause swap and total_swap in cgroup v1 memory.stat to remain at 0 for all vswap-allocated pages backed by physical swap slots?

[ ... ]

Quoted 4 lines
mm/swapfile.c +0 -0
index 640e38a55497e..341077fee23be 100644

[ ... ]

Quoted 25 lines
mm/swapfile.c +14 -4
@@ -2297,18 +2353,33 @@ swp_entry_t folio_realloc_swap(struct folio *folio)
 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
 	VM_WARN_ON(!is_vswap_entry(vswap_entry));
 
-	phys_entry = vswap_to_phys(vswap_entry);
-	if (phys_entry.val)
-		return phys_entry;
+	voff = swp_cluster_offset(vswap_entry);
+	ci = __swap_entry_to_cluster(vswap_entry);
+	ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+
+	spin_lock(&ci->lock);
+	vt = __vtable_get(ci_dyn, voff);
+	if (vtable_type(vt) == VSWAP_SWAPFILE) {
+		spin_unlock(&ci->lock);
+		return vtable_to_phys(vt);
+	}
+	memcg_id = __swap_cgroup_get(ci, voff);
+	spin_unlock(&ci->lock);
 
 	phys_entry = folio_alloc_phys_swap(folio);
-	if (!phys_entry.val)
+	if (!phys_entry.val) {
+		mem_cgroup_swap_fail(memcg_id);
 		return (swp_entry_t){};

mm/swapfile.c swp_entry_t folio_realloc_swap(struct folio *folio) · line 2381

Quoted 10 lines
mm/swapfile.c +8 -1
+	}
 
-	voff = swp_cluster_offset(vswap_entry);
+	if (mem_cgroup_swap_charge(memcg_id, nr)) {
+		__swap_cluster_free_phys_backing(__swap_entry_to_info(phys_entry),
+						 __swap_entry_to_cluster(phys_entry),
+						 swp_cluster_offset(phys_entry),
+						 nr);
+		return (swp_entry_t){};
+	}

[Severity: Medium]
With vswap and zswap enabled, a cgroup with memory.swap.max set to 0 (or at its physical swap limit) can reclaim anonymous pages via:

mem_cgroup_can_swap()
shrink_folio_list()
folio_alloc_swap()

which allocates a vswap entry without charging memcg->swap. When zswap_store() subsequently fails in swap_writeout() (for example, when the global zswap pool is full or memory.zswap.max is reached), swap_writeout() calls folio_realloc_swap(folio). Similarly, zswap_writeback_entry() calls folio_realloc_swap(folio) if a cgroup reaches memory.swap.max during a writeback walk.

In folio_realloc_swap(), memcg_id and nr are already known before calling folio_alloc_phys_swap(folio), yet physical swap is allocated before mem_cgroup_swap_charge(memcg_id, nr) is checked. When mem_cgroup_swap_charge() fails, __swap_cluster_free_phys_backing() frees the newly allocated physical slot(s):

  __swap_cluster_free_phys_backing()
    pci->count -= nr_pages;
    ...
    __swap_cluster_finish_free()
      if (!ci->count)
        free_cluster(si, ci);

Whenever folio_alloc_phys_swap() isolated a fresh empty cluster from si->free_clusters (which cluster_alloc_swap_entry() prefers on discard-enabled swap devices), pci->count drops from nr back to 0 and free_cluster() is called. On discard-enabled swap devices, free_cluster() marks the entire cluster for discard and schedules discard_work; on non-discard devices, __free_cluster() frees pci->table via call_rcu(). In both cases, percpu_swap_cluster becomes unusable (!cluster_is_usable()) for the next page, forcing every subsequent rejected page into swap_alloc_slow() to populate and immediately tear down or discard another free cluster.

Could folio_realloc_swap() charge the memcg via mem_cgroup_swap_charge(memcg_id, nr) before calling folio_alloc_phys_swap(), and uncharge if physical swap allocation fails, so physical swap clusters are not allocated and immediately destroyed when the cgroup is at memory.swap.max?

[ ... ]

([c922e31fae8f ("mm, swap: only charge physical swap entries")](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c922e31fae8f71fd3ae6707b90202f40d4d0babb))

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

PATCH v6 9/12 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 whose vswap slot allocation failed

---
 mm/swapfile.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
mm/swapfile.c +25 -0
index 341077fee23b..12cd5caeaaf2 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>
@@ -146,6 +147,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,
@@ -1997,6 +1999,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;
 }
 
@@ -4874,9 +4877,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;
 
@@ -4926,6 +4945,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
#19 lore raw

PATCH v6 10/12 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.

---
 mm/swapfile.c | 83 +++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 64 insertions(+), 19 deletions(-)
mm/swapfile.c +64 -19
index 12cd5caeaaf2..e95f2441fdd7 100644
@@ -476,7 +476,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;
@@ -497,7 +498,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 direct-use
+	 * slot, including one for hibernation.
+	 */
+	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) {
@@ -575,8 +583,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;
 
 	/*
@@ -589,8 +597,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
@@ -867,7 +875,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. */
@@ -1090,7 +1098,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);
@@ -1119,6 +1129,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;
@@ -1128,7 +1155,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);
@@ -1149,7 +1184,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;
@@ -1157,10 +1198,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;
 }
@@ -1181,7 +1222,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;
 	}
@@ -1207,7 +1249,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)
@@ -1314,7 +1356,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);
 		}
@@ -1358,7 +1401,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).
 		 */
@@ -1373,7 +1416,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);
@@ -1594,7 +1637,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);
 	}
@@ -1982,7 +2025,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);
 		}
@@ -2843,7 +2887,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
#20 lore raw

Re: [PATCH v6 10/12] mm, swap: defer memcg_table allocation for physical swap clusters

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] mm, swap: infinite loop and cluster demotion on lazy memcg_table alloc failure - [High] mm, swap…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] mm, swap: infinite loop and cluster demotion on lazy memcg_table alloc failure
- [High] mm, swap: NULL ci->table deref when lazy memcg_table alloc fails in race --

commit d992a89e7fdb8e94a85278f2c60420245b2472d5
Author: Nhat Pham <[email protected]>

mm, swap: defer memcg_table allocation for physical swap clusters

This patch defers allocating ci->memcg_table for physical swap clusters when vswap is enabled until a direct-use swap slot is allocated in alloc_swap_scan_cluster(). Clusters that only hold vswap backings skip allocating ci->memcg_table altogether.

Quoted 52 lines
mm/swapfile.c +14 -6
index 12cd5caeaaf23..e95f2441fdd7c 100644
@@ -476,7 +476,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;
@@ -497,7 +498,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 direct-use
+	 * slot, including one for hibernation.
+	 */
+	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) {
@@ -575,8 +583,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;
 
 	/*
@@ -589,8 +597,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

[ ... ]

Quoted 39 lines
mm/swapfile.c +20 -1
@@ -1090,7 +1098,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);
@@ -1119,6 +1129,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;
@@ -1128,7 +1155,15 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 		break;
 	}
 out:

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

Quoted 10 lines
mm/swapfile.c +9 -1
-	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);

[Severity: High]
Can a concurrent caller with nomem == NULL race with swap_cluster_populate() here and free ci->table before swap_cluster_populate() finishes isolating the cluster?

In mm/swapfile.c, when isolate_lock_cluster() isolates an empty physical cluster from si->free_clusters and the initial atomic table allocation fails, swap_cluster_populate() drops ci->lock and percpu_swap_cluster.lock to call swap_cluster_alloc_table() with GFP_KERNEL:

    spin_unlock(&ci->lock);
    if (!(si->flags & SWP_SOLIDSTATE))
        spin_unlock(&si->global_cluster_lock);
    local_unlock(&percpu_swap_cluster.lock);

    ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
                                           GFP_KERNEL);

With this patch, swap_cluster_alloc_table() skips allocating ci->memcg_table for physical clusters when vswap_is_enabled() is true, and publishes rcu_assign_pointer(ci->table, table) while ci->lock is not held.

Before swap_cluster_populate() re-acquires ci->lock, another caller whose cached percpu_swap_cluster.offset[order] or si->global_cluster->next[order] still points into ci (such as swap_alloc_fast(), cluster_alloc_swap_entry(), or swap_alloc_hibernation_slot()) can lock ci, see cluster_is_usable(ci, order) == true and cluster_is_empty(ci) == true, and call alloc_swap_scan_cluster(si, ci, folio, offset, NULL) with nomem == NULL for a direct-use slot.

If the lazy kzalloc_obj(*ci->memcg_table, GFP_ATOMIC | __GFP_NOWARN) fails in alloc_swap_scan_cluster(), it jumps to out with ci->count == 0. Because nomem is NULL, the check (nomem && *nomem && !ci->count) is false, so it calls relocate_cluster(si, ci) -> free_cluster(si, ci), which either frees ci->table via __free_cluster() and moves ci back to si->free_clusters, or queues ci on si->discard_clusters when SWP_PAGE_DISCARD is set.

When swap_cluster_populate() then re-acquires ci->lock, it only checks if (ret) before returning ci to isolate_lock_cluster() -> alloc_swap_scan_list() -> alloc_swap_scan_cluster() -> cluster_scan_range() -> __swap_table_get(), dereferencing a NULL ci->table (or allocating from a cluster on si->discard_clusters).

Quoted 20 lines
mm/swapfile.c +6 -0
 	swap_cluster_unlock(ci);
 	if (swap_is_vswap(si)) {
 		this_cpu_write(percpu_vswap_cluster.offset[order], next);
@@ -1149,7 +1184,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;
@@ -1157,10 +1198,10 @@ static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,
 		if (!ci)
 			break;

mm/swapfile.c static unsigned int alloc_swap_scan_list(struct swap_info_struct *si, · line 1207

Quoted 10 lines
mm/swapfile.c +2 -2
 		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;
 }

[Severity: High]
What happens in cluster_alloc_swap_entry() and swap_alloc_slow() when the lazy GFP_ATOMIC allocation of ci->memcg_table fails under memory pressure?

Previously, swap_cluster_populate() had a lock-dropping GFP_KERNEL fallback when allocating ci->memcg_table, and swapon pre-allocated ci->memcg_table with GFP_KERNEL for cluster 0 and the bad/EOF clusters. Moving physical cluster ci->memcg_table allocation into alloc_swap_scan_cluster() under ci->lock and percpu_swap_cluster.lock with GFP_ATOMIC | __GFP_NOWARN appears to cause several issues when that atomic allocation fails during direct physical swap allocation:

1. For an empty cluster isolated from si->free_clusters, swap_cluster_populate() has just allocated ci->table (potentially dropping locks to use GFP_KERNEL), and alloc_swap_scan_cluster() immediately calls __free_cluster(si, ci) -> swap_cluster_free_table(ci), freeing the newly allocated ci->table via call_rcu() and returning ci to si->free_clusters.

2. For a non-empty cluster (ci->count > 0) isolated from si->nonfull_clusters[order] (such as cluster 0, the EOF cluster, or a partially filled vswap-backing cluster), the check (nomem && *nomem && !ci->count) in alloc_swap_scan_cluster() is false, so relocate_cluster(si, ci) demotes the cluster from si->nonfull_clusters[order] to si->frag_clusters[ci->order].

3. In alloc_swap_scan_list(), stopping on !nomem skips any remaining clusters on si->nonfull_clusters[order] that already have ci->memcg_table allocated, while nomem is not propagated to cluster_alloc_swap_entry(). As a result, cluster_alloc_swap_entry() continues to si->free_clusters, swap_reclaim_full_clusters(), and the order-0 higher-order stealing loop over si->frag_clusters[o] and si->nonfull_clusters[o], demoting or fragmenting higher-order clusters.

4. When cluster_alloc_swap_entry(si, folio) returns 0 to swap_alloc_slow(folio) for an order-0 folio (!folio_test_large(folio)), swap_alloc_slow() does not bail out:

    plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
        /* Rotate the device and switch to a new cluster */
        plist_requeue(&si->avail_list, &swap_avail_head);
        spin_unlock(&swap_avail_lock);
        if (get_swap_device_info(si)) {
            found = cluster_alloc_swap_entry(si, folio);
            put_swap_device(si);
            if (found)
                return swp_entry(si->type, found);
            if (folio_test_large(folio))
                return (swp_entry_t){};
        }

Because no slots were allocated, si is not full and stays on swap_avail_head. When two or more swap devices share the same priority on swap_avail_head, plist_requeue(&si->avail_list, &swap_avail_head) moves si after next on each iteration, causing swap_alloc_slow() to loop indefinitely between those devices while holding percpu_swap_cluster.lock.

Could swap_cluster_populate() or a lock-dropping fallback in the caller handle allocating ci->memcg_table with GFP_KERNEL, and avoid demoting clusters or looping in swap_alloc_slow() when allocation fails?

Quoted 1 line
mm/swapfile.c +0 -0
@@ -1181,7 +1222,8 @@ static unsigned int vswap_alloc_cluster(struct swap_info_struct *si,

[ ... ]

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

PATCH v6 11/12 mm, swap: add vmstat and memcg counters for vswap

In reply to Nhat Pham

Add nr_vswap to /proc/vmstat and vswap to cgroup's memory.stat to report virtual swap usage.

These counters help diagnose swapping issues. Userspace can also use vswap as a component of a workload's logical memory footprint when making policy decisions.

---
 .../admin-guide/cgroup-v1/memory.rst          |  1 +
 Documentation/admin-guide/cgroup-v2.rst       |  3 +++
 include/linux/memcontrol.h                    |  1 +
 include/linux/swap.h                          |  1 +
 include/linux/vmstat.h                        |  3 +++
 mm/memcontrol-v1.c                            |  6 +++++-
 mm/memcontrol.c                               | 20 +++++++++++++++----
 mm/swapfile.c                                 | 10 +++++++---
 mm/vmstat.c                                   |  6 ++++++
 9 files changed, 43 insertions(+), 8 deletions(-)
Documentation/admin-guide/cgroup-v1/memory.rst +1 -0
index 2a67356d25a0..8ca9ef2bca9f 100644
@@ -555,6 +555,7 @@ memory.stat file includes following statistics:
                     cgroup.
     swap            # of bytes of physical swap usage
     swapcached      # of bytes of swap cached in memory
+    vswap           # of bytes of virtual swap usage
     dirty           # of bytes that are waiting to get written back to the disk.
     writeback       # of bytes of file/anon cache that are queued for syncing to
                     disk.
Documentation/admin-guide/cgroup-v2.rst +3 -0
index 623d29ea8c41..b1f97a61a1dc 100644
@@ -1633,6 +1633,9 @@ The following nested keys are defined.
 		against memory usage, and against swap usage when the swap
 		entry has physical backing.
 
+	  vswap
+		Amount of virtual swap usage.
+
 	  anon_thp
 		Amount of memory used in anonymous mappings backed by
 		transparent hugepages
include/linux/memcontrol.h +1 -0
index b9072a3c9a2a..99beb676d8e7 100644
@@ -41,6 +41,7 @@ enum memcg_stat_item {
 	MEMCG_ZSWAP_B,
 	MEMCG_ZSWAPPED,
 	MEMCG_ZSWAP_INCOMP,
+	MEMCG_VSWAP,
 	MEMCG_NR_STAT,
 };
 
include/linux/swap.h +1 -0
index a05189c92dae..891442264ca9 100644
@@ -371,6 +371,7 @@ bool current_is_kswapd(void);
 
 #ifdef CONFIG_SWAP
 bool mem_cgroup_can_vswap(struct mem_cgroup *memcg);
+unsigned long vswap_usage_in_pages(void);
 
 int add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
 		unsigned long nr_pages, sector_t start_block);
include/linux/vmstat.h +3 -0
index 5b31d8e7ae40..37aff1ffac08 100644
@@ -33,6 +33,9 @@ enum vm_stat_item {
 	NR_DIRTY_BG_THRESHOLD,
 	NR_MEMMAP_PAGES,	/* page metadata allocated through buddy allocator */
 	NR_MEMMAP_BOOT_PAGES,	/* page metadata allocated through boot allocator */
+#ifdef CONFIG_SWAP
+	NR_VSWAP,		/* pages occupying a virtual swap slot */
+#endif
 	NR_VM_STAT_ITEMS,
 };
 
mm/memcontrol-v1.c +5 -1
index 4e4946728db5..8fa7b2fb109d 100644
@@ -300,7 +300,9 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
 	 */
 	nr_entries = folio_nr_pages(folio);
 	private_id = mem_cgroup_private_id_get(memcg, nr_entries);
-	if (!is_vswap_entry(folio->swap))
+	if (is_vswap_entry(folio->swap))
+		mod_memcg_state(memcg, MEMCG_VSWAP, nr_entries);
+	else
 		mod_memcg_state(memcg, MEMCG_SWAP, nr_entries);
 
 	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_entries, private_id);
@@ -1842,6 +1844,7 @@ static const unsigned int memcg1_stats[] = {
 #ifdef CONFIG_SWAP
 	MEMCG_SWAP,
 	NR_SWAPCACHE,
+	MEMCG_VSWAP,
 #endif
 };
 
@@ -1860,6 +1863,7 @@ static const char *const memcg1_stat_names[] = {
 #ifdef CONFIG_SWAP
 	"swap",
 	"swapcached",
+	"vswap",
 #endif
 };
 
mm/memcontrol.c +16 -4
index e2aa75a292ed..eedaa094a867 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"
@@ -459,6 +460,7 @@ static const unsigned int memcg_stat_items[] = {
 	MEMCG_ZSWAP_B,
 	MEMCG_ZSWAPPED,
 	MEMCG_ZSWAP_INCOMP,
+	MEMCG_VSWAP,
 };
 
 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
@@ -1628,6 +1630,7 @@ static const struct memory_stat memory_stats[] = {
 	{ "file_writeback",		NR_WRITEBACK			},
 #ifdef CONFIG_SWAP
 	{ "swapcached",			NR_SWAPCACHE			},
+	{ "vswap",			MEMCG_VSWAP			},
 #endif
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
 	{ "anon_thp",			NR_ANON_THPS			},
@@ -6004,6 +6007,7 @@ unsigned short __mem_cgroup_swap_get(struct folio *folio)
 	unsigned int nr_pages = folio_nr_pages(folio);
 	struct mem_cgroup *memcg;
 	struct obj_cgroup *objcg;
+	unsigned short id;
 
 	if (do_memsw_account())
 		return 0;
@@ -6020,7 +6024,12 @@ unsigned short __mem_cgroup_swap_get(struct folio *folio)
 		return 0;
 	}
 
-	return mem_cgroup_private_id_get(memcg, nr_pages);
+	id = mem_cgroup_private_id_get(memcg, nr_pages);
+	if (is_vswap_entry(folio->swap)) {
+		memcg = obj_cgroup_memcg(obj_cgroup_from_private_id(id));
+		mod_memcg_state(memcg, MEMCG_VSWAP, nr_pages);
+	}
+	return id;
 }
 
 /**
@@ -6109,7 +6118,7 @@ void __mem_cgroup_swap_uncharge(unsigned short id, unsigned int nr_pages)
  * __mem_cgroup_swap_put - drop the private ID refs taken for swap slots
  * @id: the pinned private ID
  * @nr_pages: number of refs to drop
- * @is_vswap: whether the released swap slots are virtual
+ * @is_vswap: release virtual-swap accounting along with the refs
  */
 void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages,
 			   bool is_vswap)
@@ -6117,9 +6126,12 @@ void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages,
 	struct mem_cgroup *memcg;
 
 	guard(rcu)();
-	if (do_memsw_account() && !is_vswap) {
+	if (is_vswap || do_memsw_account()) {
 		memcg = obj_cgroup_memcg(obj_cgroup_from_private_id(id));
-		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
+		if (is_vswap)
+			mod_memcg_state(memcg, MEMCG_VSWAP, -nr_pages);
+		else
+			mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
 	}
 	mem_cgroup_private_id_put(id, nr_pages);
 }
mm/swapfile.c +7 -3
index e95f2441fdd7..fe5460d15f55 100644
@@ -2612,9 +2612,8 @@ static void __swap_cluster_free_phys_backing(struct swap_info_struct *psi,
 }
 
 /*
- * Release the cgroup accounting of a batch of freed slots. For vswap the
- * physical swap was already uncharged by __vswap_release_backing(), so only
- * the ID ref is left to drop.
+ * Release cgroup accounting for freed swap slots. Physical backing of
+ * vswap entries was already uncharged by __vswap_release_backing().
  */
 static void memcg_swap_free(unsigned short id, unsigned int nr, bool is_vswap)
 {
@@ -4922,6 +4921,11 @@ early_param("vswap", early_vswap);
 /* vswap does no IO on its own. */
 static const struct swap_ops vswap_ops = { };
 
+unsigned long vswap_usage_in_pages(void)
+{
+	return vswap_is_enabled() ? swap_usage_in_pages(vswap_si) : 0;
+}
+
 static int vswap_used_get(void *data, u64 *val)
 {
 	*val = swap_usage_in_pages(vswap_si);
mm/vmstat.c +6 -0
index a3e809c57f29..b7077a6f244d 100644
@@ -1320,6 +1320,9 @@ const char * const vmstat_text[] = {
 	[I(NR_DIRTY_BG_THRESHOLD)]		= "nr_dirty_background_threshold",
 	[I(NR_MEMMAP_PAGES)]			= "nr_memmap_pages",
 	[I(NR_MEMMAP_BOOT_PAGES)]		= "nr_memmap_boot_pages",
+#ifdef CONFIG_SWAP
+	[I(NR_VSWAP)]				= "nr_vswap",
+#endif
 #undef I
 
 #if defined(CONFIG_VM_EVENT_COUNTERS)
@@ -1936,6 +1939,9 @@ static void *vmstat_start(struct seq_file *m, loff_t *pos)
 			    v + NR_DIRTY_THRESHOLD);
 	v[NR_MEMMAP_PAGES] = atomic_long_read(&nr_memmap_pages);
 	v[NR_MEMMAP_BOOT_PAGES] = atomic_long_read(&nr_memmap_boot_pages);
+#ifdef CONFIG_SWAP
+	v[NR_VSWAP] = vswap_usage_in_pages();
+#endif
 	v += NR_VM_STAT_ITEMS;
 
 #ifdef CONFIG_VM_EVENT_COUNTERS
Signature · 1 line
2.53.0-Meta
author maintainer
#22 lore raw

RFC PATCH v6 12/12 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 index and rcu_head fields, the kfree_rcu(), CLUSTER_FLAG_DEAD and __vswap_cluster_lock() go away. 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      |  28 ++--
 mm/swap_table.h      |   9 --
 mm/swapfile.c        | 352 ++++++++++++++++++++++++++++---------------
 mm/vswap.h           | 104 +++++++------
 6 files changed, 298 insertions(+), 261 deletions(-)
include/linux/swap.h +4 -1
index 891442264ca9..06d3324b045c 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 +12 -16
index 6c8e8f49e349..64d284c4b943 100644
@@ -174,7 +174,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;
 
@@ -210,8 +209,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;
@@ -460,12 +458,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);
 
@@ -486,13 +481,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);
 	}
@@ -504,7 +496,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);
@@ -913,6 +904,7 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 	unsigned long offset = entry_offset;
 	unsigned long start_offset, end_offset;
 	unsigned long mask;
+	unsigned int max;
 	struct swap_info_struct *si = __swap_entry_to_info(entry);
 	struct swap_io_ctx ctx = {};
 	struct blk_plug plug;
@@ -927,8 +919,12 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 	end_offset = offset | mask;
 	if (!start_offset)	/* First page is swap header. */
 		start_offset++;
-	if (end_offset >= si->max)
-		end_offset = si->max - 1;
+	max = si->max;
+	if (swap_is_vswap(si))
+		max = min(max, READ_ONCE(si->nr_mapped_clusters) *
+			       SWAPFILE_CLUSTER);
+	if (end_offset >= max)
+		end_offset = max - 1;
 
 	blk_start_plug(&plug);
 	for (offset = start_offset; offset <= end_offset ; offset++) {
mm/swap_table.h +0 -9
index 88d1bb0e65fd..442df276ab83 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 +227 -125

614 lines not on this page · raw message

mm/vswap.h +51 -53

213 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
#23 lore raw

Re: [RFC PATCH v6 12/12] mm, swap: back vswap clusters with a VM_SPARSE array

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] mm: vswap_grow_clusters() publishes nr_mapped_clusters before spin_lock_init() - [High] mm, swap…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] mm: vswap_grow_clusters() publishes nr_mapped_clusters before spin_lock_init()
- [High] mm, swap: race on unlocked table publish in swap_cluster_populate() --

commit f6800a3010801f9cd20edba92bfbe97989790bd2
Author: Nhat Pham <[email protected]>

mm, swap: back vswap clusters with a VM_SPARSE array

This commit replaces the xarray of dynamically allocated vswap cluster structures with a VM_SPARSE vmalloc array that grows on demand a page at a time. Emptied vswap clusters now free their tables and return to si->free_clusters for reuse rather than being freed via RCU.

Quoted 4 lines
mm/swapfile.c +0 -0
index fe5460d15f555..4cb6586327c45 100644

[ ... ]

Quoted 43 lines
mm/swapfile.c +10 -5
@@ -519,12 +550,19 @@ static int swap_cluster_alloc_table(struct swap_info_struct *si,
 	VM_WARN_ON_ONCE(ci->zero_bitmap);
 	ci->zero_bitmap = bitmap_zalloc(SWAPFILE_CLUSTER, gfp);
 	if (!ci->zero_bitmap) {
-		swap_cluster_free_table(ci);
+		swap_cluster_free_table(si, ci);
 		swap_cluster_free_count_table(table);
 		return -ENOMEM;
 	}
 #endif
 
+	/* The virtual table shares the swap table's lifetime. */
+	if (swap_is_vswap(si) && vswap_cluster_alloc_vtable(ci, gfp)) {
+		swap_cluster_free_table(si, ci);
+		swap_cluster_free_count_table(table);
+		return -ENOMEM;
+	}
+
 	/*
 	 * Make tables visible to cluster_is_usable() after everything is
 	 * ready.
@@ -575,10 +613,8 @@ swap_cluster_populate(struct swap_info_struct *si,
 	/*
 	 * Only cluster isolation from the allocator does table allocation.
 	 * Swap allocator uses percpu clusters and holds the local lock.
-	 * vswap clusters are destroyed rather than freed to si->free_clusters.
 	 */
-	VM_WARN_ON_ONCE(swap_is_vswap(si));
-	lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock);
+	swap_percpu_cluster_assert_held(si);
 	if (!(si->flags & SWP_SOLIDSTATE))
 		lockdep_assert_held(&si->global_cluster_lock);
 	lockdep_assert_held(&ci->lock);
@@ -595,7 +631,7 @@ swap_cluster_populate(struct swap_info_struct *si,
 	spin_unlock(&ci->lock);
 	if (!(si->flags & SWP_SOLIDSTATE))
 		spin_unlock(&si->global_cluster_lock);
-	local_unlock(&percpu_swap_cluster.lock);
+	swap_percpu_cluster_unlock(si);
 
 	ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
 					       GFP_KERNEL);

mm/swapfile.c swap_cluster_populate(struct swap_info_struct *si, · line 650

Quoted 8 lines
mm/swapfile.c +1 -1
@@ -608,7 +644,7 @@ swap_cluster_populate(struct swap_info_struct *si,
 	 * could happen with ignoring the percpu cluster is fragmentation,
 	 * which is acceptable since this fallback and race is rare.
 	 */
-	local_lock(&percpu_swap_cluster.lock);
+	swap_percpu_cluster_lock(si);
 	if (!(si->flags & SWP_SOLIDSTATE))
 		spin_lock(&si->global_cluster_lock);
 	spin_lock(&ci->lock);

[Severity: High]
Can a concurrent fast-path allocator race with the unlocked swap_cluster_alloc_table() call in swap_cluster_populate()?

With vswap clusters now returning to si->free_clusters in __free_cluster() instead of being destroyed with CLUSTER_FLAG_DEAD, other CPUs (or other orders on the same CPU) can still hold an offset into a freed cluster in percpu_vswap_cluster.offset[order].

When cluster_alloc_swap_entry() -> alloc_swap_scan_list() -> isolate_lock_cluster() isolates ci from si->free_clusters, it sets ci->flags = CLUSTER_FLAG_NONE and calls swap_cluster_populate(). If the initial atomic allocation fails, swap_cluster_populate() drops ci->lock and calls swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC | GFP_KERNEL), which publishes ci->virtual_table and ci->table before ci->lock is re-acquired:

mm/swapfile.c:swap_cluster_alloc_table() {
	...
	rcu_assign_pointer(ci->table, table);
	return 0;
}

Because CLUSTER_FLAG_NONE is <= CLUSTER_FLAG_USABLE, an isolated cluster is only prevented from passing cluster_is_usable(ci, order) by ci->table being NULL. Once rcu_assign_pointer(ci->table, table) executes while ci->lock is dropped, a concurrent vswap_alloc() (or swap_alloc_fast()) with a cached offset into ci can lock ci->lock, see cluster_is_usable(ci, order) return true, and allocate entries via alloc_swap_scan_cluster():

mm/swapfile.c:vswap_alloc() {
	if (offset != SWAP_ENTRY_INVALID) {
		ci = swap_cluster_lock(vswap_si, offset);
		if (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,
						NULL);
		} ...
	}
}

If that fast-path allocation claims ci for a different order and relocates it onto another cluster list, or if those entries are then freed so __free_cluster() frees ci->table and ci->virtual_table back to NULL before swap_cluster_populate() re-acquires spin_lock(&ci->lock), swap_cluster_populate() will still see ret == 0 and return ci to alloc_swap_scan_list() -> alloc_swap_scan_cluster().

Could this trigger VM_WARN_ON(!cluster_is_usable(ci, order)) in alloc_swap_scan_cluster(), corrupt cluster list and order state, or dereference a NULL ci->table in cluster_scan_range() -> __swap_table_get()?

[ ... ]

Quoted 1 line
mm/swapfile.c +0 -0
@@ -1206,50 +1229,146 @@ static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,

[ ... ]

Quoted 2 lines

+static int vswap_grow_clusters(struct swap_info_struct *si)
{

[ ... ]

Quoted 4 lines
mm/swapfile.c +4 -0
+	/*
+	 * Publish the new clusters before they become reachable by offset.
+	 * A zeroed page leaves them off-list with CLUSTER_FLAG_NONE, which
+	 * is what move_cluster() expects.

mm/swapfile.c static unsigned int alloc_swap_scan_list(struct swap_info_struct *si, · line 1365

Quoted 10 lines
mm/swapfile.c +9 -0
+	 */
+	WRITE_ONCE(si->nr_mapped_clusters, first + nr);
+	for (i = first; i < first + nr; i++) {
+		ci = &si->cluster_info[i];
+		spin_lock_init(&ci->lock);
+		INIT_LIST_HEAD(&ci->list);
+		spin_lock(&ci->lock);
+		move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
+		spin_unlock(&ci->lock);
 	}

[Severity: High]
What happens if swap_cluster_readahead() observes the updated si->nr_mapped_clusters in vswap_grow_clusters() before the loop finishes running spin_lock_init(&ci->lock) on each new cluster?

In mm/swap_state.c, swap_cluster_readahead() bounds end_offset using READ_ONCE(si->nr_mapped_clusters) and then locks each cluster in the range via swap_cache_read_folio() -> __swap_cache_alloc_folio() -> __swap_cache_alloc() -> swap_cluster_lock():

mm/swap_state.c:swap_cluster_readahead() {
	...
	max = si->max;
	if (swap_is_vswap(si))
		max = min(max, READ_ONCE(si->nr_mapped_clusters) *
			       SWAPFILE_CLUSTER);
	if (end_offset >= max)
		end_offset = max - 1;

	blk_start_plug(&plug);
	for (offset = start_offset; offset <= end_offset ; offset++) {
		/* Ok, do the async read-ahead now */
		ra_entry = swp_entry(swp_type(entry), offset);
		folio = swap_cache_read_folio(&ctx, ra_entry, gfp_mask, mpol,
				ilx, offset != entry_offset);
	...
}

When a readahead window spans across a cluster boundary into the newly grown range [first, first + nr) (or after cluster first is added to si->free_clusters while clusters first + 1 .. first + nr - 1 are still being initialized), swap_cluster_readahead() can call spin_lock(&ci->lock) on si->cluster_info[i] before spin_lock_init(&ci->lock) has executed, or while spin_lock_init(&ci->lock) is concurrently resetting the lock.

Should vswap_grow_clusters() initialize the new clusters before publishing si->nr_mapped_clusters with smp_store_release() (paired with smp_load_acquire() in readers), or initialize spin_lock_init(&ci->lock) and INIT_LIST_HEAD(&ci->list) for the entire batch before making the new clusters visible?

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#24 lore raw
In reply to Nhat Pham
Quoted 9 lines · Nhat Pham

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.

I get that the motivation is zswap, but it would be nice to have disk-swap performance numbers here as well right in the cover.

If only because...

Quoted 6 lines

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.

If the numbers you presented carry through, I'm left wondering why this is a boot option and not a build option. I rather dislike the boot option compromise in general - but other reasoning aside, if there's no performance impact, then I don't see why it shouldn't be the default.

~Gregory

Signature · 1 line
Gregory Price (Meta) <[email protected]>
author maintainer
#25 lore raw
Quoted 12 lines · Gregory Price (Meta)
Quoted 9 lines · Nhat Pham

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.

Quoted 4 lines

I get that the motivation is zswap, but it would be nice to have disk-swap performance numbers here as well right in the cover.

If only because...

I probably should test it regardless, but likely there will be no difference in performance numbers. Right now for straight disk swapping we incur 0 overhead, because I just bypass the virtualization layer :) There just isn't any feature for me to entertain vswap+disk swap quite yet (it might come soon-ish though).

Vswap's physical swapfile backend is only used for cgroups that support zswap (for zswap writeback and fallback if vswap fails to allocate or zswap rejects the page etc.).

For the older version, I put vswap in front of all swap backends. Disk swap sees no regression, but Kairui found some regression with fast in-memory swapfile (pmem). I reproduced it with zram, and I think I closed that gap in my own testing, but Kairui did not test the fixed version AFAICT, and I also don't have his full suite, only the ones he quoted.

(Btw, Kairui, could you publish your full suite, or at least the full set of testing parameters? I would like to hammer the thing myself to expose bugs etc.).

Quoted 8 lines
Quoted 7 lines

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.

Quoted 4 lines

If the numbers you presented carry through, I'm left wondering why this is a boot option and not a build option. I rather dislike the boot option compromise in general - but other reasoning aside, if there's no performance impact, then I don't see why it shouldn't be the default.

That's a good point yeah. Lemme think about it. I added the boot param before I decided to bypass vswap for physical swapfile by default...

Quoted 5 lines

~Gregory

--
Gregory Price (Meta) <[email protected]>