mm, swap: Virtual Swap Space (Swap Table Edition)
Subsystems (8)
Nhat Pham
maintainerv2 cover mm, swap: Virtual Swap Space (Swap Table Edition)
Changelog:
* 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 [14].
* 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 6).
* 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 7).
* 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 the arguably central shortcoming of zswap:
* 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 [4].
* Resource-wise, it is hugely wasteful in terms of disk usage. At Meta, we have swapfile in the order of tens to hundreds of GBs, which are mostly unused and only exist to enable zswap usage and zero-filled pages swap optimizations.
* 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).
There are a lot of other future use cases as well - see [1] for more details.
This is the culmination of many years worth of discussions, designs, and prototypes. A brief history:
* The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [16]).
* Yosry brought up this proposal again at LSFMMBPF 2023 (see [17]), and I have been working on this shortly after (see [1]).
* The final missing piece is the swap table infrastructure and efficient swap allocator, which is conceptualized and implemented by Kairui Song and Chris Li (the latest version is [18]). I added the dynamicization of swap allocator via radix trees/xarrays (but the concept of dynamic clusters is not mine - Johannes proposed it to me).
There are more contexts (and references) in the [1], for those interested.
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.
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 | |
| | PHYS(swp_entry_t) | |
| | ZSWAP(struct zswap_entry*) | |
| +----------------------------+ |
+---------------------------------+
|
| PHYS 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 PHYS: |-- (type:5,off:N)|001| on a physical swapfile (shifted) ZSWAP: |--- zswap_entry* |010| compressed in zswap
Zero-filled pages and swap-cached folios do not get their own vtable tag. A zero page is recorded in the swap_table per-slot zero flag, and a cached folio is just the swap_table PFN entry. We still have VSWAP_ZERO and VSWAP_FOLIO in the backing type enum, but this is purely for convenience in the code that needs to determine the backing of vswap entries.
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 practically have very minimal (if not 0) extra space overhead!
Other design points:
* Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens. When CONFIG_VSWAP=n, the vswap branches compile out and behavior should be unchanged.
* 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 [7]).
See the patch series for more of the gory implementation details :)
III. Benchmarks
===============
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. This is to double check that I did not regress the 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) 107.56 +/- 10.69 110.44 +/- 20.80 108.36 +/- 17.10
sys (s) 90.72 +/- 10.57 93.33 +/- 20.23 91.39 +/- 16.18
delta real - +2.7% +0.7% delta sys - +2.9% +0.7%
Note: for some reason, the first 1-2 rounds are significantly slower, for all 3 kernels. No idea why, but probably because we need to allocate swap clusters etc.? So I have decided to run 20 rounds to cancel out the noise :)
If I drop the worst and the best rounds, the variance is even lower, and all 3 kernels are very close to each other:
memhog Baseline VSS off VSS on
real (s) 106.69 +/- 8.87 107.40 +/- 13.11 105.95 +/- 11.98
sys (s) 89.91 +/- 8.83 90.40 +/- 12.83 89.28 +/- 11.90
2. Usemem single-threaded: 56GB allocation on a host with 32GB RAM, 16 rounds.
Baseline VSS off VSS on
real (s) 178.89 +/- 4.25 176.28 +/- 8.04 177.39 +/- 5.43 sys (s) 124.39 +/- 4.62 124.32 +/- 8.01 125.47 +/- 5.62 tput (KB/s) 386398 +/- 9469 392976 +/- 17972 387264 +/- 12167 free (ms) 7821 +/- 108 7825 +/- 116 6646 +/- 103 delta real - -1.5% -0.8% delta sys - -0.1% +0.9% delta tput - +1.7% +0.2% delta free - +0.1% -15.0%
3. Kernel build: 52 workers (one per processor), memory.max=3GB, 5 rounds.
Baseline VSS off VSS on
real (s) 169.08 +/- 0.31 169.23 +/- 0.73 168.90 +/- 0.53 sys (s) 814.25 +/- 17.12 817.75 +/- 20.27 809.35 +/- 16.76 user (s) 5131.69 +/- 1.29 5130.93 +/- 0.76 5129.26 +/- 1.63 delta real - +0.1% -0.1% delta sys - +0.4% -0.6%
Commentary: as I have suspected (in [20]), for zswap backend, vswap matches the performance of the baseline kernel. This is because a lot of vswap space and CPU indirection overhead already exists in zswap due to its xarray tree. Nice to see things work out of the box though.
In fact, vswap seems to be better than baseline for usemem freeing. I have not perfed things yet, but I suspect it is a combination of:
1. vswap does not do swap charging and uncharging for zswap backend.
2. The allocator is more efficient for vswap, because we spend less time on trying to free up swap-cache-only slots (since vswap is infinitely large).
3. Zswap metadata is merged into the vswap cluster. This allows us to merge lock sections and eliminate xarray tree walking.
Note that the goal is not to match vswap performance with baseline on every single case yet - that's why we still maintain !CONFIG_VSWAP cases. It is fine to trade a bit of performance to gain the flexibility of this new design. It is nice to know that it might not be as much where it is most useful (zswap) though :)
Please let me know if there is any other result you'd like to see. If no one objects, I will drop the RFC tag for the next version.
IV. Follow-ups
===============
Some of these depend on patches not yet in mm-unstable. I'm not 100% sure what's their status, but if they land in mm-unstable before this patch series, I am happy to rebase. But otherwise, they can all be done as follow-up patch series :)
* Simplify the memcg charging in "only charge physical swap entries" (patch 4) via the mechanism proposed by Kairui in [14].
* Once we have per-swap-device per-CPU allocation caching, we can get rid of the dedicated allocation cache of vswap (see discussion of Kairui and I in [14]).
* Swap read/write handlers can be simplified with swap_ops, whenever that lands (suggested by Kairui Song in [14], and the line of work pursued in [15]).
* Allocate the per-cluster virtual_table from the page allocator (like the swap table), and make those pages movable. This might reduce memory fragmentation issues of long-lived vswap clusters tremendously.
Perhaps we can even free the virtual_table when the cluster is not backed by any zswap or swapfile slots?
* Free the per-cluster virtual_table when a cluster holds no zswap or physical backing (all slots cache-only or free), and re-allocate it lazily, mirroring the deferred memcg_table allocation. Reclaims a page per 2 MB of cache-only vswap.
* Integration with swap.tier by Youngjun (see [12]). For now, I'm leaning towards opting out the vswap device from swap.tier entirely, and treat it as a special device. Integrating it with swap.tiers will benefit the cases where you want some cgroups to skip vswap for fast swap devices (pmem), whereas other should go through zswap first. But most other use cases, either the overhead of vswap will be acceptable (or not the bottleneck), or we can just disable CONFIG_VSWAP entirely :)
Youngjun, may I ask for your thoughts on this?
* Supporting 32-bit architectures. We can make zswap depends on vswap after this, getting rid of a lot of the complexity (see my discussion with Yosry in [19]).
* Further optimization of swapfile backend case, especially for fast swapfile (zram, pmem, etc.).
[v1]: https://lore.kernel.org/all/[email protected]/
[1]: https://lore.kernel.org/all/[email protected]/
[2]: https://lore.kernel.org/all/[email protected]/
[3]: https://lwn.net/Articles/1072657/
[4]: https://lore.kernel.org/all/[email protected]/
[5]: https://lore.kernel.org/all/aerrps94j70MkgdW@gourry-fedora-PF4VCD3F/
[6]: https://lore.kernel.org/all/[email protected]/
[7]: https://lore.kernel.org/linux-mm/CAKEwX=P4syV38jAVCWq198r2OHXXc=xA-fx1dk6+qYef6yzxWQ@mail.gmail.com/
[8]: https://lore.kernel.org/all/CAKEwX=NrUhUrAFx+8BYJEfaVKpCm-H9JhBzYSrqOQb-NW7QRug@mail.gmail.com/
[9]: https://lore.kernel.org/all/[email protected]/
[10]: https://lore.kernel.org/all/aerrps94j70MkgdW@gourry-fedora-PF4VCD3F/
[11]: https://lore.kernel.org/all/afIKxG5mJZE6QgpR@gourry-fedora-PF4VCD3F/
[12]: https://lore.kernel.org/all/[email protected]/
[13]: https://lore.kernel.org/all/[email protected]/
[14]: https://lore.kernel.org/all/CAMgjq7BhOn48xEyC=2j837R7qddfjeBVHMiRqdx8no4ZEBpBLg@mail.gmail.com/
[15]: https://lore.kernel.org/all/[email protected]/
[16]: https://lore.kernel.org/linux-mm/[email protected]/
[17]: https://lore.kernel.org/all/CAJD7tkbCnXJ95Qow_aOjNX6NOMU5ovMSHRC+95U4wtW6cM+puw@mail.gmail.com/
[18]: https://lore.kernel.org/all/[email protected]/
[19]: https://lore.kernel.org/all/CAKEwX=P95D7wNpWhEAXQpeNPM6eQa2mEZE8Srzfpct=-=Q40tg@mail.gmail.com/
[20]: https://lore.kernel.org/all/CAKEwX=M3WAkSY=Zd35dEuQ6V3ZiNR02bKAN_DnCgVr69w9=0sQ@mail.gmail.com/
Nhat Pham (7):
mm, swap: add virtual swap device infrastructure mm, swap: support zswap and zeroswap as vswap backends mm, swap: support physical swap as a vswap backend mm, swap: only charge physical swap entries
mm, swap: add debugfs counters for vswap
mm, swap: defer memcg_table allocation on physical clusters mm, swap: widen swap_info_struct max/pages to unsigned long
MAINTAINERS | 1 + include/linux/memcontrol.h | 5 + include/linux/swap.h | 75 ++- include/linux/zswap.h | 3 + mm/Kconfig | 10 + mm/memcontrol.c | 166 ++++- mm/memory.c | 28 +- mm/page_io.c | 172 +++-- mm/swap.h | 58 +- mm/swap_state.c | 60 +- mm/swap_table.h | 62 ++ mm/swapfile.c | 1219 ++++++++++++++++++++++++++++++++---- mm/vmscan.c | 14 +- mm/vswap.h | 455 ++++++++++++++ mm/zswap.c | 166 +++-- 15 files changed, 2244 insertions(+), 250 deletions(-) create mode 100644 mm/vswap.h
base-commit: 01a87376d94249407343653a63e8ecfbe4c79cda
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerRFC PATCH v2 1/7 mm, swap: add virtual swap device infrastructure
Create a massive 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: per-cluster dynamic info kept in an xarray, allowing arbitrary-size devices without the static cluster_info[] array.
* virtual_table: a per-slot side table for vswap backend metadata (tag-encoded in low bits). The field itself is added in the next patch; this commit only introduces the dynamic cluster container that will hold it.
* The size of the vswap device is ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) pages.
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 | 4 + mm/Kconfig | 10 ++ mm/page_io.c | 18 ++- mm/swap.h | 46 ++++++-- mm/swap_state.c | 43 ++++--- mm/swap_table.h | 2 + mm/swapfile.c | 260 +++++++++++++++++++++++++++++++++++++++---- mm/vswap.h | 43 +++++++ mm/zswap.c | 10 +- 10 files changed, 387 insertions(+), 50 deletions(-) create mode 100644 mm/vswap.h
MAINTAINERS +1 -0
@@ -17061,6 +17061,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 +4 -0
@@ -214,6 +214,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... */ };
@@ -282,6 +283,7 @@ struct swap_info_struct {struct work_struct reclaim_work;/* reclaim worker */ struct list_head discard_clusters;/* discard clusters list */ struct plist_node avail_list;/* entry in swap_avail_head */ +struct xarray cluster_info_pool;/* Xarray for vswap dynamic cluster info */ };static inline swp_entry_t page_swap_entry (struct page *page)
@@ -471,6 +473,8 @@ void swap_free_hibernation_slot(swp_entry_t entry);static inline void put_swap_device (struct swap_info_struct *si) { +if (si->flags &SWP_VSWAP ) +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 -3
@@ -295,8 +295,7 @@ int swap_writeout(struct folio *folio, struct swap_iocb **swap_plug) }rcu_read_unlock (); -__swap_writepage (folio, swap_plug); -return 0 ; +return __swap_writepage (folio, swap_plug); out_unlock:folio_unlock (folio);return ret;
@@ -458,11 +457,18 @@ static void swap_writepage_bdev_async(struct folio *folio,submit_bio (bio); } -void __swap_writepage (struct folio *folio,struct swap_iocb **swap_plug) +int __swap_writepage (struct folio *folio,struct swap_iocb **swap_plug) {struct swap_info_struct *sis =__swap_entry_to_info (folio->swap);VM_BUG_ON_FOLIO (!folio_test_swapcache (folio), folio); + +if (sis->flags &SWP_VSWAP ) { +/* Prevent the page from getting reclaimed. */ +folio_set_dirty (folio); +return AOP_WRITEPAGE_ACTIVATE ; + } +/* * ->flags can be updated non-atomically, * but that will never affect SWP_FS_OPS, so the data_race
@@ -479,6 +485,7 @@ void __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug)swap_writepage_bdev_sync (folio, sis); elseswap_writepage_bdev_async (folio ,sis ); +return 0 ; }void swap_write_unplug (struct swap_iocb *sio)
@@ -684,6 +691,11 @@ void swap_read_folio(struct folio *folio, struct swap_iocb **plug)if (zswap_load (folio) != -ENOENT ) goto finish; +if (unlikely (sis->flags &SWP_VSWAP )) { +folio_unlock (folio); + goto finish; + } +/* We have to read from slower devices. Increase zswap protection. */ zswap_folio_swapin (folio);
mm/swap.h +39 -7
84 lines not on this page · raw message
mm/swap_state.c +28 -15
119 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 +237 -23
497 lines not on this page · raw message
mm/vswap.h new file +43 -0
43 lines not on this page · raw message
mm/zswap.c +8 -2
@@ -994,11 +994,16 @@ static int zswap_writeback_entry(struct zswap_entry *entry,struct swap_info_struct *si;int ret =0 ; -/* try to allocate swap cache folio */ si =get_swap_device (swpentry);if (!si)return -EEXIST ; +if (si->flags &SWP_VSWAP ) { +put_swap_device (si); +return -EINVAL ; + } + +/* try to allocate swap cache folio */ mpol =get_task_policy (current); folio =swap_cache_alloc_folio (swpentry,GFP_KERNEL ,BIT (0 ),NULL , mpol,NO_INTERLEAVE_INDEX );
@@ -1049,7 +1054,8 @@ static int zswap_writeback_entry(struct zswap_entry *entry,folio_set_reclaim (folio);/* start writeback */ -__swap_writepage (folio,NULL ); + ret =__swap_writepage (folio,NULL ); +WARN_ON_ONCE (ret); out:if (ret) {
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: [RFC PATCH v2 1/7] mm, swap: add virtual swap device infrastructure
Quoted 14 lines · On Fri, Jun 12, 2026 at 4:02 PM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Dead code inswap_type_str: VSWAP devices are never displayed in/proc/swaps.mm/swapfile.c static void swap_stop(struct seq_file *swap, void *v) · line 3388
Quoted 7 lines
mm/swapfile.c +6
-0+static const char *swap_type_str (struct swap_info_struct *si) +{ +struct file *file = si->swap_file; + +if (si->flags &SWP_VSWAP ) +return "vswap\t" ;[Severity: Low]
Is this branch actually reachable?
Quoted 8 lines
Looking at
swap_start()andswap_next()inmm/swapfile.c, theseq_fileiterator skips any swap device wheresi->swap_fileis NULL. Since thevswap_sicreated at boot has no backing file, it seems the vswap device will never be yielded toswap_show(), making this dead code.Additionally, if the device were somehow yielded to
swap_show()without addressing the file check, wouldseq_file_path(swap, file, ...)crash by dereferencing the NULL file pointer?
Looks correct yeah. I think this was a hold-over from older version of this.
I'll fix this.
Nhat Pham
maintainerRFC PATCH v2 2/7 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 (AOP_WRITEPAGE_ACTIVATE)
- physical disk backing fallback comes in the next patch. Zswap writeback of vswap-backed entries is also disabled - the shrinker skips when no physical swap pages are available.
--- include/linux/zswap.h | 3 + mm/memory.c | 22 ++- mm/page_io.c | 39 ++++-- mm/swap.h | 4 +- mm/swap_state.c | 17 +++ mm/swapfile.c | 262 ++++++++++++++++++++++++++++++----- mm/vmscan.c | 14 +- mm/vswap.h | 307 +++++++++++++++++++++++++++++++++++++++++- mm/zswap.c | 93 +++++++------ 9 files changed, 664 insertions(+), 97 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/memory.c +17 -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.
@@ -4525,6 +4526,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;
@@ -4675,15 +4682,20 @@ 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. +* 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 (!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 +28 -11
@@ -27,6 +27,7 @@#include <linux/zswap.h> #include "swap.h" #include "swap_table.h" +#include "vswap.h" static void __end_swap_bio_write (struct bio *bio) {
@@ -207,14 +208,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)); }
@@ -282,6 +288,9 @@ int swap_writeout(struct folio *folio, struct swap_iocb **swap_plug)*/ 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;
@@ -295,6 +304,11 @@ int swap_writeout(struct folio *folio, struct swap_iocb **swap_plug) }rcu_read_unlock (); +if (is_vswap_entry (folio->swap)) { +folio_mark_dirty (folio); +return AOP_WRITEPAGE_ACTIVATE ; + } +return __swap_writepage (folio, swap_plug); out_unlock:folio_unlock (folio);
@@ -537,23 +551,26 @@ static void sio_read_complete(struct kiocb *iocb, long ret)static int swap_zeromap_batch (swp_entry_t entry,int max_nr,bool *is_zerop) { -int i; -bool is_zero; -unsigned int ci_start =swp_cluster_offset (entry);struct swap_cluster_info *ci =__swap_entry_to_cluster (entry); +unsigned int ci_start =swp_cluster_offset (entry), ci_off, ci_end; +bool is_zero;VM_WARN_ON_ONCE (ci_start + max_nr >SWAPFILE_CLUSTER ); + ci_off = ci_start; + ci_end = ci_off + max_nr; +rcu_read_lock (); - is_zero =__swap_table_test_zero (ci, ci_start); -for (i =1 ; i < max_nr; i++) -if (is_zero !=__swap_table_test_zero (ci, ci_start + i)) -break ; -rcu_read_unlock (); + is_zero =__swap_table_test_zero (ci, ci_off);if (is_zerop) *is_zerop = is_zero; +while (++ci_off < ci_end) { +if (is_zero !=__swap_table_test_zero (ci, ci_off)) +break ; + } +rcu_read_unlock (); -return i; +return ci_off - ci_start; }static bool swap_read_folio_zeromap (struct folio *folio)
mm/swap.h +3 -1
@@ -69,7 +69,9 @@ struct swap_cluster_info_dynamic {struct swap_cluster_info ci;/* Underlying cluster info */ unsigned int index;/* for cluster_index() */ struct rcu_head rcu;/* For kfree_rcu deferred free */ -/* Backend pointers (virtual_table) added in a later patch. */ +#ifdef CONFIG_VSWAP +atomic_long_t *virtual_table;/* Backing pointers for vswap slots */ +#endif };/* All on-list cluster must have a non-zero flag. */
mm/swap_state.c +17 -0
@@ -25,6 +25,7 @@#include "internal.h" #include "swap_table.h" #include "swap.h" +#include "vswap.h" /* * swapper_space is a fiction, retained to simplify the path through
@@ -167,6 +168,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);
@@ -191,6 +195,19 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,if (nr ==1 )return 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)) { + 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); ci_end = ci_off + nr;
mm/swapfile.c +228 -34
423 lines not on this page · raw message
mm/vmscan.c +11 -3
@@ -67,6 +67,7 @@#include "internal.h" #include "swap.h" +#include "vswap.h" #define CREATE_TRACE_POINTS #include <trace/events/vmscan.h>
@@ -350,6 +351,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 (IS_ENABLED (CONFIG_VSWAP ) &&zswap_is_enabled ()) +return true; }else {/* Is the memcg below its swap limit? */ if (mem_cgroup_get_nr_swap_pages (memcg) >0 )
@@ -1524,9 +1528,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)) {
@@ -2614,7 +2622,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 || (IS_ENABLED (CONFIG_VSWAP ) &&zswap_is_enabled ()))return true;/* Also valuable if anon pages can be demoted: */
mm/vswap.h +302 -5
326 lines not on this page · raw message
mm/zswap.c +55 -38
170 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
Yosry Ahmed
maintainerRe: [RFC PATCH v2 2/7] mm, swap: support zswap and zeroswap as vswap backends
Quoted 13 lines · Nhat Pham
Build the virtual swap layer on top of the swap-table infrastructure. Virtual swap entries decouple PTE swap entries from physical backing, allowing pages to be compressed by zswap (or detected as zero-filled) without pre-allocating a physical swap slot.
This patch only supports zswap and zero-page backends. If
zswap_storefails, the page stays dirty in the swap cache (AOP_WRITEPAGE_ACTIVATE)
- physical disk backing fallback comes in the next patch. Zswap writeback of vswap-backed entries is also disabled - the shrinker skips when no physical swap pages are available.Suggested-by Kairui Song <[email protected]>Signed-off-by Nhat Pham <[email protected]>
[..]
Quoted 25 lines
mm/zswap.c +2
-1@@ -38,6 +38,7 @@#include <linux/zsmalloc.h> #include "swap.h" +#include "vswap.h" #include "internal.h" /********************************* @@ -762,7 +763,7 @@ static void zswap_entry_cache_free(struct zswap_entry *entry)* Carries out the common pattern of freeing an entry's zsmalloc allocation, * freeing the entry itself, and decrementing the number of stored pages. */ -static void zswap_entry_free (struct zswap_entry *entry) +void zswap_entry_free (struct zswap_entry *entry) {zswap_lru_del (&zswap_list_lru, entry);zs_free (entry->pool->zs_pool, entry->handle);@@ -994,16 +995,21 @@ static int zswap_writeback_entry(struct zswap_entry *entry,struct swap_info_struct *si;int ret =0 ;
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1007
Quoted 10 lines
mm/zswap.c +6
-0+/* try to allocate swap cache folio */ si =get_swap_device (swpentry);if (!si)return -EEXIST ; +/* +* Vswap entries have no physical backing - writeback would fail +* and SIGBUS the caller. Bail before we waste a swap-cache folio +* allocation. +*/
Seems like this comment belongs in the previous patch, and the other comment movement is undoing what last patch did.
Quoted 72 lines
mm/zswap.c +20
-18if (si->flags &SWP_VSWAP ) {put_swap_device (si);return -EINVAL ; } -/* try to allocate swap cache folio */ mpol =get_task_policy (current); folio =swap_cache_alloc_folio (swpentry,GFP_KERNEL ,BIT (0 ),NULL , mpol,NO_INTERLEAVE_INDEX );@@ -1416,25 +1422,25 @@ static bool zswap_store_page(struct page *page,if (!zswap_compress (page, entry, pool)) goto compress_failed; - old =xa_store (swap_zswap_tree (page_swpentry), -swp_offset (page_swpentry), - entry,GFP_KERNEL ); -if (xa_is_err (old)) { -int err =xa_err (old); +if (is_vswap_entry (page_swpentry)) { +vswap_zswap_store (page_swpentry, entry); + }else { + old =xa_store (swap_zswap_tree (page_swpentry), +swp_offset (page_swpentry), + entry,GFP_KERNEL ); +if (xa_is_err (old)) { +int err =xa_err (old); + +WARN_ONCE (err != -ENOMEM , +"unexpected xarray error: %d\n" , err); + zswap_reject_alloc_fail++; + goto store_failed; + } -WARN_ONCE (err != -ENOMEM ,"unexpected xarray error: %d\n" , err); - zswap_reject_alloc_fail++; - goto store_failed; +if (old) +zswap_entry_free (old); } -/* -* We may have had an existing entry that became stale when -* the folio was redirtied and now the new version is being -* swapped out. Get rid of the old. -*/ -if (old) -zswap_entry_free (old); -/* * The entry is successfully compressed and stored in the tree, there is * no further possibility of failure. Grab refs to the pool and objcg, @@ -1487,6 +1493,7 @@ bool zswap_store(struct folio *folio)struct mem_cgroup *memcg =NULL ;struct zswap_pool *pool;bool ret = false; +bool partial_store = false;long index;VM_WARN_ON_ONCE (!folio_test_locked (folio));@@ -1524,8 +1531,10 @@ bool zswap_store(struct folio *folio)for (index =0 ; index < nr_pages; ++index) {struct page *page =folio_page (folio, index); -if (!zswap_store_page (page, objcg, pool)) +if (!zswap_store_page (page, objcg, pool)) { + partial_store = index >0 ; goto put_pool; + } }if (objcg)
mm/zswap.c bool zswap_store(struct folio *folio) · line 1561
Quoted 6 lines
mm/zswap.c +2
-1@@ -1548,7 +1557,9 @@ bool zswap_store(struct folio *folio)* offsets corresponding to each page of the folio. Otherwise, * writeback could overwrite the new data in the swapfile. */ -if (!ret) { +if (partial_store &&is_vswap_entry (swp)) +folio_release_vswap_backing (folio);
Hmm the above should also only happen in the !ret case, but that's not obvious from the code here. I think all of this should go under if (!ret), but maybe reverse the polarity to avoid the indentation?
if (ret)
return ret;
if (is_vswap_entry(swp)) {
if (partial_store)
folio_release_vswap_backing(folio);
return ret;
}
...Alternatively you can move the check_old code for xarray into a helper and do:
if (!ret) {
if (is_vswap_entry(swp)) {
if (partial_store)
folio_release_vswap_backing(folio);
} else {
zswap_free_old_xa_entries(swp, nr_pages)
}
}Also, I think you can probably drop partial_store and check the index directly here.
Quoted 17 lines
mm/zswap.c +2
-2+else if (!ret && !is_vswap_entry (swp)) {unsigned type =swp_type (swp);pgoff_t offset =swp_offset (swp);struct zswap_entry *entry;@@ -1588,8 +1599,7 @@ bool zswap_store(struct folio *folio)int zswap_load (struct folio *folio) {swp_entry_t swp = folio->swap; -pgoff_t offset =swp_offset (swp); -struct xarray *tree =swap_zswap_tree (swp); +struct swap_info_struct *si =__swap_entry_to_info (swp);struct zswap_entry *entry;VM_WARN_ON_ONCE (!folio_test_locked (folio));@@ -1599,16 +1609,25 @@ int zswap_load(struct folio *folio)return -ENOENT ;
mm/zswap.c int zswap_load(struct folio *folio) · line 1617
Quoted 10 lines
mm/zswap.c +6
-3/* -* 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 to +* fall through to the phys/zero IO path.
Hmm should we start simple and avoid THP swapin for vswap initially?
IIUC, it isn't really vswap specific. Even without vswap, it's possible that an entire folio is on-disk, not in zswap, in which case THP swap should be allowed.
I assume it's not common for zswap to be enabled and an entire THP worth of pages are not in zswap, so maybe we can add this later?
Quoted 27 lines
mm/zswap.c +10
-7*/ -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 =xa_load (tree, offset); +if (swap_is_vswap (si)) + entry =vswap_zswap_load (swp); +else + entry =xa_load (swap_zswap_tree (swp),swp_offset (swp));if (!entry)return -ENOENT ;@@ -1623,16 +1642,14 @@ int zswap_load(struct folio *folio)if (entry->objcg)count_objcg_events (entry->objcg,ZSWPIN ,1 ); -/* -* We are reading into the swapcache, invalidate zswap entry. -* The swapcache is the authoritative owner of the page and
mm/zswap.c int zswap_load(struct folio *folio) · line 1648
Quoted 10 lines
mm/zswap.c +3
-6-* its mappings, and the pressure that results from having two -* in-memory copies outweighs any benefits of caching the -* compression work. -*/ folio_mark_dirty (folio); -xa_erase (tree, offset); -zswap_entry_free (entry); + +if (swap_is_vswap (si)) { +folio_release_vswap_backing (folio);
Is there any advantage to calling folio_release_vswap_backing() over zswap_entry_free()? Seems like __vswap_release_backing() ends up just calling zswap_entry_free() -- and I don't see any vswap-specific state being cleaned up.
I wonder if the zswap code should call zswap_entry_free() directly? Same goes for the call in zswap_store() above.
Quoted 10 lines
mm/zswap.c +4
-0+ }else { +xa_erase (swap_zswap_tree (swp),swp_offset (swp)); +zswap_entry_free (entry); + }folio_unlock (folio);return 0 ;Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerRe: [RFC PATCH v2 2/7] mm, swap: support zswap and zeroswap as vswap backends
Quoted 46 lines · Yosry Ahmed
Quoted 13 lines · Nhat Pham
Build the virtual swap layer on top of the swap-table infrastructure. Virtual swap entries decouple PTE swap entries from physical backing, allowing pages to be compressed by zswap (or detected as zero-filled) without pre-allocating a physical swap slot.
This patch only supports zswap and zero-page backends. If
zswap_storefails, the page stays dirty in the swap cache (AOP_WRITEPAGE_ACTIVATE)
- physical disk backing fallback comes in the next patch. Zswap writeback of vswap-backed entries is also disabled - the shrinker skips when no physical swap pages are available.Suggested-by Kairui Song <[email protected]>Signed-off-by Nhat Pham <[email protected]>[..]
Quoted 30 lines
mm/zswap.c +3
-1@@ -38,6 +38,7 @@#include <linux/zsmalloc.h> #include "swap.h" +#include "vswap.h" #include "internal.h" /********************************* @@ -762,7 +763,7 @@ static void zswap_entry_cache_free(struct zswap_entry *entry)* Carries out the common pattern of freeing an entry's zsmalloc allocation, * freeing the entry itself, and decrementing the number of stored pages. */ -static void zswap_entry_free (struct zswap_entry *entry) +void zswap_entry_free (struct zswap_entry *entry) {zswap_lru_del (&zswap_list_lru, entry);zs_free (entry->pool->zs_pool, entry->handle);@@ -994,16 +995,21 @@ static int zswap_writeback_entry(struct zswap_entry *entry,struct swap_info_struct *si;int ret =0 ; +/* try to allocate swap cache folio */ si =get_swap_device (swpentry);if (!si)return -EEXIST ;
Quoted 8 lines
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1007
Quoted 5 lines
mm/zswap.c +5
-0+/* +* Vswap entries have no physical backing - writeback would fail +* and SIGBUS the caller. Bail before we waste a swap-cache folio +* allocation. +*/ Seems like this comment belongs in the previous patch, and the other comment movement is undoing what last patch did.
Yeah this comment belongs to the first patch. I added it after the fact but commit to the second patch.
TBH, the first patch kinda not do much. It just declares a new special struct swap_info_struct, with some helpers and checks, but it's not hooked to any allocation path. Logically it should be squashed into this patch, but this patch is already 600 LoC, lol.
Quoted 71 lines
Quoted 71 lines
mm/zswap.c +20
-18if (si->flags &SWP_VSWAP ) {put_swap_device (si);return -EINVAL ; } -/* try to allocate swap cache folio */ mpol =get_task_policy (current); folio =swap_cache_alloc_folio (swpentry,GFP_KERNEL ,BIT (0 ),NULL , mpol,NO_INTERLEAVE_INDEX );@@ -1416,25 +1422,25 @@ static bool zswap_store_page(struct page *page,if (!zswap_compress (page, entry, pool)) goto compress_failed; - old =xa_store (swap_zswap_tree (page_swpentry), -swp_offset (page_swpentry), - entry,GFP_KERNEL ); -if (xa_is_err (old)) { -int err =xa_err (old); +if (is_vswap_entry (page_swpentry)) { +vswap_zswap_store (page_swpentry, entry); + }else { + old =xa_store (swap_zswap_tree (page_swpentry), +swp_offset (page_swpentry), + entry,GFP_KERNEL ); +if (xa_is_err (old)) { +int err =xa_err (old); + +WARN_ONCE (err != -ENOMEM , +"unexpected xarray error: %d\n" , err); + zswap_reject_alloc_fail++; + goto store_failed; + } -WARN_ONCE (err != -ENOMEM ,"unexpected xarray error: %d\n" , err); - zswap_reject_alloc_fail++; - goto store_failed; +if (old) +zswap_entry_free (old); } -/* -* We may have had an existing entry that became stale when -* the folio was redirtied and now the new version is being -* swapped out. Get rid of the old. -*/ -if (old) -zswap_entry_free (old); -/* * The entry is successfully compressed and stored in the tree, there is * no further possibility of failure. Grab refs to the pool and objcg, @@ -1487,6 +1493,7 @@ bool zswap_store(struct folio *folio)struct mem_cgroup *memcg =NULL ;struct zswap_pool *pool;bool ret = false; +bool partial_store = false;long index;VM_WARN_ON_ONCE (!folio_test_locked (folio));@@ -1524,8 +1531,10 @@ bool zswap_store(struct folio *folio)for (index =0 ; index < nr_pages; ++index) {struct page *page =folio_page (folio, index); -if (!zswap_store_page (page, objcg, pool)) +if (!zswap_store_page (page, objcg, pool)) { + partial_store = index >0 ; goto put_pool; + } }
Quoted 12 lines
mm/zswap.c bool zswap_store(struct folio *folio) · line 1561
Quoted 8 lines
mm/zswap.c +2
-1if (objcg)@@ -1548,7 +1557,9 @@ bool zswap_store(struct folio *folio)* offsets corresponding to each page of the folio. Otherwise, * writeback could overwrite the new data in the swapfile. */ -if (!ret) { +if (partial_store &&is_vswap_entry (swp)) +folio_release_vswap_backing (folio);Hmm the above should also only happen in the !ret case, but that's not obvious from the code here. I think all of this should go under if (!ret), but maybe reverse the polarity to avoid the indentation?
Yeah that's just me avoiding indentation lol. But yes, it only happens in !ret case:
Quoted 15 lines
if (ret) return ret; if (is_vswap_entry(swp)) { if (partial_store) folio_release_vswap_backing(folio); return ret; } ...Alternatively you can move the
check_oldcode for xarray into a helper and do:
Quoted 8 lines
if (!ret) {
if (is_vswap_entry(swp)) {
if (partial_store)
folio_release_vswap_backing(folio);
} else {
zswap_free_old_xa_entries(swp, nr_pages)
}
}Yup! I can switch to this if you think it's cleaner.
Quoted 3 lines
Also, I think you can probably drop
partial_storeand check the index directly here.
Ah yeah. That's true!
Quoted 31 lines
Quoted 18 lines
mm/zswap.c +2
-2+else if (!ret && !is_vswap_entry (swp)) {unsigned type =swp_type (swp);pgoff_t offset =swp_offset (swp);struct zswap_entry *entry;@@ -1588,8 +1599,7 @@ bool zswap_store(struct folio *folio)int zswap_load (struct folio *folio) {swp_entry_t swp = folio->swap; -pgoff_t offset =swp_offset (swp); -struct xarray *tree =swap_zswap_tree (swp); +struct swap_info_struct *si =__swap_entry_to_info (swp);struct zswap_entry *entry;VM_WARN_ON_ONCE (!folio_test_locked (folio));@@ -1599,16 +1609,25 @@ int zswap_load(struct folio *folio)return -ENOENT ;mm/zswap.c int zswap_load(struct folio *folio) · line 1617
Quoted 10 lines
mm/zswap.c +6
-3/* -* 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 to +* fall through to the phys/zero IO path. Hmm should we start simple and avoid THP swapin for vswap initially?
Quoted 6 lines
IIUC, it isn't really vswap specific. Even without vswap, it's possible that an entire folio is on-disk, not in zswap, in which case THP swap should be allowed.
I assume it's not common for zswap to be enabled and an entire THP worth of pages are not in zswap, so maybe we can add this later?
I was thinking of removing it altogether haha. Are we even doing THP swap in for non-sync IO devices?
if (!folio) {
/* Swapin bypasses readahead for SWP_SYNCHRONOUS_IO devices */
if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
folio = swapin_sync(entry, GFP_HIGHUSER_MOVABLE,
[...]
else
folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vmf);So I guess it's primarily zram that does THP swap in here? on non-SWP_SYNCHRONOUS_IO devices, seems like we only do "THP swapin" if we catch the page in swap cache (minor page fault). :) Will zram users like vswap?
OTOH, zswap might be getting THP zswap-in support soon, so it's not just zram backend that cares about these kinds of check? :)
Or maybe I can keep it, but separate it from this big patch to make it easier to review :) Lemme play with it.
Quoted 44 lines
Quoted 28 lines
mm/zswap.c +10
-7*/ -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 =xa_load (tree, offset); +if (swap_is_vswap (si)) + entry =vswap_zswap_load (swp); +else + entry =xa_load (swap_zswap_tree (swp),swp_offset (swp));if (!entry)return -ENOENT ;@@ -1623,16 +1642,14 @@ int zswap_load(struct folio *folio)if (entry->objcg)count_objcg_events (entry->objcg,ZSWPIN ,1 ); -/* -* We are reading into the swapcache, invalidate zswap entry. -* The swapcache is the authoritative owner of the page and mm/zswap.c int zswap_load(struct folio *folio) · line 1648
Quoted 10 lines
mm/zswap.c +3
-6-* its mappings, and the pressure that results from having two -* in-memory copies outweighs any benefits of caching the -* compression work. -*/ folio_mark_dirty (folio); -xa_erase (tree, offset); -zswap_entry_free (entry); + +if (swap_is_vswap (si)) { +folio_release_vswap_backing (folio);Is there any advantage to calling
folio_release_vswap_backing()overzswap_entry_free()? Seems like__vswap_release_backing()ends up just callingzswap_entry_free()-- and I don't see any vswap-specific state being cleaned up.
Quoted 2 lines
I wonder if the zswap code should call
zswap_entry_free()directly? Same goes for the call inzswap_store()above.
Most just not repeating the vtable lookup-and-lock and what not. :) The pattern is repeated the third time in swapoff when I allow phys swap to be the backend of vswap in the next patch so I figure probably should add some helper.
Quoted 11 lines
Quoted 11 lines
mm/zswap.c +4
-1+ }else { +xa_erase (swap_zswap_tree (swp),swp_offset (swp)); +zswap_entry_free (entry); + }folio_unlock (folio);return 0 ; --2.53.0-Meta
Yosry Ahmed
maintainerRe: [RFC PATCH v2 2/7] mm, swap: support zswap and zeroswap as vswap backends
In reply to Nhat Pham[..]
mm/zswap.c int zswap_load(struct folio *folio) · line 1632
Quoted 11 lines
mm/zswap.c +0
-7@@ -1623,16 +1642,14 @@ int zswap_load(struct folio *folio)if (entry->objcg)count_objcg_events (entry->objcg,ZSWPIN ,1 ); -/* -* We are reading into the swapcache, invalidate zswap entry. -* The swapcache is the authoritative owner of the page and -* its mappings, and the pressure that results from having two -* in-memory copies outweighs any benefits of caching the -* compression work. -*/
Forgot to ask, is dropping this comment intentional?
Quoted 16 lines
mm/zswap.c +7
-2folio_mark_dirty (folio); -xa_erase (tree, offset); -zswap_entry_free (entry); + +if (swap_is_vswap (si)) { +folio_release_vswap_backing (folio); + }else { +xa_erase (swap_zswap_tree (swp),swp_offset (swp)); +zswap_entry_free (entry); + }folio_unlock (folio);return 0 ;Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerRe: [RFC PATCH v2 2/7] mm, swap: support zswap and zeroswap as vswap backends
Quoted 6 lines · Yosry Ahmed
[..]
Quoted 4 lines
mm/zswap.c +0
-0@@ -1623,16 +1642,14 @@ int zswap_load(struct folio *folio)if (entry->objcg)count_objcg_events (entry->objcg,ZSWPIN ,1 );
Quoted 9 lines
mm/zswap.c int zswap_load(struct folio *folio) · line 1632
Quoted 7 lines
mm/zswap.c +0
-7-/* -* We are reading into the swapcache, invalidate zswap entry. -* The swapcache is the authoritative owner of the page and -* its mappings, and the pressure that results from having two -* in-memory copies outweighs any benefits of caching the -* compression work. -*/ Forgot to ask, is dropping this comment intentional?
Ooops. Lemme restore it.
Quoted 17 lines
Quoted 17 lines
mm/zswap.c +7
-3folio_mark_dirty (folio); -xa_erase (tree, offset); -zswap_entry_free (entry); + +if (swap_is_vswap (si)) { +folio_release_vswap_backing (folio); + }else { +xa_erase (swap_zswap_tree (swp),swp_offset (swp)); +zswap_entry_free (entry); + }folio_unlock (folio);return 0 ; --2.53.0-Meta
Nhat Pham
maintainerRFC PATCH v2 3/7 mm, swap: support physical swap as a vswap backend
In reply to Nhat PhamAdd physical swap as a backend for the virtual swap layer.
With physical swap backing, vswap can allocate a physical slot on demand when needed: as a fallback for zswap_store failures, or as the destination for zswap writeback.
Each vswap entry's physical slot is tracked via a Pointer-tagged swap_table entry on the physical cluster (rmap back to the vswap entry).
--- include/linux/swap.h | 10 + mm/memory.c | 8 +- mm/page_io.c | 131 ++++++++--- mm/swap.h | 10 + mm/swap_table.h | 60 +++++ mm/swapfile.c | 538 ++++++++++++++++++++++++++++++++++++++++--- mm/vmscan.c | 2 +- mm/vswap.h | 139 ++++++++++- mm/zswap.c | 93 +++++--- 9 files changed, 879 insertions(+), 112 deletions(-)
include/linux/swap.h +10 -0
@@ -447,6 +447,16 @@ extern int swp_swapcount(swp_entry_t entry);struct backing_dev_info ;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); + +#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
mm/memory.c +4 -4
@@ -4524,13 +4524,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))
@@ -4840,7 +4840,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 );
@@ -5015,7 +5015,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 +96 -35
231 lines not on this page · raw message
mm/swap.h +10 -0
@@ -285,6 +285,16 @@ static inline void swap_read_unplug(struct swap_iocb *plug)void swap_write_unplug (struct swap_iocb *sio);int swap_writeout (struct folio *folio,struct swap_iocb **swap_plug);int __swap_writepage (struct folio *folio,struct swap_iocb **swap_plug); +#ifdef CONFIG_VSWAP +void __swap_writepage_phys (struct folio *folio,struct swap_iocb **swap_plug, +swp_entry_t phys_entry); +#else +static inline void __swap_writepage_phys (struct folio *folio, +struct swap_iocb **swap_plug, +swp_entry_t phys_entry) +{ +} +#endif /* linux/mm/swap_state.c */ extern struct address_space swap_space__read_mostly ;
mm/swap_table.h +60 -0
72 lines not on this page · raw message
mm/swapfile.c +504 -34
754 lines not on this page · raw message
mm/vmscan.c +1 -1
@@ -1533,7 +1533,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 +127 -12
190 lines not on this page · raw message
mm/zswap.c +67 -26
142 lines not on this page · raw message
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: [RFC PATCH v2 3/7] mm, swap: support physical swap as a vswap backend
Quoted 6 lines · On Fri, Jun 12, 2026 at 3:59 PM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] Large folios with fragmented or heterogeneous vswap physical backings cause out-of-bounds physical swap reads and writes.
- [Critical] MissingPG_uptodatecheck intry_to_unuse()causes silent data corruption and memory leak to userspace on swap read errors.
- [High] Physical swap slots are permanently leaked when a vswap entry is successfully stored in zswap, or when zswap writeback decompression fails.
- [High] Non-uptodate ghost folios left in swap cache on concurrent backing release cause SIGBUS.
Seems like all of these are false positives.
Quoted 43 lines
--
commit
b0de967e96de0b0840388227b716d4c3f3e653de
Author: Nhat Pham <[email protected]>
Subject: mm, swap: support physical swap as a vswap backendThis commit introduces physical swap as a backend for the virtual swap layer. With physical swap backing, vswap can allocate a physical slot on demand when needed as a fallback for
zswap_storefailures or as the destination for zswap writeback. Each vswap entry's physical slot is tracked via a pointer-taggedswap_tableentry on the physical cluster.Quoted 3 lines
mm/swapfile.c +0
-0[ ... ]
Quoted 4 lines
mm/swapfile.c +0
-0@@ -3012,19 +3400,93 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,static int try_to_unuse (unsigned int type) {[ ... ]
Quoted 4 lines
mm/swapfile.c +4
-0+/* +* Re-validate under folio lock: rmap holds folio->swap + j +* for some j in [0, nr_pages). Check folio->swap still maps +* to the contiguous physical run that includes our slot i. mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3478
Quoted 10 lines
mm/swapfile.c +10
-0+*/ + j = vswap_entry.val - folio->swap.val; + phys =vswap_to_phys (folio->swap); +if (!phys.val ||swp_type (phys) != type || +swp_offset (phys) + j != i || + j >=folio_nr_pages (folio)) { +folio_unlock (folio); +folio_put (folio); +continue ; + }[Severity: High]
Could this leave a poisoned, non-uptodate ghost folio in the swap cache?If
swap_cache_alloc_folio()was called to add the folio, but the physical backing was concurrently released or migrated to ZSWAP,swap_read_folio()will see phys.val == 0 and abort early without setting the folioPG_uptodate.
Quoted 5 lines
When the code reaches this check, if phys.val == 0, it unlocks and puts the folio and continues. However, because it doesn't call
swap_cache_del_folio(), the uninitialized folio remains in the swap cache. Wouldn't a subsequent access to this folio trigger aVM_FAULT_SIGBUSeven though the data safely exists in ZSWAP?
This case basically happens when the data on the swapfile is corrupted. Pagefault-er SIGBUS-ing on this folio is the expected behavior. Besides, this caller is not the one added the folio to swap cache or discover the data corruption.
FWIW, __try_to_reclaim_swap() has similar patterns here too.
Quoted 12 lines
mm/swapfile.c static unsigned int find_next_to_unuse(struct swap_info_struct *si, · line 3485
Quoted 8 lines
mm/swapfile.c +7
-0+ +folio_wait_writeback (folio); +folio_release_vswap_backing (folio); +folio_mark_dirty (folio); +folio_unlock (folio); +folio_put (folio); + }[Severity: Critical]
Is it possible for the folio to be uninitialized here if the swap read failed?
Quoted 8 lines
After calling
swap_read_folio()andfolio_wait_writeback(), there is no check to verify if the read was successful viafolio_test_uptodate(folio).If the block device read fails due to an IO error, the folio remains uninitialized. By unconditionally calling
folio_release_vswap_backing()andfolio_mark_dirty(), doesn't this destroy the original physical backing and certify the garbage memory as valid dirty data, potentially leaking uninitialized kernel memory to userspace?
If IO error happens, the original physical backing is a goner, no...?
I'm pretty sure unuse_pte_range() (the existing swapoff scheme) has the same pattern here.
Quoted 35 lines
Quoted 4 lines
mm/vswap.h +0
-0[ ... ]
Quoted 12 lines
mm/vswap.h +8
-0@@ -159,6 +203,25 @@ vswap_lock_cluster(swp_entry_t entry, unsigned int *voff)return ci_dyn; } +static inline swp_entry_t vswap_to_phys (swp_entry_t entry) +{ +struct swap_cluster_info_dynamic *ci_dyn; +unsigned int voff; +unsigned long vt; + + ci_dyn =vswap_lock_cluster (entry, &voff); +if (!ci_dyn)mm/vswap.h vswap_lock_cluster(swp_entry_t entry, unsigned int *voff) · line 223
Quoted 10 lines
mm/vswap.h +10
-0+return (swp_entry_t ){}; + + vt =__vtable_get (ci_dyn, voff); +spin_unlock (&ci_dyn->ci.lock); + +if (vtable_type (vt) !=VSWAP_SWAPFILE ) +return (swp_entry_t ){}; + +return vtable_to_phys (vt); +}[Severity: Critical]
Does this function handle large folios with heterogeneous backings safely?When swapping in or writing out a large folio,
vswap_to_phys()only inspects the first subpage's vtable entry. If it seesVSWAP_SWAPFILE, it returns the order-0 physical slot.
Quoted 7 lines
The caller (like
swap_read_folio_phys()or__swap_writepage_phys()) might then build a sequential bio for the fullfolio_size(folio)starting from that single slot. If the large folio isn't fully contiguously backed by the swapfile (e.g., if part of it is in ZSWAP), won't reading or writing multiple pages from this slot overflow into adjacent physical swap slots belonging to other processes, causing data corruption or an information leak?
We explicitly check for this in __swap_cache_add_check(), and (while under a single atomic context protected by swap cluster lock) adding the folio into the cache, which makes swap backend stable.
False positive I think.
Quoted 20 lines
Quoted 3 lines
mm/zswap.c +0
-0[ ... ]
Quoted 1 line
mm/zswap.c +0
-0@@ -1028,40 +1019,78 @@ static int zswap_writeback_entry(struct zswap_entry *entry,[ ... ]
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1064
Quoted 13 lines
if (!zswap_decompress(entry, folio)) { ret = -EIO;mm/zswap.c +9
-0+/* +* 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; }
Quoted 8 lines
[Severity: High]
Doesvswap_zswap_store()leak the newly allocated physical slot?If
zswap_decompress()fails, this error path attempts to restore the old zswap entry into the vtable by callingvswap_zswap_store(swpentry, entry). However, it appearsvswap_zswap_store()blindly overwrites the vtable entry withVSWAP_ZSWAPwithout freeing the priorVSWAP_SWAPFILEphysical slot that was just allocated byfolio_realloc_swap().
vswap_zswap_store() calls __vswap_release_backing(). This seems like a false positive...
Quoted 16 lines
Since
vswap_to_phys()will now return empty, the physical reclaim scanner will fail to reclaim it. Does this permanently leak the physical slot?[ ... ]
mm/zswap.c bool zswap_store(struct folio *folio) · line 1603
Quoted 7 lines
mm/zswap.c +1
-1@@ -1558,7 +1599,7 @@ bool zswap_store(struct folio *folio)* writeback could overwrite the new data in the swapfile. */ if (partial_store &&is_vswap_entry (swp)) -folio_release_vswap_backing (folio); +folio_release_non_phys_swap_backing (folio);else if (!ret && !is_vswap_entry (swp)) {[Severity: High]
Does a successfulzswap_store()leak the physical swap backing?
Quoted 8 lines
When a folio with an existing
VSWAP_SWAPFILEphysical vswap backing is swapped out again,swap_writeout()preserves the physical backing to allow fast reuse ifzswap_store()fails.If
zswap_store()succeeds, it will eventually callvswap_zswap_store()which overwrites the vtable entry withVSWAP_ZSWAPwithout freeing the prior physical slot. Should there be a cleanup for the preserved physical slot here or insidevswap_zswap_store()to prevent leaking the physical slots?
Ditto.
Quoted 3 lines
--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Yosry Ahmed
maintainerRe: [RFC PATCH v2 3/7] mm, swap: support physical swap as a vswap backend
In reply to Nhat PhamQuoted 13 lines · Nhat Pham
Add physical swap as a backend for the virtual swap layer.
With physical swap backing, vswap can allocate a physical slot on demand when needed: as a fallback for
zswap_storefailures, or as the destination for zswap writeback.Each vswap entry's physical slot is tracked via a Pointer-tagged
swap_tableentry on the physical cluster (rmap back to the vswap entry).Suggested-by Kairui Song <[email protected]>Signed-off-by Nhat Pham <[email protected]>---
[..]
Quoted 54 lines
mm/zswap.c +12
-19@@ -993,6 +993,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,struct folio *folio;struct mempolicy *mpol;struct swap_info_struct *si; +swp_entry_t phys = {};int ret =0 ;/* try to allocate swap cache folio */ @@ -1000,16 +1001,6 @@ static int zswap_writeback_entry(struct zswap_entry *entry,if (!si)return -EEXIST ; -/* -* Vswap entries have no physical backing - writeback would fail -* and SIGBUS the caller. Bail before we waste a swap-cache folio -* allocation. -*/ -if (si->flags &SWP_VSWAP ) { -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 );@@ -1028,40 +1019,78 @@ 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)) { - ret = -ENOMEM ; - goto out; +if (swap_is_vswap (si)) { +if (entry !=vswap_zswap_load (swpentry)) { + ret = -ENOMEM ; + goto out; + } +/*
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1043
Quoted 10 lines
mm/zswap.c +10
-0+* Allocate physical backing BEFORE decompress - if it fails, +* no wasted work. folio_realloc_swap sets vtable to PHYS, +* overwriting ZSWAP - the old entry pointer is only held +* by the caller now. +*/ + phys =folio_realloc_swap (folio); +if (!phys.val) { + ret = -ENOMEM ; + goto out; + }
I didn't look through the rest of the series, but are there use cases for calling folio_realloc_swap() without calling vswap_zswap_load() first? I wonder if the realloc_swap API should take the swpentry directly and do the load within? Something like vswap_alloc_phys(swpentry, folio)?
Nhat Pham
maintainerRe: [RFC PATCH v2 3/7] mm, swap: support physical swap as a vswap backend
Quoted 12 lines · Yosry Ahmed
Quoted 10 lines · Nhat Pham
Add physical swap as a backend for the virtual swap layer.
With physical swap backing, vswap can allocate a physical slot on demand when needed: as a fallback for
zswap_storefailures, or as the destination for zswap writeback.Each vswap entry's physical slot is tracked via a Pointer-tagged
swap_tableentry on the physical cluster (rmap back to the vswap entry).
Quoted 8 lines
Quoted 2 lines
Suggested-by Kairui Song <[email protected]>Signed-off-by Nhat Pham <[email protected]>I didn't look through the rest of the series, but are there use cases for calling
folio_realloc_swap()without callingvswap_zswap_load()first? I wonder if therealloc_swapAPI should take the swpentry directly and do the load within? Something likevswap_alloc_phys(swpentry, folio)?
It's also use on the swapout fallback path! If zswap rejects the page or is disabled, and memory.zswap.writeback=1, then we allocate phys swap space. We probably don't wanna do zswap_load() there again :)
Yosry Ahmed
maintainerRe: [RFC PATCH v2 3/7] mm, swap: support physical swap as a vswap backend
In reply to Nhat PhamQuoted 60 lines
mm/zswap.c +18
-19@@ -993,6 +993,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,struct folio *folio;struct mempolicy *mpol;struct swap_info_struct *si; +swp_entry_t phys = {};int ret =0 ;/* try to allocate swap cache folio */ @@ -1000,16 +1001,6 @@ static int zswap_writeback_entry(struct zswap_entry *entry,if (!si)return -EEXIST ; -/* -* Vswap entries have no physical backing - writeback would fail -* and SIGBUS the caller. Bail before we waste a swap-cache folio -* allocation. -*/ -if (si->flags &SWP_VSWAP ) { -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 );@@ -1028,40 +1019,78 @@ 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)) { - ret = -ENOMEM ; - goto out; +if (swap_is_vswap (si)) { +if (entry !=vswap_zswap_load (swpentry)) { + ret = -ENOMEM ; + goto out; + } +/* +* Allocate physical backing BEFORE decompress - if it fails, +* no wasted work. folio_realloc_swap sets vtable to PHYS, +* overwriting ZSWAP - the old entry pointer is only held +* by the caller now. +*/ + phys =folio_realloc_swap (folio);
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1049
Quoted 10 lines
mm/zswap.c +10
-0+if (!phys.val) { + ret = -ENOMEM ; + goto out; + } + }else { + tree =swap_zswap_tree (swpentry); +if (entry !=xa_load (tree, offset)) { + ret = -ENOMEM ; + goto out; + }
There's a lot of divergence in the code (in this patch and previous ones). Seems like a lot of it is to do xarray operations vs vswap operations. I wonder if we can abstract these into helpers, e.g. zswap_tree_store(), zswap_tree_load(), etc. Maybe the name is not the best, but you get the point :)
Here we can then do zswap_tree_load() for both code paths and only the folio_realloc_swap() needs to be different for vswap. We can do similar cleanups for the load/store paths as well.
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1062
Quoted 13 lines
mm/zswap.c +9
-0}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);
Should this go in the cleanup path instead (i.e. in the 'out' label?).
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1067
Quoted 6 lines
mm/zswap.c +2
-1goto out; } -xa_erase (tree, offset); +if (!swap_is_vswap (si)) +xa_erase (tree, offset);
Maybe this can also be abstracted into a helper, but I wonder what the corresponding vswap operation would be. I think folio_realloc_swap() will have already "erased" the zswap entry from vswap. Maybe have a vswap helper that will only remove it if it's a zswap entry? We can probably do a lockless check first to make it cheap?
It's probably silly to do this, and maybe there's a better way. Generally, I think the code would be easier to follow if we abstract away the xarray vs. vswap stuff into helpers (where it's reasonable).
Quoted 65 lines
mm/zswap.c +28
-7count_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 */ - ret =__swap_writepage (folio,NULL ); -WARN_ON_ONCE (ret); +/* +* Start writeback. __swap_writepage_phys is void; __swap_writepage +* returns 0 today (async IO errors surface in the bio end_io +* callback). Either way the entry has been moved out of its prior +* location (vtable PHYS for vswap, removed from tree otherwise), +* so we own the free. +*/ +if (swap_is_vswap (si)) { +__swap_writepage_phys (folio,NULL , phys); + }else { + ret =__swap_writepage (folio,NULL ); +WARN_ON_ONCE (ret); + } + +zswap_entry_free (entry); out:if (ret) {@@ -1212,6 +1241,18 @@ static unsigned long zswap_shrinker_count(struct shrinker *shrinker,if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled (memcg))return 0 ; +/* +* With CONFIG_VSWAP, vswap-backed zswap entries need a physical +* swap slot allocated on demand (via folio_realloc_swap) for +* writeback. If no physical slots are available, writeback will +* fail - skip the shrinker to avoid spinning on entries we cannot +* drain. Vanilla zswap-on-swapfile is unaffected because every +* zswap entry already has a backing slot; gate on CONFIG_VSWAP so +* the check compiles out there. +*/ +if (IS_ENABLED (CONFIG_VSWAP ) && !get_nr_swap_pages ()) +return 0 ; +/* * The shrinker resumes swap writeback, which will enter block * and may enter fs. XXX: Harmonize with vmscan.c __GFP_FS @@ -1558,7 +1599,7 @@ bool zswap_store(struct folio *folio)* writeback could overwrite the new data in the swapfile. */ if (partial_store &&is_vswap_entry (swp)) -folio_release_vswap_backing (folio); +folio_release_non_phys_swap_backing (folio);else if (!ret && !is_vswap_entry (swp)) {unsigned type =swp_type (swp);pgoff_t offset =swp_offset (swp); --2.53.0-Meta
Nhat Pham
maintainerRe: [RFC PATCH v2 3/7] mm, swap: support physical swap as a vswap backend
Quoted 69 lines · Yosry Ahmed
Quoted 69 lines
mm/zswap.c +26
-19@@ -993,6 +993,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,struct folio *folio;struct mempolicy *mpol;struct swap_info_struct *si; +swp_entry_t phys = {};int ret =0 ;/* try to allocate swap cache folio */ @@ -1000,16 +1001,6 @@ static int zswap_writeback_entry(struct zswap_entry *entry,if (!si)return -EEXIST ; -/* -* Vswap entries have no physical backing - writeback would fail -* and SIGBUS the caller. Bail before we waste a swap-cache folio -* allocation. -*/ -if (si->flags &SWP_VSWAP ) { -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 );@@ -1028,40 +1019,78 @@ 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)) { - ret = -ENOMEM ; - goto out; +if (swap_is_vswap (si)) { +if (entry !=vswap_zswap_load (swpentry)) { + ret = -ENOMEM ; + goto out; + } +/* +* Allocate physical backing BEFORE decompress - if it fails, +* no wasted work. folio_realloc_swap sets vtable to PHYS, +* overwriting ZSWAP - the old entry pointer is only held +* by the caller now. +*/ + phys =folio_realloc_swap (folio); +if (!phys.val) { + ret = -ENOMEM ; + goto out; + } + }else { + tree =swap_zswap_tree (swpentry); +if (entry !=xa_load (tree, offset)) { + ret = -ENOMEM ;
Quoted 8 lines
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1049
Quoted 2 lines
mm/zswap.c +2
-0+ goto out; + }There's a lot of divergence in the code (in this patch and previous ones). Seems like a lot of it is to do xarray operations vs vswap operations. I wonder if we can abstract these into helpers, e.g.
zswap_tree_store(),zswap_tree_load(), etc. Maybe the name is not the best, but you get the point :)
How about zswap_entry_load() and zswap_entry_store()? :)
Quoted 19 lines
Here we can then do
zswap_tree_load()for both code paths and only thefolio_realloc_swap()needs to be different for vswap. We can do similar cleanups for the load/store paths as well.mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1062
Quoted 13 lines
mm/zswap.c +9
-0}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);
Quoted 1 line
Should this go in the cleanup path instead (i.e. in the 'out' label?).
Ah, maybe if (ret == -EIO &&)...
Quoted 11 lines
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1067
Quoted 7 lines
mm/zswap.c +2
-1goto out; } -xa_erase (tree, offset); +if (!swap_is_vswap (si)) +xa_erase (tree, offset);Maybe this can also be abstracted into a helper, but I wonder what the corresponding vswap operation would be. I think
folio_realloc_swap()will have already "erased" the zswap entry from vswap. Maybe have a
Yup that's the right logic. We already change the backend to physical swap slot here, so there's no real "erase".
Quoted 6 lines
vswap helper that will only remove it if it's a zswap entry? We can probably do a lockless check first to make it cheap?
It's probably silly to do this, and maybe there's a better way. Generally, I think the code would be easier to follow if we abstract away the xarray vs. vswap stuff into helpers (where it's reasonable).
I'm not entirely sure if its worth it either, yeah. Unlike load and store, erase seems a bit asymmetric in the sense that we only need to do it for non-vswap cases.
Yosry Ahmed
maintainerRe: [RFC PATCH v2 3/7] mm, swap: support physical swap as a vswap backend
Quoted 23 lines
Quoted 23 lines
Quoted 22 lines
mm/zswap.c +22
-0+if (swap_is_vswap (si)) { +if (entry !=vswap_zswap_load (swpentry)) { + ret = -ENOMEM ; + goto out; + } +/* +* Allocate physical backing BEFORE decompress - if it fails, +* no wasted work. folio_realloc_swap sets vtable to PHYS, +* overwriting ZSWAP - the old entry pointer is only held +* by the caller now. +*/ + phys =folio_realloc_swap (folio); +if (!phys.val) { + ret = -ENOMEM ; + goto out; + } + }else { + tree =swap_zswap_tree (swpentry); +if (entry !=xa_load (tree, offset)) { + ret = -ENOMEM ; + goto out; + }
Quoted 7 lines
Quoted 5 lines
There's a lot of divergence in the code (in this patch and previous ones). Seems like a lot of it is to do xarray operations vs vswap operations. I wonder if we can abstract these into helpers, e.g.
zswap_tree_store(),zswap_tree_load(), etc. Maybe the name is not the best, but you get the point :)How about
zswap_entry_load()andzswap_entry_store()? :)
Even better!
Quoted 14 lines
Quoted 7 lines
mm/zswap.c static int zswap_writeback_entry(struct zswap_entry *entry, · line 1067
Quoted 3 lines
mm/zswap.c +2
-1-xa_erase (tree, offset); +if (!swap_is_vswap (si)) +xa_erase (tree, offset);Maybe this can also be abstracted into a helper, but I wonder what the corresponding vswap operation would be. I think
folio_realloc_swap()will have already "erased" the zswap entry from vswap. Maybe have aYup that's the right logic. We already change the backend to physical swap slot here, so there's no real "erase".
Quoted 3 lines
vswap helper that will only remove it if it's a zswap entry? We can probably do a lockless check first to make it cheap?
Quoted 7 lines
Quoted 3 lines
It's probably silly to do this, and maybe there's a better way. Generally, I think the code would be easier to follow if we abstract away the xarray vs. vswap stuff into helpers (where it's reasonable).
I'm not entirely sure if its worth it either, yeah. Unlike load and store, erase seems a bit asymmetric in the sense that we only need to do it for non-vswap cases.
Yeah :/
Maybe just add a comment why no erase is needed for the vswap case.
Nhat Pham
maintainerRFC PATCH v2 4/7 mm, swap: only charge physical swap entries
In reply to Nhat PhamDefer the memcg->swap charge for vswap entries from vswap allocation time to physical-backing allocation time, so memcg->swap reflects actual on-disk swap usage rather than virtual swap reservations. Previously, vswap entries were charged at allocation via mem_cgroup_try_charge_swap regardless of whether they ever acquired physical backing (zswap and zero pages do not consume physical swap space).
Split the lifecycle into four operations: record the memcg private ID at vswap alloc without charging; charge memcg->swap only when physical backing is allocated via folio_realloc_swap; uncharge in __vswap_release_backing (only nr_swapfile entries on v2, all nr on v1 memsw); and drop the ID ref at __swap_cluster_free_entries without uncharging.
Direct-mapped physical swap charging is unchanged.
--- include/linux/memcontrol.h | 5 ++ include/linux/swap.h | 57 +++++++++++++ mm/memcontrol.c | 166 +++++++++++++++++++++++++++++++++---- mm/swapfile.c | 123 ++++++++++++++++++++++----- 4 files changed, 313 insertions(+), 38 deletions(-)
include/linux/memcontrol.h +5 -0
@@ -1846,6 +1846,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);
@@ -1854,6 +1855,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 +148 -18
211 lines not on this page · raw message
mm/swapfile.c +103 -20
220 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
Nhat Pham
maintainerRFC PATCH v2 5/7 mm, swap: add debugfs counters for vswap
In reply to Nhat PhamAdd /sys/kernel/debug/vswap/ with two counters:
* used: number of virtual swap slots currently allocated
* alloc_reject: cumulative count of failed vswap allocations
--- mm/swapfile.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-)
mm/swapfile.c +15 -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>
@@ -132,6 +133,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 struct percpu_vswap_cluster { unsigned long offset[SWAP_NR_ORDERS];
@@ -2038,11 +2042,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
@@ -2666,8 +2672,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 {
@@ -4849,6 +4857,7 @@ struct swap_info_struct *vswap_si;static int __init vswap_init (void ) {struct swap_info_struct *si; +struct dentry *root;unsigned long maxpages;int err;
@@ -4878,6 +4887,11 @@ static int __init vswap_init(void)mutex_unlock (&swapon_mutex); vswap_si = si; + + 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
maintainerRFC PATCH v2 6/7 mm, swap: defer memcg_table allocation on physical clusters
In reply to Nhat PhamPhysical swap clusters whose slots only serve as Pointer-tagged vswap backings never have their memcg_table read or written. Vswap-layer memcg charging records on the VSWAP cluster's table, not the physical cluster's. Allocating memcg_table eagerly for such clusters wastes SWAPFILE_CLUSTER * sizeof(unsigned short) bytes per cluster, which adds up on vswap-heavy workloads where zswap writeback is the only consumer of physical swap.
Allocate eagerly only when the cluster is known to need a memcg
table: any cluster in a !CONFIG_VSWAP build (all slots are direct use), or any vswap cluster (every vswap allocation records memcg). For physical clusters in CONFIG_VSWAP builds, defer the allocation to alloc_swap_scan_cluster, which lazy-allocates on the first direct-use slot and skips entirely when the cluster only holds Pointer-tagged vswap backings (folio in swap cache).
--- mm/swapfile.c | 48 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 8 deletions(-)
mm/swapfile.c +40 -8
@@ -493,7 +493,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;
@@ -516,7 +517,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) {
@@ -590,8 +600,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;/*
@@ -609,8 +619,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
@@ -883,7 +893,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. */
@@ -1175,6 +1185,28 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,if (!ret)continue ; } +#ifdef CONFIG_MEMCG +/* +* Physical cluster in a CONFIG_VSWAP build: lazy alloc +* memcg_table on the first direct-use slot. Checked here +* (not above the loop) because cluster_reclaim_range may +* have dropped ci->lock and a concurrent vswap-backing +* alloc could have freed and re-populated the cluster +* without the lazy alloc firing (that path has +* folio_test_swapcache(folio) true and skips it). For +* vswap-backing allocs here, the lazy alloc is also +* skipped because vswap-backing slots never touch +* memcg_table on the 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;
@@ -1241,7 +1273,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: [RFC PATCH v2 6/7] mm, swap: defer memcg_table allocation on physical clusters
Quoted 5 lines · On Fri, Jun 12, 2026 at 1:00 PM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] LazyGFP_ATOMICallocation ofmemcg_tablecauses swap-out failures and lock recursion under memory pressure. --
Quoted 8 lines
[Severity: High]
Will thisGFP_ATOMICallocation reliably succeed under memory pressure?Because swap allocation occurs during reclaim when free memory is already scarce, a non-blocking allocation seems highly likely to fail. This would abort the swap slot allocation and could potentially lead to premature OOMs.
Furthermore, does this violate locking rules for preemption-disabled sections?
We're holding a lock, so GFP_ATOMIC seems like the right choice. And I haven't observed swap slot allocation failure in my testing yet FWIW.
If it proves to be a problem then we can retry with the lock dropped and a more lenient GFP flag.
Quoted 4 lines
alloc_swap_scan_cluster()runs withci->lockheld and preemption disabled vialocal_lock(). TheGFP_ATOMICflag includes__GFP_KSWAPD_RECLAIM, which can triggerwakeup_kswapd()and enter the scheduler.
This doesn't sound correct to me...
Nhat Pham
maintainerRFC PATCH v2 7/7 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
@@ -253,7 +253,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 */
@@ -261,7 +261,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
A message that is not in the archive (sent off-list or not yet received): [email protected]
Nhat Pham
maintainerRe: [RFC PATCH v2 7/7] mm, swap: widen swap_info_struct max/pages to unsigned long
Quoted 41 lines · On Fri, Jun 12, 2026 at 4:19 PM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
Pre-existing issues:
- [Critical] Iterating overswap_active_headinsys_swapoffdereferences a NULLswap_fileforvswapdevices.
- [High]SWAP_USAGE_OFFLIST_BIToverlaps with the active page count, permanently corrupting statistics for swap devices exceeding 4 TB.
- [High]try_to_unuseblindly marks folios dirty without verifying the success of asynchronous I/O.
--[Severity: High]
This isn't a bug introduced by this patch, but cantry_to_unuse()blindly mark folios dirty without verifying the success of asynchronous I/O?When a vswap entry is read asynchronously via
swap_read_folio(), the code waits for completion by callingfolio_lock(), but fails to checkfolio_test_uptodate(folio)afterward:mm/swapfile.c:try_to_unuse() { ... swap_read_folio(folio, NULL); folio_lock(folio); } else { folio_lock(folio); } if (!folio_matches_swap_entry(folio, vswap_entry)) { folio_unlock(folio); folio_put(folio); continue; } /* Re-validate under folio lock: ... */ // ... folio_wait_writeback(folio); folio_release_vswap_backing(folio); folio_mark_dirty(folio); ... }
Quoted 2 lines
If the underlying I/O fails, could the folio contain garbage that is then marked dirty and committed, causing silent data corruption?
Hmm I mean, if the IO fails, likely the data is a gonner, no? Doesn't feel like it's worth failing swapoff here. If the process owning the page never access the data again, no problem. If it does, then it's going to SIGBUS trying to read from the swap device the same way it's reading from swapoff's produced folio :)
Quoted 11 lines
[ ... ]
Quoted 8 lines
mm/swapfile.c +1
-1@@ -3970,7 +3971,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)struct file *swap_file, *victim;struct address_space *mapping;struct inode *inode; -unsigned int maxpages; +unsigned long maxpages;int err, found =0 ;
Quoted 8 lines
mm/swapfile.c SYSCALL_DEFINE1(swapoff, const char __user *, specialfile) · line 3977
Quoted 1 line
mm/swapfile.c +0
-0if (!capable (CAP_SYS_ADMIN ))[Severity: Critical]
This is a pre-existing issue, but is it possible forsys_swapoff()to dereference a NULLswap_filefor vswap devices?
vswap_init()creates a swap device withsi->swap_file== NULL and adds it toswap_active_headwithSWP_WRITEOKset.
I excluded vswap device from swap_active_head list in _enable_swap_info(). False positive.
Quoted 21 lines
[ ... ]
mm/swapfile.c static int __init vswap_init(void) · line 4907
Quoted 13 lines
mm/swapfile.c +6
-1@@ -4900,8 +4897,13 @@ static int __init vswap_init(void)return 0 ; } +/* +* Cap at the cluster_info_pool xarray's allocator limit +* (XA_FLAGS_ALLOC stores IDs in u32, tops out at UINT_MAX). +*/ maxpages =min (swapfile_maximum_size, -ALIGN_DOWN ((unsigned long )UINT_MAX ,SWAPFILE_CLUSTER )); +ALIGN_DOWN ((unsigned long )UINT_MAX *SWAPFILE_CLUSTER , +SWAPFILE_CLUSTER )); si->flags |=SWP_VSWAP |SWP_SOLIDSTATE |SWP_WRITEOK ;[Severity: High]
This isn't a bug introduced by this patch, but since vswap devices can now exceed 16 TB, willSWAP_USAGE_OFFLIST_BITcorrupt the statistics?
Quoted 4 lines
SWAP_USAGE_OFFLIST_BITis hardcoded to use bit 30:
mm/swapfile.c:
#defineSWAP_USAGE_OFFLIST_BIT(1UL << (BITS_PER_TYPE(atomic_t)- 2))
Technically it's already a bit weird in existing code lol. The type of inuse_page is atomic_long_t already, but we use the 30th bit, which contradicts comment "Use the second highest bit of inuse_pages counter". It's only incidentally correct because the range of the swap device never reaches this high.
Quoted 12 lines
#define
SWAP_USAGE_COUNTER_MASK(~SWAP_USAGE_OFFLIST_BIT)mm/swapfile.c:swap_usage_in_pages() { static long swap_usage_in_pages(struct swap_info_struct *si) { return atomic_long_read(&si->inuse_pages) & SWAP_USAGE_COUNTER_MASK; } }When a swap device's
inuse_pagescounter reaches exactly 2^30 pages (4 TB), the 30th bit flips.
Quoted 6 lines
Because
swap_usage_in_pages()masks out this bit, would the usage count artificially wrap to 0?Could this cause
try_to_unuse()to abort prematurely thinking the device is empty, causingsys_swapoff()to forcefully tear down the swap device while it still contains active swapped-out pages?
Yes, this is a bug, but it's already a bug for existing physical swap devices IIUC.
In fact vswap device is the only device safe here :) We don't use swap_usage_in_pages's output, since vswap is not swapoff-able, not used for suspend, does not display to userspace. We don't do reclaim swap_reclaim_full_clusters() for vswap device either.
Nhat Pham
maintainerRe: [RFC PATCH v2 7/7] mm, swap: widen swap_info_struct max/pages to unsigned long
Quoted 8 lines · Nhat Pham
Quoted 2 lines
#define
SWAP_USAGE_OFFLIST_BIT(1UL << (BITS_PER_TYPE(atomic_t)- 2))Technically it's already a bit weird in existing code lol. The type of
inuse_pageisatomic_long_talready, but we use the 30th bit, which contradicts comment "Use the second highest bit ofinuse_pagescounter". It's only incidentally correct because the range of the swap device never reaches this high.
to clarify a bit - I meant to say the range of the swap devices never reach this high in real system that I have seen, not that it's not possible even theoretically.
[...]
Quoted 7 lines
Quoted 4 lines
Could this cause
try_to_unuse()to abort prematurely thinking the device is empty, causingsys_swapoff()to forcefully tear down the swap device while it still contains active swapped-out pages?Yes, this is a bug, but it's already a bug for existing physical swap devices IIUC.
existing bug from before this patch series.
YoungJun Park
reviewer...
Quoted 9 lines
* Integration with swap.tier by Youngjun (see [12]). For now, I'm leaning towards opting out the vswap device from swap.tier entirely, and treat it as a special device. Integrating it with swap.tiers will benefit the cases where you want some cgroups to skip vswap for fast swap devices (pmem), whereas other should go through zswap first. But most other use cases, either the overhead of vswap will be acceptable (or not the bottleneck), or we can just disable
CONFIG_VSWAPentirely :)Youngjun, may I ask for your thoughts on this?
Hi Nhat,
Tier 1: VSWAP, Tier 2: ZSWAP ...
I don't see any problem applying the desired functionality with the currently proposed mechanism and interface. With this, a user would be assigned the default Virtual -> RAM swap tier, and the overall picture becomes one where swap tiers are composed according to the priority setting.
A few more thoughts came to mind.
Shakeel also proposed a per-tier max for the swap tier interface.
https://lore.kernel.org/linux-mm/[email protected]/
However, for vswap, rather than treating it as a case for limiting the amount via such a per-tier max, I think the current interface is the better fit. (But, as Shakeel mentioned, if we only allow the limit to be set to 0 or max, the usage could end up being the same. I'm still thinking this part through.)
I have a few other thoughts as well, but I plan to raise those points in the swap tier discussion thread instead. Please take a look at the related thread, and let me know if you have any opinions. :)
And I'll share more if other thoughts come to mind
Thanks,
Youngjun Park
Nhat Pham
maintainerQuoted 14 lines · YoungJun Park
...
Quoted 9 lines
* Integration with swap.tier by Youngjun (see [12]). For now, I'm leaning towards opting out the vswap device from swap.tier entirely, and treat it as a special device. Integrating it with swap.tiers will benefit the cases where you want some cgroups to skip vswap for fast swap devices (pmem), whereas other should go through zswap first. But most other use cases, either the overhead of vswap will be acceptable (or not the bottleneck), or we can just disable
CONFIG_VSWAPentirely :)Youngjun, may I ask for your thoughts on this?
Hi Nhat,
Quoted 7 lines
Tier 1: VSWAP, Tier 2: ZSWAP ...
I don't see any problem applying the desired functionality with the currently proposed mechanism and interface. With this, a user would be assigned the default Virtual -> RAM swap tier, and the overall picture becomes one where swap tiers are composed according to the priority setting.
It's more - is there a strong argument to let vswap be a tier (which is not supported by just turning of vswap altogether).
Because right now I'm not exposing vswap device to userspace in any manner, pretty much. It's abstract and transparent, and minimizes complexity (no vswap and swap.tier interaction) and surfaces for issues.
But if you have a strong use case in mind please let me know :)
Worst case scenario if we're wrong, we can always do it as a follow-up down the line.
Quoted 13 lines
A few more thoughts came to mind.
Shakeel also proposed a per-tier max for the swap tier interface.
https://lore.kernel.org/linux-mm/[email protected]/
However, for vswap, rather than treating it as a case for limiting the amount via such a per-tier max, I think the current interface is the better fit. (But, as Shakeel mentioned, if we only allow the limit to be set to 0 or max, the usage could end up being the same. I'm still thinking this part through.)
Quoted 3 lines
I have a few other thoughts as well, but I plan to raise those points in the swap tier discussion thread instead. Please take a look at the related thread, and let me know if you have any opinions. :)
I'm following that thread too. I'm still thinking about it - will let you know when I have a more definitive opinion.
Yosry Ahmed
maintainerQuoted 24 lines · Nhat Pham
Quoted 14 lines · YoungJun Park
...
Quoted 9 lines
* Integration with swap.tier by Youngjun (see [12]). For now, I'm leaning towards opting out the vswap device from swap.tier entirely, and treat it as a special device. Integrating it with swap.tiers will benefit the cases where you want some cgroups to skip vswap for fast swap devices (pmem), whereas other should go through zswap first. But most other use cases, either the overhead of vswap will be acceptable (or not the bottleneck), or we can just disable
CONFIG_VSWAPentirely :)Youngjun, may I ask for your thoughts on this?
Hi Nhat,
Quoted 7 lines
Tier 1: VSWAP, Tier 2: ZSWAP ...
I don't see any problem applying the desired functionality with the currently proposed mechanism and interface. With this, a user would be assigned the default Virtual -> RAM swap tier, and the overall picture becomes one where swap tiers are composed according to the priority setting.
Quoted 7 lines
It's more - is there a strong argument to let vswap be a tier (which is not supported by just turning of vswap altogether).
Because right now I'm not exposing vswap device to userspace in any manner, pretty much. It's abstract and transparent, and minimizes complexity (no vswap and swap.tier interaction) and surfaces for issues.
I definitely think vswap should *not* be a tier. First of all, a vswap entry can be backed by zswap or an actual swap device, which would be two different tiers. How does that work?
I also think vswap should not be exposed to userspace in any way, at least not now. I still think we should aim to just make the redirection layer always on and eliminate "vswap devices".
YoungJun Park
reviewerQuoted 33 lines · Yosry Ahmed
Quoted 24 lines · Nhat Pham
Quoted 14 lines · YoungJun Park
...
Quoted 9 lines
* Integration with swap.tier by Youngjun (see [12]). For now, I'm leaning towards opting out the vswap device from swap.tier entirely, and treat it as a special device. Integrating it with swap.tiers will benefit the cases where you want some cgroups to skip vswap for fast swap devices (pmem), whereas other should go through zswap first. But most other use cases, either the overhead of vswap will be acceptable (or not the bottleneck), or we can just disable
CONFIG_VSWAPentirely :)Youngjun, may I ask for your thoughts on this?
Hi Nhat,
Quoted 7 lines
Tier 1: VSWAP, Tier 2: ZSWAP ...
I don't see any problem applying the desired functionality with the currently proposed mechanism and interface. With this, a user would be assigned the default Virtual -> RAM swap tier, and the overall picture becomes one where swap tiers are composed according to the priority setting.
Quoted 7 lines
It's more - is there a strong argument to let vswap be a tier (which is not supported by just turning of vswap altogether).
Because right now I'm not exposing vswap device to userspace in any manner, pretty much. It's abstract and transparent, and minimizes complexity (no vswap and swap.tier interaction) and surfaces for issues.
Quoted 7 lines
I definitely think vswap should *not* be a tier. First of all, a vswap entry can be backed by zswap or an actual swap device, which would be two different tiers. How does that work?
I also think vswap should not be exposed to userspace in any way, at least not now. I still think we should aim to just make the redirection layer always on and eliminate "vswap devices".
After following the answers and giving it some thought, I agree that vswap should be kept user-transparent. If there is a strict need to disable it, relying on CONFIG_VSWAP to remove it entirely seems like the right approach.
If a strong use case for user interaction emerges in the future, we can revisit the design and figure out how to handle it at that time.
Thanks,
Youngjun Park
Nhat Pham
maintainerQuoted 35 lines · YoungJun Park
Quoted 33 lines · Yosry Ahmed
Quoted 31 lines · Nhat Pham
Quoted 14 lines · YoungJun Park
...
Quoted 9 lines
* Integration with swap.tier by Youngjun (see [12]). For now, I'm leaning towards opting out the vswap device from swap.tier entirely, and treat it as a special device. Integrating it with swap.tiers will benefit the cases where you want some cgroups to skip vswap for fast swap devices (pmem), whereas other should go through zswap first. But most other use cases, either the overhead of vswap will be acceptable (or not the bottleneck), or we can just disable
CONFIG_VSWAPentirely :)Youngjun, may I ask for your thoughts on this?
Hi Nhat,
Quoted 7 lines
Tier 1: VSWAP, Tier 2: ZSWAP ...
I don't see any problem applying the desired functionality with the currently proposed mechanism and interface. With this, a user would be assigned the default Virtual -> RAM swap tier, and the overall picture becomes one where swap tiers are composed according to the priority setting.
It's more - is there a strong argument to let vswap be a tier (which is not supported by just turning of vswap altogether).
Because right now I'm not exposing vswap device to userspace in any manner, pretty much. It's abstract and transparent, and minimizes complexity (no vswap and swap.tier interaction) and surfaces for issues.
Quoted 7 lines
Quoted 7 lines
I definitely think vswap should *not* be a tier. First of all, a vswap entry can be backed by zswap or an actual swap device, which would be two different tiers. How does that work?
I also think vswap should not be exposed to userspace in any way, at least not now. I still think we should aim to just make the redirection layer always on and eliminate "vswap devices".
Yeah I will just expose a pair of usage/failure for diagnostics purposes :)
Quoted 8 lines
After following the answers and giving it some thought, I agree that vswap should be kept user-transparent. If there is a strict need to disable it, relying on
CONFIG_VSWAPto remove it entirely seems like the right approach.If a strong use case for user interaction emerges in the future, we can revisit the design and figure out how to handle it at that time.
Yeah the only argument for adding vswap to swap tier is if we want it to virtualize swap on a per-cgroup basis, assuming:
1. There's a setup where some cgroups benefit from vswap and some don't, in the same deployment or host (so you can't just use CONFIG_VSWAP).
2. We can't decide it with some heuristics purely based on kernel's knowledge (so for e.g, if a cgroup enables zswap, then vswap probably makes more sense than not, etc. etc.).
Maybe I'm missing something, and if so please let me know. But otherwise I'll stick with transparent vswap for the next version.
With Youngjun's new interface, if we made a mistake here and per-cgroup vswapping turned out to be necessary, fixing it is fairly cheap. We don't need to add any new knob - just need to expose it to memory.swap.tier somehow, and we're done. That can be done as follow-up :)