Virtual Swap Space (Swap Table Edition)
Subsystems (10)
Nhat Pham
maintainerv3 cover Virtual Swap Space (Swap Table Edition)
Changelog:
* 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.
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 availaiblity. 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 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 we compile kernel with CONFIG_VSWAP, a special vswap device is allocated at boot time, and all swapped out pages try to allocate from this device first, falling back to a physical swap device on failure.
Routing can also be turned off at runtime with the vm.vswap_enabled sysctl, which defaults to 0 unless CONFIG_VSWAP_DEFAULT_ON=y. It is
allocation-only: new swapouts go straight to physical swap, while entries already backed by vswap keep being served and drain as they are faulted back in or freed.
These swap entries can subsequently acquire backend on-demand, such as a zswap entry, or a slot on a physical swap device.
We repurpose much of the existing swap_table infrastructure and swapfile allocator for this new vswap device, with two notable differences:
* Clusters are dynamically allocated on demand and managed through an xarray. This in turn allows us to avoid static provisioning and let swap space grow dynamically.
* Each cluster of this new vswap device has a virtual_table that stores the backend information of the entries in the cluster (see below).
Diagrams:
Case 1: vswap entry (virtualized)
PTE swap_cluster_info_dynamic
vswap_entry +---------------------------------+
(swp_entry_t) ------>| swap_cluster_info (ci) |
| +----------------------------+ |
| | swap_table | |
| | PFN / Shadow | |
| | memcg_table | |
| | count,flags,order | |
| | lock, list | |
| +----------------------------+ |
| |
| virtual_table |
| +----------------------------+ |
| | NONE | |
| | SWAPFILE(swp_entry_t) | |
| | ZSWAP(struct zswap_entry*) | |
| +----------------------------+ |
+---------------------------------+
|
| SWAPFILE resolves to v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+
Case 2: direct-mapped physical entry (no vswap)
PTE PHYSICAL CLUSTER (swap_cluster_info)
phys_entry +--------------------------+
(swp_entry_t) ------>| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Bad - unusable |
+--------------------------+struct swap_cluster_info_dynamic {
struct swap_cluster_info ci; /* swap_table, lock, etc. */
unsigned int index; /* position in xarray */
struct rcu_head rcu; /* kfree_rcu deferred free */
atomic_long_t *virtual_table; /* backend info, 8 B/slot */};
Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate the backend type:
NONE: |----- 0000 ------|000| free / unbacked SWAPFILE: |- type:5,off:56 -|001| on a physical swapfile ZSWAP: |--- zswap_entry* |010| compressed in zswap
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. When CONFIG_VSWAP=n the vswap paths compile out.
* Backend transitions in the virtual_table are synchronized through the swap cache and the folio lock - the same mechanism that already serializes ordinary swap operations (swapin, swapout, zswap writeback, swap cache reclaim). IOW, we can only assume that the backend of a vswap entry is stable through swap cache/folio lock. Looking at the backend without this should be done at best for optimization purposes, as there is no guarantee that the backend will not change under the observer.
* Pointer-tagged swap_table entries on physical clusters provide the rmap (physical -> virtual) lookup.
* Virtual swap slots not backed by physical swap are not charged to memcg swap counters - only physical backing is charged (I made the case for this in [4]).
III. Benchmarks
===============
Note that the goal is not to match vswap performance with baseline on every single case yet - we still maintain !CONFIG_VSWAP setup. 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, CONFIG_VSWAP not set, to verify that there is no regression to existing swap paths when we disable vswap.
* VSS on: vswap series applied, CONFIG_VSWAP=y.
1. Memhog: single-threaded, 48GB allocation on a host with 16GB RAM, 20 rounds.
Baseline VSS off VSS on
real (s) 131.71 +/- 13.54 132.47 +/- 10.10 120.56 +/- 15.37 sys (s) 114.05 +/- 13.03 115.11 +/- 9.76 103.73 +/- 15.06 user (s) 10.86 +/- 0.13 10.97 +/- 0.10 10.87 +/- 0.11 delta real - +0.6% -8.5% delta sys - +0.9% -9.1%
Dropping the best and the worst round to reduce variance:
memhog Baseline VSS off VSS on
real (s) 130.24 +/- 8.56 131.51 +/- 5.82 119.39 +/- 12.06 sys (s) 112.58 +/- 7.88 114.26 +/- 5.74 102.63 +/- 11.83 user (s) 10.86 +/- 0.14 10.97 +/- 0.10 10.86 +/- 0.10 delta real - +1.0% -8.3% delta sys - +1.5% -8.8%
2. Usemem single-threaded: 56GB allocation on a host with 32GB RAM, 16 rounds.
Baseline VSS off VSS on
real (s) 177.14 +/- 7.34 178.20 +/- 5.12 175.83 +/- 6.96 sys (s) 125.30 +/- 7.47 125.19 +/- 5.18 124.09 +/- 7.07 tput (KB/s) 390668 +/- 16840 387878 +/- 11769 390921 +/- 15798 free (ms) 7739 +/- 125 7734 +/- 120 6572 +/- 121 delta real - +0.6% -0.7% delta sys - -0.1% -1.0% delta tput - -0.7% +0.1% delta free - -0.1% -15.1%
3. Kernel build: 52 workers (one per processor), memory.max=3GB, 10 rounds.
Baseline VSS off VSS on
real (s) 168.13 +/- 0.77 168.46 +/- 0.45 167.75 +/- 0.65 sys (s) 772.49 +/- 19.77 781.82 +/- 26.32 763.60 +/- 33.02 user (s) 5128.41 +/- 1.31 5130.64 +/- 1.67 5130.74 +/- 1.66 delta real - +0.2% -0.2% delta sys - +1.2% -1.1% delta user - +0.0% +0.0%
For zswap backend, vswap outperforms baseline on usemem freeing, and memhog benchmark, and is on par with baseline on the rest.
In the RFC v2 ([v2]), I put out several theories for this. I have done some prototyping to isolate effects, and it turns out the performance wins come primarily from the elimination of zswap's xarray and the merging of zswap's metadata to swap device's cluster. Several code paths are optimized thanks to this - for instance, in swap_range_free(), we call zswap_invalidate() once for each entry the range, resulting in multiple xarray tree walks. With vswap, we perform one single xarray walk to grab a 512-slot cluster, then performs a flat array scan to free zswap metadata. Similar wins can be observed in Baoquan's optimization ([8]), which also optimizes away the zswap tree.
IV. References
==============
[v1]: https://lore.kernel.org/all/[email protected]/
[v2]: 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/CAKEwX=P50av2rfocpsqZoDQowZ=EEhQ-5vj5tBykbNz8vtKTzA@mail.gmail.com/
[6]: https://lore.kernel.org/all/[email protected]/
[7]: https://lore.kernel.org/all/[email protected]/
[8]: https://lore.kernel.org/all/[email protected]/
Appendix: Alternative Designs and Improvements
==============================================
A. Vmalloc Data Structure:
==========================
This is a promising alternative to the xarray data structure, reducing the indirection overhead. The initial version relies on userspace knob to trigger swap address space growth - I have commented on why this is shaky in [5].
Baoquan has followed-up with a new version (see [6]) that should give us kernel-driven dynamic growth and (tail-only) shrink. This seems sufficient for vswap use case, AFAICT - but seems like it would need a couple more versions to finalize the design.
I think it is better to proceed with the xarray data structure first, especially since we already see some positive signals on performance by storing zswap metadata in a per-cluster flat table. With vswap landed, we will have a concrete setup to show vmalloc data structure's wins.
B. Moving the backend table to struct swap_cluster_info
=======================================================
Another approach Baoquan and I discussed on is to structure vswap patch series as follows:
1. Moving vtable (renamed to something more generic) to swap cluster, which removes the xarray.
2. Once vswap is introduced, we simply use this field to store the backend.
I have a prototype for this, but I ended up scrapping the whole thing, for the following reasons:
1. It ended up being even more code than what I sent out here - most of which touches the non-vswap code paths, which we either want to leave alone (generic swap logic) or want to rip out wholesale down the line (zswap).
2. There are several fields that are ONLY needed for the vswap clusters (for instance, rcu_head and index). Shoving them into the shared struct swap_cluster_info imposes memory and mental overhead for non-vswap clusters and users.
We can avoid this by simply moving it to the wrapper struct (swap_cluster_info_dynamic). This is actually Kairui's design (see [7]), but after trying to deviate from it, I have to conclude it is the right choice too.
3. Replacing zswap tree with the per-cluster backend table results in performance wins even when vswap is turned off (this is how I verified that vswap's performance wins comes from here).
However, it requires more code to make sure this table is not allocated when not needed. Note that the eventual goal is to make vswap the ONLY way to use zswap, so we are literally adding complexity and overhead (even for non-vswap users) to optimize for a code path that is rarely exercised after vswap lands, and will be ripped out soon after. That seems very off to me.
To close out, this design brings together the ideas from the earlier discussions:
1. All of the requirements I set out to solve (dynamicity, backend decoupling, efficient backend transfer) are implemented.
2. Vswap device now repurpose the swap table design and most of the generic swap operations.
3. Minimal overhead for non-vswap users, and zswap-no-writeback users. If you disable writeback, vswap *is* a ghost swapfile.
Nhat Pham (11):
mm, swap: add virtual swap device infrastructure
mm, swap: support zswap and zeroswap 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: widen swap_info_struct max/pages to unsigned long
Documentation/admin-guide/sysctl/vm.rst | 16 + MAINTAINERS | 1 + include/linux/memcontrol.h | 5 + include/linux/swap.h | 88 +- include/linux/zswap.h | 3 + mm/Kconfig | 21 + mm/memcontrol.c | 166 +++- mm/memory.c | 28 +- mm/page_io.c | 103 +- mm/shmem.c | 4 +- mm/swap.h | 55 +- mm/swap_state.c | 64 +- mm/swap_table.h | 62 ++ mm/swapfile.c | 1194 +++++++++++++++++++++-- mm/vmscan.c | 14 +- mm/vswap.h | 454 +++++++++ mm/zswap.c | 140 ++- 17 files changed, 2207 insertions(+), 211 deletions(-) create mode 100644 mm/vswap.h
base-commit: bacc32cc7de65ffff70080a48eb294f89e434d5e --
2.53.0-Meta
Nhat Pham
maintainerPATCH v3 1/11 mm, swap: add virtual swap device infrastructure
Create a 16 TB virtual swap device at boot, 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.
Gated by a new CONFIG_VSWAP (depends on SWAP && 64BIT). For now the vswap device cannot be swapon'd or swapoff'd. It is created unconditionally at boot when CONFIG_VSWAP=y and lives for the lifetime of the kernel. The SWP_VSWAP flag and swap_is_vswap() helper let hot paths skip per-device bookkeeping that doesn't apply (avail-list management, percpu_ref get/put, hibernation target lookup, etc.).
This patch is pure scaffolding. It wires the dynamic-cluster allocator into cluster_alloc_swap_entry (via an SWP_VSWAP branch that dispatches to alloc_swap_scan_dynamic), but the branch is not yet reachable because vswap_si is kept off swap_avail_head and swap_active_head and folio_alloc_swap has no path that calls into vswap_si directly. Backends (zswap, zero, physical disk) and the vswap-aware swap-out / swap-in / writeback paths arrive in subsequent patches.
--- MAINTAINERS | 1 + include/linux/swap.h | 16 +++ mm/Kconfig | 10 ++ mm/page_io.c | 15 +++ mm/swap.h | 47 ++++++-- mm/swap_state.c | 41 ++++--- mm/swap_table.h | 2 + mm/swapfile.c | 270 +++++++++++++++++++++++++++++++++++++++---- mm/vswap.h | 31 +++++ mm/zswap.c | 6 + 10 files changed, 396 insertions(+), 43 deletions(-) create mode 100644 mm/vswap.h
MAINTAINERS +1 -0
@@ -17248,6 +17248,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 +16 -0
@@ -207,6 +207,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... */ };
@@ -276,8 +277,21 @@ 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 */ }; +#ifdef CONFIG_VSWAP +static inline bool swap_is_vswap (struct swap_info_struct *si) +{ +return si->flags &SWP_VSWAP ; +} +#else +static inline bool swap_is_vswap (struct swap_info_struct *si) +{ +return false; +} +#endif +static inline swp_entry_t page_swap_entry (struct page *page) {struct folio *folio =page_folio (page);
@@ -402,6 +416,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 +10 -0
@@ -19,6 +19,16 @@ menuconfig SWAP used to provide more virtual memory than the actual RAM present in your computer. If unsure say Y. +config VSWAP + bool "Virtual swap device" + depends on SWAP && 64BIT + help + Adds a virtual swap layer that decouples swap entries in page + tables from physical backing storage. Swap entries are allocated + from a virtual swap device and can be backed by zswap, a physical + swapfile, or kept in memory - with the backing changeable at + runtime without invalidating page table entries. + config ZSWAP bool "Compressed cache for swap pages" depends on SWAP
mm/page_io.c +15 -0
@@ -27,6 +27,7 @@#include <linux/zswap.h> #include "swap.h" #include "swap_table.h" +#include "vswap.h" int generic_swapfile_activate(struct swap_info_struct *sis, struct file *swap_file,
@@ -247,6 +248,15 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio) }rcu_read_unlock (); +/* +* A vswap folio that reaches here could not be stored to a backend +* (zswap) and has no physical slot to write to, so keep it dirty. +*/ +if (is_vswap_entry (folio->swap)) { +folio_mark_dirty (folio); +return AOP_WRITEPAGE_ACTIVATE ; + } +__swap_writepage (ctx, folio);return 0 ; out_unlock:
@@ -479,6 +489,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 +40 -7
88 lines not on this page · raw message
mm/swap_state.c +27 -14
113 lines not on this page · raw message
mm/swap_table.h +2 -0
@@ -255,6 +255,8 @@ static inline unsigned long swap_table_get(struct swap_cluster_info *ci,unsigned long swp_tb;VM_WARN_ON_ONCE (off >=SWAPFILE_CLUSTER ); +if (!ci) +return SWP_TB_NULL ;rcu_read_lock (); table =rcu_dereference (ci->table);
mm/swapfile.c +248 -22
492 lines not on this page · raw message
mm/vswap.h new file +31 -0
@@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Virtual swap space +* +* Copyright (C) 2026 Nhat Pham +*/ +#ifndef _MM_VSWAP_H +#define _MM_VSWAP_H + +#include <linux/swap.h> +#include "swap.h" + +#ifdef CONFIG_VSWAP + +extern struct swap_info_struct *vswap_si; + +static inline bool is_vswap_entry (swp_entry_t entry) +{ +return swap_is_vswap (__swap_entry_to_info (entry)); +} + +#else + +static inline bool is_vswap_entry (swp_entry_t entry) +{ +return false; +} + +#endif /* CONFIG_VSWAP */ + +#endif /* _MM_VSWAP_H */
mm/zswap.c +6 -0
@@ -1000,6 +1000,12 @@ static int zswap_writeback_entry(struct zswap_entry *entry,if (!si)return -EEXIST ; +/* 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
Johannes Weiner
maintainerRe: [PATCH v3 01/11] mm, swap: add virtual swap device infrastructure
Hello Nhat,
This looks pretty clean to me overall. Nice. A few comments inline:
include/linux/swap.h struct swap_info_struct { · line 288
Quoted 13 lines · Nhat Pham
include/linux/swap.h +7
-0@@ -276,8 +277,21 @@ 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 */ }; +#ifdef CONFIG_VSWAP +static inline bool swap_is_vswap (struct swap_info_struct *si) +{ +return si->flags &SWP_VSWAP ; +} +#else
I think what could make sense is have
- CONFIG_VSWAP
- CONFIG_VSWAP_DEFAULT_ENABLED
- a boot flag that's = CONFIG_VSWAP_DEFAULT_ENABLED
Then you can use jump labels to cut runtime overhead to 0 if it isn't enabled at boot.
This way distributions can ship it with no overhead out of the box, while allowing users to opt in for early testing.
IMO this is more valuable than a runtime toggle.
It should be part of this patch if you add it.
Quoted 25 lines
include/linux/swap.h +8
-0+static inline bool swap_is_vswap (struct swap_info_struct *si) +{ +return false; +} +#endif +static inline swp_entry_t page_swap_entry (struct page *page) {struct folio *folio =page_folio (page);@@ -402,6 +416,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 +0
-0@@ -19,6 +19,16 @@ menuconfig SWAP used to provide more virtual memory than the actual RAM present in your computer. If unsure say Y.
mm/Kconfig menuconfig SWAP · line 30
Quoted 10 lines
mm/Kconfig +9
-0+config VSWAP + bool "Virtual swap device" + depends on SWAP && 64BIT + help + Adds a virtual swap layer that decouples swap entries in page + tables from physical backing storage. Swap entries are allocated + from a virtual swap device and can be backed by zswap, a physical + swapfile, or kept in memory - with the backing changeable at + runtime without invalidating page table entries.
IMO this is difficult for a user to decide.
If we want to make this as a config, then IMO the help text should be about not requiring a swapfile to use zswap, zerofill pages etc.
From where I'm standing, though, this code is no longer a separate vswap.c feature like it used to be. It's pretty integrated into the swapcode, and it looks like a good chunk of the core datastructures aren't conditional either.
At that point, the usefulness of the config option is limited. If you go with the jump label and there is no runtime overhead, it might make sense to just keep the option on what the JL should default to.
Quoted 9 lines
mm/Kconfig +2
-1@@ -143,9 +150,19 @@ static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry) static inline struct swap_cluster_info *__swap_offset_to_cluster( struct swap_info_struct *si, pgoff_t offset) { + unsigned int cluster_idx = offset / SWAPFILE_CLUSTER; + VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ VM_WARN_ON_ONCE(offset >= roundup(si->max, SWAPFILE_CLUSTER)); - return &si->cluster_info[offset / SWAPFILE_CLUSTER];
mm/Kconfig static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry) · line 166
Quoted 10 lines
mm/Kconfig +9
-0+ + if (swap_is_vswap(si)) { + struct swap_cluster_info_dynamic *ci_dyn; + + ci_dyn = xa_load(&si->cluster_info_pool, cluster_idx); + return ci_dyn ? &ci_dyn->ci : NULL; + } + + return &si->cluster_info[cluster_idx]; }
This now requires rcu. IMO a kdoc explaining that would be good.
mm/Kconfig static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info * · line 773
Quoted 10 lines
mm/Kconfig +5
-0@@ -733,6 +765,11 @@ static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info * return; } + if (swap_is_vswap(si)) { + vswap_free_cluster(si, ci); + return; + } + __free_cluster(si, ci);
Should this be part of __free_cluster() instead?
- swap_cluster_assert_empty() seems useful.
- move_cluster() handles the list linkage and could do the list_del().
- swap_cluster_free_table() is the same.
The other caller is the discard path. That one isn't relevant, but it shouldn't hurt. The layering would still be a bit cleaner this way.
Quoted 11 lines
mm/Kconfig +2
-1@@ -835,14 +872,21 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, * stolen by a lower order). @usable will be set to false if that happens. */ static bool cluster_reclaim_range(struct swap_info_struct *si, - struct swap_cluster_info *ci, + struct swap_cluster_info **pcip, unsigned long start, unsigned int order, bool *usable) { + struct swap_cluster_info *ci = *pcip; unsigned int nr_pages = 1 << order;
mm/Kconfig static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, · line 890
Quoted 10 lines
mm/Kconfig +6
-0unsigned long offset = start, end = start + nr_pages; unsigned long swp_tb; + /* + * Take RCU read lock before releasing the cluster lock to keep ci + * alive - for vswap dynamic clusters, ci is freed via kfree_rcu + * and the grace period could otherwise elapse in the window. + */ + rcu_read_lock(); spin_unlock(&ci->lock);
Since you replace the naked spin_lock() below with swap_cluster_lock(), change this to swap_cluster_unlock() as well?
Quoted 21 lines
mm/Kconfig +9
-1do { swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);@@ -852,7 +896,15 @@ static bool cluster_reclaim_range(struct swap_info_struct *si, if (__try_to_reclaim_swap(si, offset, TTRS_ANYWAY) < 0) break; } while (++offset < end); - spin_lock(&ci->lock); + rcu_read_unlock(); + + /* Re-lookup: dynamic cluster may have been freed while lock was dropped */ + ci = swap_cluster_lock(si, start); + *pcip = ci; + if (!ci) { + *usable = false; + return false; + } /* * We just dropped ci->lock so cluster could be used by another
mm/Kconfig static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, · line 1246
Quoted 8 lines
mm/Kconfig +5
-0@@ -1146,6 +1239,12 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, goto done; } + if (swap_is_vswap(si)) { + found = alloc_swap_scan_dynamic(si, folio); + if (found) + goto done; + }
The name and the composability look off to me.
Can you make this a pure allocation function - vswap_alloc_cluster() or something - that links it to &si->free_clusters, then jump back and use the existing alloc_swap_scan_list() sites?
There is a new_cluster: label upstream you could use for the retry.
Quoted 5 lines
mm/Kconfig +1
-0+ if (!(si->flags & SWP_PAGE_DISCARD)) { found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); if (found)
mm/Kconfig static void add_to_avail_list(struct swap_info_struct *si, bool swapon) · line 1371
Quoted 9 lines
mm/Kconfig +6
-0@@ -1264,6 +1363,13 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon) goto skip; } + /* + * Keep vswap off the avail list - it is not allocated from by + * the physical swap allocator (swap_alloc_fast/slow). + */ + if (swap_is_vswap(si)) + goto skip;
This is describing what the code does, followed by a why not.
Describe the why: Vswap space is only allocated through [...], not [...]
Quoted 13 lines
mm/Kconfig +5
-1@@ -3528,10 +3668,43 @@ static int setup_swap_clusters_info(struct swap_info_struct *si, unsigned long maxpages) { unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); - struct swap_cluster_info *cluster_info; + struct swap_cluster_info *cluster_info = NULL; + struct swap_cluster_info_dynamic *ci_dyn; int err = -ENOMEM; unsigned long i; + /* For SWP_VSWAP files, initialize Xarray pool instead of static array */ + if (swap_is_vswap(si)) { + /*
mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3688
Quoted 10 lines
mm/Kconfig +10
-0+ * Pre-allocate cluster 0 and mark slot 0 (header page) + * as bad so the allocator never hands out page offset 0. + */ + ci_dyn = kzalloc_obj(*ci_dyn, GFP_KERNEL); + if (!ci_dyn) + goto err; + spin_lock_init(&ci_dyn->ci.lock); + INIT_LIST_HEAD(&ci_dyn->ci.list); + + nr_clusters = 0;
But it's one, not zero. And only the first slot is bad. Why is the rest not usable and the cluster on the nonfull_clusters list?
I think you can make the integration a bit more organic in general:
Don't do the DIV_ROUND_UP per default only to overwrite it here again e.g.
If you come out of this branch with cluster_info == &ci_dyn->ci, you should be able to reuse the existing swap_cluster_setup_bad_slot(0).
swap_header && i < swap_header->info.nr_badpages should skip that loop as well.
Your maxpages is SWAPFILE_CLUSTER aligned, so that
for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) {loop is skipped as well.
mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3700
Quoted 12 lines
mm/Kconfig +12
-0+ xa_init_flags(&si->cluster_info_pool, XA_FLAGS_ALLOC); + err = xa_insert(&si->cluster_info_pool, 0, ci_dyn, GFP_KERNEL); + if (err) { + kfree(ci_dyn); + goto err; + } + + err = swap_cluster_setup_bad_slot(si, &ci_dyn->ci, 0, false); + if (err) { + xa_erase(&si->cluster_info_pool, 0); + swap_cluster_free_table(&ci_dyn->ci); + kfree(ci_dyn);
IMO it would be nicer to make this part of free_swap_cluster_info() instead of duplicating it.
mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3701
Quoted 1 line
mm/Kconfig +1
-0+ xa_destroy(&si->cluster_info_pool);
That one probably doesn't matter. If these allocations fail at boot, the system is in trouble.
Quoted 10 lines
mm/Kconfig +6
-0+ goto err; + } + + goto setup_cluster_info; + } + cluster_info = kvzalloc_objs(*cluster_info, nr_clusters); if (!cluster_info) goto err;
mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3734
Quoted 6 lines
mm/Kconfig +3
-0@@ -3556,6 +3729,10 @@ static int setup_swap_clusters_info(struct swap_info_struct *si, err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false); if (err) goto err; + + if (!swap_header) + goto setup_cluster_info;
Is this reachable?
Quoted 14 lines
mm/Kconfig +10
-0@@ -3949,3 +4127,51 @@ static int __init swapfile_init(void) return 0; } subsys_initcall(swapfile_init); + +#ifdef CONFIG_VSWAP +struct swap_info_struct *vswap_si; + +/* vswap does no IO on its own. */ +static const struct swap_ops vswap_ops = { }; + +static int __init vswap_init(void) +{ + struct swap_info_struct *si;
mm/Kconfig static int __init swapfile_init(void) · line 4149
Quoted 10 lines
mm/Kconfig +10
-0+ unsigned long maxpages; + int err; + + si = alloc_swap_info(); + if (IS_ERR(si)) + return PTR_ERR(si); + + maxpages = min(swapfile_maximum_size, + ALIGN_DOWN((unsigned long)UINT_MAX, SWAPFILE_CLUSTER)); + si->flags |= SWP_VSWAP | SWP_SOLIDSTATE | SWP_WRITEOK;
Please add a comment on the flag choices besides SWP_VSWAP.
Nhat Pham
maintainerRe: [PATCH v3 01/11] mm, swap: add virtual swap device infrastructure
On Fri, Aug 7, 2026 at 8:49 AM Johannes Weiner <[email protected]> wrote:
Hi Johannes,
My apologies for the delayed response. I saw and read your email, but I wanted to stew on it, code things out, and stare at things before responding.
I think most of our suggestions here make sense. I coded most of them out already, and I'm stress testing them - will report back if there are surprises.
Quoted 29 lines
Hello Nhat,
This looks pretty clean to me overall. Nice. A few comments inline:
include/linux/swap.h struct swap_info_struct { · line 288
Quoted 13 lines · Nhat Pham
include/linux/swap.h +7
-0@@ -276,8 +277,21 @@ 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 */ }; +#ifdef CONFIG_VSWAP +static inline bool swap_is_vswap (struct swap_info_struct *si) +{ +return si->flags &SWP_VSWAP ; +} +#else I think what could make sense is have
-
CONFIG_VSWAP
-CONFIG_VSWAP_DEFAULT_ENABLED
- a boot flag that's =CONFIG_VSWAP_DEFAULT_ENABLEDThen you can use jump labels to cut runtime overhead to 0 if it isn't enabled at boot.
Quoted 6 lines
This way distributions can ship it with no overhead out of the box, while allowing users to opt in for early testing.
IMO this is more valuable than a runtime toggle.
It should be part of this patch if you add it.
I've been thinking about this and your other suggestions regarding removing CONFIG_VSWAP. I've coded them out - it does indeed look cleaner :)
Let me test things first to make sure I did not introduce some weird bugs, but to recap:
1. CONFIG_VSWAP gone (along with most of the !CONFIG_VSWAP stubs, saving 100 LoCs or so).
2. Runtime param gone, replaced by a boot param.
3. CONFIG_VSWAP_DEFAULT_ENABLED only decides the default value of the boot param (still gated by 64bit config).
4. If we detect that the system is 32 bit, we ignore bootparam selection by users (with a small warn).
If the boot param is false (either because of user selection, the build config, or because the system is 32 bit), we don't allocate the vswap device, and bypass all vswap code paths. There should be negligible overhead here.
Quoted 64 lines
Quoted 26 lines
include/linux/swap.h +8
-0+static inline bool swap_is_vswap (struct swap_info_struct *si) +{ +return false; +} +#endif +static inline swp_entry_t page_swap_entry (struct page *page) {struct folio *folio =page_folio (page);@@ -402,6 +416,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 +0
-0@@ -19,6 +19,16 @@ menuconfig SWAP used to provide more virtual memory than the actual RAM present in your computer. If unsure say Y.mm/Kconfig menuconfig SWAP · line 30
Quoted 10 lines
mm/Kconfig +9
-0+config VSWAP + bool "Virtual swap device" + depends on SWAP && 64BIT + help + Adds a virtual swap layer that decouples swap entries in page + tables from physical backing storage. Swap entries are allocated + from a virtual swap device and can be backed by zswap, a physical + swapfile, or kept in memory - with the backing changeable at + runtime without invalidating page table entries.IMO this is difficult for a user to decide.
If we want to make this as a config, then IMO the help text should be about not requiring a swapfile to use zswap, zerofill pages etc.
From where I'm standing, though, this code is no longer a separate
vswap.cfeature like it used to be. It's pretty integrated into the swapcode, and it looks like a good chunk of the core datastructures aren't conditional either.At that point, the usefulness of the config option is limited. If you go with the jump label and there is no runtime overhead, it might make sense to just keep the option on what the JL should default to.
Quoted 13 lines
mm/Kconfig +6
-1@@ -143,9 +150,19 @@ static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry) static inline struct swap_cluster_info *__swap_offset_to_cluster( struct swap_info_struct *si, pgoff_t offset) { + unsigned int cluster_idx = offset / SWAPFILE_CLUSTER; + VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ VM_WARN_ON_ONCE(offset >= roundup(si->max, SWAPFILE_CLUSTER)); - return &si->cluster_info[offset / SWAPFILE_CLUSTER]; + + if (swap_is_vswap(si)) { + struct swap_cluster_info_dynamic *ci_dyn; +
Quoted 8 lines
mm/Kconfig static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry) · line 166
Quoted 6 lines
mm/Kconfig +5
-0+ ci_dyn = xa_load(&si->cluster_info_pool, cluster_idx); + return ci_dyn ? &ci_dyn->ci : NULL; + } + + return &si->cluster_info[cluster_idx]; }This now requires rcu. IMO a kdoc explaining that would be good.
Good point yeah.
Quoted 14 lines
mm/Kconfig static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info * · line 773
Quoted 11 lines
mm/Kconfig +5
-0@@ -733,6 +765,11 @@ static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info * return; } + if (swap_is_vswap(si)) { + vswap_free_cluster(si, ci); + return; + } + __free_cluster(si, ci);Should this be part of
__free_cluster()instead?
Quoted 6 lines
-
swap_cluster_assert_empty()seems useful.
-move_cluster()handles the list linkage and could do thelist_del().
-swap_cluster_free_table()is the same.The other caller is the discard path. That one isn't relevant, but it shouldn't hurt. The layering would still be a bit cleaner this way.
I think this should work.
Quoted 15 lines
Quoted 15 lines
mm/Kconfig +2
-1@@ -835,14 +872,21 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, * stolen by a lower order). @usable will be set to false if that happens. */ static bool cluster_reclaim_range(struct swap_info_struct *si, - struct swap_cluster_info *ci, + struct swap_cluster_info **pcip, unsigned long start, unsigned int order, bool *usable) { + struct swap_cluster_info *ci = *pcip; unsigned int nr_pages = 1 << order; unsigned long offset = start, end = start + nr_pages; unsigned long swp_tb;
Quoted 10 lines
mm/Kconfig static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, · line 890
Quoted 7 lines
mm/Kconfig +6
-0+ /* + * Take RCU read lock before releasing the cluster lock to keep ci + * alive - for vswap dynamic clusters, ci is freed via kfree_rcu + * and the grace period could otherwise elapse in the window. + */ + rcu_read_lock(); spin_unlock(&ci->lock);Since you replace the naked
spin_lock()below withswap_cluster_lock(), change this toswap_cluster_unlock()as well?
Good point in the renaming, yeah.
On a related note, I'm thinking of just removing this piece of code in cluster_reclaim_range(). We have no signal to trigger cluster_reclaim_range() (i.e swap-cache-only reclamation) for vswap clusters, and vswap (similar to swap-sync-io devices such as zram) already try to free swap slots (and swap cache) when the last PTE reference of the swap entry is dropped. I don't think this code path is triggered at all in my benchmarks.
Let's keep cluster_reclaim_range() for phys swap device only.
Quoted 33 lines
Quoted 22 lines
mm/Kconfig +9
-1do { swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);@@ -852,7 +896,15 @@ static bool cluster_reclaim_range(struct swap_info_struct *si, if (__try_to_reclaim_swap(si, offset, TTRS_ANYWAY) < 0) break; } while (++offset < end); - spin_lock(&ci->lock); + rcu_read_unlock(); + + /* Re-lookup: dynamic cluster may have been freed while lock was dropped */ + ci = swap_cluster_lock(si, start); + *pcip = ci; + if (!ci) { + *usable = false; + return false; + } /* * We just dropped ci->lock so cluster could be used by anothermm/Kconfig static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, · line 1246
Quoted 8 lines
mm/Kconfig +5
-0@@ -1146,6 +1239,12 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, goto done; } + if (swap_is_vswap(si)) { + found = alloc_swap_scan_dynamic(si, folio); + if (found) + goto done; + }The name and the composability look off to me.
Quoted 3 lines
Can you make this a pure allocation function -
vswap_alloc_cluster()or something - that links it to&si->free_clusters, then jump back and use the existingalloc_swap_scan_list()sites?
That name was vestigial from Kairui's RFC, but yeah I agree vswap_alloc_cluster sounds better.
Regarding the linkage of the newly allocated cluster to the free list
- I'm a bit hesitant to introduce new surface for these clusters, mostly because I'm afraid I might mess up the handling of these clusters (when I unlink them from the free list), but I can give it a shot.
Quoted 124 lines
There is a
new_cluster: label upstream you could use for the retry.Quoted 5 lines
mm/Kconfig +1
-0+ if (!(si->flags & SWP_PAGE_DISCARD)) { found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); if (found)mm/Kconfig static void add_to_avail_list(struct swap_info_struct *si, bool swapon) · line 1371
Quoted 9 lines
mm/Kconfig +6
-0@@ -1264,6 +1363,13 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon) goto skip; } + /* + * Keep vswap off the avail list - it is not allocated from by + * the physical swap allocator (swap_alloc_fast/slow). + */ + if (swap_is_vswap(si)) + goto skip;This is describing what the code does, followed by a why not.
Describe the why: Vswap space is only allocated through [...], not [...]
Quoted 13 lines
mm/Kconfig +5
-1@@ -3528,10 +3668,43 @@ static int setup_swap_clusters_info(struct swap_info_struct *si, unsigned long maxpages) { unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); - struct swap_cluster_info *cluster_info; + struct swap_cluster_info *cluster_info = NULL; + struct swap_cluster_info_dynamic *ci_dyn; int err = -ENOMEM; unsigned long i; + /* For SWP_VSWAP files, initialize Xarray pool instead of static array */ + if (swap_is_vswap(si)) { + /*mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3688
Quoted 10 lines
mm/Kconfig +10
-0+ * Pre-allocate cluster 0 and mark slot 0 (header page) + * as bad so the allocator never hands out page offset 0. + */ + ci_dyn = kzalloc_obj(*ci_dyn, GFP_KERNEL); + if (!ci_dyn) + goto err; + spin_lock_init(&ci_dyn->ci.lock); + INIT_LIST_HEAD(&ci_dyn->ci.list); + + nr_clusters = 0;But it's one, not zero. And only the first slot is bad. Why is the rest not usable and the cluster on the
nonfull_clusterslist?I think you can make the integration a bit more organic in general:
Don't do the
DIV_ROUND_UPper default only to overwrite it here again e.g.If you come out of this branch with
cluster_info==&ci_dyn->ci, you should be able to reuse the existingswap_cluster_setup_bad_slot(0).
swap_header&& i <swap_header->info.nr_badpagesshould skip that loop as well.Your maxpages is
SWAPFILE_CLUSTERaligned, so thatfor (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) {loop is skipped as well.
mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3700
Quoted 12 lines
mm/Kconfig +12
-0+ xa_init_flags(&si->cluster_info_pool, XA_FLAGS_ALLOC); + err = xa_insert(&si->cluster_info_pool, 0, ci_dyn, GFP_KERNEL); + if (err) { + kfree(ci_dyn); + goto err; + } + + err = swap_cluster_setup_bad_slot(si, &ci_dyn->ci, 0, false); + if (err) { + xa_erase(&si->cluster_info_pool, 0); + swap_cluster_free_table(&ci_dyn->ci); + kfree(ci_dyn);IMO it would be nicer to make this part of
free_swap_cluster_info()instead of duplicating it.mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3701
Quoted 1 line
mm/Kconfig +1
-0+ xa_destroy(&si->cluster_info_pool);That one probably doesn't matter. If these allocations fail at boot, the system is in trouble.
Quoted 10 lines
mm/Kconfig +6
-0+ goto err; + } + + goto setup_cluster_info; + } + cluster_info = kvzalloc_objs(*cluster_info, nr_clusters); if (!cluster_info) goto err;mm/Kconfig static int setup_swap_clusters_info(struct swap_info_struct *si, · line 3734
Quoted 6 lines
mm/Kconfig +3
-0@@ -3556,6 +3729,10 @@ static int setup_swap_clusters_info(struct swap_info_struct *si, err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false); if (err) goto err; + + if (!swap_header) + goto setup_cluster_info;Is this reachable?
Quoted 18 lines
mm/Kconfig +14
-0@@ -3949,3 +4127,51 @@ static int __init swapfile_init(void) return 0; } subsys_initcall(swapfile_init); + +#ifdef CONFIG_VSWAP +struct swap_info_struct *vswap_si; + +/* vswap does no IO on its own. */ +static const struct swap_ops vswap_ops = { }; + +static int __init vswap_init(void) +{ + struct swap_info_struct *si; + unsigned long maxpages; + int err; + + si = alloc_swap_info();
Quoted 8 lines
mm/Kconfig static int __init swapfile_init(void) · line 4149
Quoted 6 lines
mm/Kconfig +6
-0+ if (IS_ERR(si)) + return PTR_ERR(si); + + maxpages = min(swapfile_maximum_size, + ALIGN_DOWN((unsigned long)UINT_MAX, SWAPFILE_CLUSTER)); + si->flags |= SWP_VSWAP | SWP_SOLIDSTATE | SWP_WRITEOK;Please add a comment on the flag choices besides
SWP_VSWAP.
Will do yeah. I tend to forget them myself too :) SWP_SOLIDSTATE is mostly to opt-in to the cluster-based allocaiton algo. SWP_WRITEOK is checked in a couple of places to allow allocation.
Nhat Pham
maintainerRe: [PATCH v3 01/11] mm, swap: add virtual swap device infrastructure
Quoted 6 lines · Nhat Pham
Quoted 5 lines
Can you make this a pure allocation function -
vswap_alloc_cluster()or something - that links it to&si->free_clusters, then jump back and use the existingalloc_swap_scan_list()sites?
Quoted 11 lines
That name was vestigial from Kairui's RFC, but yeah I agree
vswap_alloc_clustersounds better.Regarding the linkage of the newly allocated cluster to the free list
- I'm a bit hesitant to introduce new surface for these clusters, mostly because I'm afraid I might mess up the handling of these clusters (when I unlink them from the free list), but I can give it a shot.Quoted 2 lines
There is a
new_cluster: label upstream you could use for the retry.
Actually, I stared at it a bit more. I don't think we should jump to new_cluster here - it's not what physical swap allocator does in the first place (we never do any backward jump to retry).
So basically, this is the old code:
new_cluster:
if (discard)
alloc_swap_scan_list(free list); /* not taken by vswap */
if (alloc_swap_scan_list(nonfull)) return;
/*
* Added by me. vswap (almost) always succeeds here */
if (alloc_swap_scan_dynamic()) return;
/*
* not taken by vswap, because we succeeds above
* and free list is always empty.
*/
if (not discard)
alloc_swap_scan_list(free list);
/* if free list scan fail, keep going */
etc. etc.
The new code becomes:
new_cluster:
if (discard)
alloc_swap_scan_list(free list) /* still not taken by vswap */
if (alloc_swap_scan_list(nonfull)) return;
/* vswap puts new cluster into free list, then falls through */ if (si is vswap)
vswap_cluster_alloc();
/* vswap now scans free list to get the cluster it just allocated */ if (not discard)
alloc_swap_scan_list(free list)
/* if free list scan fail, keep going */
This works, but I'm not sure if putting the new cluster on free list buy us much other than more lock contention points (we need si->lock to scan free list) :/
I'll just rename alloc_swap_scan_dynamic to vswap_cluster_alloc(), for now?
Nhat Pham
maintainerPATCH v3 2/11 mm, swap: support zswap and zeroswap as vswap backends
In reply to Nhat PhamBuild the virtual swap layer on top of the swap-table infrastructure. Virtual swap entries decouple PTE swap entries from physical backing, allowing pages to be compressed by zswap (or detected as zero-filled) without pre-allocating a physical swap slot.
This patch only supports zswap and zero-page backends. If zswap_store fails, the page stays dirty in the swap cache. Physical disk backing arrives in the next patch.
Zswap writeback of vswap-backed entries is also disabled: they have no physical slot to write back to yet, so the zswap shrinker (both the dynamic count path and the pool-full worker path) is skipped while vswap is enabled. Physical backing and real writeback come in later patches.
THP swapin is disabled for vswap entries for now.
Add a /proc/sys/vm/vswap_enabled sysctl and a CONFIG_VSWAP_DEFAULT_ON build option so vswap allocation can be enabled and disabled at runtime, defaulting off unless CONFIG_VSWAP_DEFAULT_ON=y. The knob only gates vswap_alloc(), so existing virtual entries keep resolving their backend and drain naturally when it is turned off.
--- Documentation/admin-guide/sysctl/vm.rst | 16 ++ include/linux/zswap.h | 3 + mm/Kconfig | 11 ++ mm/memcontrol.c | 8 + mm/memory.c | 18 +- mm/page_io.c | 12 +- mm/shmem.c | 4 +- mm/swap.h | 1 + mm/swap_state.c | 8 + mm/swapfile.c | 242 ++++++++++++++++++++++-- mm/vmscan.c | 14 +- mm/vswap.h | 206 +++++++++++++++++++- mm/zswap.c | 56 ++++-- 13 files changed, 561 insertions(+), 38 deletions(-)
Documentation/admin-guide/sysctl/vm.rst +16 -0
@@ -74,6 +74,7 @@ Currently, these files are in /proc/sys/vm: - user_reserve_kbytes - vfs_cache_pressure - vfs_cache_pressure_denom +- vswap_enabled - watermark_boost_factor - watermark_scale_factor - zone_reclaim_mode
@@ -1152,6 +1153,21 @@ vfs_cache_pressure_denom Defaults to 100 (minimum allowed value). Requires corresponding vfs_cache_pressure setting to take effect. +vswap_enabled +============= + +Controls whether new swapouts are routed through the virtual swap layer +(only present when the kernel is built with CONFIG_VSWAP). Set to 1 to +route swapouts through vswap, 0 to send them straight to the physical +swap device. + +The default is 0 unless the kernel was built with +CONFIG_VSWAP_DEFAULT_ON=y. + +Disabling is allocation-only: it only stops new swapouts from using +vswap. Swap entries already backed by vswap keep being served and drain +naturally as they are faulted back in or freed. + watermark_boost_factor ======================
include/linux/zswap.h +3 -0
@@ -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 (swp_entry_t swp); +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);
@@ -50,6 +52,7 @@ static inline int zswap_load(struct folio *folio) }static inline void zswap_invalidate (swp_entry_t swp) {} +static inline void zswap_entry_free (struct zswap_entry *entry) {}static inline int zswap_swapon (int type,unsigned long nr_pages) {return 0 ;
mm/Kconfig +11 -0
@@ -29,6 +29,17 @@ config VSWAP swapfile, or kept in memory - with the backing changeable at runtime without invalidating page table entries. +config VSWAP_DEFAULT_ON + bool "Route swapouts through virtual swap by default" + depends on VSWAP + default n + help + Say Y to route swapouts through the virtual swap layer from + boot. + + Say N (default) to leave vswap off until it is enabled at + runtime via /proc/sys/vm/vswap_enabled. + config ZSWAP bool "Compressed cache for swap pages" depends on SWAP
mm/memcontrol.c +8 -0
@@ -65,6 +65,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"
@@ -5728,6 +5729,13 @@ long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg) {long nr_swap_pages =get_nr_swap_pages (); +/* +* vswap zswap-backed swapout needs no physical slot, so gate anon +* reclaim on the swap.max headroom instead of the physical free count. +*/ +if (vswap_is_enabled () &&zswap_is_enabled ()) + nr_swap_pages =PAGE_COUNTER_MAX ; +if (mem_cgroup_disabled () ||do_memsw_account ())return nr_swap_pages;for (; !mem_cgroup_is_root (memcg); memcg =parent_mem_cgroup (memcg))
mm/memory.c +13 -5
@@ -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.
@@ -4657,6 +4658,12 @@ static inline bool should_try_to_free_swap(struct swap_info_struct *si,*/ if (data_race (si->flags &SWP_SYNCHRONOUS_IO ))return true; +/* +* Non-swapfile backends cannot be reused for future swapouts. +* Free the swap slot unless backed by contiguous physical swap. +*/ +if (is_vswap_entry (folio->swap)) +return true;if (mem_cgroup_swap_full (folio) || (vma->vm_flags &VM_LOCKED ) ||folio_test_mlocked (folio))return true;
@@ -4805,15 +4812,16 @@ 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. Also, a large swapped +* out folio could be partially or fully in zswap, which we lack +* handling for. In both cases, fall back to order-0 swapin. */ -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
@@ -160,14 +160,19 @@ static void swap_zeromap_folio_set(struct folio *folio)struct obj_cgroup *objcg =get_obj_cgroup_from_folio (folio);int nr_pages =folio_nr_pages (folio);struct swap_cluster_info *ci; +unsigned int voff, i;swp_entry_t entry; -unsigned int 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++) { entry =page_swap_entry (folio_page (folio, i));__swap_table_set_zero (ci,swp_cluster_offset (entry)); }
@@ -235,6 +240,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
@@ -85,6 +85,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)
@@ -1617,7 +1618,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
@@ -70,6 +70,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
@@ -26,6 +26,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;
@@ -196,6 +197,13 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,if (nr ==1 )return 0 ; +/* +* THP swapin for vswap is not supported yet; reject the 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 +227 -15
409 lines not on this page · raw message
mm/vmscan.c +11 -3
@@ -68,6 +68,7 @@#include "internal.h" #include "page_alloc.h" #include "swap.h" +#include "vswap.h" #define CREATE_TRACE_POINTS #include <trace/events/vmscan.h>
@@ -352,6 +353,9 @@ static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,*/ if (get_nr_swap_pages () >0 )return true; +/* vswap doesn't contribute to nr_swap_pages */ +if (vswap_is_enabled () &&zswap_is_enabled ()) +return true; }else {/* Is the memcg below its swap limit? */ if (mem_cgroup_get_nr_swap_pages (memcg) >0 )
@@ -1521,9 +1525,13 @@ static unsigned int shrink_folio_list(struct list_head *folio_list, nr_pages =1 ; } activate_locked: -/* Not a candidate for swapping, so reclaim swap space. */ +/* +* Not a candidate for swapping, so reclaim physical swap +* space if we are running out. +*/ 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)) {
@@ -2680,7 +2688,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: */
mm/vswap.h +205 -1
226 lines not on this page · raw message
mm/zswap.c +45 -11
128 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
Youngjun Park
reviewerRe: [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
mm/swapfile.c swap_cluster_populate(struct swap_info_struct *si, · line 569
Quoted 10 lines · Nhat Pham
mm/swapfile.c +5
-1@@ -537,7 +562,12 @@ 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. */ -lockdep_assert_held (&this_cpu_ptr (&percpu_swap_cluster)->lock); +#ifdef CONFIG_VSWAP +if (swap_is_vswap (si)) +lockdep_assert_held (&this_cpu_ptr (&percpu_vswap_cluster)->lock); +#endif +if (!swap_is_vswap (si))
Hello Nhat
Does vswap actually come in at populate time?
For free clusters (dynamic ci),
isn't the cluster freed immediately rather than going through this path?
If it is right, then just validation seems good enough. (assure vswap does not come in)
Thanks
Youngjun
Nhat Pham
maintainerRe: [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
Quoted 16 lines · Youngjun Park
mm/swapfile.c swap_cluster_populate(struct swap_info_struct *si, · line 569
Quoted 10 lines · Nhat Pham
mm/swapfile.c +5
-1@@ -537,7 +562,12 @@ 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. */ -lockdep_assert_held (&this_cpu_ptr (&percpu_swap_cluster)->lock); +#ifdef CONFIG_VSWAP +if (swap_is_vswap (si)) +lockdep_assert_held (&this_cpu_ptr (&percpu_vswap_cluster)->lock); +#endif +if (!swap_is_vswap (si))Hello Nhat
Quoted 5 lines
Does vswap actually come in at populate time?
For free clusters (dynamic ci),
isn't the cluster freed immediately rather than going through this path?If it is right, then just validation seems good enough. (assure vswap does not come in)
Acked. You're right I think. This got me staring at the code along this direction, and I discovered another code path where I provisioned for vswap's sake unnecessarily (cluster_reclaim_range()) - will fix this in the next version.
Thanks for the review, Youngjun!
Quoted 4 lines
Thanks
Youngjun
Re: [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
In reply to Nhat PhamOn Thu, 6 Aug 2026 11:42:45 -0700 Nhat Pham <[email protected]> wrote:
Hi Nhat,
[...]
syzbot reported a NULL dereference in the v3 series:
__vtable_get()
vswap_to_phys()
swap_entry_backend_has_flag()Seems like the underlying issue is introduced by this patch's virtual_table lifetime management.
This patch adds:
mm/swap.h struct swap_cluster_info_dynamic { · line 74
Quoted 6 lines
mm/swap.h +1
-0@@ -70,6 +70,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 */ };
[...]
while the read side does:
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 103
Quoted 7 lines
mm/vswap.h +7
-0+static inline unsigned long __vtable_get (struct swap_cluster_info_dynamic *ci_dyn, +unsigned int off) +{ +VM_WARN_ON_ONCE (off >=SWAPFILE_CLUSTER ); +return atomic_long_read (&ci_dyn->virtual_table[off]); +} +
atomic_long_read() only makes the access atomic; it does not protect the lifetime of the allocation being accessed.
[...]
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 197
Quoted 4 lines
mm/vswap.h +4
-0+static inline void vswap_cluster_free_vtable (struct swap_cluster_info *ci) +{ +struct swap_cluster_info_dynamic *ci_dyn; +
and frees it synchronously:
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 202
Quoted 5 lines
mm/vswap.h +5
-0+ ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci); +kfree (ci_dyn->virtual_table); + ci_dyn->virtual_table =NULL ; +} +
The existing ci->table already has an RCU-aware lifetime: readers use the corresponding RCU access rules, and the storage is not freed until after the appropriate grace period. virtual_table introduced here does not have an equivalent lifetime rule.
The syzbot crash shows that the current teardown/read-side synchronization is insufficient: __vtable_get() can observe a torn-down virtual_table and dereference NULL.
I don't think a NULL check in __vtable_get() alone would be the right fix. The NULL dereference is a symptom of the missing lifetime guarantee. virtual_table needs to remain valid for as long as a reader can reach and access the corresponding dynamic cluster.
It probably makes sense to make virtual_table follow the same lifetime scheme as the existing cluster table, or otherwise tie its freeing to the lifetime of swap_cluster_info_dynamic.
[...]
Thanks,
KunWu
Nhat Pham
maintainerRe: [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
Quoted 58 lines · Kunwu Chan
On Thu, 6 Aug 2026 11:42:45 -0700 Nhat Pham <[email protected]> wrote:
Hi Nhat,
[...]
syzbot reported a NULL dereference in the v3 series:
__vtable_get()vswap_to_phys() swap_entry_backend_has_flag()Seems like the underlying issue is introduced by this patch's
virtual_tablelifetime management.This patch adds:
mm/swap.h struct swap_cluster_info_dynamic { · line 74
Quoted 6 lines
mm/swap.h +1
-0@@ -70,6 +70,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 */ };[...]
while the read side does:
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 103
Quoted 7 lines
mm/vswap.h +7
-0+static inline unsigned long __vtable_get (struct swap_cluster_info_dynamic *ci_dyn, +unsigned int off) +{ +VM_WARN_ON_ONCE (off >=SWAPFILE_CLUSTER ); +return atomic_long_read (&ci_dyn->virtual_table[off]); +} +
atomic_long_read()only makes the access atomic; it does not protect the lifetime of the allocation being accessed.[...]
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 197
Quoted 4 lines
mm/vswap.h +4
-0+static inline void vswap_cluster_free_vtable (struct swap_cluster_info *ci) +{ +struct swap_cluster_info_dynamic *ci_dyn; +and frees it synchronously:
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 202
Quoted 5 lines
mm/vswap.h +5
-0+ ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci); +kfree (ci_dyn->virtual_table); + ci_dyn->virtual_table =NULL ; +} +The existing
ci->tablealready has an RCU-aware lifetime: readers use the corresponding RCU access rules, and the storage is not freed until after the appropriate grace period.virtual_tableintroduced here does not have an equivalent lifetime rule.
Quoted 8 lines
The syzbot crash shows that the current teardown/read-side synchronization is insufficient:
__vtable_get()can observe a torn-downvirtual_tableand dereference NULL.I don't think a NULL check in
__vtable_get()alone would be the right fix. The NULL dereference is a symptom of the missing lifetime guarantee.virtual_tableneeds to remain valid for as long as a reader can reach and access the corresponding dynamic cluster.
Thanks for taking a look, Kunwu.
Null-check by itself is not sufficient, correct. But I think a full dance of: rcu read section + spin_lock + checking for CLUSTER_FLAG_DEAD should suffice. As long as cluster is valid inside this rcu read section, we can get the lock. Once we have the lock, no one can free the cluster under us. and as long as the "CLUSTER_FLAG_DEAD" flag checks out under the lock, we can exit the rcu_read_section(), and proceed with reading the vtable. I already fixed this in (to-be-sent) v4.
Note that this is actually only required where we don't have any reference pin. One example is the one syzbot detected phys swap device backend flag check, because at do_swap_time() we don't actually have any reference pins. The PTE is not locked, so swap entry can gets released underneath us. But if we have a pin - for e.g if we own the swap cache folio, then we don't really need this dance.
Re: [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
Quoted 71 lines · Nhat Pham
Quoted 58 lines · Kunwu Chan
On Thu, 6 Aug 2026 11:42:45 -0700 Nhat Pham <[email protected]> wrote:
Hi Nhat,
[...]
syzbot reported a NULL dereference in the v3 series:
__vtable_get()vswap_to_phys() swap_entry_backend_has_flag()Seems like the underlying issue is introduced by this patch's
virtual_tablelifetime management.This patch adds:
mm/swap.h struct swap_cluster_info_dynamic { · line 74
Quoted 6 lines
mm/swap.h +1
-0@@ -70,6 +70,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 */ };[...]
while the read side does:
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 103
Quoted 7 lines
mm/vswap.h +7
-0+static inline unsigned long __vtable_get (struct swap_cluster_info_dynamic *ci_dyn, +unsigned int off) +{ +VM_WARN_ON_ONCE (off >=SWAPFILE_CLUSTER ); +return atomic_long_read (&ci_dyn->virtual_table[off]); +} +
atomic_long_read()only makes the access atomic; it does not protect the lifetime of the allocation being accessed.[...]
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 197
Quoted 4 lines
mm/vswap.h +4
-0+static inline void vswap_cluster_free_vtable (struct swap_cluster_info *ci) +{ +struct swap_cluster_info_dynamic *ci_dyn; +and frees it synchronously:
mm/vswap.h static inline bool is_vswap_entry(swp_entry_t entry) · line 202
Quoted 5 lines
mm/vswap.h +5
-0+ ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci); +kfree (ci_dyn->virtual_table); + ci_dyn->virtual_table =NULL ; +} +The existing
ci->tablealready has an RCU-aware lifetime: readers use the corresponding RCU access rules, and the storage is not freed until after the appropriate grace period.virtual_tableintroduced here does not have an equivalent lifetime rule.Quoted 8 lines
The syzbot crash shows that the current teardown/read-side synchronization is insufficient:
__vtable_get()can observe a torn-downvirtual_tableand dereference NULL.I don't think a NULL check in
__vtable_get()alone would be the right fix. The NULL dereference is a symptom of the missing lifetime guarantee.virtual_tableneeds to remain valid for as long as a reader can reach and access the corresponding dynamic cluster.Thanks for taking a look, Kunwu.
Quoted 9 lines
Null-check by itself is not sufficient, correct. But I think a full dance of: rcu read section +
spin_lock+ checking forCLUSTER_FLAG_DEADshould suffice. As long as cluster is valid inside this rcu read section, we can get the lock. Once we have the lock, no one can free the cluster under us. and as long as the "CLUSTER_FLAG_DEAD" flag checks out under the lock, we can exit thercu_read_section(), and proceed with reading the vtable. I already fixed this in (to-be-sent) v4.
Hi Nhat,
Thanks for the clarification. That makes sense.
I agree that the NULL check alone would only mask the underlying lifetime issue. I see the lifetime dependency now: virtual_table is protected by the lifetime of the containing cluster, rather than by an independent RCU lifetime.
Quoted 6 lines
Note that this is actually only required where we don't have any reference pin. One example is the one syzbot detected phys swap device backend flag check, because at
do_swap_time()we don't actually have any reference pins. The PTE is not locked, so swap entry can gets released underneath us. But if we have a pin - for e.g if we own the swap cache folio, then we don't really need this dance.
I also understand the distinction between the unpinned path, such as the syzbot-reported physical-swap backend flag check, and paths where we already have a reference pin, such as owning the swap cache folio.
I'll take a closer look at the v4 implementation once it is posted, particularly the lock/CLUSTER_FLAG_DEAD ordering and the teardown path.
Thanks,
KunWu
Nhat Pham
maintainerPATCH v3 3/11 mm, swap: prepare the swap IO path for vswap
In reply to Nhat PhamIn 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.
swap_add_folio() and __swap_writepage() derive 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_writepage and ops->can_merge, and stash it in swap_iocb so the submit path addresses the IO from it rather than from folio->swap.
This lets the batching path serve both vswap entries (backed by a physical slot) and physical entries mapped directly into PTEs.
All callers pass folio->swap for now, so there is no functional change.
--- include/linux/swap.h | 2 +- mm/page_io.c | 51 ++++++++++++++++++++++---------------------- mm/swap.h | 7 +++--- mm/swapfile.c | 6 +++--- mm/zswap.c | 2 +- 5 files changed, 35 insertions(+), 33 deletions(-)
include/linux/swap.h +1 -1
@@ -389,7 +389,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
mm/page_io.c +26 -25
135 lines not on this page · raw message
mm/swap.h +4 -3
@@ -103,8 +103,8 @@ 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); };
@@ -313,7 +313,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_writepage (struct swap_io_ctx *ctx,struct folio *folio); +void __swap_writepage (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
@@ -355,14 +355,14 @@ offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)BUG (); } -sector_t swap_folio_sector (struct folio *folio) +sector_t swap_entry_sector (swp_entry_t entry) { -struct swap_info_struct *sis =__swap_entry_to_info (folio->swap); +struct swap_info_struct *sis =__swap_entry_to_info (entry);struct swap_extent *se;sector_t sector;pgoff_t offset; - offset =swp_offset (folio->swap); + offset =swp_offset (entry); se =offset_to_swap_extent (sis, offset); sector = se->start_block + (offset - se->start_page);return sector << (PAGE_SHIFT -9 );
mm/zswap.c +1 -1
@@ -1076,7 +1076,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,folio_set_reclaim (folio);/* start writeback */ -__swap_writepage (&ctx, folio); +__swap_writepage (&ctx, folio, folio->swap);swap_write_submit (&ctx); out:
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v3 4/11 mm, swap: support physical swap as a vswap backend
In reply to Nhat PhamAdd physical swap as a backend for the virtual swap layer. When zswap declines a page, the swapout path allocates a physical slot on demand for swap out.
Each vswap entry's physical slot is tracked via a pointer-tagged swap_table entry on the physical cluster (an rmap back to the vswap entry).
Physical readahead scans a whole offset window and would trip over these rmap slots, so __swap_cache_add_check() now skips swp_tb_is_pointer() entries. Nothing is lost: a backing slot is faulted through its owning vswap entry, never through the physical offset.
Writeback of zswap-backed vswap entries to physical swap, and reclaim of physical slots backing cache-only vswap entries, are added in the following patches.
--- include/linux/swap.h | 9 ++ mm/memory.c | 8 +- mm/page_io.c | 43 ++++-- mm/swap_state.c | 6 +- mm/swap_table.h | 55 +++++++ mm/swapfile.c | 352 +++++++++++++++++++++++++++++++++++++++---- mm/vmscan.c | 2 +- mm/vswap.h | 198 +++++++++++++++++++++++- mm/zswap.c | 2 +- 9 files changed, 627 insertions(+), 48 deletions(-)
include/linux/swap.h +9 -0
@@ -391,6 +391,15 @@ extern int swp_swapcount(swp_entry_t entry);extern struct swap_info_struct *get_swap_device (swp_entry_t entry);sector_t swap_entry_sector (swp_entry_t entry); +#ifdef CONFIG_VSWAP +swp_entry_t folio_realloc_swap (struct folio *folio); +#else +static inline swp_entry_t folio_realloc_swap (struct folio *folio) +{ +return (swp_entry_t ){}; +} +#endif +/* * If there is an existing swap slot reference (swap entry) and the caller * guarantees that there is no race modification of it (e.g., PTL
mm/memory.c +4 -4
@@ -4656,13 +4656,13 @@ 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;/* * Non-swapfile backends cannot be reused for future swapouts. * Free the swap slot unless backed by contiguous physical swap. */ -if (is_vswap_entry (folio->swap)) +if (!folio_phys_swap_backed (folio))return true;if (mem_cgroup_swap_full (folio) || (vma->vm_flags &VM_LOCKED ) ||folio_test_mlocked (folio))
@@ -4968,7 +4968,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 );
@@ -5133,7 +5133,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 +34 -9
80 lines not on this page · raw message
mm/swap_state.c +5 -1
@@ -185,6 +185,9 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,return -ENOENT ; ci_off =swp_cluster_offset (targ_entry); old_tb =__swap_table_get (ci, ci_off); +/* Physical readahead can hit a vswap-backing rmap slot; skip it. */ +if (swp_tb_is_pointer (old_tb)) +return -ENOENT ;if (swp_tb_is_folio (old_tb))return -EEXIST ;if (!__swp_tb_get_count (old_tb))
@@ -209,7 +212,8 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci, ci_end = ci_off + nr; do { old_tb = __swap_table_get(ci, ci_off); - if (unlikely(swp_tb_is_folio(old_tb) || + if (unlikely(swp_tb_is_pointer(old_tb) || + swp_tb_is_folio(old_tb) || !__swp_tb_get_count(old_tb) || is_zero != __swap_table_test_zero(ci, ci_off) || (memcg_id && *memcg_id != __swap_cgroup_get(ci, ci_off))))
mm/swap_table.h +55 -0
67 lines not on this page · raw message
mm/swapfile.c +326 -26
499 lines not on this page · raw message
mm/vmscan.c +1 -1
@@ -1530,7 +1530,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,* space if we are running out. */ 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 +192 -6
251 lines not on this page · raw message
mm/zswap.c +1 -1
@@ -1579,7 +1579,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 {unsigned type =swp_type (swp);pgoff_t offset =swp_offset (swp);
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v3 5/11 mm, swap: enable THP swapin for vswap entries
In reply to Nhat PhamSwap a large folio back in as a unit when its vswap entries share a THP-amenable backing (a contiguous physical run, or all zero-filled), 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 | 12 ++++++++---- mm/swap_state.c | 17 +++++++++++++---- mm/vswap.h | 7 +++++++ mm/zswap.c | 18 ++++++++++++------ 4 files changed, 40 insertions(+), 14 deletions(-)
mm/memory.c +8 -4
@@ -4815,11 +4815,15 @@ static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf) entry =softleaf_from_pte (vmf->orig_pte);/* -* THP swapin for vswap is not supported yet. Also, a large swapped -* out folio could be partially or fully in zswap, which we lack -* handling for. In both cases, fall back to order-0 swapin. +* A large swapped out folio could be partially or fully in zswap. +* For vswap entries the THP-amenability of the backing is checked +* later under the cluster lock in __swap_cache_add_check, which +* rejects ZSWAP and mixed batches via -EBUSY and triggers +* order-fallback. For non-vswap entries we still need the +* zswap_never_enabled() bail: zswap_load rejects large folios with +* -EINVAL, which would SIGBUS the fault. */ -if (is_vswap_entry (entry) || !zswap_never_enabled ()) +if (!is_vswap_entry (entry) && !zswap_never_enabled ())return 0 ;/*
mm/swap_state.c +13 -4
@@ -173,6 +173,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);
@@ -201,11 +204,17 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,return 0 ;/* -* THP swapin for vswap is not supported yet; reject the 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/vswap.h +7 -0
@@ -378,6 +378,13 @@ static inline struct zswap_entry *vswap_zswap_load(swp_entry_t entry)static inline void folio_release_vswap_backing (struct folio *folio) {}static inline void folio_release_non_phys_swap_backing (struct folio *folio) {} +static inline int __vswap_check_backing (struct swap_cluster_info_dynamic *ci_dyn, +unsigned int voff,int nr, +enum vswap_backing_type *typep) +{ +return 0 ; +} +static inline int vswap_cluster_alloc_vtable (struct swap_cluster_info_dynamic *ci_dyn) {return 0 ;
mm/zswap.c +12 -6
@@ -1630,13 +1630,19 @@ int zswap_load(struct folio *folio)return -ENOENT ;/* -* Large folios should not be swapped in while zswap is being used, as -* they are not properly handled. Zswap does not properly load large -* folios, and a large folio may only be partially in zswap. +* zswap_load() does not support large folios. For non-vswap +* entries this is unexpected on the swapin path: WARN and +* sigbus. For vswap entries __swap_cache_add_check() has already +* filtered out ZSWAP-backed THPs under the cluster lock, so the +* large folio here is zero- or phys-backed; return -ENOENT so the +* phys/zero IO path handles it. */ -if (WARN_ON_ONCE (folio_test_large (folio))) { -folio_unlock (folio); -return -EINVAL ; +if (folio_test_large (folio)) { +if (WARN_ON_ONCE (!swap_is_vswap (si))) { +folio_unlock (folio); +return -EINVAL ; + } +return -ENOENT ; } entry =zswap_entry_load (swp);
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v3 6/11 mm, swap: write back vswap zswap entries to physical swap
In reply to Nhat PhamAdd 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.
Now that vswap entries can be written back, relax the zswap shrinker
gate: replace the blanket "skip while vswap is enabled" check with can_zswap_writeback(), which only skips when no physical slot is free to allocate on demand. This keeps the shrinker off futile writeback when no physical swap is available while letting it drain vswap entries otherwise.
--- mm/zswap.c | 76 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 55 insertions(+), 21 deletions(-)
mm/zswap.c +55 -21
@@ -1007,12 +1007,12 @@ 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 = {};int ret =0 ;/* try to allocate swap cache folio */
@@ -1020,12 +1020,6 @@ static int zswap_writeback_entry(struct zswap_entry *entry,if (!si)return -EEXIST ; -/* 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 );
@@ -1044,41 +1038,71 @@ 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. -* 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. +* swapoff so we can safely dereference the zswap tree (or vswap +* vtable) here. Verify that the swap entry hasn't been +* invalidated and recycled behind our backs, to avoid overwriting +* a new swap folio with old compressed data. Only when this is +* successful can the entry be dereferenced. */ - tree =swap_zswap_tree (swpentry); -if (entry !=xa_load (tree, offset)) { +if (entry !=zswap_entry_load (swpentry)) { ret = -ENOMEM ; goto out; } +if (swap_is_vswap (si)) { +/* +* Allocate physical backing before decompress so a failure +* wastes no work. folio_realloc_swap retags the vtable to +* PHYS, leaving the entry pointer held only by the caller. +*/ + phys =folio_realloc_swap (folio); +if (!phys.val) { + ret = -ENOMEM ; + goto out; + } + } +if (!zswap_decompress (entry, folio)) { ret = -EIO ; +/* +* For vswap: folio_realloc_swap already moved the entry +* out of the vtable. Restore it via vswap_zswap_store so +* the entry stays tracked (and the just-allocated PHYS +* slot is freed). For non-vswap: entry is still in the +* zswap tree. +*/ +if (swap_is_vswap (si) && phys.val) +vswap_zswap_store (swpentry, entry); goto out; } -xa_erase (tree, offset); +if (!swap_is_vswap (si)) +xa_erase (swap_zswap_tree (swpentry), offset);count_vm_event (ZSWPWB );if (entry->objcg)count_objcg_events (entry->objcg,ZSWPWB ,1 ); -zswap_entry_free (entry); -/* folio is up to date */ folio_mark_uptodate (folio);/* move it to the tail of the inactive list after end_writeback */ folio_set_reclaim (folio); -/* start writeback */ -__swap_writepage (&ctx, folio, folio->swap); +/* +* Start writeback. The entry has been moved out of its prior location +* (vtable PHYS for vswap, removed from the tree otherwise), so we own +* the free. vswap writes to the on-demand physical slot; others write +* to the folio's own entry. +*/ +if (swap_is_vswap (si)) +__swap_writepage (&ctx, folio, phys); +else +__swap_writepage (&ctx, folio, folio->swap);swap_write_submit (&ctx); +zswap_entry_free (entry); + out:if (ret) {swap_cache_del_folio (folio);
@@ -1091,6 +1115,16 @@ static int zswap_writeback_entry(struct zswap_entry *entry,/********************************* * shrinker functions **********************************/ +/* +* vswap zswap entries need a physical slot allocated on demand (via +* folio_realloc_swap) for writeback; if none is free, writeback fails, so +* skip the shrinker to avoid spinning on entries we cannot drain. +*/ +static bool can_zswap_writeback (void ) +{ +return !vswap_is_enabled () ||get_nr_swap_pages (); +} +/* * The dynamic shrinker is modulated by the following factors: *
@@ -1228,7 +1262,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 (!can_zswap_writeback ())return 0 ;/*
@@ -1313,7 +1347,7 @@ static int shrink_memcg(struct mem_cgroup *memcg)if (!mem_cgroup_zswap_writeback_enabled (memcg))return -ENOENT ; -if (vswap_is_enabled ()) +if (!can_zswap_writeback ())return -ENOENT ;/*
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v3 7/11 mm, swap: reclaim physical slots backing cache-only vswap entries
In reply to Nhat PhamA vswap entry backed by a physical slot can become cache-only: its swap_count drops to 0 while the folio is still in the swap cache, so the physical slot is redundant and reclaimable. Until now such a slot was only freed when the vswap entry itself was freed, pinning otherwise reclaimable physical capacity.
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 | 11 +++- mm/swapfile.c | 142 ++++++++++++++++++++++++++++++++++++++++++++++++ mm/vswap.h | 26 +++++++++ 3 files changed, 176 insertions(+), 3 deletions(-)
mm/swap_table.h +8 -3
@@ -377,9 +377,12 @@ static inline unsigned short __swap_cgroup_clear(struct swap_cluster_info *ci,* On physical clusters, a Pointer-tagged entry stores the offset of the * vswap entry that owns this physical slot (the reverse map). Only the * offset is stored; the swap type is implicit (always vswap_si->type, -* since there is exactly one vswap device). +* since there is exactly one vswap device). The top bit is reserved as +* a cache-only flag, set when vswap swap_count drops to 0 but the folio +* is still in swap cache. * -* Pointer: |---- vswap offset ----|100| +* Pointer: |C|---- vswap offset ----|100| +* C = SWP_RMAP_CACHE_ONLY (bit 63) */ #ifdef CONFIG_VSWAP extern struct swap_info_struct *vswap_si;
@@ -387,7 +390,8 @@ extern struct swap_info_struct *vswap_si;#define SWP_TB_PTR_MARK_BITS 3#define SWP_TB_PTR_MARK 0b100UL#define SWP_TB_PTR_MARK_MASK ((1UL << SWP_TB_PTR_MARK_BITS) - 1) -#define SWP_RMAP_ENTRY_MASK (~SWP_TB_PTR_MARK_MASK) +#define SWP_RMAP_CACHE_ONLY (1UL << (BITS_PER_LONG - 1)) +#define SWP_RMAP_ENTRY_MASK (~(SWP_RMAP_CACHE_ONLY | SWP_TB_PTR_MARK_MASK))static inline bool swp_tb_is_pointer (unsigned long swp_tb) {
@@ -408,6 +412,7 @@ static inline swp_entry_t swp_tb_ptr_to_swp_entry(unsigned long swp_tb) return swp_entry(vswap_si->type, offset); }#else +#define SWP_RMAP_CACHE_ONLY 0ULstatic inline bool swp_tb_is_pointer (unsigned long swp_tb) {return false;
mm/swapfile.c +142 -0
198 lines not on this page · raw message
mm/vswap.h +26 -0
@@ -35,6 +35,32 @@ static inline bool is_vswap_entry(swp_entry_t entry)bool vswap_is_enabled (void ); +/* +* Rmap cache-only helpers for physical cluster Pointer-tagged entries. +* SWP_RMAP_CACHE_ONLY records, inline on the physical swap_table entry, +* that the backing vswap entry has swap_count == 0 (swap-cache-only, so +* reclaimable). The physical reclaim scanner reads it directly instead of +* chasing the rmap into the vswap layer and paying the cluster-lookup +* indirection. +*/ +static inline void swap_rmap_mark_cache_only (struct swap_cluster_info *ci, +unsigned int off) +{ +atomic_long_t *table; + + table =rcu_dereference_check (ci->table, true); +atomic_long_or (SWP_RMAP_CACHE_ONLY , &table[off]); +} + +static inline void swap_rmap_clear_cache_only (struct swap_cluster_info *ci, +unsigned int off) +{ +atomic_long_t *table; + + table =rcu_dereference_check (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
Nhat Pham
maintainerPATCH v3 8/11 mm, swap: only charge physical swap entries
In reply to Nhat PhamCharge memcg->swap when a vswap entry acquires physical backing rather than when it is allocated, so memory.swap.current tracks on-disk swap usage. Zswap-backed and zero-filled pages occupy no swap space but were charged as though they did.
memory.swap.current therefore no longer counts them, and a cgroup whose pages all land in zswap can now reclaim anon memory with memory.swap.max set to 0.
Direct-mapped physical swap charging is unchanged.
--- include/linux/memcontrol.h | 5 ++ include/linux/swap.h | 57 +++++++++++++ mm/memcontrol.c | 166 ++++++++++++++++++++++++++++++++----- mm/swapfile.c | 111 +++++++++++++++++++++---- 4 files changed, 303 insertions(+), 36 deletions(-)
include/linux/memcontrol.h +5 -0
@@ -1900,6 +1900,7 @@ static inline bool memcg_is_dying(struct mem_cgroup *memcg)#if defined(CONFIG_MEMCG ) && defined(CONFIG_ZSWAP )bool obj_cgroup_may_zswap (struct obj_cgroup *objcg); +bool mem_cgroup_may_zswap (struct mem_cgroup *memcg,bool may_flush);void obj_cgroup_charge_zswap (struct obj_cgroup *objcg,size_t size);void obj_cgroup_uncharge_zswap (struct obj_cgroup *objcg,size_t size);bool mem_cgroup_zswap_writeback_enabled (struct mem_cgroup *memcg);
@@ -1908,6 +1909,10 @@ 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 +57 -0
69 lines not on this page · raw message
mm/memcontrol.c +145 -21
215 lines not on this page · raw message
mm/swapfile.c +96 -15
202 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
Johannes Weiner
maintainerRe: [PATCH v3 08/11] mm, swap: only charge physical swap entries
Quoted 5 lines · Nhat Pham
Charge
memcg->swapwhen a vswap entry acquires physical backing rather than when it is allocated, so memory.swap.current tracks on-disk swap usage. Zswap-backed and zero-filled pages occupy no swap space but were charged as though they did.
Quoted 7 lines
memory.swap.current therefore no longer counts them, and a cgroup whose pages all land in zswap can now reclaim anon memory with memory.swap.max set to 0.
Direct-mapped physical swap charging is unchanged.
Signed-off-by Nhat Pham <[email protected]>
To head off any uncertainty about this: this is exactly what needs to happen in terms of cgroup semantics.
memory.swap.* are about physical swap space. They track, control, and enforce fairness for a finite resource that is separate from memory.
When a user switches on vswsap and a bunch of empty pages are stored inside the zeromap without consuming swapfile space, these counters must be 0.
When a user switches on vswap to use zswap without a backing file, these counters must be 0.
When a user switches on vswap to use zswap with writeback, only the pages that get written to the swapfile must be tracked and controlled by these counters.
A few inline comments on the implementation:
Quoted 63 lines
mm/memcontrol.c +59
-0@@ -5701,6 +5702,116 @@ int __mem_cgroup_try_charge_swap(struct folio *folio)return 0 ; } +/** +* __mem_cgroup_record_swap - record memcg for swap without charging +* @folio: folio being added to swap +* +* Pin the memcg private ID ref and record it in the swap cgroup table +* without charging memcg->swap; the charge is deferred to physical-backing +* allocation (vswap). +*/ +void __mem_cgroup_record_swap (struct folio *folio) +{ +unsigned int nr_pages =folio_nr_pages (folio); +struct swap_cluster_info *ci; +struct mem_cgroup *memcg; +struct obj_cgroup *objcg; + +if (do_memsw_account ()) +return ; + + objcg =folio_objcg (folio); +VM_WARN_ON_ONCE_FOLIO (!objcg, folio); +if (!objcg) +return ; + +rcu_read_lock (); + memcg =obj_cgroup_memcg (objcg); +if (!folio_test_swapcache (folio)) { +rcu_read_unlock (); +return ; + } + + memcg =mem_cgroup_private_id_get_online (memcg, nr_pages); +rcu_read_unlock (); + + ci =swap_cluster_get_and_lock (folio); +__swap_cgroup_set (ci,swp_cluster_offset (folio->swap), nr_pages, +mem_cgroup_private_id (memcg)); +swap_cluster_unlock (ci); +} + +/** +* __mem_cgroup_charge_backing_phys_swap - charge memcg->swap +* @memcg: the mem_cgroup to charge (may be NULL) +* @nr_pages: number of physical swap pages to charge +* +* Charge the swap counter when a vswap entry gains physical backing. The +* private ID ref is already held (pinned by __mem_cgroup_record_swap() at +* vswap allocation), so this only moves the counter. +* +* Return: 0 on success, -ENOMEM on failure. +*/ +int __mem_cgroup_charge_backing_phys_swap (struct mem_cgroup *memcg, +unsigned int nr_pages) +{ +struct page_counter *counter; + +if (do_memsw_account ()) +return 0 ; +if (!memcg) +return 0 ;
mm/memcontrol.c int __mem_cgroup_try_charge_swap(struct folio *folio) · line 5773
Quoted 10 lines
mm/memcontrol.c +10
-0+ +if (!mem_cgroup_is_root (memcg) && + !page_counter_try_charge (&memcg->swap, nr_pages, &counter)) { +memcg_memory_event (memcg,MEMCG_SWAP_MAX ); +memcg_memory_event (memcg,MEMCG_SWAP_FAIL ); +return -ENOMEM ; + } +mod_memcg_state (memcg,MEMCG_SWAP , nr_pages); +return 0 ; +}
These functions are just __mem_cgroup_try_charge_swap() in two acts :-)
Please refactor this properly:
__mem_cgroup_swap_record()__mem_cgroup_swap_charge()
mm/memcontrol.c int __mem_cgroup_try_charge_swap(struct folio *folio) · line 5785
Quoted 10 lines
mm/memcontrol.c +10
-0+* __mem_cgroup_uncharge_backing_phys_swap - uncharge memcg->swap counter +* @memcg: the mem_cgroup to uncharge (may be NULL) +* @nr_pages: number of physical swap pages to uncharge +* +* Uncharge the swap counter on physical backing release for a vswap entry. +* The private ID ref is dropped separately via __mem_cgroup_id_put_swap() when +* the vswap entry is freed. +*/ +void __mem_cgroup_uncharge_backing_phys_swap (struct mem_cgroup *memcg, +unsigned int nr_pages)
Same on the uncharge side...
__mem_cgroup_swap_uncharge()
Quoted 18 lines
mm/memcontrol.c +18
-0+{ +if (!memcg) +return ; + +if (!mem_cgroup_is_root (memcg)) { +if (do_memsw_account ()) +page_counter_uncharge (&memcg->memsw, nr_pages); +else +page_counter_uncharge (&memcg->swap, nr_pages); + } +mod_memcg_state (memcg,MEMCG_SWAP , -nr_pages); +} + +/** +* __mem_cgroup_id_put_swap - drop memcg private ID ref without uncharging +* @id: cgroup private id +* @nr_pages: number of refs to drop +*/
mm/memcontrol.c int __mem_cgroup_try_charge_swap(struct folio *folio) · line 5813
Quoted 10 lines
mm/memcontrol.c +10
-0+void __mem_cgroup_id_put_swap (unsigned short id,unsigned int nr_pages) +{ +struct mem_cgroup *memcg; + +rcu_read_lock (); + memcg =mem_cgroup_from_private_id (id); +if (memcg) +mem_cgroup_private_id_put (memcg, nr_pages); +rcu_read_unlock (); +}
__mem_cgroup_swap_put()
and then remove __mem_cgroup_uncharge_swap(). Handle this split the same way as on the charge path.
Quoted 7 lines
mm/swapfile.c +1
-2@@ -2116,8 +2117,16 @@ int folio_alloc_swap(struct folio *folio) goto again; } -/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */ -if (unlikely (mem_cgroup_try_charge_swap (folio))) +/*
mm/swapfile.c int folio_alloc_swap(struct folio *folio) · line 2130
Quoted 10 lines
mm/swapfile.c +9
-0+* A vswap entry has no physical swap yet, so only record the memcg; +* folio_realloc_swap() charges once backing is allocated. +* +* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. +*/ +if (folio_test_swapcache (folio) && +is_vswap_entry (folio->swap)) +mem_cgroup_record_swap (folio); +else if (unlikely (mem_cgroup_try_charge_swap (folio)))swap_cache_del_folio (folio);
This becomes:
if (!vswap && mem_cgroup_swap_try_charge()) abort mem_cgroup_swap_record()
Quoted 7 lines
mm/swapfile.c +2
-0@@ -2614,18 +2685,28 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,/* * Uncharge swap slots by memcg in batches. Consecutive * slots with the same cgroup id are uncharged together. +* For vswap, only drop the ID ref - physical swap was +* already uncharged in __vswap_release_backing above. */
mm/swapfile.c void __swap_cluster_free_entries(struct swap_info_struct *si, · line 2698
Quoted 10 lines
mm/swapfile.c +6
-2id_cur =__swap_cgroup_clear (ci, ci_off,1 );if (batch_id != id_cur) { -if (batch_id) -mem_cgroup_uncharge_swap (batch_id, ci_off - batch_off); +if (batch_id) { +if (is_vswap) +mem_cgroup_id_put_swap (batch_id, ci_off - batch_off); +else +mem_cgroup_uncharge_swap (batch_id, ci_off - batch_off); + }
And this becomes:
if (!vswap) mem_cgroup_swap_uncharge() mem_cgroup_swap_put()
Nhat Pham
maintainerRe: [PATCH v3 08/11] mm, swap: only charge physical swap entries
Quoted 25 lines · Johannes Weiner
Quoted 5 lines · Nhat Pham
Charge
memcg->swapwhen a vswap entry acquires physical backing rather than when it is allocated, so memory.swap.current tracks on-disk swap usage. Zswap-backed and zero-filled pages occupy no swap space but were charged as though they did.Quoted 7 lines
memory.swap.current therefore no longer counts them, and a cgroup whose pages all land in zswap can now reclaim anon memory with memory.swap.max set to 0.
Direct-mapped physical swap charging is unchanged.
Signed-off-by Nhat Pham <[email protected]>To head off any uncertainty about this: this is exactly what needs to happen in terms of cgroup semantics.
memory.swap.* are about physical swap space. They track, control, and enforce fairness for a finite resource that is separate from memory.
When a user switches on vswsap and a bunch of empty pages are stored inside the zeromap without consuming swapfile space, these counters must be 0.
Quoted 6 lines
When a user switches on vswap to use zswap without a backing file, these counters must be 0.
When a user switches on vswap to use zswap with writeback, only the pages that get written to the swapfile must be tracked and controlled by these counters.
I agree, and yeah I should have been clearer about the reasoning in this patch commit message itself. I made the argument in a response to Kairui's inquiry in the past, but forgot to include it here. My apologies - will expand on this in the next version.
It really does not make sense to make zswap and phys swap competes for the same limit, when they don't compete for a tangible resource (zswap consumes memory, where as phys swap consumes storage space).
Quoted 2 lines
A few inline comments on the implementation:
Acked. I'm trying to implement this. Will report back if something doesn't work, but otherwise it will be in the next version.
Nhat Pham
maintainerPATCH v3 9/11 mm, swap: add debugfs counters for vswap
In reply to Nhat PhamAdd /sys/kernel/debug/vswap/ with two counters:
* used: virtual swap slots (pages) currently allocated
* alloc_reject: cumulative pages that failed to get a vswap slot
--- mm/swapfile.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-)
mm/swapfile.c +14 -1
@@ -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>
@@ -133,6 +134,9 @@ static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) = { .lock = INIT_LOCAL_LOCK(), }; +static atomic_t __maybe_unused vswap_used =ATOMIC_INIT (0 ); +static atomic_t __maybe_unused vswap_alloc_reject =ATOMIC_INIT (0 ); +#ifdef CONFIG_VSWAP static int sysctl_vswap_enabled =IS_ENABLED (CONFIG_VSWAP_DEFAULT_ON );
@@ -2056,11 +2060,13 @@ static bool vswap_alloc(struct folio *folio)if (folio_test_swapcache (folio)) {/* alloc_swap_scan_cluster updated percpu offset already */ local_unlock (&percpu_vswap_cluster.lock); +atomic_add (folio_nr_pages (folio), &vswap_used);return true; }this_cpu_write (percpu_vswap_cluster.offset[order],SWAP_ENTRY_INVALID );local_unlock (&percpu_vswap_cluster.lock); +atomic_add (folio_nr_pages (folio), &vswap_alloc_reject); return false; }#endif
@@ -2665,8 +2671,10 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,VM_WARN_ON (ci->count < nr_pages); -if (is_vswap) +if (is_vswap) {__vswap_release_backing (ci, ci_start, nr_pages); +atomic_sub (nr_pages, &vswap_used); + } ci->count -= nr_pages; do {
@@ -4862,6 +4870,7 @@ static const struct ctl_table vswap_sysctls[] = {static int __init vswap_init (void ) {struct swap_info_struct *si; +struct dentry *root;unsigned long maxpages;int err;
@@ -4896,6 +4905,10 @@ static int __init vswap_init(void)register_sysctl_init ("vm" , vswap_sysctls); + root =debugfs_create_dir ("vswap" ,NULL ); +debugfs_create_atomic_t ("used" ,0444 , root, &vswap_used); +debugfs_create_atomic_t ("alloc_reject" ,0444 , root, &vswap_alloc_reject); +pr_info ("vswap: created virtual swap device (%lu pages)\n" , maxpages);return 0 ;
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v3 10/11 mm, swap: defer memcg_table allocation for physical swap clusters
In reply to Nhat PhamStop 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 when the cluster is known to need a table: any cluster in a !CONFIG_VSWAP build, or any vswap cluster. For physical clusters in CONFIG_VSWAP builds, defer to alloc_swap_scan_cluster(), which allocates on the first direct-use slot and skips entirely when the cluster only holds pointer-tagged vswap backings.
--- mm/swapfile.c | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-)
mm/swapfile.c +32 -8
@@ -492,7 +492,8 @@ static void swap_cluster_free_table(struct swap_cluster_info *ci) swap_cluster_free_table_folio_rcu_cb); } -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;
@@ -515,7 +516,16 @@ static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp)rcu_assign_pointer (ci->table, table);#ifdef CONFIG_MEMCG -if (!mem_cgroup_disabled ()) { +/* +* Allocate memcg_table eagerly only when we know it will be used: +* any cluster in a !CONFIG_VSWAP build (all slots are direct use), +* or any vswap cluster (every vswap alloc records memcg). Physical +* clusters in a CONFIG_VSWAP build defer to alloc_swap_scan_cluster, +* which allocates on the first direct-use slot and skips entirely +* when the cluster only holds Pointer-tagged vswap backings. +*/ +if ((!IS_ENABLED (CONFIG_VSWAP ) ||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) {
@@ -589,8 +599,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;/*
@@ -608,8 +618,8 @@ swap_cluster_populate(struct swap_info_struct *si,if (!swap_is_vswap (si))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
@@ -911,7 +921,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. */
@@ -1193,6 +1203,20 @@ 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 (IS_ENABLED (CONFIG_VSWAP ) && 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) + goto out; + } +#endif if (!__swap_cluster_alloc_entries (si, ci, folio, offset %SWAPFILE_CLUSTER ))break ; found = offset;
@@ -1259,7 +1283,7 @@ static unsigned int alloc_swap_scan_dynamic(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 )) { +if (swap_cluster_alloc_table (si, &ci_dyn->ci,GFP_ATOMIC )) {kfree (ci_dyn);return SWAP_ENTRY_INVALID ; }
Signature · 1 line
2.53.0-Meta
A message that is not in the archive (sent off-list or not yet received): [email protected]
Nhat Pham
maintainerRe: [PATCH v3 10/11] mm, swap: defer memcg_table allocation for physical swap clusters
On Thu, Aug 6, 2026 at 12:19 PM <[email protected]> wrote:
Hmm seems like this is not sent to the list. I'll just cc the response to my original sent list...
Quoted 38 lines
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Deferringmemcg_tableallocation toalloc_swap_scan_clusterunderlocal_lockusingGFP_ATOMICcauses an infinite loop under memory pressure and violates allocation constraints. --Quoted 4 lines
mm/swapfile.c +4
-0+#ifdef CONFIG_MEMCG +/* +* Lazy-allocate memcg_table on the first direct-use slot of a +* physical cluster. mm/swapfile.c static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si, · line 1219
Quoted 10 lines
mm/swapfile.c +10
-0+*/ +if (IS_ENABLED (CONFIG_VSWAP ) && 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) + goto out; + } +#endif [Severity: Critical]
Does this error path create an infinite loop under memory pressure?If the
GFP_ATOMICallocation fails, we jump to the out label, which callsrelocate_cluster()and puts the unmodified cluster back on the list, returning 0.When called via this path:
cluster_alloc_swap_entry()
alloc_swap_scan_list(..., scan_all = true)do { ci = isolate_lock_cluster(si, list); found = alloc_swap_scan_cluster(si, ci, ...); if (found) break; } while (scan_all);
Quoted 3 lines
Won't
alloc_swap_scan_list()continuously dequeue the exact same cluster and fail the allocation indefinitely, since the cluster is never consumed or discarded?
Oh nice catch! It's a a bit of a rare construction. You need:
1. Vswap enabled.
2. The physical swap clusters start out backing vswap entries.
3. Then we use these same cluster to directly map to PTEs, bypassing vswap. This usually means vswap allocation fails (rare), or is disabled during runtime (rare).
4. The deferred memcg_table (1KB per cluster IIRC) allocation must fail.
Technically possible, but does not seem very likely, so I'll just do the minimum to not infinite-loop here: i.e if memcg_table allocation fails, just propagate that information up the call stack and short-circuit the list scan.
We can add complexity (dropping the lock and retry allocation) if the rate of allocation failure is high enough in this case (which I doubt).
Quoted 5 lines
Additionally,
alloc_swap_scan_cluster()runs with preemption disabled under alocal_lock. Does usingGFP_ATOMIChere risk lock recursion?GFP_ATOMICincludes__GFP_KSWAPD_RECLAIM, which wakes kswapd and can take scheduler locks while preemption is disabled.
I don't think this is correct.
Nhat Pham
maintainerPATCH v3 11/11 mm, swap: widen swap_info_struct max/pages to unsigned long
In reply to Nhat PhamWiden swap_info_struct->max and ->pages from unsigned int to unsigned long so the vswap device can exceed the current 16 TB cap (ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) pages).
Physical swap is unaffected; backing files/bdevs continue to bound it independently of the field width.
The new vswap cap is the cluster_info_pool xarray's allocator limit. XA_FLAGS_ALLOC stores allocated IDs in u32, so max_pages = UINT_MAX * SWAPFILE_CLUSTER (~8 PB at the typical SWAPFILE_CLUSTER=512 layout).
--- include/linux/swap.h | 4 +-- mm/swapfile.c | 62 +++++++++++++++++++++++--------------------- 2 files changed, 34 insertions(+), 32 deletions(-)
include/linux/swap.h +2 -2
@@ -246,7 +246,7 @@ struct swap_info_struct {signed short prio;/* swap priority of this type */ struct plist_node list;/* entry in swap_active_head */ signed char type;/* strange name for an index */ -unsigned int max;/* size of this swap device */ +unsigned long max;/* size of this swap device */ struct swap_cluster_info *cluster_info;/* cluster info. Only for SSD */ struct list_head free_clusters;/* free clusters list */ struct list_head full_clusters;/* full clusters list */
@@ -254,7 +254,7 @@ struct swap_info_struct {/* list of cluster that contains at least one free slot */ struct list_head frag_clusters[SWAP_NR_ORDERS ];/* list of cluster that are fragmented or contented */ -unsigned int pages;/* total of usable pages of swap */ +unsigned long pages;/* total of usable pages of swap */ atomic_long_t inuse_pages;/* number of those currently in use */ struct swap_sequential_cluster *global_cluster;/* Use one global cluster for rotating device */ spinlock_t global_cluster_lock;/* Serialize usage of global cluster */
mm/swapfile.c +32 -30
146 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
syzbot ci has tested the following series
syzbot ci has tested the following series
[v3] Virtual Swap Space (Swap Table Edition)
https://lore.kernel.org/all/[email protected]
* [PATCH v3 01/11] mm, swap: add virtual swap device infrastructure
* [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
* [PATCH v3 03/11] mm, swap: prepare the swap IO path for vswap
* [PATCH v3 04/11] mm, swap: support physical swap as a vswap backend
* [PATCH v3 05/11] mm, swap: enable THP swapin for vswap entries
* [PATCH v3 06/11] mm, swap: write back vswap zswap entries to physical swap
* [PATCH v3 07/11] mm, swap: reclaim physical slots backing cache-only vswap entries
* [PATCH v3 08/11] mm, swap: only charge physical swap entries
* [PATCH v3 09/11] mm, swap: add debugfs counters for vswap
* [PATCH v3 10/11] mm, swap: defer memcg_table allocation for physical swap clusters
* [PATCH v3 11/11] mm, swap: widen swap_info_struct max/pages to unsigned long
and found the following issue:
KASAN: null-ptr-deref Read in swap_entry_backend_has_flag
Full report is available here:
https://ci.syzbot.org/series/e7da1097-3230-4e50-80cb-1dfafeebea40
***
KASAN: null-ptr-deref Read in swap_entry_backend_has_flag
tree: linux-next URL: https://kernel.googlesource.com/pub/scm/linux/kernel/git/next/linux-next base: bacc32cc7de65ffff70080a48eb294f89e434d5e arch: amd64 compiler: Debian clang version 22.1.8 (++20260613092233+e80beda6e255-1~exp1~20260613092250.77), Debian LLD 22.1.8 config: https://ci.syzbot.org/builds/4f943657-9481-4637-9b1f-9be1bff18f92/config syz repro: https://ci.syzbot.org/findings/f6c4f1ab-951c-4759-b397-e22c23c3bf32/syz_repro
==================================================================
BUG: KASAN: null-ptr-deref in instrument_atomic_read include/linux/instrumented.h:82 [inline] BUG: KASAN: null-ptr-deref in atomic_long_read include/linux/atomic/atomic-instrumented.h:3188 [inline] BUG: KASAN: null-ptr-deref in __vtable_get mm/vswap.h:147 [inline] BUG: KASAN: null-ptr-deref in vswap_to_phys mm/vswap.h:197 [inline] BUG: KASAN: null-ptr-deref in swap_entry_backend_has_flag+0xfe/0x220 mm/vswap.h:441 Read of size 8 at addr 0000000000000000 by task syz.2.20/5818 CPU: 1 UID: 0 PID: 5818 Comm: syz.2.20 Not tainted syzkaller #0 PREEMPT(full) Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014 Call Trace: <TASK> dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120 kasan_report+0x117/0x150 mm/kasan/report.c:595 check_region_inline mm/kasan/generic.c:-1 [inline] kasan_check_range+0x264/0x2c0 mm/kasan/generic.c:200 instrument_atomic_read include/linux/instrumented.h:82 [inline] atomic_long_read include/linux/atomic/atomic-instrumented.h:3188 [inline] __vtable_get mm/vswap.h:147 [inline] vswap_to_phys mm/vswap.h:197 [inline] swap_entry_backend_has_flag+0xfe/0x220 mm/vswap.h:441 do_swap_page+0x3c0/0x5620 mm/memory.c:4975 __collapse_huge_page_swapin mm/khugepaged.c:1202 [inline] collapse_huge_page mm/khugepaged.c:1325 [inline] mthp_collapse mm/khugepaged.c:1524 [inline] collapse_scan_pmd mm/khugepaged.c:1786 [inline] collapse_single_pmd+0x24c6/0x3da0 mm/khugepaged.c:2803 madvise_collapse+0x2cf/0x790 mm/khugepaged.c:3237 madvise_vma_behavior+0x115f/0x4170 mm/madvise.c:1363 madvise_walk_vmas+0x576/0xb00 mm/madvise.c:1712 madvise_do_behavior+0x385/0x540 mm/madvise.c:1907 do_madvise+0x327/0x3a0 mm/madvise.c:2005 __do_sys_madvise mm/madvise.c:2014 [inline] __se_sys_madvise mm/madvise.c:2012 [inline] __x64_sys_madvise+0xa6/0xc0 mm/madvise.c:2012 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline] do_syscall_64+0x174/0x580 arch/x86/entry/syscall_64.c:94 entry_SYSCALL_64_after_hwframe+0x77/0x7f RIP: 0033:0x7fbcad79e019 Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007fbcae5c4028 EFLAGS: 00000246 ORIG_RAX: 000000000000001c RAX: ffffffffffffffda RBX: 00007fbcada25fa0 RCX: 00007fbcad79e019 RDX: 0000000000000019 RSI: 0000000000c00000 RDI: 0000200000000000 RBP: 00007fbcad83500c R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000 R13: 00007fbcada26038 R14: 00007fbcada25fa0 R15: 00007fff095fa0b8 </TASK> ==================================================================
***
If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:
---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].
To test a patch for this bug, please reply with #syz test (should be on a separate line).
The patch should be attached to the email.
Note: arguments like custom git repos and branches are not supported.
Chris Li
maintainerHi Nhat,
Quoted 17 lines · syzbot ci
syzbot ci has tested the following series
[v3] Virtual Swap Space (Swap Table Edition)
https://lore.kernel.org/all/[email protected]
* [PATCH v3 01/11] mm, swap: add virtual swap device infrastructure
* [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
* [PATCH v3 03/11] mm, swap: prepare the swap IO path for vswap
* [PATCH v3 04/11] mm, swap: support physical swap as a vswap backend
* [PATCH v3 05/11] mm, swap: enable THP swapin for vswap entries
* [PATCH v3 06/11] mm, swap: write back vswap zswap entries to physical swap
* [PATCH v3 07/11] mm, swap: reclaim physical slots backing cache-only vswap entries
* [PATCH v3 08/11] mm, swap: only charge physical swap entries
* [PATCH v3 09/11] mm, swap: add debugfs counters for vswap
* [PATCH v3 10/11] mm, swap: defermemcg_tableallocation for physical swap clusters
* [PATCH v3 11/11] mm, swap: widenswap_info_structmax/pages to unsigned long
Quoted 5 lines
and found the following issue:
KASAN: null-ptr-deref Read in swap_entry_backend_has_flagFull report is available here:
https://ci.syzbot.org/series/e7da1097-3230-4e50-80cb-1dfafeebea40
Please take a look at the syzbot report and let us know what you think.
Chris
Quoted 78 lines
***
KASAN: null-ptr-deref Read in swap_entry_backend_has_flagtree: linux-next URL: https://kernel.googlesource.com/pub/scm/linux/kernel/git/next/linux-next base: bacc32cc7de65ffff70080a48eb294f89e434d5e arch: amd64 compiler: Debian clang version 22.1.8 (++20260613092233+e80beda6e255-1~exp1~20260613092250.77), Debian LLD 22.1.8 config: https://ci.syzbot.org/builds/4f943657-9481-4637-9b1f-9be1bff18f92/config syz repro: https://ci.syzbot.org/findings/f6c4f1ab-951c-4759-b397-e22c23c3bf32/syz_repro==================================================================
BUG: KASAN: null-ptr-deref in instrument_atomic_read include/linux/instrumented.h:82 [inline] BUG: KASAN: null-ptr-deref in atomic_long_read include/linux/atomic/atomic-instrumented.h:3188 [inline] BUG: KASAN: null-ptr-deref in __vtable_get mm/vswap.h:147 [inline] BUG: KASAN: null-ptr-deref in vswap_to_phys mm/vswap.h:197 [inline] BUG: KASAN: null-ptr-deref in swap_entry_backend_has_flag+0xfe/0x220 mm/vswap.h:441 Read of size 8 at addr 0000000000000000 by task syz.2.20/5818 CPU: 1 UID: 0 PID: 5818 Comm: syz.2.20 Not tainted syzkaller #0 PREEMPT(full) Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014 Call Trace: <TASK> dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120 kasan_report+0x117/0x150 mm/kasan/report.c:595 check_region_inline mm/kasan/generic.c:-1 [inline] kasan_check_range+0x264/0x2c0 mm/kasan/generic.c:200 instrument_atomic_read include/linux/instrumented.h:82 [inline] atomic_long_read include/linux/atomic/atomic-instrumented.h:3188 [inline] __vtable_get mm/vswap.h:147 [inline] vswap_to_phys mm/vswap.h:197 [inline] swap_entry_backend_has_flag+0xfe/0x220 mm/vswap.h:441 do_swap_page+0x3c0/0x5620 mm/memory.c:4975 __collapse_huge_page_swapin mm/khugepaged.c:1202 [inline] collapse_huge_page mm/khugepaged.c:1325 [inline] mthp_collapse mm/khugepaged.c:1524 [inline] collapse_scan_pmd mm/khugepaged.c:1786 [inline] collapse_single_pmd+0x24c6/0x3da0 mm/khugepaged.c:2803 madvise_collapse+0x2cf/0x790 mm/khugepaged.c:3237 madvise_vma_behavior+0x115f/0x4170 mm/madvise.c:1363 madvise_walk_vmas+0x576/0xb00 mm/madvise.c:1712 madvise_do_behavior+0x385/0x540 mm/madvise.c:1907 do_madvise+0x327/0x3a0 mm/madvise.c:2005 __do_sys_madvise mm/madvise.c:2014 [inline] __se_sys_madvise mm/madvise.c:2012 [inline] __x64_sys_madvise+0xa6/0xc0 mm/madvise.c:2012 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline] do_syscall_64+0x174/0x580 arch/x86/entry/syscall_64.c:94 entry_SYSCALL_64_after_hwframe+0x77/0x7f RIP: 0033:0x7fbcad79e019 Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007fbcae5c4028 EFLAGS: 00000246 ORIG_RAX: 000000000000001c RAX: ffffffffffffffda RBX: 00007fbcada25fa0 RCX: 00007fbcad79e019 RDX: 0000000000000019 RSI: 0000000000c00000 RDI: 0000200000000000 RBP: 00007fbcad83500c R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000 R13: 00007fbcada26038 R14: 00007fbcada25fa0 R15: 00007fff095fa0b8 </TASK> ==================================================================***
If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:
Tested-by [email protected]---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].To test a patch for this bug, please reply with
#syz test(should be on a separate line).The patch should be attached to the email.
Note: arguments like custom git repos and branches are not supported.
Nhat Pham
maintainerQuoted 25 lines · Chris Li
Hi Nhat,
Quoted 20 lines · syzbot ci
syzbot ci has tested the following series
[v3] Virtual Swap Space (Swap Table Edition)
https://lore.kernel.org/all/[email protected]
* [PATCH v3 01/11] mm, swap: add virtual swap device infrastructure
* [PATCH v3 02/11] mm, swap: support zswap and zeroswap as vswap backends
* [PATCH v3 03/11] mm, swap: prepare the swap IO path for vswap
* [PATCH v3 04/11] mm, swap: support physical swap as a vswap backend
* [PATCH v3 05/11] mm, swap: enable THP swapin for vswap entries
* [PATCH v3 06/11] mm, swap: write back vswap zswap entries to physical swap
* [PATCH v3 07/11] mm, swap: reclaim physical slots backing cache-only vswap entries
* [PATCH v3 08/11] mm, swap: only charge physical swap entries
* [PATCH v3 09/11] mm, swap: add debugfs counters for vswap
* [PATCH v3 10/11] mm, swap: defermemcg_tableallocation for physical swap clusters
* [PATCH v3 11/11] mm, swap: widenswap_info_structmax/pages to unsigned longand found the following issue:
KASAN: null-ptr-deref Read in swap_entry_backend_has_flag
Quoted 7 lines
Quoted 2 lines
Full report is available here:
https://ci.syzbot.org/series/e7da1097-3230-4e50-80cb-1dfafeebea40Please take a look at the syzbot report and let us know what you think.
Chris
Oh it's a real bug. Not too hard to fix though.
Basically, before adding the folio to the swap cache, all bets are off. If you don't lock the PTE ("and pte mapped but not yet locked"), the swap entry can even go away under you. With the old code and no indirection, it's fine - we pin the swap device, and we only need that swap device's property here (for the sync IO dispatch). With vswap though, you need to also check vswap's entry backend device. I need to add proper rcu/null check here in the case the vswap entry (and its cluster) goes away.
Ironically, I think I got this correct in the pre-swap-table version :) I was way, way overly defensive over there (I think I add one extra pin for the vswap entry, and then pin the backend device to just for good measures, which is not really necessary).
Chris Li
maintainerHi Nhat,
First of all, thank you very much for addressing the feedback regarding the swap metadata size concern and for stopping the punishment of zram usage. I'm unsure how to proceed with your earlier VS series (before swap table version V2), given the previous concerns.
I was a bit nervous when you reverted the swap table and replaced it with something that performed worse in earlier series. I'm not attached to the swap table. The performance regression for existing use cases simply doesn't make sense to me. Thanks again that is no longer the case.
Quoted 113 lines · Nhat Pham
Changelog:
* v2 [v2] -> v3:
* Rebased onto current mm-unstable.
* Add a runtime vm.vswap_enabled sysctl andCONFIG_VSWAP_DEFAULT_ONto 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 theswap_tablefor vswap entries, etc.. Many of these are proposed by Kairui Song in [1].
* Defermemcg_tableallocation 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).
* Widenswap_info_struct->maxand ->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.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 availaiblity. 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 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).
Quoted 7 lines
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 we compile kernel with
CONFIG_VSWAP, a special vswap device is
Does the CONFIG_VSWAP only make sense for zswap right now? No other swap usage can benifit from CONFIG_VSWAP.
Quoted 2 lines
allocated at boot time, and all swapped out pages try to allocate from this device first, falling back to a physical swap device on failure.
Does it create a new user visible behavior change where users don't need to swapon and can start using VSWAP for zswap?
That is a user-visible behavior change and we need to be more cautious about it.
I think a system should not use zswap or any type of swap if no device is swapped on.
Have vm.vswap_enabled is no the answer to address the new API change because existing distro that use fstab to control swap will need to jump through hooks.
Previously, using fstab to control was at least consistent for all swap types.
Quoted 7 lines
Routing can also be turned off at runtime with the vm.vswap_enabled sysctl, which defaults to 0 unless
CONFIG_VSWAP_DEFAULT_ON=y. It is
allocation-only: new swapouts go straight to physical swap, while entries already backed by vswap keep being served and drain as they are faulted back in or freed.These swap entries can subsequently acquire backend on-demand, such as
What do "These" refer to? Are they entries already backed by vswap?
Quoted 62 lines
a zswap entry, or a slot on a physical swap device.
We repurpose much of the existing
swap_tableinfrastructure 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_tablethat 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 tov
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
|swap_tableper-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
|Pointer(C|swp_entry_t)|
| rmap back to vswap |
+--------------------------+Case 2: direct-mapped physical entry (no vswap)
PTE PHYSICAL CLUSTER (swap_cluster_info) phys_entry +--------------------------+ (swp_entry_t) ------>| swap_table per-slot: | | NULL - free | | PFN - cached folio | | Shadow - swapped out | | Bad - unusable | +--------------------------+
Quoted 6 lines
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 */};
No a big fan of this two personality data structure thing depending on whether it is VS or not.
If ci is the common part, I prefer to keep it separate and leave it alone.
Also the extension is too vswap specific, it does not apply to other swap device types that might need their own private extension. You can take the VFS layer as an example. There is a VFS layer generic inode, which is common and shared by all file systems. And then you have filesystem-specific inodes as extensions, e.g. ext4_inode. The ext4_inode does not contain VFS inode. You don't see VFS having a code path like: if it is ext4, get the inode this way, else if f2fs, get the inode that way.
In the first swap abstraction LPC talk, where I co-hosted with Yosry, I talked about the alternative approach: "VFS-like swap layers". That is exactly what I have in mind. We are getting very close to fulfilling that promise via swap ops and xswap extension interfaces.
I think implementing the generic interface first is simpler than implementing the non-generic vswap interface, ripping it out to replace it with a generic interface, and then putting back the generic modified version of vswap.
If the two personality vswap xarray lookup gets in first, it will ultimately take more work to achieve the desired VFS-like extendable swap operations.
I am happy to spend some time working with you to discuss the generic adopted version of vswap, if you are open to it. Or if you don't want to waste time on it. I can have someone else or myself come up with the generic adopted version of vswap for you to review, which I prefer less.
Another piece of feedback is to please come up with a plan to submit your vswap changes piecemeal rather than as one long series. There is a lot of change like swap charging, that deserves a separate discussion before it gets merged. Look, the swap table changes took four phases. Each phase achieved a smaller milestone, with four of them ultimately reaching the finish line. I wish vswap had a similar piecemeal plan.
Sorry I have to crash now, to be continued...
Quoted 194 lines
Each vswap cluster (
swap_cluster_info_dynamic) extends the classicswap_cluster_infostruct with avirtual_tablearray that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate the backend type:NONE: |----- 0000 ------|000| free / unbacked SWAPFILE: |- type:5,off:56 -|001| on a physical swapfile ZSWAP: |--- zswap_entry* |010| compressed in zswapOther 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. When
CONFIG_VSWAP=nthe vswap paths compile out.* Backend transitions in the
virtual_tableare synchronized through the swap cache and the folio lock - the same mechanism that already serializes ordinary swap operations (swapin, swapout, zswap writeback, swap cache reclaim). IOW, we can only assume that the backend of a vswap entry is stable through swap cache/folio lock. Looking at the backend without this should be done at best for optimization purposes, as there is no guarantee that the backend will not change under the observer.* Pointer-tagged
swap_tableentries on physical clusters provide the rmap (physical -> virtual) lookup.* Virtual swap slots not backed by physical swap are not charged to memcg swap counters - only physical backing is charged (I made the case for this in [4]).
III. Benchmarks
===============Note that the goal is not to match vswap performance with baseline on every single case yet - we still maintain !CONFIG_VSWAP setup. 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,CONFIG_VSWAPnot set, to verify that there is no regression to existing swap paths when we disable vswap.
* VSS on: vswap series applied,CONFIG_VSWAP=y.1. Memhog: single-threaded, 48GB allocation on a host with 16GB RAM, 20 rounds.
Baseline VSS off VSS on
real (s) 131.71 +/- 13.54 132.47 +/- 10.10 120.56 +/- 15.37 sys (s) 114.05 +/- 13.03 115.11 +/- 9.76 103.73 +/- 15.06 user (s) 10.86 +/- 0.13 10.97 +/- 0.10 10.87 +/- 0.11 delta real - +0.6% -8.5% delta sys - +0.9% -9.1%Dropping the best and the worst round to reduce variance:
memhog Baseline VSS off VSS on
real (s) 130.24 +/- 8.56 131.51 +/- 5.82 119.39 +/- 12.06 sys (s) 112.58 +/- 7.88 114.26 +/- 5.74 102.63 +/- 11.83 user (s) 10.86 +/- 0.14 10.97 +/- 0.10 10.86 +/- 0.10 delta real - +1.0% -8.3% delta sys - +1.5% -8.8%2. Usemem single-threaded: 56GB allocation on a host with 32GB RAM, 16 rounds.
Baseline VSS off VSS on
real (s) 177.14 +/- 7.34 178.20 +/- 5.12 175.83 +/- 6.96 sys (s) 125.30 +/- 7.47 125.19 +/- 5.18 124.09 +/- 7.07 tput (KB/s) 390668 +/- 16840 387878 +/- 11769 390921 +/- 15798 free (ms) 7739 +/- 125 7734 +/- 120 6572 +/- 121 delta real - +0.6% -0.7% delta sys - -0.1% -1.0% delta tput - -0.7% +0.1% delta free - -0.1% -15.1%3. Kernel build: 52 workers (one per processor), memory.max=3GB, 10 rounds.
Baseline VSS off VSS on
real (s) 168.13 +/- 0.77 168.46 +/- 0.45 167.75 +/- 0.65 sys (s) 772.49 +/- 19.77 781.82 +/- 26.32 763.60 +/- 33.02 user (s) 5128.41 +/- 1.31 5130.64 +/- 1.67 5130.74 +/- 1.66 delta real - +0.2% -0.2% delta sys - +1.2% -1.1% delta user - +0.0% +0.0%For zswap backend, vswap outperforms baseline on usemem freeing, and memhog benchmark, and is on par with baseline on the rest.
In the RFC v2 ([v2]), I put out several theories for this. I have done some prototyping to isolate effects, and it turns out the performance wins come primarily from the elimination of zswap's xarray and the merging of zswap's metadata to swap device's cluster. Several code paths are optimized thanks to this - for instance, in
swap_range_free(), we callzswap_invalidate()once for each entry the range, resulting in multiple xarray tree walks. With vswap, we perform one single xarray walk to grab a 512-slot cluster, then performs a flat array scan to free zswap metadata. Similar wins can be observed in Baoquan's optimization ([8]), which also optimizes away the zswap tree.IV. References
==============[v1]: https://lore.kernel.org/all/[email protected]/
[v2]: 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/CAKEwX=P50av2rfocpsqZoDQowZ=EEhQ-5vj5tBykbNz8vtKTzA@mail.gmail.com/
[6]: https://lore.kernel.org/all/[email protected]/
[7]: https://lore.kernel.org/all/[email protected]/
[8]: https://lore.kernel.org/all/[email protected]/Appendix: Alternative Designs and Improvements
==============================================A. Vmalloc Data Structure:
==========================This is a promising alternative to the xarray data structure, reducing the indirection overhead. The initial version relies on userspace knob to trigger swap address space growth - I have commented on why this is shaky in [5].
Baoquan has followed-up with a new version (see [6]) that should give us kernel-driven dynamic growth and (tail-only) shrink. This seems sufficient for vswap use case, AFAICT - but seems like it would need a couple more versions to finalize the design.
I think it is better to proceed with the xarray data structure first, especially since we already see some positive signals on performance by storing zswap metadata in a per-cluster flat table. With vswap landed, we will have a concrete setup to show vmalloc data structure's wins.
B. Moving the backend table to struct
swap_cluster_info
=======================================================Another approach Baoquan and I discussed on is to structure vswap patch series as follows:
1. Moving vtable (renamed to something more generic) to swap cluster, which removes the xarray.
2. Once vswap is introduced, we simply use this field to store the backend.
I have a prototype for this, but I ended up scrapping the whole thing, for the following reasons:
1. It ended up being even more code than what I sent out here - most of which touches the non-vswap code paths, which we either want to leave alone (generic swap logic) or want to rip out wholesale down the line (zswap).
2. There are several fields that are ONLY needed for the vswap clusters (for instance,
rcu_headand index). Shoving them into the shared structswap_cluster_infoimposes memory and mental overhead for non-vswap clusters and users.
Quoted 4 lines
We can avoid this by simply moving it to the wrapper struct (
swap_cluster_info_dynamic). This is actually Kairui's design (see [7]), but after trying to deviate from it, I have to conclude it is the right choice too.
Kairui took a shortcut to deliver a simpler demo RFC, it is not ready for merge as is. Please take a look at the VFS inode vs ext4_inode_info for the effect I am trying to get to.
I am really crashing now.
Chris
Quoted 61 lines
3. Replacing zswap tree with the per-cluster backend table results in performance wins even when vswap is turned off (this is how I verified that vswap's performance wins comes from here).
However, it requires more code to make sure this table is not allocated when not needed. Note that the eventual goal is to make vswap the ONLY way to use zswap, so we are literally adding complexity and overhead (even for non-vswap users) to optimize for a code path that is rarely exercised after vswap lands, and will be ripped out soon after. That seems very off to me.
To close out, this design brings together the ideas from the earlier discussions:
1. All of the requirements I set out to solve (dynamicity, backend decoupling, efficient backend transfer) are implemented.
2. Vswap device now repurpose the swap table design and most of the generic swap operations.
3. Minimal overhead for non-vswap users, and zswap-no-writeback users. If you disable writeback, vswap *is* a ghost swapfile.
Nhat Pham (11):
mm, swap: add virtual swap device infrastructure
mm, swap: support zswap and zeroswap 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: defermemcg_tableallocation for physical swap clusters mm, swap: widenswap_info_structmax/pages to unsigned longDocumentation/admin-guide/sysctl/vm.rst | 16 + MAINTAINERS | 1 + include/linux/memcontrol.h | 5 + include/linux/swap.h | 88 +- include/linux/zswap.h | 3 + mm/Kconfig | 21 + mm/memcontrol.c | 166 +++- mm/memory.c | 28 +- mm/page_io.c | 103 +- mm/shmem.c | 4 +- mm/swap.h | 55 +- mm/swap_state.c | 64 +- mm/swap_table.h | 62 ++ mm/swapfile.c | 1194 +++++++++++++++++++++-- mm/vmscan.c | 14 +- mm/vswap.h | 454 +++++++++ mm/zswap.c | 140 ++- 17 files changed, 2207 insertions(+), 211 deletions(-) create mode 100644 mm/vswap.hbase-commit:
bacc32cc7de65ffff70080a48eb294f89e434d5e--
2.53.0-Meta
Nhat Pham
maintainerQuoted 8 lines · Chris Li
Hi Nhat,
First of all, thank you very much for addressing the feedback regarding the swap metadata size concern and for stopping the punishment of zram usage. I'm unsure how to proceed with your earlier VS series (before swap table version V2), given the previous concerns.
Quoted 5 lines
I was a bit nervous when you reverted the swap table and replaced it with something that performed worse in earlier series. I'm not attached to the swap table. The performance regression for existing use cases simply doesn't make sense to me. Thanks again that is no longer the case.
Eh, I'm open minded. I try lots of stuff - I tried the swap table direction twice actually.
Quoted 118 lines · Nhat Pham
Quoted 116 lines
Changelog:
* v2 [v2] -> v3:
* Rebased onto current mm-unstable.
* Add a runtime vm.vswap_enabled sysctl andCONFIG_VSWAP_DEFAULT_ONto 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 theswap_tablefor vswap entries, etc.. Many of these are proposed by Kairui Song in [1].
* Defermemcg_tableallocation 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).
* Widenswap_info_struct->maxand ->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.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 availaiblity. 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 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]).
Quoted 7 lines
Quoted 4 lines
II. Design
==========When we compile kernel with
CONFIG_VSWAP, a special vswap device isDoes the
CONFIG_VSWAPonly make sense for zswap right now? No other swap usage can benifit fromCONFIG_VSWAP.
Good point, yeah.
Maybe have CONFIG_VSWAP depends on CONFIG_ZSWAP, until another use case comes (I was thinking of discontig physical swapping, but this damn patch series is long.)
Quoted 7 lines
Quoted 3 lines
allocated at boot time, and all swapped out pages try to allocate from this device first, falling back to a physical swap device on failure.
Does it create a new user visible behavior change where users don't need to swapon and can start using VSWAP for zswap?
That is a user-visible behavior change and we need to be more cautious about it.
Userspace behavior change *is* the whole point here though. I want the users to not having to specify a static capacity :)
Furthermore, the implication of not breaking existing users' deployment is that if users want this new feature, they have to change their existing config. It's just about where it makes the most sense (a compile time config? boot time config? runtime config? some combinations of these?)
However, I absolutely agree with you about being cautious with the exact API. I'm still evaluating the best way to bring about this (perhaps a boot time parameters is better than this runtime knob, but let me prototype and test things).
Quoted 3 lines
I think a system should not use zswap or any type of swap if no device is swapped on.
Why not? If we don't specify the size, and just want on/off knob (say at boot time), seems like an overkill to use this interface. But maybe I'm missing something.
Quoted 12 lines
Have vm.vswap_enabled is no the answer to address the new API change because existing distro that use fstab to control swap will need to jump through hooks.
Previously, using fstab to control was at least consistent for all swap types.Quoted 6 lines
Routing can also be turned off at runtime with the vm.vswap_enabled sysctl, which defaults to 0 unless
CONFIG_VSWAP_DEFAULT_ON=y. It is
allocation-only: new swapouts go straight to physical swap, while entries already backed by vswap keep being served and drain as they are faulted back in or freed.
Quoted 3 lines
Quoted 1 line
These swap entries can subsequently acquire backend on-demand, such as
What do "These" refer to? Are they entries already backed by vswap?
Yep. Vswap entries
Quoted 70 lines
Quoted 63 lines
a zswap entry, or a slot on a physical swap device.
We repurpose much of the existing
swap_tableinfrastructure 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_tablethat 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 tov
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
|swap_tableper-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
|Pointer(C|swp_entry_t)|
| rmap back to vswap |
+--------------------------+Case 2: direct-mapped physical entry (no vswap)
PTE PHYSICAL CLUSTER (swap_cluster_info) phys_entry +--------------------------+ (swp_entry_t) ------>| swap_table per-slot: | | NULL - free | | PFN - cached folio | | Shadow - swapped out | | Bad - unusable | +--------------------------+Quoted 6 lines
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 */};
Quoted 3 lines
No a big fan of this two personality data structure thing depending on whether it is VS or not.
If ci is the common part, I prefer to keep it separate and leave it alone.
I don't get what you meant. It is separate, and alone, no?
Originally Baoquan and I were thinking of shoving the virtual table into "struct swap_cluster_info". I tried prototyping that one out, but it looks uglier than I anticipated, so I dropped that approach.
Quoted 9 lines
Also the extension is too vswap specific, it does not apply to other swap device types that might need their own private extension. You can take the VFS layer as an example. There is a VFS layer generic inode, which is common and shared by all file systems. And then you have filesystem-specific inodes as extensions, e.g.
ext4_inode. Theext4_inodedoes not contain VFS inode. You don't see VFS having a code path like: if it is ext4, get the inode this way, else if f2fs, get the inode that way.
Hmmm, I'm not an FS expert. But struct ext4_inode_info does contain a generic vfs inode field ("struct inode vfs_inode"), no? That is actually more analogous than I would think: we have a vswap-specific cluster struct (struct swap_cluster_info_dynamic) that wraps the generic, shared metadata struct (struct swap_cluster_info).
I also never claim to re-implement vfs for swap. We take inspirations where appropriate, but we're just writing our own thing at this point :)
Quoted 5 lines
In the first swap abstraction LPC talk, where I co-hosted with Yosry, I talked about the alternative approach: "VFS-like swap layers". That is exactly what I have in mind. We are getting very close to fulfilling that promise via swap ops and xswap extension interfaces.
I remember that talk. I don't remember how backend transfer would be implemented in that proposal.
Quoted 9 lines
I think implementing the generic interface first is simpler than implementing the non-generic vswap interface, ripping it out to replace it with a generic interface, and then putting back the generic modified version of vswap.
If the two personality vswap xarray lookup gets in first, it will ultimately take more work to achieve the desired VFS-like extendable swap operations.
Quoted 5 lines
I am happy to spend some time working with you to discuss the generic adopted version of vswap, if you are open to it. Or if you don't want to waste time on it. I can have someone else or myself come up with the generic adopted version of vswap for you to review, which I prefer less.
I would love to hear more about it, but so far I haven't quite understood how it's going to achieve all of the requirements vswap is trying to solve.
Quoted 8 lines
Another piece of feedback is to please come up with a plan to submit your vswap changes piecemeal rather than as one long series. There is a lot of change like swap charging, that deserves a separate discussion before it gets merged. Look, the swap table changes took four phases. Each phase achieved a smaller milestone, with four of them ultimately reaching the finish line. I wish vswap had a similar piecemeal plan.
Lemme think about this a bit more. But in the meantime, could you at least take a look at the general directions? For your use case (zswap as the terminal swap level), I think the first two patches are the most relevant, but the rest is crucial too for a generic use case.