Virtual Swap Space (Swap Table Edition)
Subsystems (10)
Nhat Pham
maintainerv4 cover Virtual Swap Space (Swap Table Edition)
Changelog:
* v3 [v3] -> v4
* Replaced the runtime sysctl with a cmdline param, and remove CONFIG_VSWAP (suggested by Johannes Weiner). CONFIG_VSWAP_DEFAULT_ON now only gives the default value of the vswap cmdline parameter.
* Refactor swap-related memcg operations into composable building
blocks: reference acquisitions, charging, etc. (patch 8, suggested by Johannes Weiner).
* Fixed vtable UAF bug reported by syzbot and Kunwu.
* Rebased onto mm-unstable (minimal merge conflicts).
* Re-run benchmarks (no signal change).
* v2 [v2] -> v3:
* Rebased onto current mm-unstable.
* Add a runtime vm.vswap_enabled sysctl and CONFIG_VSWAP_DEFAULT_ON to gate vswap allocation.
* More cleanups and small bug fixes.
* Split THP swapin enablement into its own patch (patch 5).
* Add production workload benchmark results, and drop RFC tag.
* v1 [v1] -> v2:
* Rebased to a newer mm-unstable tip.
* Fix a bunch of assorted issues (incorrect zswap store failure rollback, vswap_init() failure handling, rmap-encoding collision, etc.) and clean up the code (rename a bunch of functions to more closely follow existing patterns, etc.).
* Some more code clean up and simplification: some renamings to more closely follow existing patterns, move vswap backing check to __swap_cache_add_check, store zero state in the swap_table for vswap entries, etc.. Many of these are proposed by Kairui Song in [1].
* Defer memcg_table allocation on physical clusters until the first vswap-backing slot installs. Saves ~512 bytes per physical cluster that only serves vswap-backing slots (this is the new patch 8).
* Widen swap_info_struct->max and ->pages (and the swapoff unuse-path index) so vswap supports ~8 PB of swap space (this is the new patch 9).
* Split the physical-swap-backend patch into three for reviewability:
the core backend (patch 3), zswap writeback to physical swap (patch 4), and reclaim of cache-only physical slots (patch 5). No functional change.
* Add kerneldoc for the vswap API.
* Add some benchmark numbers for zswap case.
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 vswap is enabled (via vswap=on cmdline parameter), a special vswap device is allocated at boot time. Anon pages that can be zswapped will obtain a vswap slot at swap allocation time.
These swap entries can subsequently acquire backend on-demand, such as a zswap entry, or a slot on a physical swap device (as a fallback option or at zswap writeback time).
We repurpose much of the existing swap_table infrastructure and swapfile allocator for this new vswap device, with two notable differences:
* Clusters are dynamically allocated on demand and managed through an xarray. This in turn allows us to avoid static provisioning and let swap space grow dynamically.
* Each cluster of this new vswap device has a virtual_table that stores the backend information of the entries in the cluster (see below).
Diagrams:
Case 1: vswap entry (virtualized)
PTE swap_cluster_info_dynamic
vswap_entry +---------------------------------+
(swp_entry_t) ------>| swap_cluster_info (ci) |
| +----------------------------+ |
| | swap_table | |
| | PFN / Shadow | |
| | memcg_table | |
| | count,flags,order | |
| | lock, list | |
| +----------------------------+ |
| |
| virtual_table |
| +----------------------------+ |
| | NONE | |
| | SWAPFILE(swp_entry_t) | |
| | ZSWAP(struct zswap_entry*) | |
| +----------------------------+ |
+---------------------------------+
|
| SWAPFILE resolves to v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+
Case 2: direct-mapped physical entry (no vswap)
PTE PHYSICAL CLUSTER (swap_cluster_info)
phys_entry +--------------------------+
(swp_entry_t) ------>| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Bad - unusable |
+--------------------------+struct swap_cluster_info_dynamic {
struct swap_cluster_info ci; /* swap_table, lock, etc. */
unsigned int index; /* position in xarray */
struct rcu_head rcu; /* kfree_rcu deferred free */
atomic_long_t *virtual_table; /* backend info, 8 B/slot */};
Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate the backend type:
NONE: |----- 0000 ------|000| free / unbacked ZSWAP: |--- zswap_entry* |001| compressed in zswap SWAPFILE: |- type:5,off:56 -|010| on a physical swapfile
Other design highlights:
* Note that for the vswap device, we have merged the zswap xarray tree with the swapfile-level clusters. This means that for zswap only users, we have negligible extra space overhead.
* Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens.
* Backend transitions in the virtual_table are synchronized through the swap cache and the folio lock - the same mechanism that already serializes ordinary swap operations (swapin, swapout, zswap writeback, swap cache reclaim). IOW, we can only assume that the backend of a vswap entry is stable through swap cache/folio lock. Looking at the backend without this should be done at best for optimization purposes, as there is no guarantee that the backend will not change under the observer.
* Pointer-tagged swap_table entries on physical clusters provide the rmap (physical -> virtual) lookup.
* Virtual swap slots not backed by physical swap are not charged to memcg swap counters - only physical backing is charged (I made the case for this in [4]).
III. Benchmarks
===============
Note that the goal is not to match vswap performance with baseline on every single case yet - running with vswap off is still supported. We can optimize further once we have landed this new feature.
A. Production Workload: Instagram
=================================
To test vswap's stability and performance, I ran an A/B experiment on Instagram (django) workload, with zswap as the swap backend. On these hosts, the swapfiles' size is 50% of RAM.
Compared to baseline, vswap gives:
* On par request throughput.
* Lower request serving latency (by about 1-3%).
* Lower memory pressure in the system service cgroups running alongside the workload. PSI-based proactive reclaimer can therefore recover more from them, lowering their overall memory footprint, allowing the main workload to expand.
* Elimination of swapfile footprint for all zswap users in the host.
B. Semi-synthetic Workloads (memhog, usemem, kernel build)
==========================================================
All values are mean +/- standard deviation across rounds.
Test system: x86_64, 52 cores, 64 GB swapfile for all 3 benchmarks. Swap backend: zswap (zstd) with the traditional active/inactive LRU. We focus on zswap here because it is the motivating use case for vswap.
For each benchmark, we test 3 kernels:
* Baseline: mm-unstable, no vswap patches.
* VSS off: vswap series applied, vswap=off, to verify that there is no regression to existing swap paths when we disable vswap.
* VSS on: vswap series applied, vswap=on.
1. Memhog: single-threaded, 48GB allocation on a host with 16GB RAM, 20 rounds.
Baseline VSS off VSS on
real (s) 124.05 +/- 11.64 122.31 +/- 10.29 118.57 +/- 15.68 sys (s) 106.75 +/- 10.86 105.01 +/- 9.64 101.34 +/- 13.97 user (s) 10.81 +/- 0.11 10.85 +/- 0.09 10.79 +/- 0.09 delta real - -1.4% -4.4% delta sys - -1.6% -5.1%
Dropping the best and the worst round to reduce variance:
memhog Baseline VSS off VSS on
real (s) 123.75 +/- 10.39 122.04 +/- 9.10 116.06 +/- 8.22 sys (s) 106.80 +/- 10.21 104.99 +/- 8.86 99.29 +/- 8.27 user (s) 10.82 +/- 0.11 10.85 +/- 0.08 10.79 +/- 0.10 delta real - -1.4% -6.2% delta sys - -1.7% -7.0%
2. Usemem single-threaded: 56GB allocation on a host with 32GB RAM, 16 rounds.
Baseline VSS off VSS on
real (s) 178.75 +/- 6.47 178.95 +/- 6.56 175.97 +/- 7.74 sys (s) 127.03 +/- 6.56 128.08 +/- 6.59 124.71 +/- 7.90 tput (KB/s) 386662 +/- 14648 386264 +/- 15150 390443 +/- 17532 free (ms) 7669 +/- 146 7678 +/- 136 6439 +/- 111 delta real - +0.1% -1.6% delta sys - +0.8% -1.8% delta tput - -0.1% +1.0% delta free - +0.1% -16.0%
3. Kernel build: 52 workers (one per processor), memory.max=3GB, 10 rounds.
Baseline VSS off VSS on
real (s) 165.58 +/- 0.45 165.83 +/- 0.49 166.01 +/- 0.58 sys (s) 694.24 +/- 26.13 710.76 +/- 19.83 705.06 +/- 21.40 user (s) 5132.62 +/- 1.12 5133.69 +/- 1.57 5134.68 +/- 1.68 delta real - +0.2% +0.3% delta sys - +2.4% +1.6% delta user - +0.0% +0.0%
For zswap backend, vswap outperforms baseline on usemem freeing, and is on par with baseline on the rest.
IV. References
==============
[v1]: https://lore.kernel.org/all/[email protected]/
[v2]: https://lore.kernel.org/all/[email protected]/
[v3]: https://lore.kernel.org/all/[email protected]/
[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/
Nhat Pham (11):
mm, swap: add virtual swap device infrastructure
mm, swap: support zswap and zero-filled swap pages as vswap backends mm, swap: prepare the swap IO path for vswap
mm, swap: support physical swap as a vswap backend
mm, swap: enable THP swapin for vswap entries
mm, swap: write back vswap zswap entries to physical swap mm, swap: reclaim physical slots backing cache-only vswap entries mm, swap: only charge physical swap entries
mm, swap: add debugfs counters for vswap
mm, swap: defer memcg_table allocation for physical swap clusters mm, swap: widen swap_info_struct max/pages to unsigned long
Nhat Pham (11):
mm, swap: add virtual swap device infrastructure
mm, swap: support zswap and zero-filled swap pages as vswap backends mm, swap: prepare the swap IO path for vswap
mm, swap: support physical swap as a vswap backend
mm, swap: enable THP swapin for vswap entries
mm, swap: write back vswap zswap entries to physical swap mm, swap: reclaim physical slots backing cache-only vswap entries mm, swap: only charge physical swap entries
mm, swap: add debugfs counters for vswap
mm, swap: defer memcg_table allocation for physical swap clusters mm, swap: widen swap_info_struct max/pages to unsigned long
.../admin-guide/cgroup-v1/memcg_test.rst | 2 +- .../admin-guide/kernel-parameters.txt | 7 + MAINTAINERS | 1 + include/linux/memcontrol.h | 6 + include/linux/swap.h | 76 +- include/linux/swap_ops.h | 9 +- include/linux/zswap.h | 3 + mm/Kconfig | 20 + mm/memcontrol-v1.c | 10 +- mm/memcontrol.c | 148 ++- mm/memory.c | 21 +- mm/page_io.c | 106 +- mm/shmem.c | 4 +- mm/swap.h | 71 +- mm/swap_state.c | 60 +- mm/swap_table.h | 50 +- mm/swapfile.c | 1182 +++++++++++++++-- mm/vmscan.c | 9 +- mm/vswap.h | 440 ++++++ mm/zswap.c | 129 +- 20 files changed, 2100 insertions(+), 254 deletions(-) create mode 100644 mm/vswap.h
base-commit: efecab401cb15fd3bb9bc05990609acb6b267ff2
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v4 1/11 mm, swap: add virtual swap device infrastructure
Create a virtual swap device (16 TB with 4 KB pages), along with the dynamic cluster infrastructure that the rest of the vswap layer is built on. swap_cluster_info_dynamic keeps per-cluster info in an xarray, so a device can be sized without a static cluster_info[] array. For now, vswap requires a 64-bit architecture.
The dynamic-cluster allocator is wired in, but nothing reaches it yet. vswap_si is kept off the swap device lists, and no allocation path can select it. Backends (zswap, zero, physical disk) and the vswap-aware swap-out / swap-in / writeback paths arrive in subsequent patches.
Routing is controlled by the "vswap=" kernel parameter, defaulting to CONFIG_VSWAP_DEFAULT_ON. When off, no device exists, every vswap path is skipped, and swap behavior is unchanged. When on, vswap_init() creates the device and enables a static key only after it is fully published, so callers never observe a half-built device. The device lives for the lifetime of the kernel and cannot be swapon'd or swapoff'd.
--- .../admin-guide/kernel-parameters.txt | 7 + MAINTAINERS | 1 + include/linux/swap.h | 9 + mm/Kconfig | 20 ++ mm/page_io.c | 14 + mm/swap.h | 67 ++++- mm/swap_state.c | 37 ++- mm/swap_table.h | 4 + mm/swapfile.c | 271 ++++++++++++++++-- mm/vswap.h | 34 +++ mm/zswap.c | 6 + 11 files changed, 437 insertions(+), 33 deletions(-) create mode 100644 mm/vswap.h
Documentation/admin-guide/kernel-parameters.txt +7 -0
@@ -8364,6 +8364,13 @@ Kernel parameters force - force vulnerability detection even on unaffected processors + vswap= [MM,EARLY] + Route swapouts through the virtual swap layer, which + allows zswap and zero-filled pages to be used without + a physical swap device. 64-bit only. + Format: { on | off } + Default: on if CONFIG_VSWAP_DEFAULT_ON=y, else off. + vsyscall= [X86-64,EARLY] Controls the behavior of vsyscalls (i.e. calls to fixed addresses of 0xffffffffff600x00 from legacy
MAINTAINERS +1 -0
@@ -17251,6 +17251,7 @@ F: mm/swap.h F: mm/swap_table.h F: mm/swap_state.c F: mm/swapfile.c +F: mm/vswap.h MEMORY MANAGEMENT - THP (TRANSPARENT HUGE PAGE) M: Andrew Morton <[email protected]>
include/linux/swap.h +9 -0
@@ -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,14 @@ struct swap_info_struct {struct list_head discard_clusters;/* discard clusters list */ struct plist_node avail_list;/* entry in swap_avail_head */ const struct swap_ops *ops; +struct xarray cluster_info_pool;/* Xarray for vswap dynamic cluster info */ }; +static inline bool swap_is_vswap (struct swap_info_struct *si) +{ +return si->flags &SWP_VSWAP ; +} +static inline swp_entry_t page_swap_entry (struct page *page) {struct folio *folio =page_folio (page);
@@ -408,6 +415,8 @@ void swap_free_hibernation_slot(swp_entry_t entry);static inline void put_swap_device (struct swap_info_struct *si) { +if (swap_is_vswap (si)) +return ;percpu_ref_put (&si->users); }
mm/Kconfig +20 -0
@@ -19,6 +19,26 @@ menuconfig SWAP used to provide more virtual memory than the actual RAM present in your computer. If unsure say Y. +config VSWAP_DEFAULT_ON + bool "Route swapouts through virtual swap by default" + depends on SWAP && 64BIT + default n + help + Virtual swap allows zswap and zero-filled pages to be used + without swapping on a physical device first, and lets a page + move between zswap and a swapfile without invalidating the page + table entries that refer to it. + + Swap entries are handed out by a virtual swap device instead of + naming a slot on a real one, so the backing can be chosen and + changed after the entry exists. + + Say Y to make "vswap=on" the default, routing swapouts through + the virtual swap layer from boot. + + Say N (default) to leave vswap off unless "vswap=on" is passed + on the kernel command line. + config ZSWAP bool "Compressed cache for swap pages" depends on SWAP
mm/page_io.c +14 -0
@@ -28,6 +28,7 @@#include <linux/swap_ops.h> #include "swap.h" #include "swap_table.h" +#include "vswap.h" int generic_swapfile_activate(struct swap_info_struct *sis, struct file *swap_file,
@@ -248,6 +249,14 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio) }rcu_read_unlock (); +/* +* A vswap folio has no physical slot to write to, so keep it dirty. +*/ +if (is_vswap_entry (folio->swap)) { +folio_mark_dirty (folio); +return AOP_WRITEPAGE_ACTIVATE ; + } +__swap_writepage (ctx, folio);return 0 ; out_unlock:
@@ -480,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 +64 -3
114 lines not on this page · raw message
mm/swap_state.c +25 -12
@@ -96,8 +96,10 @@ struct folio *swap_cache_get_folio(swp_entry_t entry)struct folio *folio;for (;;) { +rcu_read_lock (); swp_tb =swap_table_get (__swap_entry_to_cluster (entry),swp_cluster_offset (entry)); +rcu_read_unlock ();if (!swp_tb_is_folio (swp_tb))return NULL ; folio =swp_tb_to_folio (swp_tb);
@@ -119,8 +121,10 @@ bool swap_cache_has_folio(swp_entry_t entry) {unsigned long swp_tb; +rcu_read_lock (); swp_tb =swap_table_get (__swap_entry_to_cluster (entry),swp_cluster_offset (entry)); +rcu_read_unlock ();return swp_tb_is_folio (swp_tb); }
@@ -136,8 +140,10 @@ void *swap_cache_get_shadow(swp_entry_t entry) {unsigned long swp_tb; +rcu_read_lock (); swp_tb =swap_table_get (__swap_entry_to_cluster (entry),swp_cluster_offset (entry)); +rcu_read_unlock ();if (swp_tb_is_shadow (swp_tb))return swp_tb_to_shadow (swp_tb);return NULL ;
@@ -406,14 +412,16 @@ void __swap_cache_replace_folio(struct swap_cluster_info *ci,* -ENOENT / -EEXIST: Target swap entry is unavailable or cached, the caller * should abort or try to use the cached folio instead */ -static struct folio *__swap_cache_alloc (struct swap_cluster_info *ci, -swp_entry_t targ_entry,gfp_t gfp, +static struct folio *__swap_cache_alloc (swp_entry_t targ_entry,gfp_t gfp,unsigned int order,struct vm_fault *vmf,struct mempolicy *mpol,pgoff_t ilx) {int err;swp_entry_t entry;struct folio *folio; +struct swap_cluster_info *ci; +struct swap_info_struct *si =__swap_entry_to_info (targ_entry); +unsigned long offset =swp_offset (targ_entry);void *shadow =NULL ;unsigned short memcg_id;unsigned long address, nr_pages =1UL << order;
@@ -423,9 +431,12 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci, entry.val =round_down (targ_entry.val, nr_pages);/* Check if the slot and range are available, skip allocation if not */ -spin_lock (&ci->lock); - err =__swap_cache_add_check (ci, targ_entry, nr_pages,NULL ,NULL ); -spin_unlock (&ci->lock); + err = -ENOENT ; + ci =swap_cluster_lock (si, offset); +if (ci) { + err =__swap_cache_add_check (ci, targ_entry, nr_pages,NULL ,NULL ); +swap_cluster_unlock (ci); + }if (unlikely (err))return ERR_PTR (err);
@@ -446,10 +457,13 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,return ERR_PTR (-ENOMEM );/* Double check the range is still not in conflict */ -spin_lock (&ci->lock); - err =__swap_cache_add_check (ci, targ_entry, nr_pages, &shadow, &memcg_id); + err = -ENOENT ; + ci =swap_cluster_lock (si, offset); +if (ci) + err =__swap_cache_add_check (ci, targ_entry, nr_pages, &shadow, &memcg_id);if (unlikely (err)) { -spin_unlock (&ci->lock); +if (ci) +swap_cluster_unlock (ci);folio_put (folio);return ERR_PTR (err); }
@@ -457,10 +471,11 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,__folio_set_locked (folio);__folio_set_swapbacked (folio);__swap_cache_do_add_folio (ci, folio, entry); -spin_unlock (&ci->lock); +swap_cluster_unlock (ci);if (mem_cgroup_swapin_charge_folio (folio, memcg_id, vmf ? vmf->vma->vm_mm :NULL , gfp)) { +/* The folio pins the cluster */ spin_lock (&ci->lock);__swap_cache_do_del_folio (ci, folio, entry, shadow);spin_unlock (&ci->lock);
@@ -517,9 +532,7 @@ struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp, {int order, err;struct folio *ret; -struct swap_cluster_info *ci; - ci =__swap_entry_to_cluster (targ_entry); order =highest_order (orders);/* orders must be non-zero, and must not exceed cluster size. */
@@ -527,7 +540,7 @@ struct folio *swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp,return ERR_PTR (-EINVAL ); do { - ret = __swap_cache_alloc(ci, targ_entry, gfp, order, + ret = __swap_cache_alloc(targ_entry, gfp, order, vmf, mpol, ilx); if (!IS_ERR(ret)) break;
mm/swap_table.h +4 -0
@@ -6,6 +6,8 @@#include <linux/atomic.h> #include "swap.h" +extern struct swap_info_struct *vswap_si; +/* A typical flat array in each cluster as swap table */ struct swap_table {atomic_long_t entries[SWAPFILE_CLUSTER ];
@@ -255,6 +257,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 +253 -18
474 lines not on this page · raw message
mm/vswap.h new file +34 -0
@@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Virtual swap space +* +* Copyright (C) 2026 Nhat Pham +*/ +#ifndef _MM_VSWAP_H +#define _MM_VSWAP_H + +#include <linux/jump_label.h> +#include <linux/swap.h> +#include "swap.h" + +#ifdef CONFIG_SWAP + +DECLARE_STATIC_KEY_FALSE (vswap_key); + +/* +* Only true once vswap_init() has published vswap_si, so callers never +* see the device half built. +*/ +static inline bool vswap_is_enabled (void ) +{ +return static_branch_unlikely (&vswap_key); +} + +static inline bool is_vswap_entry (swp_entry_t entry) +{ +return swap_is_vswap (__swap_entry_to_info (entry)); +} + +#endif /* CONFIG_SWAP */ + +#endif /* _MM_VSWAP_H */
mm/zswap.c +6 -0
@@ -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
Nhat Pham
maintainerPATCH v4 2/11 mm, swap: support zswap and zero-filled swap pages 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 later patches.
Zswap writeback of vswap-backed entries is also disabled: they have no physical slot to write back to yet, so the zswap shrinker (both the dynamic count path and the pool-full worker path) is skipped while vswap is enabled. Physical backing and real writeback come in later patches.
THP swapin is disabled for vswap entries for now.
vswap_alloc() only routes a swapout through vswap when vswap is enabled, either by CONFIG_VSWAP_DEFAULT_ON or by "vswap=on" on the kernel command line. It also declines the folio when zswap is off, or when the folio's cgroup is already over its zswap limit. In both cases writeout would have to find a physical slot anyway, so the indirection would buy nothing.
--- include/linux/zswap.h | 3 + mm/memcontrol.c | 8 ++ mm/memory.c | 11 ++- mm/page_io.c | 12 ++- mm/shmem.c | 4 +- mm/swap.h | 1 + mm/swap_state.c | 8 ++ mm/swapfile.c | 178 ++++++++++++++++++++++++++++++++++++++-- mm/vmscan.c | 9 +- mm/vswap.h | 185 ++++++++++++++++++++++++++++++++++++++++++ mm/zswap.c | 65 ++++++++++++--- 11 files changed, 458 insertions(+), 26 deletions(-)
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/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"
@@ -5801,6 +5802,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 +9 -2
@@ -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.
@@ -4661,6 +4662,9 @@ static inline bool should_try_to_free_swap(struct swap_info_struct *si,*/ if (data_race (si->flags &SWP_SYNCHRONOUS_IO ))return true; +/* A vswap entry holds no physical slot, so keeping it saves no IO. */ +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;
@@ -4809,15 +4813,18 @@ static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf)if (unlikely (userfaultfd_armed (vma)))return 0 ; + entry =softleaf_from_pte (vmf->orig_pte); +/* * A large swapped out folio could be partially or fully in zswap. We * lack handling for such cases, so fallback to swapping in order-0 * folio. +* +* THP swapin for vswap is not supported yet either. */ -if (!zswap_never_enabled ()) +if (is_vswap_entry (entry) || !zswap_never_enabled ())return 0 ; - entry =softleaf_from_pte (vmf->orig_pte);/* * Get a list of all the (large) orders below PMD_ORDER that are enabled * and suitable for swapping THP.
mm/page_io.c +10 -2
@@ -161,14 +161,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)); }
@@ -236,6 +241,9 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)*/ swap_zeromap_folio_clear (folio); +if (is_vswap_entry (folio->swap)) +folio_release_vswap_backing (folio); +if (zswap_store (folio)) {count_mthp_stat (folio_order (folio),MTHP_STAT_ZSWPOUT ); goto out_unlock;
mm/shmem.c +3 -1
@@ -86,6 +86,7 @@ static struct vfsmount *shm_mnt __ro_after_init;#include <linux/uaccess.h> #include "internal.h" +#include "vswap.h" #define VM_ACCT (size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
@@ -1618,7 +1619,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
@@ -71,6 +71,7 @@ struct swap_cluster_info_dynamic {struct swap_cluster_info ci;unsigned int index;/* for cluster_index() */ struct rcu_head rcu; +atomic_long_t *virtual_table;/* Backing pointers for vswap slots */ };/* All on-list cluster must have a non-zero flag. */
mm/swap_state.c +8 -0
@@ -27,6 +27,7 @@#include "internal.h" #include "swap_table.h" #include "swap.h" +#include "vswap.h" /* Swap readahead cluster size, as a power of 2 pages. */ static int page_cluster;
@@ -197,6 +198,13 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,if (nr ==1 )return 0 ; +/* +* Reject a vswap batch so swap_cache_alloc_folio falls back to +* order 0. +*/ +if (is_vswap_entry (targ_entry)) +return -EBUSY ; + is_zero =__swap_table_test_zero (ci, ci_off); ci_off =round_down (ci_off, nr); ci_end = ci_off + nr;
mm/swapfile.c +170 -8
299 lines not on this page · raw message
mm/vmscan.c +7 -2
@@ -69,6 +69,7 @@#include "internal.h" #include "page_alloc.h" #include "swap.h" +#include "vswap.h" #define CREATE_TRACE_POINTS #include <trace/events/vmscan.h>
@@ -353,6 +354,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 )
@@ -1524,7 +1528,8 @@ static unsigned int shrink_folio_list(struct list_head *folio_list, activate_locked:/* Not a candidate for swapping, so reclaim swap space. */ if (folio_test_swapcache (folio) && - (mem_cgroup_swap_full (folio) ||folio_test_mlocked (folio))) + ((mem_cgroup_swap_full (folio) && !is_vswap_entry (folio->swap)) || +folio_test_mlocked (folio)))folio_free_swap (folio);VM_BUG_ON_FOLIO (folio_test_active (folio), folio);if (!folio_test_mlocked (folio)) {
@@ -2681,7 +2686,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 +185 -0
199 lines not on this page · raw message
mm/zswap.c +54 -11
149 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v4 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.
The swap IO path derives the target device and sector from folio->swap. For a vswap folio backed by a physical slot that entry is virtual, so it identifies neither the backing device nor the sector to submit IO against.
Compute the sector from an explicit entry (swap_folio_sector becomes swap_entry_sector), thread that entry through swap_add_folio, __swap_writepage and ops->can_merge, and stash it in swap_iocb so the submit and completion paths address the IO from it rather than from folio->swap.
This lets the batching path serve both vswap entries (backed by a physical slot) and physical entries mapped directly into PTEs.
All callers pass folio->swap for now, so there is no functional change.
--- include/linux/swap.h | 2 +- include/linux/swap_ops.h | 9 ++++--- mm/page_io.c | 54 +++++++++++++++++++--------------------- mm/swap.h | 3 ++- mm/swapfile.c | 6 ++--- mm/zswap.c | 2 +- 6 files changed, 38 insertions(+), 38 deletions(-)
include/linux/swap.h +1 -1
@@ -388,7 +388,7 @@ extern int __swap_count(swp_entry_t entry);extern bool swap_entry_swapped (struct swap_info_struct *si,swp_entry_t entry);extern int swp_swapcount (swp_entry_t entry);extern struct swap_info_struct *get_swap_device (swp_entry_t entry); -sector_t swap_folio_sector (struct folio *folio); +sector_t swap_entry_sector (swp_entry_t entry);/* * If there is an existing swap slot reference (swap entry) and the caller
include/linux/swap_ops.h +5 -4
@@ -12,6 +12,7 @@ struct swap_iocb {struct bio_vec bvecs[SWAP_CLUSTER_MAX ];int nr_bvecs;int len; +swp_entry_t entry;/* first slot in the batch; addresses the IO */ };struct swap_io_ctx {
@@ -30,15 +31,15 @@ struct swap_io_ctx {struct swap_ops {unsigned int flags; -bool (*can_merge)(struct folio *folio,struct folio *prev_folio, -size_t prev_folio_size,int rw); +bool (*can_merge)(struct folio *folio,swp_entry_t phys, +struct swap_iocb *sio,int rw);void (*submit_write)(struct swap_io_ctx *ctx);void (*submit_read)(struct swap_io_ctx *ctx); };void swap_fs_prepare_rw (struct swap_io_ctx *ctx,int rw,struct iov_iter *iter); -bool swap_fs_can_merge (struct folio *folio,struct folio *prev_folio, -size_t prev_folio_size,int rw); +bool swap_fs_can_merge (struct folio *folio,swp_entry_t phys, +struct swap_iocb *sio,int rw);int swap_fs_activate (struct swap_info_struct *sis,const struct swap_ops *ops);#endif /* _MM_SWAP_OPS_H */
mm/page_io.c +26 -28
144 lines not on this page · raw message
mm/swap.h +2 -1
@@ -320,7 +320,8 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio);void swap_read_submit (struct swap_io_ctx *ctx);void swap_write_submit (struct swap_io_ctx *ctx);int swap_writeout (struct swap_io_ctx *ctx,struct folio *folio); -void __swap_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
@@ -343,14 +343,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 v4 5/11 mm, swap: enable THP swapin for vswap entries
In reply to Nhat PhamSwap a large anon folio back in as a unit when its vswap entries share a contiguous run of physical swap slots on a synchronous IO device, instead of always falling back to order-0 faults.
A zswap-backed or mixed-backing batch is still refused, and the fault retries at a smaller order.
--- mm/memory.c | 5 +++-- mm/swap_state.c | 17 +++++++++++++---- mm/zswap.c | 19 +++++++++++++------ 3 files changed, 29 insertions(+), 12 deletions(-)
mm/memory.c +3 -2
@@ -4823,9 +4823,10 @@ static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf)* lack handling for such cases, so fallback to swapping in order-0 * folio. * -* THP swapin for vswap is not supported yet either. +* Vswap entries are checked later, under the cluster lock in +* __swap_cache_add_check(). */ -if (is_vswap_entry (entry) || !zswap_never_enabled ()) +if (!is_vswap_entry (entry) && !zswap_never_enabled ())return 0 ;/*
mm/swap_state.c +13 -4
@@ -174,6 +174,9 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,unsigned int ci_off, ci_end;unsigned long old_tb;bool is_zero; +struct swap_cluster_info_dynamic *ci_dyn; +enum vswap_backing_type type; +int ret;lockdep_assert_held (&ci->lock);
@@ -202,11 +205,17 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,return 0 ;/* -* Reject a vswap batch so swap_cache_alloc_folio falls back to -* order 0. +* For a vswap entry batch, reject if the backing is not THP-amenable +* (e.g. uniformly ZSWAP, or mixed). The order-fallback loop in +* swap_cache_alloc_folio will retry with a smaller order on -EBUSY. */ -if (is_vswap_entry (targ_entry)) -return -EBUSY ; +if (is_vswap_entry (targ_entry)) { + ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci); + ret =__vswap_check_backing (ci_dyn,round_down (ci_off, nr), + nr, &type); +if (ret != nr || type ==VSWAP_ZSWAP ) +return -EBUSY ; + } is_zero =__swap_table_test_zero (ci, ci_off); ci_off =round_down (ci_off, nr);
mm/zswap.c +13 -6
@@ -1629,9 +1629,9 @@ bool zswap_store(struct folio *folio)* will SIGBUS). * * -EINVAL: if the swapped out content was in zswap, but the page belongs -* to a large folio, which is not supported by zswap. The folio is unlocked, -* but NOT marked up-to-date, so that an IO error is emitted (e.g. -* do_swap_page() will SIGBUS). +* to a large non-vswap folio, which is not supported by zswap. The folio +* is unlocked, but NOT marked up-to-date, so that an IO error is emitted +* (e.g. do_swap_page() will SIGBUS). * * -ENOENT: if the swapped out content was not in zswap. The folio remains * locked on return.
@@ -1652,10 +1652,17 @@ int zswap_load(struct folio *folio)* 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. +* +* A large vswap folio cannot reach here ZSWAP-backed, since +* __swap_cache_add_check() refuses such a batch, so hand it to the +* phys path without warning. */ -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 v4 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.
swapoff reads each vswap entry back through its rmap slot before freeing the physical slot. A failed read leaves the folio not uptodate, so drop it instead of marking it dirty: dirtying would write uninitialised memory out to swap, and the loss is now reported as SIGBUS on the next fault rather than silently returning stale data.
If zswap is disabled at the host level or for the folio's cgroup, the folio still gets a physical swap slot, bypassing vswap and mapping the slot directly into the PTEs. In practice the swapfile backend is only reached when zswap declines the folio at swap_writeout() time, most often because the pool is full.
The machinery is in place, but its main consumer is not. Zswap writeback to physical swap is added in a following patch. Reclaim of physical slots backing cache-only vswap entries follows it.
--- mm/memory.c | 13 +- mm/page_io.c | 42 ++++-- mm/swap_state.c | 6 +- mm/swap_table.h | 42 +++++- mm/swapfile.c | 358 +++++++++++++++++++++++++++++++++++++++++++----- mm/vmscan.c | 2 +- mm/vswap.h | 198 +++++++++++++++++++++++++- mm/zswap.c | 2 +- 8 files changed, 602 insertions(+), 61 deletions(-)
mm/memory.c +8 -5
@@ -4660,10 +4660,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; -/* A vswap entry holds no physical slot, so keeping it saves no IO. */ -if (is_vswap_entry (folio->swap)) +/* +* Non-swapfile backends cannot be reused for future swapouts. +* Free the swap slot unless backed by contiguous physical swap. +*/ +if (!folio_phys_swap_backed (folio))return true;if (mem_cgroup_swap_full (folio) || (vma->vm_flags &VM_LOCKED ) ||folio_test_mlocked (folio))
@@ -4970,7 +4973,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 );
@@ -5135,7 +5138,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 -8
79 lines not on this page · raw message
mm/swap_state.c +5 -1
@@ -186,6 +186,9 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,return -ENOENT ; ci_off =swp_cluster_offset (targ_entry); old_tb =__swap_table_get (ci, ci_off); +/* Physical readahead can hit a vswap-backing rmap slot; skip it. */ +if (swp_tb_is_pointer (old_tb)) +return -ENOENT ;if (swp_tb_is_folio (old_tb))return -EEXIST ;if (!__swp_tb_get_count (old_tb))
@@ -210,7 +213,8 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci, ci_end = ci_off + nr; do { old_tb = __swap_table_get(ci, ci_off); - if (unlikely(swp_tb_is_folio(old_tb) || + if (unlikely(swp_tb_is_pointer(old_tb) || + swp_tb_is_folio(old_tb) || !__swp_tb_get_count(old_tb) || is_zero != __swap_table_test_zero(ci, ci_off) || (memcg_id && *memcg_id != __swap_cgroup_get(ci, ci_off))))
mm/swap_table.h +38 -4
64 lines not on this page · raw message
mm/swapfile.c +321 -37
507 lines not on this page · raw message
mm/vmscan.c +1 -1
@@ -1528,7 +1528,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list, activate_locked:/* Not a candidate for swapping, so reclaim swap space. */ if (folio_test_swapcache (folio) && - ((mem_cgroup_swap_full (folio) && !is_vswap_entry (folio->swap)) || + ((mem_cgroup_swap_full (folio) &&folio_phys_swap_backed (folio)) ||folio_test_mlocked (folio)))folio_free_swap (folio);VM_BUG_ON_FOLIO (folio_test_active (folio), folio);
mm/vswap.h +194 -4
241 lines not on this page · raw message
mm/zswap.c +1 -1
@@ -1598,7 +1598,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 v4 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.
The zswap shrinker no longer skips vswap entries, unless we are out of physical swap space.
--- mm/zswap.c | 67 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 21 deletions(-)
mm/zswap.c +46 -21
@@ -1007,12 +1007,13 @@ static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio)static int zswap_writeback_entry (struct zswap_entry *entry,swp_entry_t swpentry) { -struct xarray *tree;pgoff_t offset =swp_offset (swpentry);struct folio *folio;struct mempolicy *mpol;struct swap_info_struct *si;struct swap_io_ctx ctx = {}; +swp_entry_t phys = {}; +bool is_vswap;int ret =0 ;/* try to allocate swap cache folio */
@@ -1020,12 +1021,7 @@ 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 ; - } - + is_vswap =swap_is_vswap (si); mpol =get_task_policy (current); folio =swap_cache_alloc_folio (swpentry,GFP_KERNEL ,BIT (0 ),NULL , mpol,NO_INTERLEAVE_INDEX );
@@ -1044,24 +1040,44 @@ static int zswap_writeback_entry(struct zswap_entry *entry,/* * folio is locked, and the swapcache is now secured against * concurrent swapping to and from the slot, and concurrent -* swapoff so we can safely dereference the zswap tree here. +* swapoff so we can safely dereference the zswap tree (or vswap +* vtable) here. * Verify that the swap entry hasn't been invalidated and recycled * behind our backs, to avoid overwriting a new swap folio with * old compressed data. Only when this is successful can the entry * be dereferenced. */ - tree =swap_zswap_tree (swpentry); -if (entry !=xa_load (tree, offset)) { +if (entry !=zswap_entry_load (swpentry)) { ret = -ENOMEM ; goto out; } +if (is_vswap) { +/* +* Allocate physical backing before decompress so a failure +* wastes no work. +*/ + phys =folio_realloc_swap (folio); +if (!phys.val) { + ret = -ENOMEM ; + goto out; + } + } +if (!zswap_decompress (entry, folio)) { ret = -EIO ; +/* +* The phys allocation above took the entry out of the vtable. +* Restore the zswap entry to the vtable, which also frees the +* allocated physical swap space. +*/ +if (is_vswap) +vswap_zswap_store (swpentry, entry); goto out; } -xa_erase (tree, offset); +if (!is_vswap) +xa_erase (swap_zswap_tree (swpentry), offset);count_vm_event (ZSWPWB );if (entry->objcg)
@@ -1076,7 +1092,10 @@ static int zswap_writeback_entry(struct zswap_entry *entry,folio_set_reclaim (folio);/* start writeback */ -__swap_writepage (&ctx, folio, folio->swap); +if (is_vswap) +__swap_writepage (&ctx, folio, phys); +else +__swap_writepage (&ctx, folio, folio->swap);swap_write_submit (&ctx); out:
@@ -1091,6 +1110,15 @@ static int zswap_writeback_entry(struct zswap_entry *entry,/********************************* * shrinker functions **********************************/ +/* +* vswap zswap entries get a physical slot allocated on demand at writeback +* time. Skip the shrinker when none is available. +*/ +static bool zswap_writeback_possible (void ) +{ +return !vswap_is_enabled () ||get_nr_swap_pages () >0 ; +} +/* * The dynamic shrinker is modulated by the following factors: *
@@ -1228,7 +1256,7 @@ static unsigned long zswap_shrinker_count(struct shrinker *shrinker,if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled (memcg))return 0 ; -if (vswap_is_enabled ()) +if (!zswap_writeback_possible ())return 0 ;/*
@@ -1314,7 +1342,8 @@ static struct shrinker *zswap_alloc_shrinker(void)* were scanned but none could be written back, or -ENOENT if @memcg has * writeback disabled, is a zombie cgroup, or has empty zswap LRUs. * -* Also returns -ENOENT when vswap is enabled. +* Also returns -ENOENT when vswap is enabled and there is no physical +* swap to write back to. */ static int shrink_memcg (struct mem_cgroup *memcg) {
@@ -1323,7 +1352,7 @@ static int shrink_memcg(struct mem_cgroup *memcg)if (!mem_cgroup_zswap_writeback_enabled (memcg))return -ENOENT ; -if (vswap_is_enabled ()) +if (!zswap_writeback_possible ())return -ENOENT ;/*
@@ -1354,11 +1383,7 @@ static void shrink_worker(struct work_struct *w)int ret, failures =0 , attempts =0 ;unsigned long thr; -/* -* When vswap is enabled, zswap entries are almost all vswap backed, -* with no slot to write back to. -*/ -if (vswap_is_enabled ()) +if (!zswap_writeback_possible ())return ;/* Reclaim down to the accept threshold */
@@ -1439,7 +1464,7 @@ static void shrink_worker(struct work_struct *w)break ; resched:cond_resched (); - }while (zswap_total_pages () > thr); + }while (zswap_total_pages () > thr &&zswap_writeback_possible ()); }/*********************************
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v4 7/11 mm, swap: reclaim physical slots backing cache-only vswap entries
In reply to Nhat PhamWhen a vswap entry's swap_count drops to 0 while its folio is still in the swap cache, the entry is cache-only and its physical slot is redundant. 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 | 12 +++-- mm/swapfile.c | 115 ++++++++++++++++++++++++++++++++++++++++++++++++ mm/vswap.h | 31 +++++++++++++ 3 files changed, 154 insertions(+), 4 deletions(-)
mm/swap_table.h +8 -4
@@ -31,7 +31,7 @@ struct swap_memcg_table {* NULL: |---------------- 0 ---------------| - Free slot * Shadow: |SWAP_COUNT|Z|---- SHADOW_VAL ---|1| - Swapped out slot * PFN: |SWAP_COUNT|Z|------ PFN -------|10| - Cached slot -* Pointer: |-------- vswap offset --------|100| - vswap rmap +* Pointer: |C|------- vswap offset -------|100| - vswap rmap * Bad: |------------- 1 -------------|1000| - Bad slot * * COUNT is `SWP_TB_COUNT_BITS` long, Z is the `SWP_TB_ZERO_FLAG` bit,
@@ -376,14 +376,18 @@ static inline unsigned short __swap_cgroup_clear(struct swap_cluster_info *ci,* On physical clusters, a Pointer-tagged entry stores the offset of the * vswap entry that owns this physical slot (the reverse map). Only the * offset is stored; the swap type is implicit (always vswap_si->type, -* since there is exactly one vswap device). +* since there is exactly one vswap device). The top bit is reserved as +* a cache-only flag, set when vswap swap_count drops to 0 but the folio +* is still in swap cache. * -* Pointer: |---- vswap offset ----|100| +* Pointer: |C|---- vswap offset ----|100| +* C = SWP_RMAP_CACHE_ONLY (bit 63) */ #define SWP_TB_PTR_MARK_BITS 3#define SWP_TB_PTR_MARK 0b100UL#define SWP_TB_PTR_MARK_MASK ((1UL << SWP_TB_PTR_MARK_BITS) - 1) -#define SWP_RMAP_ENTRY_MASK (~SWP_TB_PTR_MARK_MASK) +#define SWP_RMAP_CACHE_ONLY (1UL << (BITS_PER_LONG - 1)) +#define SWP_RMAP_ENTRY_MASK (~(SWP_RMAP_CACHE_ONLY | SWP_TB_PTR_MARK_MASK))static inline bool swp_tb_is_pointer (unsigned long swp_tb) {
mm/swapfile.c +115 -0
157 lines not on this page · raw message
mm/vswap.h +31 -0
@@ -44,6 +44,37 @@ static inline bool is_vswap_entry(swp_entry_t entry)return swap_is_vswap (__swap_entry_to_info (entry)); } +/* +* Rmap cache-only helpers for physical cluster Pointer-tagged entries. +* SWP_RMAP_CACHE_ONLY records, inline on the physical swap_table entry, +* that the backing vswap entry has swap_count == 0 (swap-cache-only, so +* reclaimable). The physical reclaim scanner reads it directly instead of +* chasing the rmap into the vswap layer and paying the cluster-lookup +* indirection. +* +* Callers hold the vswap cluster lock, not the physical one. The rmap is +* only touched while the vtable holds the slot as SWAPFILE, and that +* window is opened and closed under the vswap cluster lock, so the +* allocator has finished writing the entry by then. +*/ +static inline void swap_rmap_mark_cache_only (struct swap_cluster_info *ci, +unsigned int off) +{ +atomic_long_t *table; + + table =rcu_dereference_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 v4 8/11 mm, swap: only charge physical swap entries
In reply to Nhat PhamZswap-backed and zero-filled pages occupy no swap space, but were charged against memcg->swap as though they did.
Charge memcg->swap when a vswap entry acquires physical backing rather than when it is allocated.
memory.swap.current therefore counts only on-disk swap usage, not zswap-backed or zero-filled pages. When vswap is enabled, a cgroup can reclaim its anon memory even with memory.swap.max set to 0, provided zswap is allowed for it.
Also refactor the swap memcg operations into separate get, record, charge, uncharge and put helpers, since recording the owner and charging it no longer happen at the same time.
Direct-mapped physical swap charging is unchanged. So is cgroup v1 memsw
accounting: the folio's memsw charge is retained across swapout regardless of backing, and released when the entry is freed.
--- .../admin-guide/cgroup-v1/memcg_test.rst | 2 +- include/linux/memcontrol.h | 6 + include/linux/swap.h | 61 +++++++- mm/memcontrol-v1.c | 10 +- mm/memcontrol.c | 148 +++++++++++------- mm/swapfile.c | 128 +++++++++++++-- 6 files changed, 279 insertions(+), 76 deletions(-)
Documentation/admin-guide/cgroup-v1/memcg_test.rst +1 -1
@@ -43,7 +43,7 @@ Please note that implementation details can be changed. mem_cgroup_uncharge() Called when a page's refcount goes down to 0. - mem_cgroup_uncharge_swap() + mem_cgroup_swap_uncharge() Called when swp_entry's refcnt goes down to 0. A charge against swap disappears.
include/linux/memcontrol.h +6 -0
@@ -1905,6 +1905,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);
@@ -1913,6 +1914,11 @@ static inline bool obj_cgroup_may_zswap(struct obj_cgroup *objcg) {return true; } + +static inline bool mem_cgroup_may_zswap (struct mem_cgroup *memcg,bool may_flush) +{ +return true; +}static inline void obj_cgroup_charge_zswap (struct obj_cgroup *objcg,size_t size) {
include/linux/swap.h +53 -8
88 lines not on this page · raw message
mm/memcontrol-v1.c +9 -1
@@ -690,6 +690,7 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)void memcg1_swapin (struct folio *folio) {struct swap_cluster_info *ci; +struct mem_cgroup *memcg;unsigned long nr_pages;unsigned short id;
@@ -721,7 +722,14 @@ void memcg1_swapin(struct folio *folio) id =__swap_cgroup_clear (ci,swp_cluster_offset (folio->swap), nr_pages);swap_cluster_unlock (ci); - mem_cgroup_uncharge_swap(id, nr_pages); + +rcu_read_lock (); + memcg =mem_cgroup_from_private_id (id); +if (memcg) { +mem_cgroup_swap_uncharge (memcg, nr_pages); +mem_cgroup_swap_put (memcg, nr_pages); + } + rcu_read_unlock(); }#endif
mm/memcontrol.c +94 -54
231 lines not on this page · raw message
mm/swapfile.c +116 -12
222 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v4 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 | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+)
mm/swapfile.c +26 -0
@@ -7,6 +7,7 @@*/ #include <linux/blkdev.h> +#include <linux/debugfs.h> #include <linux/mm.h> #include <linux/sched/mm.h> #include <linux/sched/task.h>
@@ -142,6 +143,8 @@ static DEFINE_PER_CPU(struct percpu_vswap_cluster, percpu_vswap_cluster) = { .lock = INIT_LOCAL_LOCK(), }; +static atomic_long_t vswap_alloc_reject =ATOMIC_LONG_INIT (0 ); +static bool vswap_alloc (struct folio *folio);static void vswap_mark_cache_only (struct swap_cluster_info *ci,unsigned int ci_off);
@@ -1983,6 +1986,7 @@ static bool vswap_alloc(struct folio *folio)this_cpu_write (percpu_vswap_cluster.offset[order],SWAP_ENTRY_INVALID );local_unlock (&percpu_vswap_cluster.lock); +atomic_long_add (folio_nr_pages (folio), &vswap_alloc_reject);return false; }
@@ -4795,9 +4799,25 @@ early_param("vswap", early_vswap);/* vswap does no IO on its own. */ static const struct swap_ops vswap_ops = { }; +static int vswap_used_get (void *data,u64 *val) +{ + *val =swap_usage_in_pages (vswap_si); +return 0 ; +} +DEFINE_DEBUGFS_ATTRIBUTE (vswap_used_fops, vswap_used_get,NULL ,"%llu\n" ); + +static int vswap_alloc_reject_get (void *data,u64 *val) +{ + *val =atomic_long_read (&vswap_alloc_reject); +return 0 ; +} +DEFINE_DEBUGFS_ATTRIBUTE (vswap_alloc_reject_fops, vswap_alloc_reject_get,NULL , +"%llu\n" ); +static int __init vswap_init (void ) {struct swap_info_struct *si; +struct dentry *root;unsigned long maxpages;int err;
@@ -4841,6 +4861,12 @@ static int __init vswap_init(void)mutex_unlock (&swapon_mutex); vswap_si = si; + + root =debugfs_create_dir ("vswap" ,NULL ); +debugfs_create_file ("used" ,0444 , root,NULL , &vswap_used_fops); +debugfs_create_file ("alloc_reject" ,0444 , root,NULL , + &vswap_alloc_reject_fops); +pr_info ("vswap: created virtual swap device (%lu pages)\n" , maxpages);/* Last: everything above must be visible before routing starts. */
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v4 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 where the table is known to be needed: every vswap cluster, and, when vswap is off, every physical cluster, since all of its slots then map directly into the PTEs. A physical cluster otherwise allocates on its first direct-use slot, and skips entirely if it only holds vswap backings. That deferred allocation can fail, though rarely.
--- mm/swapfile.c | 85 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 66 insertions(+), 19 deletions(-)
mm/swapfile.c +66 -19
@@ -471,7 +471,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;
@@ -494,7 +495,14 @@ 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 ()) { +/* +* A physical cluster under vswap may hold only vswap backings, which +* record their memcg on the vswap cluster's table, not this one. Such +* clusters defer memcg_table allocation until they hand out a slot +* that maps directly into the PTEs. +*/ +if ((!vswap_is_enabled () ||swap_is_vswap (si)) && + !mem_cgroup_disabled ()) {VM_WARN_ON_ONCE (ci->memcg_table); ci->memcg_table =kzalloc_obj (*ci->memcg_table, gfp);if (!ci->memcg_table) {
@@ -565,8 +573,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;/*
@@ -579,8 +587,8 @@ swap_cluster_populate(struct swap_info_struct *si,spin_unlock (&si->global_cluster_lock);local_unlock (&percpu_swap_cluster.lock); - ret =swap_cluster_alloc_table (ci, __GFP_HIGH | __GFP_NOMEMALLOC | -GFP_KERNEL ); + ret =swap_cluster_alloc_table (si, ci, __GFP_HIGH | __GFP_NOMEMALLOC | +GFP_KERNEL );/* * Back to atomic context. We might have migrated to a new CPU with a
@@ -857,7 +865,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. */
@@ -1079,7 +1087,9 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,/* Try use a new cluster for current CPU and allocate from it. */ static unsigned int alloc_swap_scan_cluster (struct swap_info_struct *si,struct swap_cluster_info *ci, -struct folio *folio,unsigned long offset) +struct folio *folio, +unsigned long offset, +bool *nomem) {unsigned int next =SWAP_ENTRY_INVALID , found =SWAP_ENTRY_INVALID ;unsigned long start =ALIGN_DOWN (offset,SWAPFILE_CLUSTER );
@@ -1108,6 +1118,24 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,if (!ret)continue ; } +#ifdef CONFIG_MEMCG +/* +* Lazy-allocate memcg_table on the first direct-use slot of a +* physical cluster. +*/ +if (vswap_is_enabled () && folio && + !folio_test_swapcache (folio) && !mem_cgroup_disabled () && + !ci->memcg_table) { + ci->memcg_table =kzalloc_obj (*ci->memcg_table, +GFP_ATOMIC | __GFP_NOMEMALLOC | + __GFP_NOWARN); +if (!ci->memcg_table) { +if (nomem) + *nomem = true; + goto out; + } + } +#endif if (!__swap_cluster_alloc_entries (si, ci, folio, offset %SWAPFILE_CLUSTER ))break ; found = offset;
@@ -1117,7 +1145,15 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,break ; } out: -relocate_cluster (si, ci); +/* +* On a discard-capable device, relocating a cluster whose memcg_table +* allocation failed queues a discard for slots that were never used, +* which folio_alloc_phys_swap() reads as progress and retries on. +*/ +if (nomem && *nomem && !ci->count) +__free_cluster (si, ci); +else +relocate_cluster (si, ci);swap_cluster_unlock (ci);if (swap_is_vswap (si)) {this_cpu_write (percpu_vswap_cluster.offset[order], next);
@@ -1138,7 +1174,13 @@ static unsigned int alloc_swap_scan_list(struct swap_info_struct *si, bool scan_all) {unsigned int found =SWAP_ENTRY_INVALID ; +bool nomem = false; +/* +* In rare cases alloc_swap_scan_cluster() can fail due to +* memcg_table allocation failure. Short-circuit to avoid looping +* over the list indefinitely. +*/ do { struct swap_cluster_info *ci = isolate_lock_cluster(si, list); unsigned long offset;
@@ -1146,10 +1188,10 @@ static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,if (!ci)break ; offset =cluster_offset (si, ci); - found =alloc_swap_scan_cluster (si, ci, folio, offset); + found =alloc_swap_scan_cluster (si, ci, folio, offset, &nomem);if (found)break ; - }while (scan_all); + }while (scan_all && !nomem);return found; }
@@ -1170,7 +1212,7 @@ static unsigned int vswap_alloc_cluster(struct swap_info_struct *si,spin_lock_init (&ci_dyn->ci.lock);INIT_LIST_HEAD (&ci_dyn->ci.list); -if (swap_cluster_alloc_table (&ci_dyn->ci,GFP_ATOMIC )) { +if (swap_cluster_alloc_table (si, &ci_dyn->ci,GFP_ATOMIC )) {kfree (ci_dyn);return SWAP_ENTRY_INVALID ; }
@@ -1196,7 +1238,7 @@ static unsigned int vswap_alloc_cluster(struct swap_info_struct *si, } offset =cluster_offset (si, ci); -return alloc_swap_scan_cluster (si, ci, folio, offset); +return alloc_swap_scan_cluster (si, ci, folio, offset,NULL ); }static void swap_reclaim_full_clusters (struct swap_info_struct *si,bool force)
@@ -1303,7 +1345,8 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,if (cluster_is_usable (ci, order)) {if (cluster_is_empty (ci)) offset =cluster_offset (si, ci); - found =alloc_swap_scan_cluster (si, ci, folio, offset); + found =alloc_swap_scan_cluster (si, ci, folio, offset, +NULL ); }else {swap_cluster_unlock (ci); }
@@ -1347,7 +1390,8 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,if (order <PMD_ORDER ) {/* * Scan only one fragment cluster is good enough. Order 0 -* allocation will surely success, and large allocation +* allocation will surely success unless the memcg table +* allocation fails, which is rare, and large allocation * failure is not critical. Scanning one cluster still * keeps the list rotated and reclaimed (for clean swap cache). */
@@ -1363,7 +1407,8 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,for (int o =1 ; o <SWAP_NR_ORDERS ; o++) {/* * Clusters here have at least one usable slots and can't fail order 0 -* allocation, but reclaim may drop si->lock and race with another user. +* allocation, but reclaim may drop si->lock and race with another user, +* and the memcg table allocation may fail. */ found =alloc_swap_scan_list (si, &si->frag_clusters[o], folio, true);if (found)
@@ -1586,7 +1631,7 @@ static swp_entry_t swap_alloc_fast(struct folio *folio)if (ci &&cluster_is_usable (ci, order)) {if (cluster_is_empty (ci)) offset =cluster_offset (si, ci); - found =alloc_swap_scan_cluster (si, ci, folio, offset); + found =alloc_swap_scan_cluster (si, ci, folio, offset,NULL ); }else if (ci) {swap_cluster_unlock (ci); }
@@ -1969,7 +2014,8 @@ static bool vswap_alloc(struct folio *folio)if (ci &&cluster_is_usable (ci, order)) {if (cluster_is_empty (ci)) offset =cluster_offset (vswap_si, ci); -alloc_swap_scan_cluster (vswap_si, ci, folio, offset); +alloc_swap_scan_cluster (vswap_si, ci, folio, offset, +NULL ); }else if (ci) {swap_cluster_unlock (ci); }
@@ -2836,7 +2882,8 @@ swp_entry_t swap_alloc_hibernation_slot(int type)if (pcp_si == si && pcp_offset) { ci =swap_cluster_lock (si, pcp_offset);if (cluster_is_usable (ci,0 )) - offset =alloc_swap_scan_cluster (si, ci,NULL , pcp_offset); + offset =alloc_swap_scan_cluster (si, ci,NULL , + pcp_offset,NULL );else swap_cluster_unlock (ci); }
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerPATCH v4 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 previous 16 TB cap with 4 KB pages (ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) pages).
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 | 63 ++++++++++++++++++++++---------------------- 2 files changed, 34 insertions(+), 33 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 -31
147 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
Andrew Morton
maintainerQuoted 8 lines · On Tue, 25 Aug 2026 08:32:26 -0700 Nhat Pham <[email protected]> wrote:
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.
Quoted 7 lines
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:
Thanks.
I asked Gemini for a tl;dr and was told
: Introduce Virtual Swap Space (vswap) to decouple swap entry management : from physical disk slots by using dynamically allocated virtual : clusters that back swap entries on demand via zswap, zero-filled pages, : or physical disk. Eliminate wasted storage space, remove the need for : static swapfile provisioning, and enable in-memory swap features on : diskless systems without degrading performance.
I'll take no action at this time - let's see what the other swap developers make of this.
Sashiko was talkative, as usual:
https://sashiko.dev/#/patchset/[email protected]
There are a few pre-existing things in among this, They look legit to me, from a quick read. SWAP_USAGE_OFFLIST_BIT should use BITS_PER_TYPE(atomic_long_t)?
Nhat Pham
maintainerQuoted 30 lines · Andrew Morton
Quoted 8 lines · On Tue, 25 Aug 2026 08:32:26 -0700 Nhat Pham <[email protected]> wrote:
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.
Quoted 7 lines
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:
Thanks.
I asked Gemini for a tl;dr and was told
: Introduce Virtual Swap Space (vswap) to decouple swap entry management : from physical disk slots by using dynamically allocated virtual : clusters that back swap entries on demand via zswap, zero-filled pages, : or physical disk. Eliminate wasted storage space, remove the need for : static swapfile provisioning, and enable in-memory swap features on : diskless systems without degrading performance.
Quoted 2 lines
I'll take no action at this time - let's see what the other swap developers make of this.
Hi Andrew!
Thanks for taking a look. I'm also waiting for review from fellow swappers :)
Quoted 3 lines
Sashiko was talkative, as usual:
https://sashiko.dev/#/patchset/[email protected]
I've been going through the sashiko review on every iterations! Hopefully the list will keep getting smaller and smaller.
There are a couple of false positives, as per usual (the first issue for e.g was intended behavior, at the point of that patch at least).
Quoted 4 lines · That
There are a few pre-existing things in among this, They look legit to me, from a quick read.
SWAP_USAGE_OFFLIST_BITshould useBITS_PER_TYPE(atomic_long_t)?
I think that might be pre-existing. Maybe we just have not seen users who used 4TB+ swapfile yet?
Might be worth just putting in a quick fix independent of this patch series just in case.
Let me see if I can quickly whip sth up :)