Virtual Swap Space
Subsystems (20)
Nhat Pham
maintainerv5 cover Virtual Swap Space
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Changelog:
* v4 -> v5:
* Fix a deadlock in memcg1_swapout (reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) with lockdep_assert_held(), and use guard(rcu) in vswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).
* Fix assorted kernel build errors reported by kernel test robots in the case of CONFIG_SWAP=n.
* RFC v2 -> v3:
* Implement a cluster-based allocation algorithm for virtual swap slots, inspired by Kairui Song and Chris Li's implementation, as well as Johannes Weiner's suggestions. This eliminates the lock contention issues on the virtual swap layer.
* Re-use swap table for the reverse mapping.
* Remove CONFIG_VIRTUAL_SWAP.
* Reducing the size of the swap descriptor from 48 bytes to 24 bytes, i.e another 50% reduction in memory overhead from v2.
* Remove swap cache and zswap tree and use the swap descriptor for this.
* Remove zeromap, and replace the swap_map bytemap with 2 bitmaps (one for allocated slots, and one for bad slots).
* Rebase on top of 6.19 (7d0a66e4bb9081d75c82ec4957c50034cb0ea449)
* Update cover letter to include new benchmark results and discussion on overhead in various cases.
* RFC v1 -> RFC v2:
* Use a single atomic type (swap_refs) for reference counting purpose. This brings the size of the swap descriptor from 64 B down to 48 B (25% reduction). Suggested by Yosry Ahmed.
* Zeromap bitmap is removed in the virtual swap implementation. This saves one bit per physical swapfile slot.
* Rearrange the patches and the code change to make things more reviewable. Suggested by Johannes Weiner.
* Update the cover letter a bit.
This patch series implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).
I. 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) to
save another resource (memory), zswap consume 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 pose 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.
Past attempts to decouple disk and compressed swap backends, namely the ghost swapfile approach (see [13]), as well as the alternative compressed swap backend zram, have mainly focused on eliminating the disk space usage of compressed backends. We want a solution that not only tackles that same problem, but also achieve the dynamicization of swap space to maximize the memory saving potentials while reducing operational and static memory overhead.
Finally, any swap redesign should support efficient backend transfer, i.e without having to perform the expensive page table walk to update all the PTEs that refer to the swap entry:
* The main motivation for this requirement is zswap writeback. To quote Johannes (from [14]): "Combining compression with disk swap is extremely powerful, because it dramatically reduces the worst aspects of both: it reduces the memory footprint of compression by shedding the coldest data to disk; it reduces the IO latencies and flash wear of disk swap through the writeback cache. In practice, this reduces *average event rates of the entire reclaim/paging/IO stack*."
* Another motivation is to simplify swapoff, which is both complicated and expensive in the current design, precisely because we are storing an encoding of the backend positional information in the page table, and thus requires a full page table walk to remove these references.
II. High Level Design Overview
To fix the aforementioned issues, we need an abstraction that separates a swap entry from its physical backing storage. IOW, we need to "virtualize" the swap space: swap clients will work with a dynamically allocated virtual swap slot, storing it in page table entries, and using it to index into various swap-related data structures. The backing storage is decoupled from the virtual swap slot, and the newly introduced layer will "resolve" the virtual swap slot to the actual storage. This layer also manages other metadata of the swap entry, such as its lifetime information (swap count), via a dynamically allocated, per-swap-entry descriptor:
struct swp_desc {
union {
swp_slot_t slot; /* 0 8 */
struct zswap_entry * zswap_entry; /* 0 8 */
}; /* 0 8 */
union {
struct folio * swap_cache; /* 8 8 */
void * shadow; /* 8 8 */
}; /* 8 8 */
unsigned int swap_count; /* 16 4 */
unsigned short memcgid:16; /* 20: 0 2 */
bool in_swapcache:1; /* 22: 0 1 */
/* Bitfield combined with previous fields */
enum swap_type type:2; /* 20:17 4 */
/* size: 24, cachelines: 1, members: 6 */
/* bit_padding: 13 bits */
/* last cacheline: 24 bytes */
};
(output from pahole).
This design allows us to:
* Decouple zswap (and zeromapped swap entry) from backing swapfile:
simply associate the virtual swap slot with one of the supported
backends: a zswap entry, a zero-filled swap page, a slot on the swapfile, or an in-memory page.
* Simplify and optimize swapoff: we only have to fault the page in and have the virtual swap slot points to the page instead of the on-disk physical swap slot. No need to perform any page table walking.
The size of the virtual swap descriptor is 24 bytes. Note that this is not all "new" overhead, as the swap descriptor will replace:
* the swap_cgroup arrays (one per swap type) in the old design, which is a massive source of static memory overhead. With the new design, it is only allocated for used clusters.
* the swap tables, which holds the swap cache and workingset shadows.
* the zeromap bitmap, which is a bitmap of physical swap slots to indicate whether the swapped out page is zero-filled or not.
* huge chunk of the swap_map. The swap_map is now replaced by 2 bitmaps, one for allocated slots, and one for bad slots, representing 3 possible states of a slot on the swapfile: allocated, free, and bad.
* the zswap tree.
So, in terms of additional memory overhead:
* For zswap entries, the added memory overhead is rather minimal. The new indirection pointer neatly replaces the existing zswap tree. We really only incur less than one word of overhead for swap count blow up (since we no longer use swap continuation) and the swap type.
* For physical swap entries, the new design will impose fewer than 3 words memory overhead. However, as noted above this overhead is only for actively used swap entries, whereas in the current design the overhead is static (including the swap cgroup array for example).
The primary victim of this overhead will be zram users. However, as zswap now no longer takes up disk space, zram users can consider switching to zswap (which, as a bonus, has a lot of useful features out of the box, such as cgroup tracking, dynamic zswap pool sizing, LRU-ordering writeback, etc.).
For a more concrete example, suppose we have a 32 GB swapfile (i.e. 8,388,608 swap entries), and we use zswap.
0% usage, or 0 entries: 0.00 MB
* Old design total overhead: 25.00 MB
* Vswap total overhead: 0.00 MB
25% usage, or 2,097,152 entries:
* Old design total overhead: 57.00 MB
* Vswap total overhead: 48.25 MB
50% usage, or 4,194,304 entries:
* Old design total overhead: 89.00 MB
* Vswap total overhead: 96.50 MB
75% usage, or 6,291,456 entries:
* Old design total overhead: 121.00 MB
* Vswap total overhead: 144.75 MB
100% usage, or 8,388,608 entries:
* Old design total overhead: 153.00 MB
* Vswap total overhead: 193.00 MB
So even in the worst case scenario for virtual swap, i.e when we somehow have an oracle to correctly size the swapfile for zswap pool to 32 GB, the added overhead is only 40 MB, which is a mere 0.12% of the total swapfile :)
In practice, the overhead will be closer to the 50-75% usage case, as systems tend to leave swap headroom for pathological events or sudden spikes in memory requirements. The added overhead in these cases are practically negligible. And in deployments where swapfiles for zswap are previously sparsely used, switching over to virtual swap will actually reduce memory overhead.
Doing the same math for the disk swap, which is the worst case for virtual swap in terms of swap backends:
0% usage, or 0 entries: 0.00 MB
* Old design total overhead: 25.00 MB
* Vswap total overhead: 2.00 MB
25% usage, or 2,097,152 entries:
* Old design total overhead: 41.00 MB
* Vswap total overhead: 66.25 MB
50% usage, or 4,194,304 entries:
* Old design total overhead: 57.00 MB
* Vswap total overhead: 130.50 MB
75% usage, or 6,291,456 entries:
* Old design total overhead: 73.00 MB
* Vswap total overhead: 194.75 MB
100% usage, or 8,388,608 entries:
* Old design total overhead: 89.00 MB
* Vswap total overhead: 259.00 MB
The added overhead is 170MB, which is 0.5% of the total swapfile size, again in the worst case when we have a sizing oracle.
Please see the attached patches for more implementation details.
III. Usage and Benchmarking
This patch series introduce no new syscalls or userspace API. Existing userspace setups will work as-is, except we no longer have to create a swapfile or set memory.swap.max if we want to use zswap, as zswap is no longer tied to physical swap. The zswap pool will be automatically and dynamically sized based on memory usage and reclaim dynamics.
To measure the performance of the new implementation, I have run the following benchmarks:
1. Kernel building: 52 workers (one per processor), memory.max = 3G.
Using zswap as the backend:
Baseline:
real: mean: 164.29s, stdev: 0.53s
user: mean: 5109.06s, stdev: 2.04s
sys: mean: 672.62s, stdev: 30.46s
Vswap:
real: mean: 164.12s, stdev: 0.4s
user: mean: 5105.24s, stdev: 2.01s
sys: mean: 668.66s, stdev: 34.45s
Using SSD swap as the backend:
Baseline:
real: mean: 189.74s, stdev: 2.03s
user: mean: 5035.93s, stdev: 3.1s
sys: mean: 500.01s, stdev: 4.16s
Vswap:
real: mean: 190.18s, stdev: 4.35s
user: mean: 5038.26s, stdev: 7.39s
sys: mean: 497.09s, stdev: 12.3s
The performance is neck-to-neck for both swap backends, with vswap slightly edging out in systime. However, the variance is high, so it is hard to draw a definitive conclusion.
2. Usemem: Per a report from Kairui Song ([15]), I have run the following benchmark:
Memory state of the system:
free -m
total used free shared buff/cache available
Mem: 31596 5094 11667 19 15302 26502 Swap: 65535 33 65502
Running the usemem benchmark with n = 1, 56G for 5 times, and average out the result:
Baseline (6.19):
real: mean: 190.93s, stdev: 5.09s
user: mean: 46.62s, stdev: 0.27s
sys: mean: 128.51s, stdev: 5.17s
throughput: mean: 382093 KB/s, stdev: 11173.6 KB/s free time: mean: 7916690.2 usecs, stdev: 88923.0 usecs
VSS:
real: mean: 187.66s, stdev: 5.67s
user: mean: 46.5s, stdev: 0.16s
sys: mean: 125.3s, stdev: 5.58s
throughput: mean: 387506.4 KB/s, stdev: 12556.56 KB/s free time: mean: 7029733.8 usecs, stdev: 124661.34 usecs
IV. Future Use Cases
While the patch series focus on two applications (decoupling swap backends and swapoff optimization/simplification), this new, future-proof design also allows us to implement new swap features more easily and efficiently:
* Multi-tier swapping (as mentioned in [5]), with transparent transferring (promotion/demotion) of pages across tiers (see [8] and [9]). Similar to swapoff, with the old design we would need to perform the expensive page table walk.
* Swapfile compaction to alleviate fragmentation (as proposed by Ying Huang in [6]).
* Mixed backing THP swapin (see [7]): Once you have pinned down the backing store of THPs, then you can dispatch each range of subpages to appropriate backend swapin handler.
* Swapping a folio out with discontiguous physical swap slots (see [10]).
* Zswap writeback optimization: The current architecture pre-reserves physical swap space for pages when they enter the zswap pool, giving the kernel no flexibility at writeback time. With the virtual swap implementation, the backends are decoupled, and physical swap space is allocated on-demand at writeback time, at which point we can make much smarter decisions: we can batch multiple zswap writeback operations into a single IO request, allocating contiguous physical swap slots for that request. We can even perform compressed writeback (i.e writing these pages without decompressing them) (see [12]).
V. References
[1]: https://lore.kernel.org/all/CAJD7tkbCnXJ95Qow_aOjNX6NOMU5ovMSHRC+95U4wtW6cM+puw@mail.gmail.com/
[2]: https://lwn.net/Articles/932077/
[3]: https://www.youtube.com/watch?v=Hwqw_TBGEhg
[4]: https://lore.kernel.org/all/[email protected]/
[5]: https://lore.kernel.org/lkml/CAF8kJuN-4UE0skVHvjUzpGefavkLULMonjgkXUZSBVJrcGFXCA@mail.gmail.com/
[6]: https://lore.kernel.org/linux-mm/[email protected]/
[7]: https://lore.kernel.org/all/CAGsJ_4ysCN6f7qt=6gvee1x3ttbOnifGneqcRm9Hoeun=uFQ2w@mail.gmail.com/
[8]: https://lore.kernel.org/linux-mm/[email protected]/
[9]: https://lore.kernel.org/all/CA+ZsKJ7DCE8PMOSaVmsmYZL9poxK6rn0gvVXbjpqxMwxS2C9TQ@mail.gmail.com/
[10]: https://lore.kernel.org/all/CACePvbUkMYMencuKfpDqtG1Ej7LiUS87VRAXb8sBn1yANikEmQ@mail.gmail.com/
[11]: https://lore.kernel.org/all/CAMgjq7BvQ0ZXvyLGp2YP96+i+6COCBBJCYmjXHGBnfisCAb8VA@mail.gmail.com/
[12]: https://lore.kernel.org/linux-mm/[email protected]/
[13]: https://lore.kernel.org/all/[email protected]/
[14]: https://lore.kernel.org/linux-mm/[email protected]/
[15]: https://lore.kernel.org/linux-mm/CAMgjq7AQNGK-a=AOgvn4-V+zGO21QMbMTVbrYSW_R2oDSLoC+A@mail.gmail.com/
[16]: https://lore.kernel.org/all/[email protected]/
[17]: https://lore.kernel.org/all/[email protected]/
Nhat Pham (21):
mm/swap: decouple swap cache from physical swap infrastructure
swap: rearrange the swap header file
mm: swap: add an abstract API for locking out swapoff
zswap: add new helpers for zswap entry operations
mm/swap: add a new function to check if a swap entry is in swap
cached.
mm: swap: add a separate type for physical swap slots
mm: create scaffolds for the new virtual swap implementation
zswap: prepare zswap for swap virtualization
mm: swap: allocate a virtual swap slot for each swapped out page
swap: move swap cache to virtual swap descriptor
zswap: move zswap entry management to the virtual swap descriptor
swap: implement the swap_cgroup API using virtual swap
swap: manage swap entry lifecycle at the virtual swap layer
mm: swap: decouple virtual swap slot from backing store
zswap: do not start zswap shrinker if there is no physical swap slots
swap: do not unnecesarily pin readahead swap entries
swapfile: remove zeromap bitmap
memcg: swap: only charge physical swap slots
swap: simplify swapoff using virtual swap
swapfile: replace the swap map with bitmaps
vswap: batch contiguous vswap free calls
Documentation/mm/swap-table.rst | 69 -- MAINTAINERS | 3 +- include/linux/cpuhotplug.h | 1 + include/linux/memcontrol.h | 6 + include/linux/mm_types.h | 16 + include/linux/shmem_fs.h | 7 +- include/linux/swap.h | 185 ++- include/linux/swap_cgroup.h | 17 +- include/linux/swapops.h | 25 + include/linux/zswap.h | 17 +- kernel/power/swap.c | 6 +- mm/Makefile | 5 +- mm/filemap.c | 14 +- mm/huge_memory.c | 11 +- mm/internal.h | 24 +- mm/madvise.c | 2 +- mm/memcontrol-v1.c | 8 +- mm/memcontrol.c | 144 ++- mm/memory.c | 109 +- mm/migrate.c | 13 +- mm/mincore.c | 15 +- mm/page_io.c | 83 +- mm/shmem.c | 227 +--- mm/swap.h | 179 +-- mm/swap_cgroup.c | 172 --- mm/swap_state.c | 306 +---- mm/swap_table.h | 78 +- mm/swapfile.c | 1517 ++++------------------- mm/userfaultfd.c | 18 +- mm/vmscan.c | 28 +- mm/vswap.c | 2034 +++++++++++++++++++++++++++++++ mm/zswap.c | 142 +-- 32 files changed, 2974 insertions(+), 2507 deletions(-) delete mode 100644 Documentation/mm/swap-table.rst delete mode 100644 mm/swap_cgroup.c create mode 100644 mm/vswap.c
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 1/21 mm/swap: decouple swap cache from physical swap infrastructure
When we virtualize the swap space, we will manage swap cache at the virtual swap layer. To prepare for this, decouple swap cache from physical swap infrastructure.
We will also remove all the swap cache related helpers of swap table. We will keep the rest of the swap table infrastructure, which will be repurposed to serve as the rmap (physical -> virtual swap mapping) later.
Note that with this patch, we will move to a single global lock to synchronize swap cache accesses. This is temporarily, as the swap cache will be re-partitioned in to (virtual) swap clusters once we move the swap cache to the soon-to-be-introduced virtual swap layer.
--- Documentation/mm/swap-table.rst | 69 ----------- MAINTAINERS | 1 - mm/huge_memory.c | 11 +- mm/migrate.c | 13 +- mm/shmem.c | 7 +- mm/swap.h | 44 +++++-- mm/swap_state.c | 205 +++++++++++++++++--------------- mm/swap_table.h | 78 +----------- mm/swapfile.c | 45 +++---- mm/vmscan.c | 9 +- 10 files changed, 178 insertions(+), 304 deletions(-) delete mode 100644 Documentation/mm/swap-table.rst
Documentation/mm/swap-table.rst deleted +0 -69
@@ -1,69 +0,0 @@ -.. SPDX-License-Identifier: GPL-2.0 - -:Author: Chris Li <[email protected]>, Kairui Song <[email protected]> - -========== -Swap Table -========== - -Swap table implements swap cache as a per-cluster swap cache value array. - -Swap Entry ----------- - -A swap entry contains the information required to serve the anonymous page -fault. - -Swap entry is encoded as two parts: swap type and swap offset. - -The swap type indicates which swap device to use. -The swap offset is the offset of the swap file to read the page data from. - -Swap Cache ----------- - -Swap cache is a map to look up folios using swap entry as the key. The result -value can have three possible types depending on which stage of this swap entry -was in. - -1. NULL: This swap entry is not used. - -2. folio: A folio has been allocated and bound to this swap entry. This is - the transient state of swap out or swap in. The folio data can be in - the folio or swap file, or both. - -3. shadow: The shadow contains the working set information of the swapped - out folio. This is the normal state for a swapped out page. - -Swap Table Internals --------------------- - -The previous swap cache is implemented by XArray. The XArray is a tree -structure. Each lookup will go through multiple nodes. Can we do better? - -Notice that most of the time when we look up the swap cache, we are either -in a swap in or swap out path. We should already have the swap cluster, -which contains the swap entry. - -If we have a per-cluster array to store swap cache value in the cluster. -Swap cache lookup within the cluster can be a very simple array lookup. - -We give such a per-cluster swap cache value array a name: the swap table. - -A swap table is an array of pointers. Each pointer is the same size as a -PTE. The size of a swap table for one swap cluster typically matches a PTE -page table, which is one page on modern 64-bit systems. - -With swap table, swap cache lookup can achieve great locality, simpler, -and faster. - -Locking -------- - -Swap table modification requires taking the cluster lock. If a folio -is being added to or removed from the swap table, the folio must be -locked prior to the cluster lock. After adding or removing is done, the -folio shall be unlocked. - -Swap table lookup is protected by RCU and atomic read. If the lookup -returns a folio, the user must lock the folio before use.
MAINTAINERS +0 -1
@@ -16730,7 +16730,6 @@ R: Baoquan He <[email protected]> R: Barry Song <[email protected]> L: [email protected] S: Maintained -F: Documentation/mm/swap-table.rst F: include/linux/swap.h F: include/linux/swapfile.h F: include/linux/swapops.h
mm/huge_memory.c +5 -6
@@ -3783,7 +3783,6 @@ static int __folio_freeze_and_split_unmapped(struct folio *folio, unsigned int n/* Prevent deferred_split_scan() touching ->_refcount */ ds_queue =folio_split_queue_lock (folio);if (folio_ref_freeze (folio,folio_cache_ref_count (folio) +1 )) { -struct swap_cluster_info *ci =NULL ;struct lruvec *lruvec;if (old_order >1 ) {
@@ -3826,7 +3825,7 @@ static int __folio_freeze_and_split_unmapped(struct folio *folio, unsigned int nreturn -EINVAL ; } - ci =swap_cluster_get_and_lock (folio); +swap_cache_lock (); }/* lock lru list/PageCompound, ref frozen by page_ref_freeze */
@@ -3862,8 +3861,8 @@ static int __folio_freeze_and_split_unmapped(struct folio *folio, unsigned int n* Anonymous folio with swap cache. * NOTE: shmem in swap cache is not supported yet. */ -if (ci) { -__swap_cache_replace_folio (ci, folio, new_folio); +if (folio_test_swapcache (folio)) { +__swap_cache_replace_folio (folio, new_folio);continue ; }
@@ -3901,8 +3900,8 @@ static int __folio_freeze_and_split_unmapped(struct folio *folio, unsigned int nif (do_lru)unlock_page_lruvec (lruvec); -if (ci) -swap_cluster_unlock (ci); +if (folio_test_swapcache (folio)) +swap_cache_unlock (); }else {split_queue_unlock (ds_queue);return -EAGAIN ;
mm/migrate.c +6 -7
@@ -571,7 +571,6 @@ static int __folio_migrate_mapping(struct address_space *mapping, struct folio *newfolio, struct folio *folio, int expected_count) { XA_STATE(xas, &mapping->i_pages, folio->index); -struct swap_cluster_info *ci =NULL ;struct zone *oldzone, *newzone;int dirty;long nr =folio_nr_pages (folio);
@@ -601,13 +600,13 @@ static int __folio_migrate_mapping(struct address_space *mapping, newzone =folio_zone (newfolio);if (folio_test_swapcache (folio)) - ci =swap_cluster_get_and_lock_irq (folio); +swap_cache_lock_irq ();else xas_lock_irq (&xas);if (!folio_ref_freeze (folio, expected_count)) { -if (ci) -swap_cluster_unlock_irq (ci); +if (folio_test_swapcache (folio)) +swap_cache_unlock_irq ();else xas_unlock_irq (&xas);return -EAGAIN ;
@@ -640,7 +639,7 @@ static int __folio_migrate_mapping(struct address_space *mapping, }if (folio_test_swapcache (folio)) -__swap_cache_replace_folio (ci, folio, newfolio); +__swap_cache_replace_folio (folio, newfolio);else xas_store (&xas, newfolio);
@@ -652,8 +651,8 @@ static int __folio_migrate_mapping(struct address_space *mapping,folio_ref_unfreeze (folio, expected_count - nr);/* Leave irq disabled to prevent preemption while updating stats */ -if (ci) -swap_cluster_unlock (ci); +if (folio_test_swapcache (folio)) +swap_cache_unlock ();else xas_unlock (&xas);
mm/shmem.c +3 -4
@@ -2133,7 +2133,6 @@ static int shmem_replace_folio(struct folio **foliop, gfp_t gfp, struct shmem_inode_info *info, pgoff_t index, struct vm_area_struct *vma) { - struct swap_cluster_info *ci; struct folio *new, *old = *foliop;swp_entry_t entry = old->swap;int nr_pages =folio_nr_pages (old);
@@ -2166,12 +2165,12 @@ static int shmem_replace_folio(struct folio **foliop, gfp_t gfp, new->swap = entry;folio_set_swapcache (new); - ci =swap_cluster_get_and_lock_irq (old); -__swap_cache_replace_folio (ci, old, new); +swap_cache_lock_irq (); +__swap_cache_replace_folio (old, new);mem_cgroup_replace_folio (old, new);shmem_update_stats (new, nr_pages);shmem_update_stats (old, -nr_pages); -swap_cluster_unlock_irq (ci); +swap_cache_unlock_irq ();folio_add_lru (new); *foliop = new;
mm/swap.h +32 -12
73 lines not on this page · raw message
mm/swap_state.c +112 -93
316 lines not on this page · raw message
mm/swap_table.h +1 -77
96 lines not on this page · raw message
mm/swapfile.c +15 -30
103 lines not on this page · raw message
mm/vmscan.c +4 -5
@@ -707,13 +707,12 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio, {int refcount;void *shadow =NULL ; -struct swap_cluster_info *ci;BUG_ON (!folio_test_locked (folio));BUG_ON (mapping !=folio_mapping (folio));if (folio_test_swapcache (folio)) { - ci =swap_cluster_get_and_lock_irq (folio); +swap_cache_lock_irq (); }else {spin_lock (&mapping->host->i_lock);xa_lock_irq (&mapping->i_pages);
@@ -758,9 +757,9 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,if (reclaimed && !mapping_exiting (mapping)) shadow =workingset_eviction (folio, target_memcg); -__swap_cache_del_folio (ci, folio, swap, shadow); +__swap_cache_del_folio (folio, swap, shadow);memcg1_swapout (folio, swap); -swap_cluster_unlock_irq (ci); +swap_cache_unlock_irq ();put_swap_folio (folio, swap); }else {void (*free_folio)(struct folio *);
@@ -799,7 +798,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio, cannot_free:if (folio_test_swapcache (folio)) { -swap_cluster_unlock_irq (ci); +swap_cache_unlock_irq (); }else {xa_unlock_irq (&mapping->i_pages);spin_unlock (&mapping->host->i_lock);
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 2/21 swap: rearrange the swap header file
In reply to Nhat PhamIn the swap header file (include/linux/swap.h), group the swap API into the following categories:
1. Lifecycle swap functions (i.e the function that changes the reference count of the swap entry).
2. Swap cache API.
3. Physical swapfile allocator and swap device API.
Also remove extern in the functions that are rearranged.
This is purely a clean up. No functional change intended.
--- include/linux/swap.h | 53 +++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 25 deletions(-)
include/linux/swap.h +28 -25
@@ -423,20 +423,34 @@ extern void __meminit kswapd_stop(int nid);#ifdef CONFIG_SWAP -int add_swap_extent (struct swap_info_struct *sis,unsigned long start_page, -unsigned long nr_pages,sector_t start_block); -int generic_swapfile_activate (struct swap_info_struct *,struct file *, -sector_t *); - +/* Lifecycle swap API (mm/swapfile.c) */ +int folio_alloc_swap (struct folio *folio); +bool folio_free_swap (struct folio *folio); +void put_swap_folio (struct folio *folio,swp_entry_t entry); +void swap_shmem_alloc (swp_entry_t ,int ); +int swap_duplicate (swp_entry_t ); +int swapcache_prepare (swp_entry_t entry,int nr); +void swap_free_nr (swp_entry_t entry,int nr_pages); +void free_swap_and_cache_nr (swp_entry_t entry,int nr); +int __swap_count (swp_entry_t entry); +bool swap_entry_swapped (struct swap_info_struct *si,swp_entry_t entry); +int swp_swapcount (swp_entry_t entry); + +/* Swap cache API (mm/swap_state.c) */ static inline unsigned long total_swapcache_pages (void ) {return global_node_page_state (NR_SWAPCACHE ); } - -void free_swap_cache (struct folio *folio);void free_folio_and_swap_cache (struct folio *folio);void free_pages_and_swap_cache (struct encoded_page **,int ); -/* linux/mm/swapfile.c */ +void free_swap_cache (struct folio *folio); + +/* Physical swap allocator and swap device API (mm/swapfile.c) */ +int add_swap_extent (struct swap_info_struct *sis,unsigned long start_page, +unsigned long nr_pages,sector_t start_block); +int generic_swapfile_activate (struct swap_info_struct *,struct file *, +sector_t *); +extern atomic_long_t nr_swap_pages;extern long total_swap_pages;extern atomic_t nr_rotate_swap;
@@ -452,26 +466,15 @@ static inline long get_nr_swap_pages(void)return atomic_long_read (&nr_swap_pages); } -extern void si_swapinfo (struct sysinfo *); -int folio_alloc_swap (struct folio *folio); -bool folio_free_swap (struct folio *folio); -void put_swap_folio (struct folio *folio,swp_entry_t entry); -extern swp_entry_t get_swap_page_of_type (int ); -extern int add_swap_count_continuation (swp_entry_t ,gfp_t ); -extern void swap_shmem_alloc (swp_entry_t ,int ); -extern int swap_duplicate (swp_entry_t ); -extern int swapcache_prepare (swp_entry_t entry,int nr); -extern void swap_free_nr (swp_entry_t entry,int nr_pages); -extern void free_swap_and_cache_nr (swp_entry_t entry,int nr); +void si_swapinfo (struct sysinfo *); +swp_entry_t get_swap_page_of_type (int ); +int add_swap_count_continuation (swp_entry_t ,gfp_t );int swap_type_of (dev_t device,sector_t offset);int find_first_swap (dev_t *device); -extern unsigned int count_swap_pages (int ,int ); -extern sector_t swapdev_block (int ,pgoff_t ); -extern int __swap_count (swp_entry_t entry); -extern bool swap_entry_swapped (struct swap_info_struct *si,swp_entry_t entry); -extern int swp_swapcount (swp_entry_t entry); +unsigned int count_swap_pages (int ,int ); +sector_t swapdev_block (int ,pgoff_t );struct backing_dev_info ; -extern struct swap_info_struct *get_swap_device (swp_entry_t entry); +struct swap_info_struct *get_swap_device (swp_entry_t entry);sector_t swap_folio_sector (struct folio *folio);static inline void put_swap_device (struct swap_info_struct *si)
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 3/21 mm: swap: add an abstract API for locking out swapoff
In reply to Nhat PhamCurrently, we get a reference to the backing swap device in order to prevent swapoff from freeing the metadata of a swap entry. This does not make sense in the new virtual swap design, especially after the swap backends are decoupled - a swap entry might not have any backing swap device at all, and its backend might change at any time during its lifetime.
In preparation for this, abstract away the swapoff locking out behavior into a generic API.
--- include/linux/swap.h | 17 +++++++++++++++++ mm/memory.c | 13 +++++++------ mm/mincore.c | 15 +++------------ mm/shmem.c | 12 ++++++------ mm/swap_state.c | 14 +++++++------- mm/userfaultfd.c | 15 +++++++++------ mm/zswap.c | 5 ++--- 7 files changed, 51 insertions(+), 40 deletions(-)
include/linux/swap.h +17 -0
@@ -659,5 +659,22 @@ static inline bool mem_cgroup_swap_full(struct folio *folio) }#endif +static inline bool tryget_swap_entry (swp_entry_t entry, +struct swap_info_struct **sip) +{ +struct swap_info_struct *si =get_swap_device (entry); + +if (sip) + *sip = si; + +return si; +} + +static inline void put_swap_entry (swp_entry_t entry, +struct swap_info_struct *si) +{ +put_swap_device (si); +} +#endif /* __KERNEL__*/ #endif /* _LINUX_SWAP_H */
mm/memory.c +7 -6
@@ -4630,6 +4630,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)struct swap_info_struct *si =NULL ;rmap_t rmap_flags =RMAP_NONE ;bool need_clear_cache = false; +bool swapoff_locked = false;bool exclusive = false;softleaf_t entry;pte_t pte;
@@ -4698,8 +4699,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) }/* Prevent swapoff from happening to us. */ - si =get_swap_device (entry); -if (unlikely (!si)) + swapoff_locked =tryget_swap_entry (entry, &si); +if (unlikely (!swapoff_locked)) goto out; folio =swap_cache_get_folio (entry);
@@ -5047,8 +5048,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (waitqueue_active (&swapcache_wq))wake_up (&swapcache_wq); } -if (si) -put_swap_device (si); +if (swapoff_locked) +put_swap_entry (entry, si);return ret; out_nomap:if (vmf->pte)
@@ -5066,8 +5067,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (waitqueue_active (&swapcache_wq))wake_up (&swapcache_wq); } -if (si) -put_swap_device (si); +if (swapoff_locked) +put_swap_entry (entry, si);return ret; }
mm/mincore.c +3 -12
@@ -77,19 +77,10 @@ static unsigned char mincore_swap(swp_entry_t entry, bool shmem)if (!softleaf_is_swap (entry))return !shmem; -/* -* Shmem mapping lookup is lockless, so we need to grab the swap -* device. mincore page table walk locks the PTL, and the swap -* device is stable, avoid touching the si for better performance. -*/ -if (shmem) { - si =get_swap_device (entry); -if (!si) -return 0 ; - } +if (!tryget_swap_entry (entry, &si)) +return 0 ; folio =swap_cache_get_folio (entry); -if (shmem) -put_swap_device (si); +put_swap_entry (entry, si);/* The swap cache space contains either folio, shadow or NULL */ if (folio && !xa_is_value (folio)) { present =folio_test_uptodate (folio);
mm/shmem.c +6 -6
@@ -2307,7 +2307,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,softleaf_t index_entry;struct swap_info_struct *si;struct folio *folio =NULL ; -bool skip_swapcache = false; +bool swapoff_locked, skip_swapcache = false;int error, nr_pages, order;pgoff_t offset;
@@ -2319,16 +2319,16 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,if (softleaf_is_poison_marker (index_entry))return -EIO ; - si =get_swap_device (index_entry); + swapoff_locked =tryget_swap_entry (index_entry, &si); order =shmem_confirm_swap (mapping, index, index_entry); -if (unlikely (!si)) { +if (unlikely (!swapoff_locked)) {if (order <0 )return -EEXIST ;else return -EINVAL ; }if (unlikely (order <0 )) { -put_swap_device (si); +put_swap_entry (index_entry, si);return -EEXIST ; }
@@ -2448,7 +2448,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index, }folio_mark_dirty (folio);swap_free_nr (swap, nr_pages); -put_swap_device (si); +put_swap_entry (swap, si); *foliop = folio;return 0 ;
@@ -2466,7 +2466,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,swapcache_clear (si, folio->swap,folio_nr_pages (folio));if (folio)folio_put (folio); -put_swap_device (si); +put_swap_entry (swap, si);return error; }
mm/swap_state.c +7 -7
@@ -538,8 +538,7 @@ struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,pgoff_t ilx;struct folio *folio; - si =get_swap_device (entry); -if (!si) +if (!tryget_swap_entry (entry, &si))return NULL ; mpol =get_vma_policy (vma, addr,0 , &ilx);
@@ -550,7 +549,7 @@ struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,if (page_allocated)swap_read_folio (folio, plug); -put_swap_device (si); +put_swap_entry (entry, si);return folio; }
@@ -763,6 +762,7 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,for (addr = start; addr < end; ilx++, addr +=PAGE_SIZE ) {struct swap_info_struct *si =NULL ;softleaf_t entry; +bool swapoff_locked = false;if (!pte++) { pte =pte_offset_map (vmf->pmd, addr);
@@ -781,14 +781,14 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,* holding a reference to, try to grab a reference, or skip. */ if (swp_type (entry) !=swp_type (targ_entry)) { - si =get_swap_device (entry); -if (!si) + swapoff_locked =tryget_swap_entry (entry, &si); +if (!swapoff_locked)continue ; } folio =__read_swap_cache_async (entry, gfp_mask, mpol, ilx, &page_allocated, false); -if (si) -put_swap_device (si); +if (swapoff_locked) +put_swap_entry (entry, si);if (!folio)continue ;if (page_allocated) {
mm/userfaultfd.c +9 -6
@@ -1262,9 +1262,11 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmdpte_t *dst_pte =NULL ;pmd_t dummy_pmdval;pmd_t dst_pmdval; +softleaf_t entry;struct folio *src_folio =NULL ;struct mmu_notifier_range range;long ret =0 ; +bool swapoff_locked = false;mmu_notifier_range_init (&range,MMU_NOTIFY_CLEAR ,0 , mm, src_addr, src_addr + len);
@@ -1429,7 +1431,7 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd len); }else {/* !pte_present() */ struct folio *folio =NULL ; -const softleaf_t entry =softleaf_from_pte (orig_src_pte); + entry =softleaf_from_pte (orig_src_pte);if (softleaf_is_migration (entry)) {pte_unmap (src_pte);
@@ -1449,8 +1451,8 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd goto out; } - si =get_swap_device (entry); -if (unlikely (!si)) { + swapoff_locked =tryget_swap_entry (entry, &si); +if (unlikely (!swapoff_locked)) { ret = -EAGAIN ; goto out; }
@@ -1480,8 +1482,9 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmdpte_unmap (src_pte);pte_unmap (dst_pte); src_pte = dst_pte =NULL ; -put_swap_device (si); +put_swap_entry (entry, si); si =NULL ; + swapoff_locked = false;/* now we can block and wait */ folio_lock (src_folio); goto retry;
@@ -1507,8 +1510,8 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmdif (dst_pte)pte_unmap (dst_pte);mmu_notifier_invalidate_range_end (&range); -if (si) -put_swap_device (si); +if (swapoff_locked) +put_swap_entry (entry, si);return ret; }
mm/zswap.c +2 -3
@@ -1009,14 +1009,13 @@ static int zswap_writeback_entry(struct zswap_entry *entry,int ret =0 ;/* try to allocate swap cache folio */ - si =get_swap_device (swpentry); -if (!si) +if (!tryget_swap_entry (swpentry, &si))return -EEXIST ; mpol =get_task_policy (current); folio =__read_swap_cache_async (swpentry,GFP_KERNEL , mpol,NO_INTERLEAVE_INDEX , &folio_was_allocated, true); -put_swap_device (si); +put_swap_entry (swpentry, si);if (!folio)return -ENOMEM ;
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 4/21 zswap: add new helpers for zswap entry operations
In reply to Nhat PhamAdd new helper functions to abstract away zswap entry operations, in order to facilitate re-implementing these functions when swap is virtualized.
--- mm/zswap.c | 59 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 19 deletions(-)
mm/zswap.c +40 -19
@@ -234,6 +234,38 @@ static inline struct xarray *swap_zswap_tree(swp_entry_t swp) >> ZSWAP_ADDRESS_SPACE_SHIFT]; } +static inline void *zswap_entry_store (swp_entry_t swpentry, +struct zswap_entry *entry) +{ +struct xarray *tree =swap_zswap_tree (swpentry); +pgoff_t offset =swp_offset (swpentry); + +return xa_store (tree, offset, entry,GFP_KERNEL ); +} + +static inline void *zswap_entry_load (swp_entry_t swpentry) +{ +struct xarray *tree =swap_zswap_tree (swpentry); +pgoff_t offset =swp_offset (swpentry); + +return xa_load (tree, offset); +} + +static inline void *zswap_entry_erase (swp_entry_t swpentry) +{ +struct xarray *tree =swap_zswap_tree (swpentry); +pgoff_t offset =swp_offset (swpentry); + +return xa_erase (tree, offset); +} + +static inline bool zswap_empty (swp_entry_t swpentry) +{ +struct xarray *tree =swap_zswap_tree (swpentry); + +return xa_empty (tree); +} +#define zswap_pool_debug (msg, p) \ pr_debug("%s pool %s\n", msg, (p)->tfm_name)
@@ -1000,8 +1032,6 @@ static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio)static int zswap_writeback_entry (struct zswap_entry *entry,swp_entry_t swpentry) { -struct xarray *tree; -pgoff_t offset =swp_offset (swpentry);struct folio *folio;struct mempolicy *mpol;bool folio_was_allocated;
@@ -1040,8 +1070,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,* old compressed data. Only when this is successful can the entry * be dereferenced. */ - tree =swap_zswap_tree (swpentry); -if (entry !=xa_load (tree, offset)) { +if (entry !=zswap_entry_load (swpentry)) { ret = -ENOMEM ; goto out; }
@@ -1051,7 +1080,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry, goto out; } -xa_erase (tree, offset); +zswap_entry_erase (swpentry);count_vm_event (ZSWPWB );if (entry->objcg)
@@ -1427,9 +1456,7 @@ 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 ); + old =zswap_entry_store (page_swpentry, entry);if (xa_is_err (old)) {int err =xa_err (old);
@@ -1563,11 +1590,9 @@ bool zswap_store(struct folio *folio)unsigned type =swp_type (swp);pgoff_t offset =swp_offset (swp);struct zswap_entry *entry; -struct xarray *tree;for (index =0 ; index < nr_pages; ++index) { - tree =swap_zswap_tree (swp_entry (type, offset + index)); - entry =xa_erase (tree, offset + index); + entry =zswap_entry_erase (swp_entry (type, offset + index));if (entry)zswap_entry_free (entry); }
@@ -1599,9 +1624,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);bool swapcache =folio_test_swapcache (folio); -struct xarray *tree =swap_zswap_tree (swp);struct zswap_entry *entry;VM_WARN_ON_ONCE (!folio_test_locked (folio));
@@ -1619,7 +1642,7 @@ int zswap_load(struct folio *folio)return -EINVAL ; } - entry =xa_load (tree, offset); + entry =zswap_entry_load (swp);if (!entry)return -ENOENT ;
@@ -1648,7 +1671,7 @@ int zswap_load(struct folio *folio)*/ if (swapcache) {folio_mark_dirty (folio); -xa_erase (tree, offset); +zswap_entry_erase (swp);zswap_entry_free (entry); }
@@ -1658,14 +1681,12 @@ int zswap_load(struct folio *folio)void zswap_invalidate (swp_entry_t swp) { -pgoff_t offset =swp_offset (swp); -struct xarray *tree =swap_zswap_tree (swp);struct zswap_entry *entry; -if (xa_empty (tree)) +if (zswap_empty (swp))return ; - entry =xa_erase (tree, offset); + entry =zswap_entry_erase (swp);if (entry)zswap_entry_free (entry); }
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 5/21 mm/swap: add a new function to check if a swap entry is in swap cached.
In reply to Nhat PhamUserfaultfd checks whether a swap entry is in swapcache. This is currently done by directly looking at the swapfile's swap map - however, the swap cached state will soon be managed at the virtual swap layer. Abstract away this function.
--- include/linux/swap.h | 6 ++++++ mm/swapfile.c | 15 +++++++++++++++ mm/userfaultfd.c | 3 +-- 3 files changed, 22 insertions(+), 2 deletions(-)
include/linux/swap.h +6 -0
@@ -435,6 +435,7 @@ void free_swap_and_cache_nr(swp_entry_t entry, int nr);int __swap_count (swp_entry_t entry);bool swap_entry_swapped (struct swap_info_struct *si,swp_entry_t entry);int swp_swapcount (swp_entry_t entry); +bool is_swap_cached (swp_entry_t entry);/* Swap cache API (mm/swap_state.c) */ static inline unsigned long total_swapcache_pages (void )
@@ -554,6 +555,11 @@ static inline int swp_swapcount(swp_entry_t entry)return 0 ; } +static inline bool is_swap_cached (swp_entry_t entry) +{ +return false; +} +static inline int folio_alloc_swap (struct folio *folio) {return -EINVAL ;
mm/swapfile.c +15 -0
@@ -194,6 +194,21 @@ static bool swap_only_has_cache(struct swap_info_struct *si,return true; } +/** +* is_swap_cached - check if the swap entry is cached +* @entry: swap entry to check +* +* Check swap_map directly to minimize overhead, READ_ONCE is sufficient. +* +* Returns true if the swap entry is cached, false otherwise. +*/ +bool is_swap_cached (swp_entry_t entry) +{ +struct swap_info_struct *si =__swap_entry_to_info (entry); + +return READ_ONCE (si->swap_map[swp_offset (entry)]) &SWAP_HAS_CACHE ; +} +static bool swap_is_last_map (struct swap_info_struct *si,unsigned long offset,int nr_pages,bool *has_cache) {
mm/userfaultfd.c +1 -2
@@ -1190,7 +1190,6 @@ static int move_swap_pte(struct mm_struct *mm, struct vm_area_struct *dst_vma,* Check if the swap entry is cached after acquiring the src_pte * lock. Otherwise, we might miss a newly loaded swap cache folio. * -* Check swap_map directly to minimize overhead, READ_ONCE is sufficient. * We are trying to catch newly added swap cache, the only possible case is * when a folio is swapped in and out again staying in swap cache, using the * same entry before the PTE check above. The PTL is acquired and released
@@ -1200,7 +1199,7 @@ static int move_swap_pte(struct mm_struct *mm, struct vm_area_struct *dst_vma,* cache, or during the tiny synchronization window between swap cache and * swap_map, but it will be gone very quickly, worst result is retry jitters. */ -if (READ_ONCE (si->swap_map[swp_offset (entry)]) &SWAP_HAS_CACHE ) { +if (is_swap_cached (entry)) {double_pt_unlock (dst_ptl, src_ptl);return -EAGAIN ; }
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 6/21 mm: swap: add a separate type for physical swap slots
In reply to Nhat PhamIn preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates:
1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type.
from:
2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type.
The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g).
Note that we have not made any behavioral change - the mapping between the two types is the identity mapping. In later patches, we shall dynamically allocate a virtual swap slot (of type swp_entry_t) for each swapped out page to store in the page table entry, and associate it with a backing store. A physical swap slot (i.e a slot on a physical swap device) is one of the backing options.
--- include/linux/mm_types.h | 16 +++ include/linux/swap.h | 47 ++++-- include/linux/swapops.h | 25 ++++ kernel/power/swap.c | 6 +- mm/internal.h | 10 +- mm/page_io.c | 33 +++-- mm/shmem.c | 19 ++- mm/swap.h | 52 +++---- mm/swap_cgroup.c | 18 +-- mm/swap_state.c | 32 +++-- mm/swapfile.c | 300 ++++++++++++++++++++++----------------- 11 files changed, 352 insertions(+), 206 deletions(-)
include/linux/mm_types.h +16 -0
@@ -279,6 +279,13 @@ static __always_inline unsigned long encoded_nr_pages(struct encoded_page *page) }/* +* Virtual swap slot. +* +* This type is used to represent a virtual swap slot, i.e an identifier of +* a swap entry. This is stored in PTEs that originally refer to the swapped +* out page, and is used to index into various swap architectures (swap cache, +* zswap tree, swap cgroup array, etc.). +* * A swap entry has to fit into a "unsigned long", as the entry is hidden * in the "index" field of the swapper address space. */
@@ -286,6 +293,15 @@ typedef struct {unsigned long val; } swp_entry_t; +/* +* Physical swap slot. +* +* This type is used to represent a PAGE_SIZED slot on a swapfile. +*/ +typedef struct { +unsigned long val; +}swp_slot_t ; +/** * typedef softleaf_t - Describes a page table software leaf entry, abstracted * from its architecture-specific encoding.
include/linux/swap.h +38 -9
114 lines not on this page · raw message
include/linux/swapops.h +25 -0
@@ -360,5 +360,30 @@ static inline pmd_t swp_entry_to_pmd(swp_entry_t entry)#endif /* CONFIG_ARCH_ENABLE_THP_MIGRATION */ +/* Physical swap slots operations */ + +/* +* Store a swap device type + offset into a swp_slot_t handle. +*/ +static inline swp_slot_t swp_slot (unsigned long type,pgoff_t offset) +{ +swp_slot_t ret; + + ret.val = (type <<SWP_TYPE_SHIFT ) | (offset &SWP_OFFSET_MASK ); +return ret; +} + +/* Extract the `type' field from a swp_slot_t. */ +static inline unsigned swp_slot_type (swp_slot_t slot) +{ +return (slot.val >>SWP_TYPE_SHIFT ); +} + +/* Extract the `offset' field from a swp_slot_t. */ +static inline pgoff_t swp_slot_offset (swp_slot_t slot) +{ +return slot.val &SWP_OFFSET_MASK ; +} +#endif /* CONFIG_MMU */ #endif /* _LINUX_SWAPOPS_H */
kernel/power/swap.c +3 -3
@@ -174,10 +174,10 @@ sector_t alloc_swapdev_block(int swap)* Allocate a swap page and register that it has been allocated, so that * it can be freed in case of an error. */ - offset =swp_offset (get_swap_page_of_type (swap)); + offset =swp_slot_offset (swap_slot_alloc_of_type (swap));if (offset) {if (swsusp_extents_insert (offset)) -swap_free (swp_entry (swap, offset)); +swap_slot_free_nr (swp_slot (swap, offset),1 );else return swapdev_block (swap, offset); }
@@ -197,7 +197,7 @@ void free_all_swap_pages(int swap) ext = rb_entry(node, struct swsusp_extent, node);rb_erase (node, &swsusp_extents); -swap_free_nr (swp_entry (swap, ext->start), +swap_slot_free_nr (swp_slot (swap, ext->start), ext->end - ext->start +1 );kfree (ext);
mm/internal.h +7 -3
@@ -334,9 +334,13 @@ unsigned int folio_pte_batch(struct folio *folio, pte_t *ptep, pte_t pte,*/ static inline pte_t pte_move_swp_offset (pte_t pte,long delta) { -const softleaf_t entry =softleaf_from_pte (pte); -pte_t new =__swp_entry_to_pte (__swp_entry (swp_type (entry), - (swp_offset (entry) + delta))); +softleaf_t entry =softleaf_from_pte (pte), new_entry; +swp_slot_t slot =swp_entry_to_swp_slot (entry); +pte_t new; + + new_entry =swp_slot_to_swp_entry (swp_slot (swp_slot_type (slot), +swp_slot_offset (slot) + delta)); + new =swp_entry_to_pte (new_entry);if (pte_swp_soft_dirty (pte)) new =pte_swp_mksoft_dirty (new);
mm/page_io.c +22 -11
@@ -204,14 +204,17 @@ static bool is_folio_zero_filled(struct folio *folio)static void swap_zeromap_folio_set (struct folio *folio) {struct obj_cgroup *objcg =get_obj_cgroup_from_folio (folio); -struct swap_info_struct *sis =__swap_entry_to_info (folio->swap); +struct swap_info_struct *sis = +__swap_slot_to_info (swp_entry_to_swp_slot (folio->swap));int nr_pages =folio_nr_pages (folio);swp_entry_t entry; +swp_slot_t slot;unsigned int i;for (i =0 ; i <folio_nr_pages (folio); i++) { entry =page_swap_entry (folio_page (folio, i)); -set_bit (swp_offset (entry), sis->zeromap); + slot =swp_entry_to_swp_slot (entry); +set_bit (swp_slot_offset (slot), sis->zeromap); }count_vm_events (SWPOUT_ZERO , nr_pages);
@@ -223,13 +226,16 @@ static void swap_zeromap_folio_set(struct folio *folio)static void swap_zeromap_folio_clear (struct folio *folio) { -struct swap_info_struct *sis =__swap_entry_to_info (folio->swap); +struct swap_info_struct *sis = +__swap_slot_to_info (swp_entry_to_swp_slot (folio->swap));swp_entry_t entry; +swp_slot_t slot;unsigned int i;for (i =0 ; i <folio_nr_pages (folio); i++) { entry =page_swap_entry (folio_page (folio, i)); -clear_bit (swp_offset (entry), sis->zeromap); + slot =swp_entry_to_swp_slot (entry); +clear_bit (swp_slot_offset (slot), sis->zeromap); } }
@@ -357,7 +363,8 @@ static void sio_write_complete(struct kiocb *iocb, long ret)* messages. */ pr_err_ratelimited ("Write error %ld on dio swapfile (%llu)\n" , - ret,swap_dev_pos (page_swap_entry (page))); + ret, +swap_slot_pos (swp_entry_to_swp_slot (page_swap_entry (page))));for (p =0 ; p < sio->pages; p++) { page = sio->bvec[p].bv_page;set_page_dirty (page);
@@ -374,9 +381,10 @@ static void sio_write_complete(struct kiocb *iocb, long ret)static void swap_writepage_fs (struct folio *folio,struct swap_iocb **swap_plug) {struct swap_iocb *sio = swap_plug ? *swap_plug :NULL ; -struct swap_info_struct *sis =__swap_entry_to_info (folio->swap); +swp_slot_t slot =swp_entry_to_swp_slot (folio->swap); +struct swap_info_struct *sis =__swap_slot_to_info (slot);struct file *swap_file = sis->swap_file; -loff_t pos =swap_dev_pos (folio->swap); +loff_t pos =swap_slot_pos (slot);count_swpout_vm_event (folio);folio_start_writeback (folio);
@@ -446,7 +454,8 @@ static void swap_writepage_bdev_async(struct folio *folio,void __swap_writepage (struct folio *folio,struct swap_iocb **swap_plug) { -struct swap_info_struct *sis =__swap_entry_to_info (folio->swap); +struct swap_info_struct *sis = +__swap_slot_to_info (swp_entry_to_swp_slot (folio->swap));VM_BUG_ON_FOLIO (!folio_test_swapcache (folio), folio);/*
@@ -537,9 +546,10 @@ static bool swap_read_folio_zeromap(struct folio *folio)static void swap_read_folio_fs (struct folio *folio,struct swap_iocb **plug) { -struct swap_info_struct *sis =__swap_entry_to_info (folio->swap); +swp_slot_t slot =swp_entry_to_swp_slot (folio->swap); +struct swap_info_struct *sis =__swap_slot_to_info (slot);struct swap_iocb *sio =NULL ; -loff_t pos =swap_dev_pos (folio->swap); +loff_t pos =swap_slot_pos (slot);if (plug) sio = *plug;
@@ -608,7 +618,8 @@ static void swap_read_folio_bdev_async(struct folio *folio,void swap_read_folio (struct folio *folio,struct swap_iocb **plug) { -struct swap_info_struct *sis =__swap_entry_to_info (folio->swap); +struct swap_info_struct *sis = +__swap_slot_to_info (swp_entry_to_swp_slot (folio->swap));bool synchronous = sis->flags &SWP_SYNCHRONOUS_IO ;bool workingset =folio_test_workingset (folio);unsigned long pflags;
mm/shmem.c +13 -6
@@ -1442,6 +1442,7 @@ static unsigned int shmem_find_swap_entries(struct address_space *mapping,XA_STATE (xas, &mapping->i_pages, start);struct folio *folio;swp_entry_t entry; +swp_slot_t slot;rcu_read_lock ();xas_for_each (&xas, folio,ULONG_MAX ) {
@@ -1452,11 +1453,13 @@ static unsigned int shmem_find_swap_entries(struct address_space *mapping,continue ; entry =radix_to_swp_entry (folio); + slot =swp_entry_to_swp_slot (entry); +/* * swapin error entries can be found in the mapping. But they're * deliberately ignored here as we've done everything we can do. */ -if (swp_type (entry) != type) +if (swp_slot_type (slot) != type)continue ; indices[folio_batch_count (fbatch)] = xas.xa_index;
@@ -2224,6 +2227,7 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,XA_STATE_ORDER (xas, &mapping->i_pages, index,0 );int split_order =0 ;int i; +swp_slot_t slot =swp_entry_to_swp_slot (swap);/* Convert user data gfp flags to xarray node gfp flags */ gfp &=GFP_RECLAIM_MASK ;
@@ -2264,13 +2268,16 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,*/ for (i =0 ; i <1 << cur_order; i += (1 << split_order)) { -swp_entry_t tmp; +swp_entry_t tmp_entry; +swp_slot_t tmp_slot; + + tmp_slot = +swp_slot (swp_slot_type (slot), +swp_slot_offset (slot) + swap_offset + i); + tmp_entry =swp_slot_to_swp_entry (tmp_slot); - tmp =swp_entry (swp_type (swap), -swp_offset (swap) + swap_offset + - i);__xa_store (&mapping->i_pages, aligned_index + i, -swp_to_radix_entry (tmp),0 ); +swp_to_radix_entry (tmp_entry),0 ); } cur_order = split_order; split_order =xas_try_split_min_order (split_order);
mm/swap.h +28 -24
132 lines not on this page · raw message
mm/swap_cgroup.c +10 -8
@@ -65,13 +65,14 @@ void swap_cgroup_record(struct folio *folio, unsigned short id, swp_entry_t ent) {unsigned int nr_ents =folio_nr_pages (folio); +swp_slot_t slot =swp_entry_to_swp_slot (ent);struct swap_cgroup *map;pgoff_t offset, end;unsigned short old; - offset =swp_offset (ent); + offset =swp_slot_offset (slot); end = offset + nr_ents; - map = swap_cgroup_ctrl[swp_type (ent)].map; + map = swap_cgroup_ctrl[swp_slot_type (slot)].map; do { old = __swap_cgroup_id_xchg(map, offset, id);
@@ -92,13 +93,13 @@ void swap_cgroup_record(struct folio *folio, unsigned short id,*/ unsigned short swap_cgroup_clear (swp_entry_t ent,unsigned int nr_ents) { -pgoff_t offset, end; +swp_slot_t slot =swp_entry_to_swp_slot (ent); +pgoff_t offset =swp_slot_offset (slot); +pgoff_t end = offset + nr_ents;struct swap_cgroup *map;unsigned short old, iter =0 ; - offset =swp_offset (ent); - end = offset + nr_ents; - map = swap_cgroup_ctrl[swp_type (ent)].map; + map = swap_cgroup_ctrl[swp_slot_type (slot)].map; do { old = __swap_cgroup_id_xchg(map, offset, 0);
@@ -119,12 +120,13 @@ unsigned short swap_cgroup_clear(swp_entry_t ent, unsigned int nr_ents)unsigned short lookup_swap_cgroup_id (swp_entry_t ent) {struct swap_cgroup_ctrl *ctrl; +swp_slot_t slot =swp_entry_to_swp_slot (ent);if (mem_cgroup_disabled ())return 0 ; - ctrl = &swap_cgroup_ctrl[swp_type (ent)]; -return __swap_cgroup_id_lookup (ctrl->map,swp_offset (ent)); + ctrl = &swap_cgroup_ctrl[swp_slot_type (slot)]; +return __swap_cgroup_id_lookup (ctrl->map,swp_slot_offset (slot)); }int swap_cgroup_swapon (int type,unsigned long max_pages)
mm/swap_state.c +19 -13
@@ -421,7 +421,8 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask, struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated, bool skip_if_exists) { - struct swap_info_struct *si = __swap_entry_to_info(entry); + struct swap_info_struct *si = +__swap_slot_to_info (swp_entry_to_swp_slot (entry));struct folio *folio;struct folio *new_folio =NULL ;struct folio *result =NULL ;
@@ -636,11 +637,12 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask, struct mempolicy *mpol, pgoff_t ilx) {struct folio *folio; -unsigned long entry_offset =swp_offset (entry); -unsigned long offset = entry_offset; +swp_slot_t slot =swp_entry_to_swp_slot (entry); +unsigned long slot_offset =swp_slot_offset (slot); +unsigned long offset = slot_offset;unsigned long start_offset, end_offset;unsigned long mask; -struct swap_info_struct *si =__swap_entry_to_info (entry); +struct swap_info_struct *si =__swap_slot_to_info (slot);struct blk_plug plug;struct swap_iocb *splug =NULL ;bool page_allocated;
@@ -661,13 +663,13 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,for (offset = start_offset; offset <= end_offset ; offset++) {/* Ok, do the async read-ahead now */ folio =__read_swap_cache_async ( -swp_entry (swp_type (entry), offset), +swp_slot_to_swp_entry (swp_slot (swp_slot_type (slot), offset)), gfp_mask, mpol, ilx, &page_allocated, false);if (!folio)continue ;if (page_allocated) {swap_read_folio (folio, &splug); -if (offset != entry_offset) { +if (offset != slot_offset) {folio_set_readahead (folio);count_vm_event (SWAP_RA ); }
@@ -779,16 +781,20 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,/* * Readahead entry may come from a device that we are not * holding a reference to, try to grab a reference, or skip. +* +* XXX: for now, always try to pin the swap entries in the +* readahead window to avoid the annoying conversion to physical +* swap slots. Once we move all swap metadata to virtual swap +* layer, we can simply compare the clusters of the target +* swap entry and the current swap entry, and pin the latter +* swap entry's cluster if it differ from the former's. */ -if (swp_type (entry) !=swp_type (targ_entry)) { - swapoff_locked =tryget_swap_entry (entry, &si); -if (!swapoff_locked) -continue ; - } + swapoff_locked =tryget_swap_entry (entry, &si); +if (!swapoff_locked) +continue ; folio =__read_swap_cache_async (entry, gfp_mask, mpol, ilx, &page_allocated, false); -if (swapoff_locked) -put_swap_entry (entry, si); +put_swap_entry (entry, si);if (!folio)continue ;if (page_allocated) {
mm/swapfile.c +171 -129
768 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 7/21 mm: create scaffolds for the new virtual swap implementation
In reply to Nhat PhamIn prepration for the implementation of swap virtualization, add new scaffolds for the new code: a new mm/vswap.c source file, which currently only holds the logic to set up the (for now, empty) vswap debugfs directory. Hook this up in the swap setup step in mm/swap_state.c, and set up vswap compilation in the Makefile.
Other than the debugfs directory, no behavioral change intended.
Finally, make Johannes a swap reviewer, given that he has contributed majorly to the developments of virtual swap.
--- MAINTAINERS | 2 ++ include/linux/swap.h | 3 +++ mm/Makefile | 2 +- mm/swap_state.c | 6 ++++++ mm/vswap.c | 35 +++++++++++++++++++++++++++++++++++ 5 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 mm/vswap.c
MAINTAINERS +2 -0
@@ -16728,6 +16728,7 @@ R: Kemeng Shi <[email protected]> R: Nhat Pham <[email protected]> R: Baoquan He <[email protected]> R: Barry Song <[email protected]> +R: Johannes Weiner <[email protected]> L: [email protected] S: Maintained F: include/linux/swap.h
@@ -16739,6 +16740,7 @@ F: mm/swap.h F: mm/swap_table.h F: mm/swap_state.c F: mm/swapfile.c +F: mm/vswap.c MEMORY MANAGEMENT - THP (TRANSPARENT HUGE PAGE) M: Andrew Morton <[email protected]>
include/linux/swap.h +3 -0
@@ -423,6 +423,9 @@ extern void __meminit kswapd_stop(int nid);#ifdef CONFIG_SWAP +/* Virtual swap space API (mm/vswap.c) */ +int vswap_init (void ); +/* Lifecycle swap API (mm/swapfile.c) */ int folio_alloc_swap (struct folio *folio);bool folio_free_swap (struct folio *folio);
mm/Makefile +1 -1
@@ -75,7 +75,7 @@ ifdef CONFIG_MMU obj-$(CONFIG_ADVISE_SYSCALLS) += madvise.o endif -obj-$(CONFIG_SWAP) += page_io.o swap_state.o swapfile.o +obj-$(CONFIG_SWAP) += page_io.o swap_state.o swapfile.o vswap.o obj-$(CONFIG_ZSWAP) += zswap.o obj-$(CONFIG_HAS_DMA) += dmapool.o obj-$(CONFIG_HUGETLBFS) += hugetlb.o hugetlb_sysfs.o hugetlb_sysctl.o
mm/swap_state.c +6 -0
@@ -882,6 +882,12 @@ static int __init swap_init(void)int err;struct kobject *swap_kobj; + err =vswap_init (); +if (err) { +pr_err ("failed to initialize virtual swap space\n" ); +return err; + } + swap_kobj =kobject_create_and_add ("swap" , mm_kobj);if (!swap_kobj) {pr_err ("failed to create swap kobject\n" );
mm/vswap.c new file +35 -0
@@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Virtual swap space +* +* Copyright (C) 2024 Meta Platforms, Inc., Nhat Pham +*/ +#include <linux/swap.h> + +#ifdef CONFIG_DEBUG_FS +#include <linux/debugfs.h> + +static struct dentry *vswap_debugfs_root; + +static int vswap_debug_fs_init (void ) +{ +if (!debugfs_initialized ()) +return -ENODEV ; + + vswap_debugfs_root =debugfs_create_dir ("vswap" ,NULL ); +return 0 ; +} +#else +static int vswap_debug_fs_init (void ) +{ +return 0 ; +} +#endif + +int vswap_init (void ) +{ +if (vswap_debug_fs_init ()) +pr_warn ("Failed to initialize vswap debugfs\n" ); + +return 0 ; +}
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 8/21 zswap: prepare zswap for swap virtualization
In reply to Nhat PhamThe zswap tree code, specifically the range partition logic, can no longer easily be reused for the new virtual swap space design. Use a simple unified zswap tree in the new implementation for now.
--- include/linux/zswap.h | 7 ----- mm/swapfile.c | 9 +----- mm/zswap.c | 69 +++++++------------------------------------ 3 files changed, 11 insertions(+), 74 deletions(-)
include/linux/zswap.h +0 -7
@@ -28,8 +28,6 @@ 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); -int zswap_swapon (int type,unsigned long nr_pages); -void zswap_swapoff (int type);void zswap_memcg_offline_cleanup (struct mem_cgroup *memcg);void zswap_lruvec_state_init (struct lruvec *lruvec);void zswap_folio_swapin (struct folio *folio);
@@ -50,11 +48,6 @@ static inline int zswap_load(struct folio *folio) }static inline void zswap_invalidate (swp_entry_t swp) {} -static inline int zswap_swapon (int type,unsigned long nr_pages) -{ -return 0 ; -} -static inline void zswap_swapoff (int type) {}static inline void zswap_memcg_offline_cleanup (struct mem_cgroup *memcg) {}static inline void zswap_lruvec_state_init (struct lruvec *lruvec) {}static inline void zswap_folio_swapin (struct folio *folio) {}
mm/swapfile.c +1 -8
@@ -2972,7 +2972,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)spin_unlock (&p->lock);spin_unlock (&swap_lock);arch_swap_invalidate_area (p->type); -zswap_swapoff (p->type);mutex_unlock (&swapon_mutex);kfree (p->global_cluster); p->global_cluster =NULL ;
@@ -3615,10 +3614,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) } } - error =zswap_swapon (si->type, maxpages); -if (error) - goto bad_swap_unlock_inode; -/* * Flush any pending IO and dirty mappings before we start using this * swap device.
@@ -3627,7 +3622,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) error =inode_drain_writes (inode);if (error) { inode->i_flags &= ~S_SWAPFILE ; - goto free_swap_zswap; + goto bad_swap_unlock_inode; }mutex_lock (&swapon_mutex);
@@ -3650,8 +3645,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) error =0 ; goto out; -free_swap_zswap: -zswap_swapoff (si->type); bad_swap_unlock_inode:inode_unlock (inode); bad_swap:
mm/zswap.c +10 -59
106 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 9/21 mm: swap: allocate a virtual swap slot for each swapped out page
In reply to Nhat PhamFor the new virtual swap space design, dynamically allocate a virtual slot (as well as an associated metadata structure) for each swapped out page, and associate it to the (physical) swap slot on the swapfile/swap partition. This virtual swap slot is now stored in page table entries and used to index into swap data structures (swap cache, zswap tree, swap cgroup array), in place of the old physical swap slot.
For now, there is always a physical slot in the swapfile associated for each virtual swap slot (except those about to be freed). The virtual swap slot's lifetime is still tied to the lifetime of its physical swap slot. We do change the freeing ordering a bit - we clear the shadow, invalidate the zswap entry, and uncharge swap cgroup when we release the virtual swap slot, as we now use virtual swap slot to index into these swap data structures.
We also repurpose the swap table infrastructure as a reverse map to look up the virtual swap slot from its associated physical swap slot on swapfile. This is used in cluster readahead, as well as several swapfile operations, such as the swap slot reclamation that happens when the swapfile is almost full. It will also be used in a future patch that simplifies swapoff.
--- include/linux/cpuhotplug.h | 1 + include/linux/swap.h | 72 ++-- mm/internal.h | 28 +- mm/page_io.c | 6 +- mm/shmem.c | 9 +- mm/swap.h | 8 +- mm/swap_state.c | 5 +- mm/swapfile.c | 64 +--- mm/vswap.c | 659 +++++++++++++++++++++++++++++++++++++ 9 files changed, 735 insertions(+), 117 deletions(-)
include/linux/cpuhotplug.h +1 -0
@@ -86,6 +86,7 @@ enum cpuhp_state {CPUHP_FS_BUFF_DEAD ,CPUHP_PRINTK_DEAD ,CPUHP_MM_MEMCQ_DEAD , +CPUHP_MM_VSWAP_DEAD ,CPUHP_PERCPU_CNT_DEAD ,CPUHP_RADIX_DEAD , CPUHP_PAGE_ALLOC,
include/linux/swap.h +30 -42
95 lines not on this page · raw message
mm/internal.h +21 -7
@@ -322,6 +322,25 @@ static inline unsigned int folio_pte_batch_flags(struct folio *folio,unsigned int folio_pte_batch (struct folio *folio,pte_t *ptep,pte_t pte,unsigned int max_nr); +static inline swp_entry_t swap_nth (swp_entry_t entry,long n) +{ +return (swp_entry_t ) { entry.val + n }; +} + +/* similar to swap_nth, but check the backing physical slots as well. */ +static inline swp_entry_t swap_move (swp_entry_t entry,long delta) +{ +swp_slot_t slot =swp_entry_to_swp_slot (entry), next_slot; +swp_entry_t next_entry =swap_nth (entry, delta); + + next_slot =swp_entry_to_swp_slot (next_entry); +if (swp_slot_type (slot) !=swp_slot_type (next_slot) || +swp_slot_offset (slot) + delta !=swp_slot_offset (next_slot)) + next_entry.val =0 ; + +return next_entry; +} +/** * pte_move_swp_offset - Move the swap entry offset field of a swap pte * forward or backward by delta
@@ -334,13 +353,8 @@ unsigned int folio_pte_batch(struct folio *folio, pte_t *ptep, pte_t pte,*/ static inline pte_t pte_move_swp_offset (pte_t pte,long delta) { -softleaf_t entry =softleaf_from_pte (pte), new_entry; -swp_slot_t slot =swp_entry_to_swp_slot (entry); -pte_t new; - - new_entry =swp_slot_to_swp_entry (swp_slot (swp_slot_type (slot), -swp_slot_offset (slot) + delta)); - new =swp_entry_to_pte (new_entry); +softleaf_t entry =softleaf_from_pte (pte); +pte_t new =swp_entry_to_pte (swap_move (entry, delta));if (pte_swp_soft_dirty (pte)) new =pte_swp_mksoft_dirty (new);
mm/page_io.c +3 -3
@@ -364,7 +364,7 @@ static void sio_write_complete(struct kiocb *iocb, long ret)*/ pr_err_ratelimited ("Write error %ld on dio swapfile (%llu)\n" , ret, -swap_slot_pos (swp_entry_to_swp_slot (page_swap_entry (page)))); +swap_slot_dev_pos (swp_entry_to_swp_slot (page_swap_entry (page))));for (p =0 ; p < sio->pages; p++) { page = sio->bvec[p].bv_page;set_page_dirty (page);
@@ -384,7 +384,7 @@ static void swap_writepage_fs(struct folio *folio, struct swap_iocb **swap_plug)swp_slot_t slot =swp_entry_to_swp_slot (folio->swap);struct swap_info_struct *sis =__swap_slot_to_info (slot);struct file *swap_file = sis->swap_file; -loff_t pos =swap_slot_pos (slot); +loff_t pos =swap_slot_dev_pos (slot);count_swpout_vm_event (folio);folio_start_writeback (folio);
@@ -549,7 +549,7 @@ static void swap_read_folio_fs(struct folio *folio, struct swap_iocb **plug)swp_slot_t slot =swp_entry_to_swp_slot (folio->swap);struct swap_info_struct *sis =__swap_slot_to_info (slot);struct swap_iocb *sio =NULL ; -loff_t pos =swap_slot_pos (slot); +loff_t pos =swap_slot_dev_pos (slot);if (plug) sio = *plug;
mm/shmem.c +1 -8
@@ -2227,7 +2227,6 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,XA_STATE_ORDER (xas, &mapping->i_pages, index,0 );int split_order =0 ;int i; -swp_slot_t slot =swp_entry_to_swp_slot (swap);/* Convert user data gfp flags to xarray node gfp flags */ gfp &=GFP_RECLAIM_MASK ;
@@ -2268,13 +2267,7 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,*/ for (i =0 ; i <1 << cur_order; i += (1 << split_order)) { -swp_entry_t tmp_entry; -swp_slot_t tmp_slot; - - tmp_slot = -swp_slot (swp_slot_type (slot), -swp_slot_offset (slot) + swap_offset + i); - tmp_entry =swp_slot_to_swp_entry (tmp_slot); +swp_entry_t tmp_entry =swap_nth (swap, swap_offset + i);__xa_store (&mapping->i_pages, aligned_index + i,swp_to_radix_entry (tmp_entry),0 );
mm/swap.h +6 -2
@@ -36,7 +36,11 @@ struct swap_cluster_info {u16 count;u8 flags;u8 order; -atomic_long_t __rcu *table;/* Swap table entries, see mm/swap_table.h */ +/* +* Reverse map, to look up the virtual swap slot backed by a given physical +* swap slot. +*/ +atomic_long_t __rcu *table;struct list_head list; };
@@ -212,7 +216,7 @@ static inline struct address_space *swap_address_space(swp_entry_t entry) }/* Return the swap device position of the swap slot. */ -static inline loff_t swap_slot_pos (swp_slot_t slot) +static inline loff_t swap_slot_dev_pos (swp_slot_t slot) {return ((loff_t )swp_slot_offset (slot)) <<PAGE_SHIFT ; }
mm/swap_state.c +4 -1
@@ -891,7 +891,8 @@ static int __init swap_init(void) swap_kobj =kobject_create_and_add ("swap" , mm_kobj);if (!swap_kobj) {pr_err ("failed to create swap kobject\n" ); -return -ENOMEM ; + err = -ENOMEM ; + goto vswap_exit; } err =sysfs_create_group (swap_kobj, &swap_attr_group);if (err) {
@@ -904,6 +905,8 @@ static int __init swap_init(void) delete_obj:kobject_put (swap_kobj); +vswap_exit: +vswap_exit ();return err; }subsys_initcall (swap_init);
mm/swapfile.c +10 -54
110 lines not on this page · raw message
mm/vswap.c +659 -0
682 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 10/21 swap: move swap cache to virtual swap descriptor
In reply to Nhat PhamMove the swap cache (and workingset shadow for anonymous pages) to the virtual swap descriptor. This effectively range-partitions the swap cache by virtual swap clusters (of PMD sized), eliminate swap cache lock contention.
--- mm/huge_memory.c | 4 +- mm/migrate.c | 6 +- mm/shmem.c | 4 +- mm/swap.h | 28 ++-- mm/swap_state.c | 251 +-------------------------------- mm/vmscan.c | 6 +- mm/vswap.c | 352 ++++++++++++++++++++++++++++++++++++++++++++++- 7 files changed, 370 insertions(+), 281 deletions(-)
mm/huge_memory.c +2 -2
@@ -3825,7 +3825,7 @@ static int __folio_freeze_and_split_unmapped(struct folio *folio, unsigned int nreturn -EINVAL ; } -swap_cache_lock (); +swap_cache_lock (folio->swap); }/* lock lru list/PageCompound, ref frozen by page_ref_freeze */
@@ -3901,7 +3901,7 @@ static int __folio_freeze_and_split_unmapped(struct folio *folio, unsigned int nunlock_page_lruvec (lruvec);if (folio_test_swapcache (folio)) -swap_cache_unlock (); +swap_cache_unlock (folio->swap); }else {split_queue_unlock (ds_queue);return -EAGAIN ;
mm/migrate.c +3 -3
@@ -600,13 +600,13 @@ static int __folio_migrate_mapping(struct address_space *mapping, newzone =folio_zone (newfolio);if (folio_test_swapcache (folio)) -swap_cache_lock_irq (); +swap_cache_lock_irq (folio->swap);else xas_lock_irq (&xas);if (!folio_ref_freeze (folio, expected_count)) {if (folio_test_swapcache (folio)) -swap_cache_unlock_irq (); +swap_cache_unlock_irq (folio->swap);else xas_unlock_irq (&xas);return -EAGAIN ;
@@ -652,7 +652,7 @@ static int __folio_migrate_mapping(struct address_space *mapping,/* Leave irq disabled to prevent preemption while updating stats */ if (folio_test_swapcache (folio)) -swap_cache_unlock (); +swap_cache_unlock (folio->swap);else xas_unlock (&xas);
mm/shmem.c +2 -2
@@ -2168,12 +2168,12 @@ static int shmem_replace_folio(struct folio **foliop, gfp_t gfp, new->swap = entry;folio_set_swapcache (new); -swap_cache_lock_irq (); +swap_cache_lock_irq (entry);__swap_cache_replace_folio (old, new);mem_cgroup_replace_folio (old, new);shmem_update_stats (new, nr_pages);shmem_update_stats (old, -nr_pages); -swap_cache_unlock_irq (); +swap_cache_unlock_irq (entry);folio_add_lru (new); *foliop = new;
mm/swap.h +14 -14
@@ -205,10 +205,12 @@ void __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug);/* linux/mm/swap_state.c */ extern struct address_space swap_space__read_mostly ; -void swap_cache_lock_irq (void ); -void swap_cache_unlock_irq (void ); -void swap_cache_lock (void ); -void swap_cache_unlock (void ); + +/* linux/mm/vswap.c */ +void swap_cache_lock_irq (swp_entry_t entry); +void swap_cache_unlock_irq (swp_entry_t entry); +void swap_cache_lock (swp_entry_t entry); +void swap_cache_unlock (swp_entry_t entry);static inline struct address_space *swap_address_space (swp_entry_t entry) {
@@ -256,13 +258,12 @@ static inline bool folio_matches_swap_entry(const struct folio *folio,*/ struct folio *swap_cache_get_folio (swp_entry_t entry);void *swap_cache_get_shadow (swp_entry_t entry); -int swap_cache_add_folio (struct folio *folio,swp_entry_t entry, -gfp_t gfp,void **shadow); +void swap_cache_add_folio (struct folio *folio,swp_entry_t entry, +void **shadow);void swap_cache_del_folio (struct folio *folio);/* Below helpers require the caller to lock the swap cache. */ void __swap_cache_del_folio (struct folio *folio,swp_entry_t entry,void *shadow);void __swap_cache_replace_folio (struct folio *old,struct folio *new); -void swap_cache_clear_shadow (swp_entry_t entry,int nr_ents);void show_swap_cache_info (void );void swapcache_clear (struct swap_info_struct *si,swp_entry_t entry,int nr);
@@ -423,10 +424,9 @@ static inline void *swap_cache_get_shadow(swp_entry_t entry)return NULL ; } -static inline int swap_cache_add_folio (struct folio *folio,swp_entry_t entry, -gfp_t gfp,void **shadow) +static inline void swap_cache_add_folio (struct folio *folio,swp_entry_t entry, +void **shadow) { -return 0 ; }static inline void swap_cache_del_folio (struct folio *folio)
@@ -441,19 +441,19 @@ static inline void __swap_cache_replace_folio(struct folio *old, struct folio *n { } -static inline void swap_cache_lock_irq (void ) +static inline void swap_cache_lock_irq (swp_entry_t entry) { } -static inline void swap_cache_unlock_irq (void ) +static inline void swap_cache_unlock_irq (swp_entry_t entry) { } -static inline void swap_cache_lock (void ) +static inline void swap_cache_lock (swp_entry_t entry) { } -static inline void swap_cache_unlock (void ) +static inline void swap_cache_unlock (swp_entry_t entry) { }
mm/swap_state.c +1 -250
269 lines not on this page · raw message
mm/vmscan.c +3 -3
@@ -712,7 +712,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,BUG_ON (mapping !=folio_mapping (folio));if (folio_test_swapcache (folio)) { -swap_cache_lock_irq (); +swap_cache_lock_irq (folio->swap); }else {spin_lock (&mapping->host->i_lock);xa_lock_irq (&mapping->i_pages);
@@ -759,7 +759,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio, shadow =workingset_eviction (folio, target_memcg);__swap_cache_del_folio (folio, swap, shadow);memcg1_swapout (folio, swap); -swap_cache_unlock_irq (); +swap_cache_unlock_irq (swap);put_swap_folio (folio, swap); }else {void (*free_folio)(struct folio *);
@@ -798,7 +798,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio, cannot_free:if (folio_test_swapcache (folio)) { -swap_cache_unlock_irq (); +swap_cache_unlock_irq (folio->swap); }else {xa_unlock_irq (&mapping->i_pages);spin_unlock (&mapping->host->i_lock);
mm/vswap.c +345 -7
397 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 11/21 zswap: move zswap entry management to the virtual swap descriptor
In reply to Nhat PhamRemove the zswap tree and manage zswap entries directly through the virtual swap descriptor. This re-partitions the zswap pool (by virtual swap cluster), which eliminates zswap tree lock contention.
--- include/linux/zswap.h | 6 +++ mm/vswap.c | 100 ++++++++++++++++++++++++++++++++++++++++++ mm/zswap.c | 40 ----------------- 3 files changed, 106 insertions(+), 40 deletions(-)
include/linux/zswap.h +6 -0
@@ -6,6 +6,7 @@#include <linux/mm_types.h> struct lruvec ; +struct zswap_entry ;extern atomic_long_t zswap_stored_pages;
@@ -33,6 +34,11 @@ void zswap_lruvec_state_init(struct lruvec *lruvec);void zswap_folio_swapin (struct folio *folio);bool zswap_is_enabled (void );bool zswap_never_enabled (void ); +void *zswap_entry_store (swp_entry_t swpentry,struct zswap_entry *entry); +void *zswap_entry_load (swp_entry_t swpentry); +void *zswap_entry_erase (swp_entry_t swpentry); +bool zswap_empty (swp_entry_t swpentry); +#else struct zswap_lruvec_state {};
mm/vswap.c +100 -0
129 lines not on this page · raw message
mm/zswap.c +0 -40
@@ -223,37 +223,6 @@ static bool zswap_has_pool;* helpers and fwd declarations **********************************/ -static DEFINE_XARRAY (zswap_tree); - -#define zswap_tree_index (entry) (entry.val) - -static inline void *zswap_entry_store (swp_entry_t swpentry, -struct zswap_entry *entry) -{ -pgoff_t offset =zswap_tree_index (swpentry); - -return xa_store (&zswap_tree, offset, entry,GFP_KERNEL ); -} - -static inline void *zswap_entry_load (swp_entry_t swpentry) -{ -pgoff_t offset =zswap_tree_index (swpentry); - -return xa_load (&zswap_tree, offset); -} - -static inline void *zswap_entry_erase (swp_entry_t swpentry) -{ -pgoff_t offset =zswap_tree_index (swpentry); - -return xa_erase (&zswap_tree, offset); -} - -static inline bool zswap_empty (swp_entry_t swpentry) -{ -return xa_empty (&zswap_tree); -} -#define zswap_pool_debug (msg, p) \ pr_debug("%s pool %s\n", msg, (p)->tfm_name)
@@ -1445,13 +1414,6 @@ static bool zswap_store_page(struct page *page, goto compress_failed; old =zswap_entry_store (page_swpentry, entry); -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; - }/* * We may have had an existing entry that became stale when
@@ -1498,8 +1460,6 @@ static bool zswap_store_page(struct page *page,return true; -store_failed: -zs_free (pool->zs_pool, entry->handle); compress_failed:zswap_entry_cache_free (entry);return false;
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 12/21 swap: implement the swap_cgroup API using virtual swap
In reply to Nhat PhamOnce we decouple a swap entry from its backing store via the virtual swap, we can no longer statically allocate an array to store the swap entries' cgroup information. Move it to the swap descriptor.
Note that the memory overhead for swap cgroup information is now on demand, i.e dynamically incurred when the virtual swap cluster is allocated. This help reduces the memory overhead in a huge but sparsely used swap space.
For instance, a 2 TB swapfile consists of 2147483648 swap slots, each incurring 2 bytes of overhead for swap cgroup, for a total of 1 GB. If we only utilize 10% of the swapfile, we will save 900 MB.
--- include/linux/swap_cgroup.h | 17 ++-- mm/Makefile | 3 - mm/memcontrol-v1.c | 2 +- mm/swap_cgroup.c | 174 ------------------------------------ mm/swapfile.c | 7 -- mm/vswap.c | 142 +++++++++++++++++++++++++++++ 6 files changed, 148 insertions(+), 197 deletions(-) delete mode 100644 mm/swap_cgroup.c
include/linux/swap_cgroup.h +5 -12
@@ -7,10 +7,9 @@#if defined(CONFIG_MEMCG ) && defined(CONFIG_SWAP )extern void swap_cgroup_record (struct folio *folio,unsigned short id,swp_entry_t ent); +extern void __swap_cgroup_record (struct folio *folio,unsigned short id,swp_entry_t ent);extern unsigned short swap_cgroup_clear (swp_entry_t ent,unsigned int nr_ents);extern unsigned short lookup_swap_cgroup_id (swp_entry_t ent); -extern int swap_cgroup_swapon (int type,unsigned long max_pages); -extern void swap_cgroup_swapoff (int type);#else
@@ -20,28 +19,22 @@ void swap_cgroup_record(struct folio *folio, unsigned short id, swp_entry_t ent) }static inline -unsigned short swap_cgroup_clear (swp_entry_t ent,unsigned int nr_ents) +void __swap_cgroup_record (struct folio *folio,unsigned short id,swp_entry_t ent) { -return 0 ; }static inline -unsigned short lookup_swap_cgroup_id (swp_entry_t ent) +unsigned short swap_cgroup_clear (swp_entry_t ent,unsigned int nr_ents) {return 0 ; } -static inline int -swap_cgroup_swapon (int type,unsigned long max_pages) +static inline +unsigned short lookup_swap_cgroup_id (swp_entry_t ent) {return 0 ; } -static inline void swap_cgroup_swapoff (int type) -{ -return ; -} -#endif #endif /* __LINUX_SWAP_CGROUP_H */
mm/Makefile +0 -3
@@ -103,9 +103,6 @@ obj-$(CONFIG_PAGE_COUNTER) += page_counter.o obj-$(CONFIG_LIVEUPDATE) += memfd_luo.o obj-$(CONFIG_MEMCG_V1) += memcontrol-v1.o obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o -ifdef CONFIG_SWAP -obj-$(CONFIG_MEMCG) += swap_cgroup.o -endif obj-$(CONFIG_CGROUP_HUGETLB) += hugetlb_cgroup.o obj-$(CONFIG_GUP_TEST) += gup_test.o obj-$(CONFIG_DMAPOOL_TEST) += dmapool_test.o
mm/memcontrol-v1.c +1 -1
@@ -620,7 +620,7 @@ void memcg1_swapout(struct folio *folio, swp_entry_t entry)mem_cgroup_id_get_many (swap_memcg, nr_entries -1 );mod_memcg_state (swap_memcg,MEMCG_SWAP , nr_entries); -swap_cgroup_record (folio,mem_cgroup_id (swap_memcg), entry); +__swap_cgroup_record (folio,mem_cgroup_id (swap_memcg), entry);folio_unqueue_deferred_split (folio); folio->memcg_data =0 ;
mm/swap_cgroup.c deleted +0 -174
174 lines not on this page · raw message
mm/swapfile.c +0 -7
@@ -2934,8 +2934,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)vfree (swap_map);kvfree (zeromap);free_cluster_info (cluster_info, maxpages); -/* Destroy swap account information */ -swap_cgroup_swapoff (p->type); inode = mapping->host;
@@ -3500,10 +3498,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) goto bad_swap_unlock_inode; } - error =swap_cgroup_swapon (si->type, maxpages); -if (error) - goto bad_swap_unlock_inode; - error =setup_swap_map (si, swap_header, swap_map, maxpages);if (error) goto bad_swap_unlock_inode;
@@ -3608,7 +3602,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) si->global_cluster =NULL ; inode =NULL ;destroy_swap_extents (si); -swap_cgroup_swapoff (si->type);spin_lock (&swap_lock); si->swap_file =NULL ; si->flags =0 ;
mm/vswap.c +142 -0
166 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 13/21 swap: manage swap entry lifecycle at the virtual swap layer
In reply to Nhat PhamThis patch moves the swap entry lifecycle management to the virtual swap layer by adding to the swap descriptor two fields:
1. in_swapcache, i.e whether the swap entry is in swap cache (or about to be added).
2. The swap count of the swap entry, which counts the number of page table entries at which the swap entry is inserted.
and re-implementing all of the swap entry lifecycle API (swap_duplicate(), swap_free_nr(), swapcache_prepare(), etc.) in the virtual swap layer.
For now, we do not implement swap count continuation - the swap_count field in the swap descriptor is big enough to hold the maximum number of swap counts. This vastly simplifies the logic.
--- include/linux/swap.h | 30 +- include/linux/zswap.h | 5 +- mm/memory.c | 8 +- mm/shmem.c | 4 +- mm/swap.h | 58 ++-- mm/swap_state.c | 4 +- mm/swapfile.c | 786 ++---------------------------------------- mm/vswap.c | 452 ++++++++++++++++++++++-- mm/zswap.c | 14 +- 9 files changed, 503 insertions(+), 858 deletions(-)
include/linux/swap.h +9 -21
@@ -223,17 +223,9 @@ enum {#define SWAP_CLUSTER_MAX_SKIPPED (SWAP_CLUSTER_MAX << 10)#define COMPACT_CLUSTER_MAX SWAP_CLUSTER_MAX -/* Bit flag in swap_map */ -#define SWAP_HAS_CACHE 0x40/* Flag page is cached, in first swap_map */ -#define COUNT_CONTINUED 0x80/* Flag swap_map continuation for full count */ - -/* Special value in first swap_map */ -#define SWAP_MAP_MAX 0x3e/* Max count */ -#define SWAP_MAP_BAD 0x3f/* Note page is bad */ -#define SWAP_MAP_SHMEM 0xbf/* Owned by shmem/tmpfs */ - -/* Special value in each swap_map continuation */ -#define SWAP_CONT_MAX 0x7f/* Max count */ +/* Swapfile's swap map state*/ +#define SWAP_MAP_ALLOCATED 0x01/* Page is allocated */ +#define SWAP_MAP_BAD 0x02/* Page is bad */ /* * The first page in the swap file is the swap header, which is always marked
@@ -426,13 +418,13 @@ extern void __meminit kswapd_stop(int nid);/* Virtual swap space API (mm/vswap.c) */ int vswap_init (void );void vswap_exit (void ); -void vswap_free (swp_entry_t entry,struct swap_cluster_info *ci);swp_slot_t swp_entry_to_swp_slot (swp_entry_t entry);swp_entry_t swp_slot_to_swp_entry (swp_slot_t slot);bool tryget_swap_entry (swp_entry_t entry,struct swap_info_struct **si);void put_swap_entry (swp_entry_t entry,struct swap_info_struct *si); -/* Lifecycle swap API (mm/swapfile.c) */ + +/* Lifecycle swap API (mm/swapfile.c and mm/vswap.c) */ int folio_alloc_swap (struct folio *folio);bool folio_free_swap (struct folio *folio);void put_swap_folio (struct folio *folio,swp_entry_t entry);
@@ -442,9 +434,10 @@ int swapcache_prepare(swp_entry_t entry, int nr);void swap_free_nr (swp_entry_t entry,int nr_pages);void free_swap_and_cache_nr (swp_entry_t entry,int nr);int __swap_count (swp_entry_t entry); -bool swap_entry_swapped (struct swap_info_struct *si,swp_entry_t entry); +bool swap_entry_swapped (swp_entry_t entry);int swp_swapcount (swp_entry_t entry);bool is_swap_cached (swp_entry_t entry); +bool folio_swapped (struct folio *folio);/* Swap cache API (mm/swap_state.c) */ static inline unsigned long total_swapcache_pages (void )
@@ -452,6 +445,7 @@ static inline unsigned long total_swapcache_pages(void)return global_node_page_state (NR_SWAPCACHE ); } +bool vswap_only_has_cache (swp_entry_t entry,int nr);void free_folio_and_swap_cache (struct folio *folio);void free_pages_and_swap_cache (struct encoded_page **,int );void free_swap_cache (struct folio *folio);
@@ -482,7 +476,6 @@ static inline long get_nr_swap_pages(void)void si_swapinfo (struct sysinfo *);int swap_slot_alloc (swp_slot_t *slot,unsigned int order);swp_slot_t swap_slot_alloc_of_type (int ); -int add_swap_count_continuation (swp_entry_t ,gfp_t );int swap_type_of (dev_t device,sector_t offset);int find_first_swap (dev_t *device);unsigned int count_swap_pages (int ,int );
@@ -549,11 +542,6 @@ static inline void free_swap_cache(struct folio *folio) { } -static inline int add_swap_count_continuation (swp_entry_t swp,gfp_t gfp_mask) -{ -return 0 ; -} -static inline void swap_shmem_alloc (swp_entry_t swp,int nr) { }
@@ -581,7 +569,7 @@ static inline int __swap_count(swp_entry_t entry)return 0 ; } -static inline bool swap_entry_swapped (struct swap_info_struct *si,swp_entry_t entry) +static inline bool swap_entry_swapped (swp_entry_t entry) {return false; }
include/linux/zswap.h +3 -2
@@ -28,7 +28,6 @@ struct zswap_lruvec_state {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_memcg_offline_cleanup (struct mem_cgroup *memcg);void zswap_lruvec_state_init (struct lruvec *lruvec);void zswap_folio_swapin (struct folio *folio);
@@ -38,6 +37,7 @@ void *zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry);void *zswap_entry_load (swp_entry_t swpentry);void *zswap_entry_erase (swp_entry_t swpentry);bool zswap_empty (swp_entry_t swpentry); +void zswap_entry_free (struct zswap_entry *entry);#else
@@ -53,7 +53,6 @@ static inline int zswap_load(struct folio *folio)return -ENOENT ; } -static inline void zswap_invalidate (swp_entry_t swp) {}static inline void zswap_memcg_offline_cleanup (struct mem_cgroup *memcg) {}static inline void zswap_lruvec_state_init (struct lruvec *lruvec) {}static inline void zswap_folio_swapin (struct folio *folio) {}
@@ -68,6 +67,8 @@ static inline bool zswap_never_enabled(void)return true; } +static inline void zswap_entry_free (struct zswap_entry *entry) {} +#endif #endif /* _LINUX_ZSWAP_H */
mm/memory.c +2 -6
@@ -1333,10 +1333,6 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,if (ret == -EIO ) {VM_WARN_ON_ONCE (!entry.val); -if (add_swap_count_continuation (entry,GFP_KERNEL ) <0 ) { - ret = -ENOMEM ; - goto out; - } entry.val =0 ; }else if (ret == -EBUSY ||unlikely (ret == -EHWPOISON )) { goto out;
@@ -5044,7 +5040,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) out:/* Clear the swap cache pin for direct swapin after PTL unlock */ if (need_clear_cache) { -swapcache_clear (si, entry, nr_pages); +swapcache_clear (entry, nr_pages);if (waitqueue_active (&swapcache_wq))wake_up (&swapcache_wq); }
@@ -5063,7 +5059,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)folio_put (swapcache); }if (need_clear_cache) { -swapcache_clear (si, entry, nr_pages); +swapcache_clear (entry, nr_pages);if (waitqueue_active (&swapcache_wq))wake_up (&swapcache_wq); }
mm/shmem.c +2 -2
@@ -2442,7 +2442,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,if (skip_swapcache) { folio->swap.val =0 ; -swapcache_clear (si, swap, nr_pages); +swapcache_clear (swap, nr_pages); }else {swap_cache_del_folio (folio); }
@@ -2463,7 +2463,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,folio_unlock (folio); failed_nolock:if (skip_swapcache) -swapcache_clear (si, folio->swap,folio_nr_pages (folio)); +swapcache_clear (folio->swap,folio_nr_pages (folio));if (folio)folio_put (folio);put_swap_entry (swap, si);
mm/swap.h +37 -21
94 lines not on this page · raw message
mm/swap_state.c +1 -3
@@ -174,8 +174,6 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask, struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated, bool skip_if_exists) { - struct swap_info_struct *si = -__swap_slot_to_info (swp_entry_to_swp_slot (entry)); struct folio *folio;struct folio *new_folio =NULL ;struct folio *result =NULL ;
@@ -196,7 +194,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,/* * Just skip read ahead for unused swap slot. */ -if (!swap_entry_swapped (si, entry)) +if (!swap_entry_swapped (entry)) goto put_and_return;/*
mm/swapfile.c +28 -758
939 lines not on this page · raw message
mm/vswap.c +420 -32
536 lines not on this page · raw message
mm/zswap.c +1 -13
@@ -703,7 +703,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);
@@ -1627,18 +1627,6 @@ int zswap_load(struct folio *folio)return 0 ; } -void zswap_invalidate (swp_entry_t swp) -{ -struct zswap_entry *entry; - -if (zswap_empty (swp)) -return ; - - entry =zswap_entry_erase (swp); -if (entry) -zswap_entry_free (entry); -} -/********************************* * debugfs functions **********************************/
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 14/21 mm: swap: decouple virtual swap slot from backing store
In reply to Nhat PhamThis patch presents the first real use case of the new virtual swap design. It leverages the virtualization of the swap space to decouple a swap entry and its backing storage. A swap entry can now be backed by one of the following options:
1. A physical swap slot (i.e on a physical swapfile/swap partition).
2. A "zero swap page", i.e the swapped out page is a zero page.
3. A compressed object in the zswap pool.
4. An in-memory page. This can happen when a page is loaded (exclusively) from the zswap pool, or if the page is rejected by zswap and zswap writeback is disabled.
This allows us to use zswap and the zero swap page optimization, without having to reserved a slot on a swapfile, or a swapfile at all. This translates to tens to hundreds of GBs of disk saving on hosts and workloads that have high memory usage, as well as removes this spurious limit on the usage of these optimizations.
One implication of this change is that we need to be much more careful with THP swapin and batched swap free operations. The central requirement is the range of entries we are working with must have no mixed backing states:
1. For now, zswap-backed entries are not supported for these batched operations.
2. All the entries must be backed by the same type.
3. If the swap entries in the batch are backed by in-memory folio, it must be the same folio (i.e they correspond to the subpages of that folio).
4. If the swap entries in the batch are backed by slots on swapfiles, it must be the same swapfile, and these physical swap slots must also be contiguous.
For now, we still charge virtual swap slots towards the memcg's swap usage. In a following patch, we will change this behavior and only charge physical (i.e on swapfile) swap slots towards the memcg's swap usage.
--- include/linux/swap.h | 31 ++- include/linux/zswap.h | 3 +- mm/internal.h | 30 +-- mm/madvise.c | 2 +- mm/memcontrol.c | 65 +++-- mm/memory.c | 92 +++++-- mm/page_io.c | 74 ++---- mm/shmem.c | 6 +- mm/swap.h | 32 +-- mm/swap_state.c | 29 ++- mm/swapfile.c | 8 - mm/vmscan.c | 19 +- mm/vswap.c | 562 +++++++++++++++++++++++++++++++++--------- mm/zswap.c | 45 ++-- 14 files changed, 679 insertions(+), 319 deletions(-)
include/linux/swap.h +30 -1
@@ -422,7 +422,13 @@ swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry);swp_entry_t swp_slot_to_swp_entry (swp_slot_t slot);bool tryget_swap_entry (swp_entry_t entry,struct swap_info_struct **si);void put_swap_entry (swp_entry_t entry,struct swap_info_struct *si); - +bool vswap_swapfile_backed (swp_entry_t entry,int nr); +bool vswap_folio_backed (swp_entry_t entry,int nr); +void vswap_store_folio (swp_entry_t entry,struct folio *folio); +void swap_zeromap_folio_set (struct folio *folio); +void vswap_assoc_zswap (swp_entry_t entry,struct zswap_entry *zswap_entry); +bool vswap_can_swapin_thp (swp_entry_t entry,int nr); +bool vswap_alloc_swap_slot (struct folio *folio);/* Lifecycle swap API (mm/swapfile.c and mm/vswap.c) */ int folio_alloc_swap (struct folio *folio);
@@ -482,6 +488,14 @@ unsigned int count_swap_pages(int, int);sector_t swapdev_block (int ,pgoff_t );struct backing_dev_info ;struct swap_info_struct *swap_slot_tryget_swap_info (swp_slot_t slot); + +static inline struct swap_info_struct *vswap_get_device (swp_entry_t entry) +{ +swp_slot_t slot =swp_entry_to_swp_slot (entry); + +return slot.val ?swap_slot_tryget_swap_info (slot) :NULL ; +} +sector_t swap_folio_sector (struct folio *folio);static inline void swap_slot_put_swap_info (struct swap_info_struct *si)
@@ -601,6 +615,21 @@ static inline int add_swap_extent(struct swap_info_struct *sis, return -EINVAL; } +static inline bool vswap_swapfile_backed (swp_entry_t entry,int nr) +{ +return false; +} + +static inline bool vswap_can_swapin_thp (swp_entry_t entry,int nr) +{ +return false; +} + +static inline struct swap_info_struct *vswap_get_device (swp_entry_t entry) +{ +return NULL ; +} +#endif /* CONFIG_SWAP */ static inline void free_swap_and_cache (swp_entry_t entry)
include/linux/zswap.h +1 -2
@@ -33,9 +33,8 @@ void zswap_lruvec_state_init(struct lruvec *lruvec);void zswap_folio_swapin (struct folio *folio);bool zswap_is_enabled (void );bool zswap_never_enabled (void ); -void *zswap_entry_store (swp_entry_t swpentry,struct zswap_entry *entry); +void zswap_entry_store (swp_entry_t swpentry,struct zswap_entry *entry);void *zswap_entry_load (swp_entry_t swpentry); -void *zswap_entry_erase (swp_entry_t swpentry);bool zswap_empty (swp_entry_t swpentry);void zswap_entry_free (struct zswap_entry *entry);
mm/internal.h +13 -17
@@ -327,20 +327,6 @@ static inline swp_entry_t swap_nth(swp_entry_t entry, long n)return (swp_entry_t ) { entry.val + n }; } -/* similar to swap_nth, but check the backing physical slots as well. */ -static inline swp_entry_t swap_move (swp_entry_t entry,long delta) -{ -swp_slot_t slot =swp_entry_to_swp_slot (entry), next_slot; -swp_entry_t next_entry =swap_nth (entry, delta); - - next_slot =swp_entry_to_swp_slot (next_entry); -if (swp_slot_type (slot) !=swp_slot_type (next_slot) || -swp_slot_offset (slot) + delta !=swp_slot_offset (next_slot)) - next_entry.val =0 ; - -return next_entry; -} -/** * pte_move_swp_offset - Move the swap entry offset field of a swap pte * forward or backward by delta
@@ -354,7 +340,7 @@ static inline swp_entry_t swap_move(swp_entry_t entry, long delta)static inline pte_t pte_move_swp_offset (pte_t pte,long delta) {softleaf_t entry =softleaf_from_pte (pte); -pte_t new =swp_entry_to_pte (swap_move (entry, delta)); +pte_t new =swp_entry_to_pte (swap_nth (entry, delta));if (pte_swp_soft_dirty (pte)) new =pte_swp_mksoft_dirty (new);
@@ -384,6 +370,7 @@ static inline pte_t pte_next_swp_offset(pte_t pte)* @start_ptep: Page table pointer for the first entry. * @max_nr: The maximum number of table entries to consider. * @pte: Page table entry for the first entry. +* @free_batch: Whether the batch will be passed to free_swap_and_cache_nr(). * * Detect a batch of contiguous swap entries: consecutive (non-present) PTEs * containing swap entries all with consecutive offsets and targeting the same
@@ -394,13 +381,15 @@ static inline pte_t pte_next_swp_offset(pte_t pte)* * Return: the number of table entries in the batch. */ -static inline int swap_pte_batch (pte_t *start_ptep,int max_nr,pte_t pte) +static inline int swap_pte_batch (pte_t *start_ptep,int max_nr,pte_t pte, +bool free_batch) {pte_t expected_pte =pte_next_swp_offset (pte);const pte_t *end_ptep = start_ptep + max_nr;const softleaf_t entry =softleaf_from_pte (pte);pte_t *ptep = start_ptep +1 ;unsigned short cgroup_id; +int nr;VM_WARN_ON (max_nr <1 );VM_WARN_ON (!softleaf_is_swap (entry));
@@ -420,7 +409,14 @@ static inline int swap_pte_batch(pte_t *start_ptep, int max_nr, pte_t pte) ptep++; } -return ptep - start_ptep; + nr = ptep - start_ptep; +/* +* free_swap_and_cache_nr can handle mixed backends, as long as virtual +* swap entries backing these PTEs are contiguous. +*/ +if (!free_batch && !vswap_can_swapin_thp (entry, nr)) +return 1 ; +return nr; }#endif /* CONFIG_MMU */
mm/madvise.c +1 -1
@@ -692,7 +692,7 @@ static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,if (softleaf_is_swap (entry)) { max_nr = (end - addr) /PAGE_SIZE ; - nr =swap_pte_batch (pte, max_nr, ptent); + nr =swap_pte_batch (pte, max_nr, ptent, true); nr_swap -= nr;free_swap_and_cache_nr (entry, nr);clear_not_present_full_ptes (mm, addr, pte, nr, tlb->fullmm);
mm/memcontrol.c +41 -24
97 lines not on this page · raw message
mm/memory.c +65 -27
171 lines not on this page · raw message
mm/page_io.c +21 -53
114 lines not on this page · raw message
mm/shmem.c +3 -3
@@ -1459,7 +1459,7 @@ static unsigned int shmem_find_swap_entries(struct address_space *mapping,* swapin error entries can be found in the mapping. But they're * deliberately ignored here as we've done everything we can do. */ -if (swp_slot_type (slot) != type) +if (!slot.val ||swp_slot_type (slot) != type)continue ; indices[folio_batch_count (fbatch)] = xas.xa_index;
@@ -1604,7 +1604,7 @@ int shmem_writeout(struct folio *folio, struct swap_iocb **plug,if ((info->flags &SHMEM_F_LOCKED ) || sbinfo->noswap) goto redirty; -if (!total_swap_pages) +if (!zswap_is_enabled () && !total_swap_pages) goto redirty;/*
@@ -2341,7 +2341,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,/* Look it up and read it in.. */ folio =swap_cache_get_folio (swap);if (!folio) { -if (data_race (si->flags &SWP_SYNCHRONOUS_IO )) { +if (si &&data_race (si->flags &SWP_SYNCHRONOUS_IO )) {/* Direct swapin skipping swap cache & readahead */ folio =shmem_swap_alloc_folio (inode, vma, index, index_entry, order, gfp);
mm/swap.h +6 -26
@@ -311,35 +311,15 @@ static inline unsigned int folio_swap_flags(struct folio *folio) {swp_slot_t swp_slot =swp_entry_to_swp_slot (folio->swap); +/* The folio might not be backed by any physical swap slots +* (for e.g zswap-backed only). +*/ +if (!swp_slot.val) +return 0 ;return __swap_slot_to_info (swp_slot)->flags; } -/* -* Return the count of contiguous swap entries that share the same -* zeromap status as the starting entry. If is_zeromap is not NULL, -* it will return the zeromap status of the starting entry. -*/ -static inline int swap_zeromap_batch (swp_entry_t entry,int max_nr, -bool *is_zeromap) -{ -swp_slot_t slot =swp_entry_to_swp_slot (entry); -struct swap_info_struct *sis =__swap_slot_to_info (slot); -unsigned long start =swp_slot_offset (slot); -unsigned long end = start + max_nr; -bool first_bit; - - first_bit =test_bit (start, sis->zeromap); -if (is_zeromap) - *is_zeromap = first_bit; - -if (max_nr <=1 ) -return max_nr; -if (first_bit) -return find_next_zero_bit (sis->zeromap, end, start) - start; -else -return find_next_bit (sis->zeromap, end, start) - start; -} - +int swap_zeromap_batch (swp_entry_t entry,int max_nr,bool *is_zeromap);int non_swapcache_batch (swp_entry_t entry,int max_nr);#else /* CONFIG_SWAP */
mm/swap_state.c +27 -2
@@ -179,6 +179,10 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,struct folio *result =NULL ;void *shadow =NULL ; +/* we might get an unsed entry from cluster readahead - just skip */ +if (!entry.val) +return NULL ; + *new_page_allocated = false;for (;;) {int err;
@@ -213,8 +217,20 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,* Swap entry may have been freed since our caller observed it. */ err =swapcache_prepare (entry,1 ); -if (!err) +if (!err) { +/* This might be invoked by swap_cluster_readahead(), which can +* race with shmem_swapin_folio(). The latter might have already +* called swap_cache_del_folio(), allowing swapcache_prepare() +* to succeed here. This can lead to reading bogus data to populate +* the page. To prevent this, skip folio-backed virtual swap slots, +* and let caller retry if necessary. +*/ +if (vswap_folio_backed (entry,1 )) { +swapcache_clear (entry,1 ); + goto put_and_return; + }break ; + }else if (err != -EEXIST ) goto put_and_return;
@@ -391,11 +407,18 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,unsigned long offset = slot_offset;unsigned long start_offset, end_offset;unsigned long mask; -struct swap_info_struct *si =__swap_slot_to_info (slot); +struct swap_info_struct *si =swap_slot_tryget_swap_info (slot);struct blk_plug plug;struct swap_iocb *splug =NULL ;bool page_allocated; +/* +* The swap entry might not be backed by any physical swap slot. In that +* case, just skip readahead and bring in the target entry. +*/ +if (!si) + goto skip; + mask =swapin_nr_pages (offset) -1 ;if (!mask) goto skip;
@@ -429,6 +452,8 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,swap_read_unplug (splug);lru_add_drain ();/* Push any new pages onto the LRU now */ skip: +if (si) +swap_slot_put_swap_info (si);/* The page was likely read above, so no need for plugging here */ folio =__read_swap_cache_async (entry, gfp_mask, mpol, ilx, &page_allocated, false);
mm/swapfile.c +0 -8
@@ -1210,14 +1210,6 @@ static void swap_range_free(struct swap_info_struct *si, unsigned long offset, {unsigned long end = offset + nr_entries -1 ;void (*swap_slot_free_notify)(struct block_device *,unsigned long ); -unsigned int i; - -/* -* Use atomic clear_bit operations only on zeromap instead of non-atomic -* bitmap_clear to prevent adjacent bits corruption due to simultaneous writes. -*/ -for (i =0 ; i < nr_entries; i++) -clear_bit (offset + i, si->zeromap);if (si->flags &SWP_BLKDEV ) swap_slot_free_notify =
mm/vmscan.c +10 -9
@@ -365,10 +365,11 @@ static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg, {if (memcg ==NULL ) {/* -* For non-memcg reclaim, is there -* space in any swap device? +* For non-memcg reclaim: +* +* Check if zswap is enabled or if there is space in any swap device? */ -if (get_nr_swap_pages () >0 ) +if (zswap_is_enabled () ||get_nr_swap_pages () >0 )return true; }else {/* Is the memcg below its swap limit? */
@@ -2640,12 +2641,12 @@ static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,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 ) -return true; - -/* Also valuable if anon pages can be demoted: */ -return can_demote (lruvec_pgdat (lruvec)->node_id, sc, +/* +* Aging the anon LRU is valuable if zswap or physical swap is available or +* anon pages can be demoted +*/ +return zswap_is_enabled () || total_swap_pages >0 || +can_demote (lruvec_pgdat (lruvec)->node_id, sc,lruvec_memcg (lruvec)); }
mm/vswap.c +439 -123
774 lines not on this page · raw message
mm/zswap.c +22 -23
102 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 15/21 zswap: do not start zswap shrinker if there is no physical swap slots
In reply to Nhat PhamWhen swap is virtualized, we no longer pre-allocate a slot on swapfile for each zswap entry. Do not start the zswap shrinker if there is no physical swap slots available.
--- mm/zswap.c | 8 ++++++++ 1 file changed, 8 insertions(+)
mm/zswap.c +8 -0
@@ -1211,6 +1211,14 @@ static unsigned long zswap_shrinker_count(struct shrinker *shrinker,if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled (memcg))return 0 ; +/* +* When swap is virtualized, we do not have any swap slots on swapfile +* preallocated for zswap objects. If there is no slot available, we +* cannot writeback and should just bail out here. +*/ +if (!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
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 16/21 swap: do not unnecesarily pin readahead swap entries
In reply to Nhat PhamWhen we perform swap readahead, the target entry is already pinned by the caller. No need to pin swap entries in the readahead window that belongs in the same virtual swap cluster as the target swap entry.
--- mm/swap.h | 1 + mm/swap_state.c | 22 +++++++++------------- mm/vswap.c | 10 ++++++++++ 3 files changed, 20 insertions(+), 13 deletions(-)
mm/swap.h +1 -0
@@ -213,6 +213,7 @@ void swap_cache_lock(swp_entry_t entry);void swap_cache_unlock (swp_entry_t entry);void vswap_rmap_set (struct swap_cluster_info *ci,swp_slot_t slot,unsigned long vswap,int nr); +bool vswap_same_cluster (swp_entry_t entry1,swp_entry_t entry2);static inline struct address_space *swap_address_space (swp_entry_t entry) {
mm/swap_state.c +9 -13
@@ -553,22 +553,18 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,pte_unmap (pte); pte =NULL ;/* -* Readahead entry may come from a device that we are not -* holding a reference to, try to grab a reference, or skip. -* -* XXX: for now, always try to pin the swap entries in the -* readahead window to avoid the annoying conversion to physical -* swap slots. Once we move all swap metadata to virtual swap -* layer, we can simply compare the clusters of the target -* swap entry and the current swap entry, and pin the latter -* swap entry's cluster if it differ from the former's. +* The target entry is already pinned - if the readahead entry +* belongs to the same cluster, it's already protected. */ - swapoff_locked =tryget_swap_entry (entry, &si); -if (!swapoff_locked) -continue ; +if (!vswap_same_cluster (entry, targ_entry)) { + swapoff_locked =tryget_swap_entry (entry, &si); +if (!swapoff_locked) +continue ; + } folio =__read_swap_cache_async (entry, gfp_mask, mpol, ilx, &page_allocated, false); -put_swap_entry (entry, si); +if (swapoff_locked) +put_swap_entry (entry, si);if (!folio)continue ;if (page_allocated) {
mm/vswap.c +10 -0
@@ -1418,6 +1418,16 @@ void put_swap_entry(swp_entry_t entry, struct swap_info_struct *si)rcu_read_unlock (); } +/* +* Check if two virtual swap entries belong to the same vswap cluster. +* Useful for optimizing readahead when entries in the same cluster +* share protection from a pinned target entry. +*/ +bool vswap_same_cluster (swp_entry_t entry1,swp_entry_t entry2) +{ +return VSWAP_CLUSTER_IDX (entry1) ==VSWAP_CLUSTER_IDX (entry2); +} +static int vswap_cpu_dead (unsigned int cpu) {struct vswap_cluster *cluster;
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 17/21 swapfile: remove zeromap bitmap
In reply to Nhat PhamZero swap entries are now treated as a separate, decoupled backend in the virtual swap layer. The zeromap bitmap of physical swapfile is no longer used - remove it. This does not have any behavioral change, and save 1 bit per swap page in terms of memory overhead.
--- include/linux/swap.h | 1 - mm/swapfile.c | 30 +++++------------------------- 2 files changed, 5 insertions(+), 26 deletions(-)
include/linux/swap.h +0 -1
@@ -260,7 +260,6 @@ struct swap_info_struct {signed char type;/* strange name for an index */ unsigned int max;/* extent of the swap_map */ unsigned char *swap_map;/* vmalloc'ed array of usage counts */ -unsigned long *zeromap;/* kvmalloc'ed bitmap to track zero pages */ 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 */
mm/swapfile.c +5 -25
@@ -2320,8 +2320,7 @@ static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)static void setup_swap_info (struct swap_info_struct *si,int prio,unsigned char *swap_map, -struct swap_cluster_info *cluster_info, -unsigned long *zeromap) +struct swap_cluster_info *cluster_info) { si->prio = prio;/*
@@ -2332,7 +2331,6 @@ static void setup_swap_info(struct swap_info_struct *si, int prio, si->avail_list.prio = -si->prio; si->swap_map = swap_map; si->cluster_info = cluster_info; - si->zeromap = zeromap; }static void _enable_swap_info (struct swap_info_struct *si)
@@ -2350,12 +2348,11 @@ static void _enable_swap_info(struct swap_info_struct *si)static void enable_swap_info (struct swap_info_struct *si,int prio,unsigned char *swap_map, -struct swap_cluster_info *cluster_info, -unsigned long *zeromap) +struct swap_cluster_info *cluster_info) {spin_lock (&swap_lock);spin_lock (&si->lock); -setup_swap_info (si, prio, swap_map, cluster_info, zeromap); +setup_swap_info (si, prio, swap_map, cluster_info);spin_unlock (&si->lock);spin_unlock (&swap_lock);/*
@@ -2373,7 +2370,7 @@ static void reinsert_swap_info(struct swap_info_struct *si) {spin_lock (&swap_lock);spin_lock (&si->lock); -setup_swap_info (si, si->prio, si->swap_map, si->cluster_info, si->zeromap); +setup_swap_info (si, si->prio, si->swap_map, si->cluster_info);_enable_swap_info (si);spin_unlock (&si->lock);spin_unlock (&swap_lock);
@@ -2444,7 +2441,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile) {struct swap_info_struct *p =NULL ;unsigned char *swap_map; -unsigned long *zeromap;struct swap_cluster_info *cluster_info;struct file *swap_file, *victim;struct address_space *mapping;
@@ -2539,8 +2535,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile) p->swap_file =NULL ; swap_map = p->swap_map; p->swap_map =NULL ; - zeromap = p->zeromap; - p->zeromap =NULL ; maxpages = p->max; cluster_info = p->cluster_info; p->max =0 ;
@@ -2552,7 +2546,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)kfree (p->global_cluster); p->global_cluster =NULL ;vfree (swap_map); -kvfree (zeromap);free_cluster_info (cluster_info, maxpages); inode = mapping->host;
@@ -3016,7 +3009,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)sector_t span;unsigned long maxpages;unsigned char *swap_map =NULL ; -unsigned long *zeromap =NULL ;struct swap_cluster_info *cluster_info =NULL ;struct folio *folio =NULL ;struct inode *inode =NULL ;
@@ -3122,17 +3114,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)if (error) goto bad_swap_unlock_inode; -/* -* Use kvmalloc_array instead of bitmap_zalloc as the allocation order might -* be above MAX_PAGE_ORDER incase of a large swap file. -*/ - zeromap =kvmalloc_array (BITS_TO_LONGS (maxpages),sizeof (long ), -GFP_KERNEL | __GFP_ZERO); -if (!zeromap) { - error = -ENOMEM ; - goto bad_swap_unlock_inode; - } -if (si->bdev &&bdev_stable_writes (si->bdev)) si->flags |=SWP_STABLE_WRITES ;
@@ -3199,7 +3180,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) prio =DEF_SWAP_PRIO ;if (swap_flags &SWAP_FLAG_PREFER ) prio = swap_flags &SWAP_FLAG_PRIO_MASK ; -enable_swap_info (si, prio, swap_map, cluster_info, zeromap); +enable_swap_info (si, prio, swap_map, cluster_info); pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", K(si->pages), name->name, si->prio, nr_extents,
@@ -3227,7 +3208,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) si->flags =0 ;spin_unlock (&swap_lock);vfree (swap_map); -kvfree (zeromap);if (cluster_info)free_cluster_info (cluster_info, maxpages);if (inced_nr_rotate_swap)
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 18/21 memcg: swap: only charge physical swap slots
In reply to Nhat PhamNow that zswap and the zero-filled swap page optimization no longer takes up any physical swap space, we should not charge towards the swap usage and limits of the memcg in these case. We will only record the memcg id on virtual swap slot allocation, and defer physical swap charging (i.e towards memory.swap.current) until the virtual swap slot is backed by an actual physical swap slot (on zswap store failure fallback or zswap writeback).
--- include/linux/swap.h | 26 ++++++++++++++ mm/memcontrol-v1.c | 6 ++++ mm/memcontrol.c | 83 ++++++++++++++++++++++++++++++++------------ mm/vswap.c | 39 +++++++++------------ 4 files changed, 108 insertions(+), 46 deletions(-)
include/linux/swap.h +26 -0
@@ -676,6 +676,22 @@ static inline void folio_throttle_swaprate(struct folio *folio, gfp_t gfp)#endif #if defined(CONFIG_MEMCG ) && defined(CONFIG_SWAP ) +void __mem_cgroup_record_swap (struct folio *folio,swp_entry_t entry); +static inline void mem_cgroup_record_swap (struct folio *folio, +swp_entry_t entry) +{ +if (!mem_cgroup_disabled ()) +__mem_cgroup_record_swap (folio, entry); +} + +void __mem_cgroup_clear_swap (swp_entry_t entry,unsigned int nr_pages); +static inline void mem_cgroup_clear_swap (swp_entry_t entry, +unsigned int nr_pages) +{ +if (!mem_cgroup_disabled ()) +__mem_cgroup_clear_swap (entry, nr_pages); +} +int __mem_cgroup_try_charge_swap (struct folio *folio,swp_entry_t entry);static inline int mem_cgroup_try_charge_swap (struct folio *folio,swp_entry_t entry)
@@ -696,6 +712,16 @@ static inline void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pextern long mem_cgroup_get_nr_swap_pages (struct mem_cgroup *memcg);extern bool mem_cgroup_swap_full (struct folio *folio);#else +static inline void mem_cgroup_record_swap (struct folio *folio, +swp_entry_t entry) +{ +} + +static inline void mem_cgroup_clear_swap (swp_entry_t entry, +unsigned int nr_pages) +{ +} +static inline int mem_cgroup_try_charge_swap (struct folio *folio,swp_entry_t entry) {
mm/memcontrol-v1.c +6 -0
@@ -680,6 +680,12 @@ void memcg1_swapin(swp_entry_t entry, unsigned int nr_pages)* memory+swap charge, drop the swap entry duplicate. */ mem_cgroup_uncharge_swap (entry, nr_pages); + +/* +* Clear the cgroup association now to prevent double memsw +* uncharging when the backends are released later. +*/ +mem_cgroup_clear_swap (entry, nr_pages); } }
mm/memcontrol.c +60 -23
128 lines not on this page · raw message
mm/vswap.c +16 -23
@@ -544,6 +544,7 @@ static void release_backing(swp_entry_t entry, int nr)struct vswap_cluster *cluster =NULL ;struct swp_desc *desc;unsigned long flush_nr, phys_swap_start =0 , phys_swap_end =0 ; +unsigned long phys_swap_released =0 ;unsigned int phys_swap_type =0 ;bool need_flushing_phys_swap = false;swp_slot_t flush_slot;
@@ -573,6 +574,7 @@ static void release_backing(swp_entry_t entry, int nr)if (desc->type ==VSWAP_ZSWAP && desc->zswap_entry) {zswap_entry_free (desc->zswap_entry); }else if (desc->type ==VSWAP_SWAPFILE ) { + phys_swap_released++;if (!phys_swap_start) {/* start a new contiguous range of phys swap */ phys_swap_start =swp_slot_offset (desc->slot);
@@ -603,6 +605,9 @@ static void release_backing(swp_entry_t entry, int nr) flush_nr = phys_swap_end - phys_swap_start;swap_slot_free_nr (flush_slot, flush_nr); } + +if (phys_swap_released) +mem_cgroup_uncharge_swap (entry, phys_swap_released); }/*
@@ -630,7 +635,7 @@ static void vswap_free(struct vswap_cluster *cluster, struct swp_desc *desc,spin_unlock (&cluster->lock);release_backing (entry,1 ); -mem_cgroup_uncharge_swap (entry,1 ); +mem_cgroup_clear_swap (entry,1 );/* erase forward mapping and release the virtual slot for reallocation */ spin_lock (&cluster->lock);
@@ -645,9 +650,6 @@ static void vswap_free(struct vswap_cluster *cluster, struct swp_desc *desc,*/ int folio_alloc_swap (struct folio *folio) { -struct vswap_cluster *cluster =NULL ; -int i, nr =folio_nr_pages (folio); -struct swp_desc *desc;swp_entry_t entry;VM_BUG_ON_FOLIO (!folio_test_locked (folio), folio);
@@ -657,25 +659,7 @@ int folio_alloc_swap(struct folio *folio)if (!entry.val)return -ENOMEM ; -/* -* XXX: for now, we charge towards the memory cgroup's swap limit on virtual -* swap slots allocation. This will be changed soon - we will only charge on -* physical swap slots allocation. -*/ -if (mem_cgroup_try_charge_swap (folio, entry)) { -rcu_read_lock (); -for (i =0 ; i < nr; i++) { - desc =vswap_iter (&cluster, entry.val + i); -VM_WARN_ON (!desc); -vswap_free (cluster, desc, (swp_entry_t ){ entry.val + i }); - } -spin_unlock (&cluster->lock); -rcu_read_unlock (); -atomic_add (nr, &vswap_alloc_reject); - entry.val =0 ; -return -ENOMEM ; - } - +mem_cgroup_record_swap (folio, entry);swap_cache_add_folio (folio, entry,NULL );return 0 ;
@@ -717,6 +701,15 @@ bool vswap_alloc_swap_slot(struct folio *folio)if (!slot.val)return false; +if (mem_cgroup_try_charge_swap (folio, entry)) { +/* +* We have not updated the backing type of the virtual swap slot. +* Simply free up the physical swap slots here! +*/ +swap_slot_free_nr (slot, nr); +return false; + } +/* establish the vrtual <-> physical swap slots linkages. */ si =__swap_slot_to_info (slot); ci =swap_cluster_lock (si,swp_slot_offset (slot));
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 19/21 swap: simplify swapoff using virtual swap
In reply to Nhat PhamThis patch presents the second applications of virtual swap design - simplifying and optimizing swapoff.
With virtual swap slots stored at page table entries and used as indices to various swap-related data structures, we no longer have to perform a page table walk in swapoff. Simply iterate through all the allocated swap slots on the swapfile, find their corresponding virtual swap slots, and fault them in.
This is significantly cleaner, as well as slightly more performant, especially when there are a lot of unrelated VMAs (since the old swapoff code would have to traverse through all of them).
In a simple benchmark, in which we swapoff a 32 GB swapfile that is 50% full, and in which there is a process that maps a 128GB file into memory:
Baseline:
sys: 11.48s
New Design:
sys: 9.96s
Disregarding the real time reduction (which is mostly due to more IO asynchrony), the new design reduces the kernel CPU time by about 13%.
--- include/linux/shmem_fs.h | 7 +- mm/filemap.c | 14 +- mm/shmem.c | 196 +--------------- mm/swapfile.c | 474 +++++++++------------------------------ 4 files changed, 126 insertions(+), 565 deletions(-)
include/linux/shmem_fs.h +1 -6
@@ -41,17 +41,13 @@ struct shmem_inode_info {unsigned long swapped;/* subtotal assigned to swap */ union {struct offset_ctx dir_offsets;/* stable directory offsets */ -struct { -struct list_head shrinklist;/* shrinkable hpage inodes */ -struct list_head swaplist;/* chain of maybes on swap */ - }; +struct list_head shrinklist;/* shrinkable hpage inodes */ };struct timespec64 i_crtime;/* file creation time */ struct shared_policy policy;/* NUMA memory alloc policy */ struct simple_xattrs xattrs;/* list of xattrs */ pgoff_t fallocend;/* highest fallocate endindex */ unsigned int fsflags;/* for FS_IOC_[SG]ETFLAGS */ -atomic_t stop_eviction;/* hold when working on inode */ #ifdef CONFIG_TMPFS_QUOTA struct dquot __rcu *i_dquot[MAXQUOTAS ];#endif
@@ -127,7 +123,6 @@ struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,int shmem_writeout (struct folio *folio,struct swap_iocb **plug,struct list_head *folio_list);void shmem_truncate_range (struct inode *inode,loff_t start,uoff_t end); -int shmem_unuse (unsigned int type);#ifdef CONFIG_TRANSPARENT_HUGEPAGE unsigned long shmem_allowable_huge_orders(struct inode *inode,
mm/filemap.c +7 -7
@@ -4614,13 +4614,13 @@ static void filemap_cachestat(struct address_space *mapping,/* * Getting a swap entry from the shmem -* inode means we beat -* shmem_unuse(). rcu_read_lock() -* ensures swapoff waits for us before -* freeing the swapper space. However, -* we can race with swapping and -* invalidation, so there might not be -* a shadow in the swapcache (yet). +* inode means we beat swapoff. +* rcu_read_lock() ensures swapoff waits +* for us before freeing the swapper +* space. However, we can race with +* swapping and invalidation, so there +* might not be a shadow in the swapcache +* (yet). */ shadow =swap_cache_get_shadow (swp);if (!shadow)
mm/shmem.c +7 -189
246 lines not on this page · raw message
mm/swapfile.c +111 -363
527 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 20/21 swapfile: replace the swap map with bitmaps
In reply to Nhat PhamNow that we have moved the swap count state to virtual swap layer, each swap map entry only has 3 possible states: free, allocated, and bad. Replace the swap map with 2 bitmaps (one for allocated state and one for bad state), saving 6 bits per swap entry.
--- include/linux/swap.h | 3 +- mm/swapfile.c | 81 +++++++++++++++++++++++--------------------- 2 files changed, 44 insertions(+), 40 deletions(-)
include/linux/swap.h +2 -1
@@ -259,7 +259,8 @@ struct swap_info_struct {struct plist_node list;/* entry in swap_active_head */ signed char type;/* strange name for an index */ unsigned int max;/* extent of the swap_map */ -unsigned char *swap_map;/* vmalloc'ed array of usage counts */ +unsigned long *swap_map;/* bitmap for allocated state */ +unsigned long *bad_map;/* bitmap for bad state */ 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 */
mm/swapfile.c +42 -39
216 lines not on this page · raw message
Signature · 1 line
2.52.0
Nhat Pham
maintainerPATCH v5 21/21 vswap: batch contiguous vswap free calls
In reply to Nhat PhamIn vswap_free(), we release and reacquire the cluster lock for every single entry, even for non-disk-swap backends where the lock drop is unnecessary. Batch consecutive free operations to avoid this overhead.
--- include/linux/memcontrol.h | 6 ++ mm/memcontrol.c | 2 +- mm/vswap.c | 185 ++++++++++++++++++++++++------------- 3 files changed, 126 insertions(+), 67 deletions(-)
include/linux/memcontrol.h +6 -0
@@ -827,6 +827,7 @@ static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)return memcg->id.id; }struct mem_cgroup *mem_cgroup_from_id (unsigned short id); +void mem_cgroup_id_put_many (struct mem_cgroup *memcg,unsigned int n);#ifdef CONFIG_SHRINKER_DEBUG static inline unsigned long mem_cgroup_ino (struct mem_cgroup *memcg)
@@ -1289,6 +1290,11 @@ static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)return NULL ; } +static inline void mem_cgroup_id_put_many (struct mem_cgroup *memcg, +unsigned int n) +{ +} +#ifdef CONFIG_SHRINKER_DEBUG static inline unsigned long mem_cgroup_ino (struct mem_cgroup *memcg) {
mm/memcontrol.c +1 -1
@@ -3597,7 +3597,7 @@ void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,refcount_add (n, &memcg->id.ref); } -static void mem_cgroup_id_put_many (struct mem_cgroup *memcg,unsigned int n) +void mem_cgroup_id_put_many (struct mem_cgroup *memcg,unsigned int n) {if (refcount_sub_and_test (n, &memcg->id.ref)) {mem_cgroup_id_remove (memcg);
mm/vswap.c +119 -66
321 lines not on this page · raw message
Signature · 1 line
2.52.0
Andrew Morton
maintainerQuoted 5 lines · On Fri, 20 Mar 2026 12:27:14 -0700 Nhat Pham <[email protected]> wrote:
This patch series implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).
AI review got partway through then decided it couldn't apply patches. So
a partial result: https://sashiko.dev/#/patchset/[email protected]
Roman Gushchin
maintainerQuoted 10 lines · Andrew Morton
Quoted 5 lines · On Fri, 20 Mar 2026 12:27:14 -0700 Nhat Pham <[email protected]> wrote:
This patch series implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).
AI review got partway through then decided it couldn't apply patches. So
a partial result: https://sashiko.dev/#/patchset/[email protected]
It's a bug in the error handling. I've already fixed it, but haven't deployed the new version yet. In the reality, the review failed for some other reason (the most popular one now is backend/llm api transient errors).
Sashiko applies the entire patchset first and if it fails, it's not reviewing anything.
Quoted 7 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Quoted 9 lines
Changelog:
* v4 -> v5:
* Fix a deadlock inmemcg1_swapout(reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) withlockdep_assert_held(), and use guard(rcu) invswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).
I tested the v5 (including the batched-free hotfix) and am still seeing significant regressions in both sequential and concurrent swap workloads
Thanks for the update as I can see It's a lot of thoughtful work. Actually I did run some tests already with your previously posted hotfix based on v3. I didn't update the result because very unfortunately, I still see a major performance regression even with a very simple setup.
BTW there seems a simpler way to reproduce that, just use memhog:
sudo mkswap /dev/pmem0; sudo swapon /dev/pmem0; time memhog 48G; sudo swapoff -a
Before:
(I'm using fish shell on that test machine so this is fish time format):
________________________________________________________
Executed in 20.80 secs fish external usr time 5.14 secs 0.00 millis 5.14 secs sys time 15.65 secs 1.17 millis 15.65 secs
________________________________________________________
Executed in 21.69 secs fish external
usr time 5.31 secs 725.00 micros 5.31 secs
sys time 16.36 secs 579.00 micros 16.36 secs
________________________________________________________
Executed in 21.86 secs fish external usr time 5.39 secs 1.02 millis 5.39 secs sys time 16.46 secs 0.27 millis 16.46 secs
After:
________________________________________________________
Executed in 30.77 secs fish external
usr time 5.16 secs 767.00 micros 5.16 secs
sys time 25.59 secs 580.00 micros 25.59 secs
________________________________________________________
Executed in 37.47 secs fish external usr time 5.48 secs 0.00 micros 5.48 secs sys time 31.98 secs 674.00 micros 31.98 secs ________________________________________________________ Executed in 31.34 secs fish external usr time 5.22 secs 0.00 millis 5.22 secs sys time 26.09 secs 1.30 millis 26.09 secs
It's obviously a lot slower.
pmem may seem rare but SSDs are good at sequential, and memhog uses the same filled page and backend like ZRAM has extremely low overhead for same filled pages. Results with ZRAM are very similar, and many production workloads have massive amounts of samefill memory.
For example on the Android phone I'm using right now at this moment:
# cat /sys/block/zram0/mm_stat 4283899904 1317373036 1370259456 0 1475977216 116457 1991851 87273 1793760 ~450M of samefill page in ZRAM, we may see more on some server workload. And I'm seeing similar memhog results with ZRAM, pmem is just easier to setup and less noisy. also simulates high speed storage.
I also ran the previous usemem matrix, which seems better than V3 but still pretty bad:
Test: usemem --init-time -O -n 1 56G, 16G mem, 48G swap, avgs of 8 run. Before:
Throughput (Sum): 528.98 MB/s Throughput (Mean): 526.113333 MB/s Free
Latency: 3037932.888889
After:
Throughput (Sum): 453.74 MB/s Throughput (Mean): 454.875000 MB/s Free
Latency: 5001144.500000 (~10%, 64% slower)
I'm not sure why our results differ so much — perhaps different LRU settings, memory pressure ratios, or THP/mTHP configs? Here's my exact config in the attachment. Also includes the full log and info, with all debug options disabled for close to production. I ran it 8 times and just attached the first result log, it's all similar anyway, my test framework reboot the machine after each test run to reduce any potential noise.
And the above tests are only about sequential performance, concurrent ones seem worse:
Test: usemem --init-time -O -R -n 32 622M, 16G mem, 48G swap, avgs of 8 run. Before:
Throughput (Sum): 5467.51 MB/s Throughput (Mean): 170.04 MB/s Free
Latency: 28648.65
After:
Throughput (Sum): 4914.86 MB/s Throughput (Mean): 152.74 MB/s Free
Latency: 67789.81 (~10%, 230% slower)
And I double checked I'm testing your latest V5 commit here:
commit 9114ebedb82089ebd3519854964c73d3959b10c0 (HEAD -> upstream/vswap)
Author: Nhat Pham <[email protected]> Date: Fri Mar 20 12:27:35 2026 -0700
vswap: batch contiguous vswap free calls
In vswap_free(), we release and reacquire the cluster lock for every single entry, even for non-disk-swap backends where the lock drop is unnecessary. Batch consecutive free operations to avoid this overhead.
The two kernels being tested:/boot/vmlinuz-6.19.0.orig-g05f7e89ab973/boot/vmlinuz-6.19.0.ptch-g9114ebedb820
These tests above are done with an EPYC 7K62, I also setup an Intel 8255C with fresh installed upstream Fedora, and using Fedora's kernel config. So far the result matches, the gap seems smaller but still
Quoted 1 line
20% slower for many cases, so this is a common problem:
3 test run on 8255C using fresh installed Fedora and Fedora kernel config:
taskset -c 3 /usr/local/bin/usemem --init-time -O -n 1 112G (That's a two nodes large machine so I pin the thread on CPU 3 for stability)
Before:
135291469824 bytes / 124326887 usecs = 1062687 KB/s 2157355 usecs to free memory
135291469824 bytes / 123930024 usecs = 1066090 KB/s 2244083 usecs to free memory
135291469824 bytes / 123484528 usecs = 1069936 KB/s 2268364 usecs to free memory
After:
135291469824 bytes / 127073712 usecs = 1039716 KB/s 3050394 usecs to free memory
135291469824 bytes / 130724757 usecs = 1010677 KB/s 3064270 usecs to free memory
135291469824 bytes / 127248347 usecs = 1038289 KB/s 3035986 usecs to free memory
And beside these known cases, my main concern is still that a mandatory virtual layer seems just wrong, it changes how swap work in many ways. Storage folks have been trying to bypass the kernel for decades, as abstraction layers come with overhead — that's common knowledge. Swap lives right at the intersection of storage and mm and has to stay inside the kernel, so we really want the kernel path to be as flat and direct as possible.
I'm also worried this risks undoing all the recent and upcoming work for reducing memory usage and performance. We've been trying to shrink per-entry overhead (I'm already feeling nervous over the current 8-byte per-entry cost, and hope soon we'll get down to <1–3 bytes). The series mentions 24 bytes of overhead, but when I account for the reverse mapping, it looks >32 bytes per entry.
The intermediate large XArray layer also worries me as the swap space is now very large. The virtual size could grow with no limit. e.g. a 1 TB swap space would be a 4 layers radix tree, increasing global contention (int(1024 * 1024 / 2) >> 6 >> 6 >> 6 == 2) and vswap could be even larger if fragmentation happens. That's the exact problem the old sub-address_space design for SWAP was created to solve. We only eliminated that complexity a few months ago, and this approach seems like it would have to bring a similar structure back to reduce contention.
And for swapoff support: minor anonymous faults during busy periods are indeed critical for some workloads, and being able to swapoff cleanly is still very useful both for performance and troubleshooting. You will need to touch many things to solve a minor fault.
For reference, I've been exploring an approach that keeps the virtual layer runtime-optional, which avoids these overheads for workloads that don't need virtualization:
https://lore.kernel.org/linux-mm/[email protected]/
Nhat Pham
maintainerQuoted 9 lines · Kairui Song
Quoted 7 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Quoted 10 lines
Quoted 9 lines
Changelog:
* v4 -> v5:
* Fix a deadlock inmemcg1_swapout(reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) withlockdep_assert_held(), and use guard(rcu) invswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).
Hi Kairui! Thanks a lot for the testing big boss :) I will focus on the regression in this patch series - we can talk more about directions in another thread :)
Quoted 49 lines
I tested the v5 (including the batched-free hotfix) and am still seeing significant regressions in both sequential and concurrent swap workloads
Thanks for the update as I can see It's a lot of thoughtful work. Actually I did run some tests already with your previously posted hotfix based on v3. I didn't update the result because very unfortunately, I still see a major performance regression even with a very simple setup.
BTW there seems a simpler way to reproduce that, just use memhog:
sudo mkswap/dev/pmem0; sudo swapon/dev/pmem0; time memhog 48G; sudo swapoff -aBefore:
(I'm using fish shell on that test machine so this is fish time format):
________________________________________________________Executed in 20.80 secs fish external usr time 5.14 secs 0.00 millis 5.14 secs sys time 15.65 secs 1.17 millis 15.65 secs________________________________________________________
Executed in 21.69 secs fish external
usr time 5.31 secs 725.00 micros 5.31 secs
sys time 16.36 secs 579.00 micros 16.36 secs
________________________________________________________Executed in 21.86 secs fish external usr time 5.39 secs 1.02 millis 5.39 secs sys time 16.46 secs 0.27 millis 16.46 secsAfter:
________________________________________________________
Executed in 30.77 secs fish external
usr time 5.16 secs 767.00 micros 5.16 secs
sys time 25.59 secs 580.00 micros 25.59 secs
________________________________________________________Executed in 37.47 secs fish external usr time 5.48 secs 0.00 micros 5.48 secs sys time 31.98 secs 674.00 micros 31.98 secs ________________________________________________________ Executed in 31.34 secs fish external usr time 5.22 secs 0.00 millis 5.22 secs sys time 26.09 secs 1.30 millis 26.09 secsIt's obviously a lot slower.
pmem may seem rare but SSDs are good at sequential, and memhog uses the same filled page and backend like ZRAM has extremely low overhead for same filled pages. Results with ZRAM are very similar, and many production workloads have massive amounts of samefill memory.
Quoted 8 lines
For example on the Android phone I'm using right now at this moment:
# cat /sys/block/zram0/mm_stat 4283899904 1317373036 1370259456 0 1475977216 116457 1991851 87273 1793760 ~450M of samefill page in ZRAM, we may see more on some server workload. And I'm seeing similar memhog results with ZRAM, pmem is just easier to setup and less noisy. also simulates high speed storage.
Interesting. Normally "lots of zero-filled page" is a very beneficial case for vswap. You don't need a swapfile, or any zram/zswap metadata overhead - it's a native swap backend. If production workload has this many zero-filled pages, I think the numbers of vswap would be much less alarming - perhaps even matching memory overhead because you don't need to maintain a zram entry metadata (it's at least 2 words per zram entry right?), while there's no reverse map overhead induced (so it's 24 bytes on both side), and no need to do zram-side locking :)
So I was surprised to see that it's not working out very well here. I checked the implementation of memhog - let me know if this is wrong place to look:
https://man7.org/linux/man-pages/man8/memhog.8.html
https://github.com/numactl/numactl/blob/master/memhog.c#L52
I think this is what happened here: memhog was populating the memory 0xff, which triggers the full overhead of a swapfile-backed swap entry because even though it's "same-filled" it's not zero-filled! I was following Usama's observation - "less than 1% of the same-filled pages were non-zero" - and so I only handled the zero-filled case here:
https://lore.kernel.org/all/[email protected]/
This sounds a bit artificial IMHO - as Usama pointed out above, I think most samefilled pages are zero pages, in real production workloads. However, if you think there are real use cases with a lot of non-zero samefilled pages, please let me know I can fix this real quick. We can support this in vswap with zero extra metadata overhead
- change the VSWAP_ZERO swap entry type to VSWAP_SAME_FILLED, then use the backend field to store that value. I can send you a patch if you're interested.
Quoted 11 lines
I also ran the previous usemem matrix, which seems better than V3 but still pretty bad:
Test: usemem --init-time -O -n 1 56G, 16G mem, 48G swap, avgs of 8 run. Before:
Throughput (Sum): 528.98 MB/s Throughput (Mean): 526.113333 MB/s Free
Latency: 3037932.888889
After:
Throughput (Sum): 453.74 MB/s Throughput (Mean): 454.875000 MB/s Free
Latency: 5001144.500000 (~10%, 64% slower)
Quoted 7 lines
I'm not sure why our results differ so much — perhaps different LRU settings, memory pressure ratios, or THP/mTHP configs? Here's my exact config in the attachment. Also includes the full log and info, with all debug options disabled for close to production. I ran it 8 times and just attached the first result log, it's all similar anyway, my test framework reboot the machine after each test run to reduce any potential noise.
Ohh interesting - I see that you're testing with MGLRU. I can give that a try.
I'm not enabling THP/mTHP, but I don't see that you're enabling it either - there's some 2MB swpout but that seems incidental.
Another difference is the swap backend:
1. Regarding pmem backend - I'm not sure if I can get my hands on one of these, but if you think SSD has the same characteristics maybe I can give that a try? The problem with SSD is for some reason variance tends to be pretty high, between iterations yes, but especially across reboots. Or maybe zram?
2. What about the other numbers below? Are they also on pmem? FTR I was running most of my benchmarks on zswap, except for one kernel build benchmark on SSD.
3. Any other backends and setup you're interested in?
BTW, sounds like you have a great benchmark suite - is it open source somewhere? If not, can you share it with us :) Vswap aside, I think this would be a good suite to run all swap related changes for every swap contributor.
Once again, thank you so much for your engagement, Kairui. Very much appreciated - I owe you a beverage of your choice whenever we meet. And have a great rest of your day :)
Quoted 22 lines · Nhat Pham
Quoted 9 lines · Kairui Song
Quoted 7 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Quoted 10 lines
Quoted 9 lines
Changelog:
* v4 -> v5:
* Fix a deadlock inmemcg1_swapout(reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) withlockdep_assert_held(), and use guard(rcu) invswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).
Quoted 3 lines
Hi Kairui! Thanks a lot for the testing big boss :) I will focus on the regression in this patch series - we can talk more about directions in another thread :)
Hi Nhat,
Quoted 23 lines
Interesting. Normally "lots of zero-filled page" is a very beneficial case for vswap. You don't need a swapfile, or any zram/zswap metadata overhead - it's a native swap backend. If production workload has this many zero-filled pages, I think the numbers of vswap would be much less alarming - perhaps even matching memory overhead because you don't need to maintain a zram entry metadata (it's at least 2 words per zram entry right?), while there's no reverse map overhead induced (so it's 24 bytes on both side), and no need to do zram-side locking :)
So I was surprised to see that it's not working out very well here. I checked the implementation of memhog - let me know if this is wrong place to look:
https://man7.org/linux/man-pages/man8/memhog.8.html
https://github.com/numactl/numactl/blob/master/memhog.c#L52I think this is what happened here: memhog was populating the memory
0xff, which triggers the full overhead of a swapfile-backed swap entry because even though it's "same-filled" it's not zero-filled! I was following Usama's observation - "less than 1% of the same-filled pages were non-zero" - and so I only handled the zero-filled case here:
Quoted 5 lines
https://lore.kernel.org/all/[email protected]/
This sounds a bit artificial IMHO - as Usama pointed out above, I think most samefilled pages are zero pages, in real production workloads. However, if you think there are real use cases with a lot
I vaguely remember some workloads like Java or some JS engine initialize their heap with fixed value, same fill might not be that common but not a rare thing, it strongly depends on the workload.
Quoted 5 lines
of non-zero samefilled pages, please let me know I can fix this real quick. We can support this in vswap with zero extra metadata overhead
- change theVSWAP_ZEROswap entry type toVSWAP_SAME_FILLED, then use the backend field to store that value. I can send you a patch if you're interested.
Actually I don't think that's the main problem. For example, I just wrote a few lines C bench program to zerofill ~50G of memory and swapout sequentially:
Before:
Swapout: 4415467us
Swapin: 49573297us
After:
Swapout: 4955874us
Swapin: 56223658us
And vmstat:
cat /proc/vmstat | grep zerothp_zero_page_alloc 0thp_zero_page_alloc_failed 0swpin_zero 12239329swpout_zero 21516634
There are all zero filled pages, but still slower. And what's more, a more critical issue, I just found the cgroup and global swap usage accounting are both somehow broken for zero page swap, maybe because you skipped some allocation? Users can
no longer see how many pages are swapped out. I don't think you can break that, that's one major reason why we use a zero entry instead of mapping to a zero readonly page. If that is acceptable, we can have a very nice optimization right away with current swap.
That's still just an example. bypassing the accounting and still slower is not a good sign. We should focus on the generic performance and design.
Yet this is just another new found issue, there are many other parts like the folio swap allocation may still occur even if a lower device can no longer accept more whole folios, which I'm currently unsure how it will affect swap.
Quoted 5 lines
1. Regarding pmem backend - I'm not sure if I can get my hands on one of these, but if you think SSD has the same characteristics maybe I can give that a try? The problem with SSD is for some reason variance tends to be pretty high, between iterations yes, but especially across reboots. Or maybe zram?
Yeah, ZRAM has a very similar number for some cases, but storage is getting faster and faster and swap occurs through high speed networks too. We definitely shouldn't ignore that.
Quoted 10 lines
2. What about the other numbers below? Are they also on pmem? FTR I was running most of my benchmarks on zswap, except for one kernel build benchmark on SSD.
3. Any other backends and setup you're interested in?
BTW, sounds like you have a great benchmark suite - is it open source somewhere? If not, can you share it with us :) Vswap aside, I think this would be a good suite to run all swap related changes for every swap contributor.
I can try to post that somewhere, really nothing fancy just some wrapper to make use of systemd for reboot and auto test. But all test steps I mentioned before are already posted and publically available.
Nhat Pham
maintainerQuoted 55 lines · Kairui Song
Quoted 22 lines · Nhat Pham
Quoted 9 lines · Kairui Song
Quoted 7 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Quoted 10 lines
Quoted 9 lines
Changelog:
* v4 -> v5:
* Fix a deadlock inmemcg1_swapout(reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) withlockdep_assert_held(), and use guard(rcu) invswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).Quoted 3 lines
Hi Kairui! Thanks a lot for the testing big boss :) I will focus on the regression in this patch series - we can talk more about directions in another thread :)
Hi Nhat,
Quoted 25 lines
Interesting. Normally "lots of zero-filled page" is a very beneficial case for vswap. You don't need a swapfile, or any zram/zswap metadata overhead - it's a native swap backend. If production workload has this many zero-filled pages, I think the numbers of vswap would be much less alarming - perhaps even matching memory overhead because you don't need to maintain a zram entry metadata (it's at least 2 words per zram entry right?), while there's no reverse map overhead induced (so it's 24 bytes on both side), and no need to do zram-side locking :)
So I was surprised to see that it's not working out very well here. I checked the implementation of memhog - let me know if this is wrong place to look:
https://man7.org/linux/man-pages/man8/memhog.8.html
https://github.com/numactl/numactl/blob/master/memhog.c#L52I think this is what happened here: memhog was populating the memory
0xff, which triggers the full overhead of a swapfile-backed swap entry because even though it's "same-filled" it's not zero-filled! I was following Usama's observation - "less than 1% of the same-filled pages were non-zero" - and so I only handled the zero-filled case here:
Quoted 7 lines
Quoted 3 lines
This sounds a bit artificial IMHO - as Usama pointed out above, I think most samefilled pages are zero pages, in real production workloads. However, if you think there are real use cases with a lot
I vaguely remember some workloads like Java or some JS engine initialize their heap with fixed value, same fill might not be that common but not a rare thing, it strongly depends on the workload.
To a non-zero value? ISTR it was initialized to zero, but if I was wrong then yeah it should just be a small simple patch.
Quoted 26 lines
Quoted 6 lines
of non-zero samefilled pages, please let me know I can fix this real quick. We can support this in vswap with zero extra metadata overhead
- change theVSWAP_ZEROswap entry type toVSWAP_SAME_FILLED, then use the backend field to store that value. I can send you a patch if you're interested.Actually I don't think that's the main problem. For example, I just wrote a few lines C bench program to zerofill ~50G of memory and swapout sequentially:
Before:
Swapout: 4415467us
Swapin: 49573297usAfter:
Swapout: 4955874us
Swapin: 56223658usAnd vmstat:
cat/proc/vmstat| grep zerothp_zero_page_alloc0thp_zero_page_alloc_failed0swpin_zero12239329swpout_zero21516634
Quoted 8 lines
There are all zero filled pages, but still slower. And what's more, a more critical issue, I just found the cgroup and global swap usage accounting are both somehow broken for zero page swap, maybe because you skipped some allocation? Users can
no longer see how many pages are swapped out. I don't think you can break that, that's one major reason why we use a zero entry instead of mapping to a zero readonly page. If that is acceptable, we can have a very nice optimization right away with current swap.
No, that was intentional :) I probably should have documented this better - but we're only charging towards swap usage (cgroup and system wide) on memory. There was a whole patch that did that in the series :)
I can add new counters to differentiate these cases, but it makes no sense to me to charge towards swap usage for non-swapfile backend (namely, zswap and zero swap pages). You are not actually occupying the limited swapfile slots, but instead occupy a dynamic, vast virtual swap space only (and memory in the case of zswap - this is actually an argument against zram which does not do any cgroup accounting, but that's another story for another day). I don't see a point in swap charging here. It's the whole point of decoupling the backends - these are not the same resource domains.
And if you follow Usama's work above, we actually were trying to figure out a way to map it to a zero readonly page. That was Usama's v2 of the patch series IIRC - but there was a bug. I think it was a potential race between the reclaimer's rmap walk to unmap the page from PTEs pointing to the page, and concurrent modifiers to the page? We couldn't fix the race in a way that does not induce more overhead than it's worth. But had that work we would also not do any swap charging :)
BTW, if you can figure that part out, please let us know. We actually quite like that idea - we just never managed to make it work (and we have a bunch more urgent tasks).
Quoted 4 lines
That's still just an example. bypassing the accounting and still slower is not a good sign. We should focus on the generic performance and design.
I will dig into the remaining regression :) Thanks for the report.
Quoted 15 lines
Yet this is just another new found issue, there are many other parts like the folio swap allocation may still occur even if a lower device can no longer accept more whole folios, which I'm currently unsure how it will affect swap.
Quoted 5 lines
1. Regarding pmem backend - I'm not sure if I can get my hands on one of these, but if you think SSD has the same characteristics maybe I can give that a try? The problem with SSD is for some reason variance tends to be pretty high, between iterations yes, but especially across reboots. Or maybe zram?
Quoted 3 lines
Yeah, ZRAM has a very similar number for some cases, but storage is getting faster and faster and swap occurs through high speed networks too. We definitely shouldn't ignore that.
I can also simulate it using tmpfs as a swap backend (although it might not work for certain benchmarks, like your usemem benchmark in which we allocate more memory than the host physical memory).
Quoted 7 lines
Quoted 7 lines
2. What about the other numbers below? Are they also on pmem? FTR I was running most of my benchmarks on zswap, except for one kernel build benchmark on SSD.
3. Any other backends and setup you're interested in?
Quoted 8 lines
Quoted 4 lines
BTW, sounds like you have a great benchmark suite - is it open source somewhere? If not, can you share it with us :) Vswap aside, I think this would be a good suite to run all swap related changes for every swap contributor.
I can try to post that somewhere, really nothing fancy just some wrapper to make use of systemd for reboot and auto test. But all test steps I mentioned before are already posted and publically available.
Okay, thanks, Kairui!
Nhat Pham <[email protected]>:
Quoted 4 lines
We can even perform compressed writeback
(i.e writing these pages without decompressing them) (see [12]).
This is supported in zram. The support was added here:
https://lore.kernel.org/all/[email protected]/ . It is already in mainline.
Signature · 1 line
Askar Safin
Nhat Pham
maintainerQuoted 10 lines · Askar Safin
Nhat Pham <[email protected]>:
Quoted 4 lines
We can even perform compressed writeback
(i.e writing these pages without decompressing them) (see [12]).This is supported in zram. The support was added here:
https://lore.kernel.org/all/[email protected]/ . It is already in mainline.
I'm aware of that work. It's an improvement, but my understanding is:
1. It only works for zram.
2. We still occupy the full PAGE_SIZE slot.
3. The writeback IO request is still of size PAGE_SIZE.
So we're saving the CPU work for decompression, but not the rest of the potential benefits of compressed writeback.
For zswap, decoupling zswap and disk swap is a pre-requisite (otherwise every zswap slot occupy a PAGE_SIZE slot in the swapfile anyway).
Then, we have two alternatives. Either we implement a small-slot allocator for swapfile-infra, or we writeback a full backing page for compressed memory. The second option is a bit more straightforward, but then we lose relative age of these objects - a backing page might combine very recent compressed pages and very old compressed pages.
These approaches have different performance tradeoffs and need to be evaluated. But anyway this is future work.
Nhat Pham <[email protected]>:
Quoted 1 line
I'm aware of that work. It's an improvement, but my understanding is:
Thank you for answer!
Also, is it possible to have checksummed swap?
I want to have checksummed swap to be protected from disk bit-rot (I already have ECC memory, so RAM is protected).
And hibernation image should be protected, too.
I tried to put swap on top of dm-integrity, but this is incompatible with hibernation in mainline kernel.
Signature · 1 line
Askar Safin
YoungJun Park
reviewerQuoted 7 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Hi Nhat,
I wanted to fully understand the patches before asking questions, but reviewing everything takes time, and I didn't want to miss the timing. So let me share some thoughts and ask about your direction.
These are the perspectives I'm coming from:
Pros:
- The architecture is very clean.
- Zero entries currently consume swap space, which can prevent actual swap usage in some cases.
- It resolves zswap's dependency on swap device size.
- And so on.
Cons:
- An additional virtual allocation step is introduced per every swap.
- not easy to merge (change swap infrastructure totally?)
To address the cons, I think if we can demonstrate that the benefits always outweigh the costs, it could fully replace the existing mechanism. However, if this can be applied selectively, we get only the pros without the cons.
1. Modularization
You removed CONFIG_* and went with a unified approach. I recall you were also considering a module-based structure at some point. What are your thoughts on that direction?
If we take that approach, we could extend the recent swap ops
patchset (https://lore.kernel.org/linux-mm/[email protected]/)
as follows:
- Make vswap a swap module
- Have cluster allocation functions reside in swapops
- Enable vswap through swapon
I think this could result in a similar structure. An additional benefit would be that it enables various configurations:
- vswap + regular swap together
- vswap only
- And other combinations
And merge is not that hard. it is not the total change of swap infra structure.
But, swapoff fastness might disappear? it is not that critical as I think.
2. Flash-friendly swap integration (for my use case)
I've been thinking about the flash-friendly swap concept that I mentioned before and recently proposed:
(https://lore.kernel.org/linux-mm/aZW0voL4MmnMQlaR@yjaykim-PowerEdge-T330/)
One of its core functions requires buffering RAM-swapped pages and writing them sequentially at an appropriate time -- not immediately, but in proper block-sized units, sequentially.
This means allocated offsets must essentially be virtual, and physical offsets need to be managed separately at the actual write time.
If we integrate this into the current vswap, we would either need vswap itself to handle the sequential writes (bypassing the physical device and receiving pages directly), or swapon a swap device and have vswap obtain physical offsets from it. But since those offsets cannot be used directly (due to buffering and sequential write requirements), they become virtual too, resulting in:
virtual -> virtual -> physical
This triple indirection is not ideal.
However, if the modularization from point 1 is achieved and vswap acts as a swap device itself, then we can cleanly establish a:
virtual -> physical
relationship within it.
I noticed you seem to be exploring collaboration with Kairui as well. I'm curious whether you have a compromise direction in mind, or if you plan to stick with the current approach.
P.S. I definitely want to review the vswap code in detail when I get the time. great work and code.
Thanks,
Youngjun Park
YoungJun Park
reviewerQuoted 25 lines · Nhat Pham
Interesting. Normally "lots of zero-filled page" is a very beneficial case for vswap. You don't need a swapfile, or any zram/zswap metadata overhead - it's a native swap backend. If production workload has this many zero-filled pages, I think the numbers of vswap would be much less alarming - perhaps even matching memory overhead because you don't need to maintain a zram entry metadata (it's at least 2 words per zram entry right?), while there's no reverse map overhead induced (so it's 24 bytes on both side), and no need to do zram-side locking :)
So I was surprised to see that it's not working out very well here. I checked the implementation of memhog - let me know if this is wrong place to look:
https://man7.org/linux/man-pages/man8/memhog.8.html
https://github.com/numactl/numactl/blob/master/memhog.c#L52I think this is what happened here: memhog was populating the memory
0xff, which triggers the full overhead of a swapfile-backed swap entry because even though it's "same-filled" it's not zero-filled! I was following Usama's observation - "less than 1% of the same-filled pages were non-zero" - and so I only handled the zero-filled case here:
Quoted 8 lines
This sounds a bit artificial IMHO - as Usama pointed out above, I think most samefilled pages are zero pages, in real production workloads. However, if you think there are real use cases with a lot of non-zero samefilled pages, please let me know I can fix this real quick. We can support this in vswap with zero extra metadata overhead
- change theVSWAP_ZEROswap entry type toVSWAP_SAME_FILLED, then use the backend field to store that value. I can send you a patch if you're interested.
This brings back memories -- I'm pretty sure we talked about exactly this at LPC. Our custom swap device already handles both zero-filled and same-filled pages on its own, so what we really wanted was a way to tell the swap layer "just skip the detection and let it through."
I looked at two approaches back then but never submitted either:
- A per-swap_info flag to opt out of zero/same-filled handling. But this felt wrong from vswap's perspective -- if even one device opts out of the zeromap, the model gets messy.
- Revisiting Usama's patch 2 approach.
Sounded good in theory, but as you said,
it's not as simple to verify in practice. And it is more clean design swapout time zero check as I see. So, I gave up on it.
Seeing this come up again is actually kind of nice :)
One thought -- maybe a compile-time CONFIG or a boot param to control the scope? e.g. zero-only, same-filled, or disabled. That way vendors like us just turn it off, and setups like Kairui's can opt into broader detection. Just an idea though -- open to other approaches if you have something in mind.
Thanks,
Youngjun Park
Nhat Pham
maintainerQuoted 54 lines · YoungJun Park
Quoted 25 lines · Nhat Pham
Interesting. Normally "lots of zero-filled page" is a very beneficial case for vswap. You don't need a swapfile, or any zram/zswap metadata overhead - it's a native swap backend. If production workload has this many zero-filled pages, I think the numbers of vswap would be much less alarming - perhaps even matching memory overhead because you don't need to maintain a zram entry metadata (it's at least 2 words per zram entry right?), while there's no reverse map overhead induced (so it's 24 bytes on both side), and no need to do zram-side locking :)
So I was surprised to see that it's not working out very well here. I checked the implementation of memhog - let me know if this is wrong place to look:
https://man7.org/linux/man-pages/man8/memhog.8.html
https://github.com/numactl/numactl/blob/master/memhog.c#L52I think this is what happened here: memhog was populating the memory
0xff, which triggers the full overhead of a swapfile-backed swap entry because even though it's "same-filled" it's not zero-filled! I was following Usama's observation - "less than 1% of the same-filled pages were non-zero" - and so I only handled the zero-filled case here:Quoted 8 lines
This sounds a bit artificial IMHO - as Usama pointed out above, I think most samefilled pages are zero pages, in real production workloads. However, if you think there are real use cases with a lot of non-zero samefilled pages, please let me know I can fix this real quick. We can support this in vswap with zero extra metadata overhead
- change theVSWAP_ZEROswap entry type toVSWAP_SAME_FILLED, then use the backend field to store that value. I can send you a patch if you're interested.This brings back memories -- I'm pretty sure we talked about exactly this at LPC. Our custom swap device already handles both zero-filled and same-filled pages on its own, so what we really wanted was a way to tell the swap layer "just skip the detection and let it through."
I looked at two approaches back then but never submitted either:
- A per-swap_info flag to opt out of zero/same-filled handling. But this felt wrong from vswap's perspective -- if even one device opts out of the zeromap, the model gets messy.
- Revisiting Usama's patch 2 approach.
Sounded good in theory, but as you said,
it's not as simple to verify in practice. And it is more clean design swapout time zero check as I see. So, I gave up on it.
Quoted 7 lines
Seeing this come up again is actually kind of nice :)
One thought -- maybe a compile-time CONFIG or a boot param to control the scope? e.g. zero-only, same-filled, or disabled. That way vendors like us just turn it off, and setups like Kairui's can opt into broader detection. Just an idea though -- open to other approaches if you have something in mind.
Yeah for vswap it's probably going to be a CONFIG or boot param.
But in the status quo, we can always add a swapfile flag. That one should work already, right?
Thanks for thinking about it :) FWIW I think zero check is really cheap, but yeah it's just wasted work.
(ZRAM folks - do you feel the overhead here?)
Quoted 4 lines
Thanks,
Youngjun Park
Nhat Pham
maintainerQuoted 16 lines · YoungJun Park
Quoted 7 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Hi Nhat,
I wanted to fully understand the patches before asking questions, but reviewing everything takes time, and I didn't want to miss the timing. So let me share some thoughts and ask about your direction.
Quoted 6 lines
These are the perspectives I'm coming from:
Pros:
- The architecture is very clean.
- Zero entries currently consume swap space, which can prevent actual swap usage in some cases.
Yeah not just zero entries. Compressed entries consuming a static space also makes no sense to me.
Quoted 12 lines
- It resolves zswap's dependency on swap device size.
- And so on.Cons:
- An additional virtual allocation step is introduced per every swap.
- not easy to merge (change swap infrastructure totally?)To address the cons, I think if we can demonstrate that the benefits always outweigh the costs, it could fully replace the existing mechanism. However, if this can be applied selectively, we get only the pros without the cons.
Quoted 6 lines
1. Modularization
You removed CONFIG_* and went with a unified approach. I recall you were also considering a module-based structure at some point. What are your thoughts on that direction?
The CONFIG-based approach was a huge mess. It makes me not want to look at the code, and I'm the author :)
Quoted 6 lines
If we take that approach, we could extend the recent swap ops
patchset (https://lore.kernel.org/linux-mm/[email protected]/)
as follows:
- Make vswap a swap module
- Have cluster allocation functions reside in swapops
- Enable vswap through swapon
Hmmmmm.
Quoted 11 lines
I think this could result in a similar structure. An additional benefit would be that it enables various configurations:
- vswap + regular swap together
- vswap only
- And other combinationsAnd merge is not that hard. it is not the total change of swap infra structure.
But, swapoff fastness might disappear? it is not that critical as I think.
Yeah that's not critical. It's a cool beans optimization but nobody does swapoff and expect fast ;)
(It is a lot cleaner tho but again not my first priority).
Quoted 25 lines
2. Flash-friendly swap integration (for my use case)
I've been thinking about the flash-friendly swap concept that I mentioned before and recently proposed:
(https://lore.kernel.org/linux-mm/aZW0voL4MmnMQlaR@yjaykim-PowerEdge-T330/)One of its core functions requires buffering RAM-swapped pages and writing them sequentially at an appropriate time -- not immediately, but in proper block-sized units, sequentially.
This means allocated offsets must essentially be virtual, and physical offsets need to be managed separately at the actual write time.
If we integrate this into the current vswap, we would either need vswap itself to handle the sequential writes (bypassing the physical device and receiving pages directly), or swapon a swap device and have vswap obtain physical offsets from it. But since those offsets cannot be used directly (due to buffering and sequential write requirements), they become virtual too, resulting in:
virtual -> virtual -> physical
Quoted 7 lines
This triple indirection is not ideal.
However, if the modularization from point 1 is achieved and vswap acts as a swap device itself, then we can cleanly establish a:
virtual -> physical
I read that thread sometimes ago. Some remarks:
1. I think Christoph has a point. Seems like some of your ideas ( are broadly applicable to swap in general. Maybe fixing swap infra generally would make a lot of sense?
2. Why do we need to do two virtual layers here? For example, If you want to buffer multiple swap outs and turn them into a sequential request, you can:
a. Allocate virtual swap space for them as you wish. They don't even need to be sequential.
b. At swap_writeout() time, don't allocate physical swap space for them right away. Instead, accumulate them into a buffer. You can add a new virtual swap entry type to flag it if necessary.
c. Once that buffer reaches a certain size, you can now allocate contiguous physical swap space for them. Then flush etc. You can flush at swap_writeout() time, or use a dedicated threads etc.
Deduplication sounds like something that should live at a lower layer
- I was thinking about it for zswap/zsmalloc back then. I mean, I assume you don't want content sharing across different swap media? :) Something along the line of:
1. Maintain an content index for swapped out pages.
2. For the swap media that support deduplication, you'll need to add some sort of reference count (more overhead ew).
3. Each time we swapped out, we can content-check to see if the same piece of conent has been swapped out before. If so, set the vswap backend to the physical location of the data, increment some sort of reference count (perhaps we can use swap count) of the older entry, and have the swap type point to it.
But have you considered the implications of sharing swap data like this? I need to read the paper you cite - seems like a potential fun read. But what happen when these two pages that share the content belong to two different cgroups? How does the charging/uncharging/charge transferring story work? That's one of the things that made me pause when I wanted to implement deduplication for zswap/zsmalloc. Zram does not charge memory towards cgroup, but zswap does, so we'll need to handle this somehow, and at that point all the complexity might no longer be worth it.
Quoted 6 lines
relationship within it.
I noticed you seem to be exploring collaboration with Kairui as well. I'm curious whether you have a compromise direction in mind, or if you plan to stick with the current approach.
I do have some ideas while discussing with Kairui. I'm still figuring that part out though.
What I'm working on right now is tracing all the inherent overhead of swap virtualization, regardless of the method we use.
Quoted 7 lines
P.S. I definitely want to review the vswap code in detail when I get the time. great work and code.Thanks,
Youngjun Park
YoungJun Park
reviewerOn Sat, Apr 11, 2026 at 06:40:44PM -0700, Nhat Pham wrote:
Hello Nhat!
Quoted 10 lines
Quoted 6 lines
1. Modularization
You removed CONFIG_* and went with a unified approach. I recall you were also considering a module-based structure at some point. What are your thoughts on that direction?
The CONFIG-based approach was a huge mess. It makes me not want to look at the code, and I'm the author :)
Quoted 8 lines
Quoted 6 lines
If we take that approach, we could extend the recent swap ops
patchset (https://lore.kernel.org/linux-mm/[email protected]/)
as follows:
- Make vswap a swap module
- Have cluster allocation functions reside in swapops
- Enable vswap through swaponHmmmmm.
I think this would be a happy world, but I wonder what others think. Anyway, I'm looking forward to the future direction.
Quoted 30 lines
Quoted 30 lines
2. Flash-friendly swap integration (for my use case)
I've been thinking about the flash-friendly swap concept that I mentioned before and recently proposed:
(https://lore.kernel.org/linux-mm/aZW0voL4MmnMQlaR@yjaykim-PowerEdge-T330/)One of its core functions requires buffering RAM-swapped pages and writing them sequentially at an appropriate time -- not immediately, but in proper block-sized units, sequentially.
This means allocated offsets must essentially be virtual, and physical offsets need to be managed separately at the actual write time.
If we integrate this into the current vswap, we would either need vswap itself to handle the sequential writes (bypassing the physical device and receiving pages directly), or swapon a swap device and have vswap obtain physical offsets from it. But since those offsets cannot be used directly (due to buffering and sequential write requirements), they become virtual too, resulting in:
virtual -> virtual -> physical
This triple indirection is not ideal.
However, if the modularization from point 1 is achieved and vswap acts as a swap device itself, then we can cleanly establish a:
Quoted 7 lines
Quoted 1 line
virtual -> physical
I read that thread sometimes ago. Some remarks:
1. I think Christoph has a point. Seems like some of your ideas ( are broadly applicable to swap in general. Maybe fixing swap infra generally would make a lot of sense?
Broadly speaking, there are two main ideas:
1. Swap I/O buffering (which is also tied to cluster management issues)
2. Deduplication
Are you leaning towards the view that these two should be placed in a higher layer?
Quoted 7 lines
2. Why do we need to do two virtual layers here? For example, If you want to buffer multiple swap outs and turn them into a sequential request, you can:
a. Allocate virtual swap space for them as you wish. They don't even need to be sequential.
Quoted 7 lines
b. At
swap_writeout()time, don't allocate physical swap space for them right away. Instead, accumulate them into a buffer. You can add a new virtual swap entry type to flag it if necessary.c. Once that buffer reaches a certain size, you can now allocate contiguous physical swap space for them. Then flush etc. You can flush at
swap_writeout()time, or use a dedicated threads etc.
I initially thought implementing this in vswap would be complicated (due to the ripple effects of altering behavior at swap_writeout timing), but it seems entirely possible!
1. We could change the behavior (e.g., buffering) at vswap_alloc_swap_slot timing by checking things like the si type.
2. Additionally, if we can handle the cluster data structures and mechanisms in the swap_info_struct privately, a virtual-to-physical one-direction approach seems feasible.
(Come to think of it, it might be better to refactor the infra to let other modules handle this, potentially removing the swap_info_struct mechanism entirely. Just imagination ;) )
Quoted 7 lines
Deduplication sounds like something that should live at a lower layer
- I was thinking about it for zswap/zsmalloc back then. I mean, I assume you don't want content sharing across different swap media? :) Something along the line of:1. Maintain an content index for swapped out pages.
Quoted 8 lines
2. For the swap media that support deduplication, you'll need to add some sort of reference count (more overhead ew).
3. Each time we swapped out, we can content-check to see if the same piece of conent has been swapped out before. If so, set the vswap backend to the physical location of the data, increment some sort of reference count (perhaps we can use swap count) of the older entry, and have the swap type point to it.
As for reference count management, applying it loosely might be a good approach. Instead of strictly managing the lifecycle of the dedup contents with refcounts, we could just periodically clean up the hash. This also has the benefit of reducing I/O for the same swap content compared to deleting it immediately.
Quoted 9 lines
But have you considered the implications of sharing swap data like this? I need to read the paper you cite - seems like a potential fun read. But what happen when these two pages that share the content belong to two different cgroups? How does the charging/uncharging/charge transferring story work? That's one of the things that made me pause when I wanted to implement deduplication for zswap/zsmalloc. Zram does not charge memory towards cgroup, but zswap does, so we'll need to handle this somehow, and at that point all the complexity might no longer be worth it.
Since our private swap device is similar to ZRAM, I hadn't considered the charging aspect. It is indeed a complex issue.
If it goes into ZSWAP, there would definitely be a clear advantage of seeing dedup benefits across all swap devices. It's a technically interesting area, and I'd like to discuss it in a separate thread if I have more ideas or thoughts.
Just a thought that comes to mind here: if vswap becomes modularized, how about doing memcg charging for this entire area?
(Come to think of it, to fully benefit from vswap modularization, zswap should also be applied within its scope.)
Best regards,
Youngjun Park
YoungJun Park
reviewerQuoted 63 lines · Nhat Pham
Quoted 54 lines · YoungJun Park
Quoted 25 lines · Nhat Pham
Interesting. Normally "lots of zero-filled page" is a very beneficial case for vswap. You don't need a swapfile, or any zram/zswap metadata overhead - it's a native swap backend. If production workload has this many zero-filled pages, I think the numbers of vswap would be much less alarming - perhaps even matching memory overhead because you don't need to maintain a zram entry metadata (it's at least 2 words per zram entry right?), while there's no reverse map overhead induced (so it's 24 bytes on both side), and no need to do zram-side locking :)
So I was surprised to see that it's not working out very well here. I checked the implementation of memhog - let me know if this is wrong place to look:
https://man7.org/linux/man-pages/man8/memhog.8.html
https://github.com/numactl/numactl/blob/master/memhog.c#L52I think this is what happened here: memhog was populating the memory
0xff, which triggers the full overhead of a swapfile-backed swap entry because even though it's "same-filled" it's not zero-filled! I was following Usama's observation - "less than 1% of the same-filled pages were non-zero" - and so I only handled the zero-filled case here:Quoted 8 lines
This sounds a bit artificial IMHO - as Usama pointed out above, I think most samefilled pages are zero pages, in real production workloads. However, if you think there are real use cases with a lot of non-zero samefilled pages, please let me know I can fix this real quick. We can support this in vswap with zero extra metadata overhead
- change theVSWAP_ZEROswap entry type toVSWAP_SAME_FILLED, then use the backend field to store that value. I can send you a patch if you're interested.This brings back memories -- I'm pretty sure we talked about exactly this at LPC. Our custom swap device already handles both zero-filled and same-filled pages on its own, so what we really wanted was a way to tell the swap layer "just skip the detection and let it through."
I looked at two approaches back then but never submitted either:
- A per-swap_info flag to opt out of zero/same-filled handling. But this felt wrong from vswap's perspective -- if even one device opts out of the zeromap, the model gets messy.
- Revisiting Usama's patch 2 approach.
Sounded good in theory, but as you said,
it's not as simple to verify in practice. And it is more clean design swapout time zero check as I see. So, I gave up on it.Quoted 7 lines
Seeing this come up again is actually kind of nice :)
One thought -- maybe a compile-time CONFIG or a boot param to control the scope? e.g. zero-only, same-filled, or disabled. That way vendors like us just turn it off, and setups like Kairui's can opt into broader detection. Just an idea though -- open to other approaches if you have something in mind.
Quoted 4 lines
Yeah for vswap it's probably going to be a CONFIG or boot param.
But in the status quo, we can always add a swapfile flag. That one should work already, right?
I'm a bit hesitant about the swapfile flag approach. If vswap gets merged, handling devices with this flag set might complicate the vswap design.
Moreover, exposing a new swap flag to the user interface (e.g., at swapon) raises concerns about backward compatibility. Do you think that would be safe?
Since our use case isn't very common, we just need a simple knob to tune it. That's why I still prefer a boot param or CONFIG approach.
Thanks :D
Youngjun Park
Quoted 1 line · YoungJun Park
Hi All,
Quoted 18 lines · Nhat Pham
Quoted 17 lines
Quoted 6 lines
1. Modularization
You removed CONFIG_* and went with a unified approach. I recall you were also considering a module-based structure at some point. What are your thoughts on that direction?
The CONFIG-based approach was a huge mess. It makes me not want to look at the code, and I'm the author :)
Quoted 6 lines
If we take that approach, we could extend the recent swap ops
patchset (https://lore.kernel.org/linux-mm/[email protected]/)
as follows:
- Make vswap a swap module
- Have cluster allocation functions reside in swapops
- Enable vswap through swapon
Quoted 5 lines
Quoted 1 line
Hmmmmm.
I think this would be a happy world, but I wonder what others think. Anyway, I'm looking forward to the future direction.
Yeah, I agree with this.
And I do think swapoff of the virtual space itself is also necessary, we really need a failsafe, e.g. a clean way to drop the swap cache and data, kind of like drop_caches or shrinker fs are commonly used.
Quoted 38 lines
Quoted 30 lines
Quoted 30 lines
2. Flash-friendly swap integration (for my use case)
I've been thinking about the flash-friendly swap concept that I mentioned before and recently proposed:
(https://lore.kernel.org/linux-mm/aZW0voL4MmnMQlaR@yjaykim-PowerEdge-T330/)One of its core functions requires buffering RAM-swapped pages and writing them sequentially at an appropriate time -- not immediately, but in proper block-sized units, sequentially.
This means allocated offsets must essentially be virtual, and physical offsets need to be managed separately at the actual write time.
If we integrate this into the current vswap, we would either need vswap itself to handle the sequential writes (bypassing the physical device and receiving pages directly), or swapon a swap device and have vswap obtain physical offsets from it. But since those offsets cannot be used directly (due to buffering and sequential write requirements), they become virtual too, resulting in:
virtual -> virtual -> physical
This triple indirection is not ideal.
However, if the modularization from point 1 is achieved and vswap acts as a swap device itself, then we can cleanly establish a:
Quoted 7 lines
Quoted 1 line
virtual -> physical
I read that thread sometimes ago. Some remarks:
1. I think Christoph has a point. Seems like some of your ideas ( are broadly applicable to swap in general. Maybe fixing swap infra generally would make a lot of sense?
Quoted 6 lines
Broadly speaking, there are two main ideas:
1. Swap I/O buffering (which is also tied to cluster management issues)
2. DeduplicationAre you leaning towards the view that these two should be placed in a higher layer?
IMHO the swap infra should be doing less, not more, so we can have more flexible design, and different backends can implement their own way to manage the data and layer. e.g. Having one backend being flash friendly and it can do this without caring or affecting other devices or backends.
Quoted 4 lines
If it goes into ZSWAP, there would definitely be a clear advantage of seeing dedup benefits across all swap devices. It's a technically interesting area, and I'd like to discuss it in a separate thread if I have more ideas or thoughts.
Just branstorm... Why don't we just merge these identical pages like KSM? Maybe at least zero folios might benefit a lot if we keep them mapped as RO instead of recording them in swap, seems better in the long term?
Quoted 11 lines · Nhat Pham
Quoted 5 lines
However, if the modularization from point 1 is achieved and vswap acts as a swap device itself, then we can cleanly establish a:
virtual -> physical
I read that thread sometimes ago. Some remarks:
1. I think Christoph has a point. Seems like some of your ideas ( are broadly applicable to swap in general. Maybe fixing swap infra generally would make a lot of sense?
I think a first step would be a dump of that code, even if it is against an old kernel so that everyone knows what we are talking about.
Quoted 7 lines
2. Why do we need to do two virtual layers here? For example, If you want to buffer multiple swap outs and turn them into a sequential request, you can:
a. Allocate virtual swap space for them as you wish. They don't even need to be sequential.
Quoted 7 lines
b. At
swap_writeout()time, don't allocate physical swap space for them right away. Instead, accumulate them into a buffer. You can add a new virtual swap entry type to flag it if necessary.c. Once that buffer reaches a certain size, you can now allocate contiguous physical swap space for them. Then flush etc. You can flush at
swap_writeout()time, or use a dedicated threads etc.
That matches what file systems do with delalloc, where space 2 just adjust an in-memory counter for space reservations.
Quoted 4 lines
Deduplication sounds like something that should live at a lower layer
- I was thinking about it for zswap/zsmalloc back then. I mean, I assume you don't want content sharing across different swap media? :) Something along the line of:
Does dedup in swap really make much sense? If you want to dedup you also want to do that in-memory, i.e. using ksm.
Nhat Pham
maintainerQuoted 79 lines · Kairui Song
Quoted 1 line · YoungJun Park
Hi All,
Quoted 18 lines · Nhat Pham
Quoted 17 lines
Quoted 6 lines
1. Modularization
You removed CONFIG_* and went with a unified approach. I recall you were also considering a module-based structure at some point. What are your thoughts on that direction?
The CONFIG-based approach was a huge mess. It makes me not want to look at the code, and I'm the author :)
Quoted 6 lines
If we take that approach, we could extend the recent swap ops
patchset (https://lore.kernel.org/linux-mm/[email protected]/)
as follows:
- Make vswap a swap module
- Have cluster allocation functions reside in swapops
- Enable vswap through swaponQuoted 5 lines
Quoted 1 line
Hmmmmm.
I think this would be a happy world, but I wonder what others think. Anyway, I'm looking forward to the future direction.
Yeah, I agree with this.
And I do think swapoff of the virtual space itself is also necessary, we really need a failsafe, e.g. a clean way to drop the swap cache and data, kind of like
drop_cachesor shrinker fs are commonly used.Quoted 42 lines
Quoted 30 lines
Quoted 30 lines
2. Flash-friendly swap integration (for my use case)
I've been thinking about the flash-friendly swap concept that I mentioned before and recently proposed:
(https://lore.kernel.org/linux-mm/aZW0voL4MmnMQlaR@yjaykim-PowerEdge-T330/)One of its core functions requires buffering RAM-swapped pages and writing them sequentially at an appropriate time -- not immediately, but in proper block-sized units, sequentially.
This means allocated offsets must essentially be virtual, and physical offsets need to be managed separately at the actual write time.
If we integrate this into the current vswap, we would either need vswap itself to handle the sequential writes (bypassing the physical device and receiving pages directly), or swapon a swap device and have vswap obtain physical offsets from it. But since those offsets cannot be used directly (due to buffering and sequential write requirements), they become virtual too, resulting in:
virtual -> virtual -> physical
This triple indirection is not ideal.
However, if the modularization from point 1 is achieved and vswap acts as a swap device itself, then we can cleanly establish a:
Quoted 7 lines
Quoted 1 line
virtual -> physical
I read that thread sometimes ago. Some remarks:
1. I think Christoph has a point. Seems like some of your ideas ( are broadly applicable to swap in general. Maybe fixing swap infra generally would make a lot of sense?
Broadly speaking, there are two main ideas:
1. Swap I/O buffering (which is also tied to cluster management issues)
2. Deduplication
Quoted 8 lines
Quoted 2 lines
Are you leaning towards the view that these two should be placed in a higher layer?
IMHO the swap infra should be doing less, not more, so we can have more flexible design, and different backends can implement their own way to manage the data and layer. e.g. Having one backend being flash friendly and it can do this without caring or affecting other devices or backends.
I think that's what Youngjun already has, unless I misunderstand his descriptions.
Quoted 10 lines
Quoted 5 lines
If it goes into ZSWAP, there would definitely be a clear advantage of seeing dedup benefits across all swap devices. It's a technically interesting area, and I'd like to discuss it in a separate thread if I have more ideas or thoughts.
Just branstorm... Why don't we just merge these identical pages like KSM? Maybe at least zero folios might benefit a lot if we keep them mapped as RO instead of recording them in swap, seems better in the long term?
That's our preferred approach too. We just didn't manage to get that to work (yet). :)
Nhat Pham
maintainerQuoted 26 lines · Nhat Pham
Quoted 24 lines · Kairui Song
Quoted 22 lines · Nhat Pham
Quoted 19 lines · Kairui Song
Quoted 16 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Changelog:
* v4 -> v5:
* Fix a deadlock inmemcg1_swapout(reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) withlockdep_assert_held(), and use guard(rcu) invswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Hi Kairui! Thanks a lot for the testing big boss :) I will focus on the regression in this patch series - we can talk more about directions in another thread :)
Hi Kairui,
My apologies if I missed your response, but could you share with me your full benchmark suite? It would be hugely useful, not just for this series, but for all swap contributions in the future :) We should do as much homework ourselves as possible :P
And apologies for the delayed response. I kept having to back and forth between regression investigating, and figuring out what was going on with the build setups (I missed some of the CONFIGs you had originally), reducing variance on hosts, etc.
I don't have PMEM, so I have only worked with zram backend so far. I did manage to reproduce the regressions you showed me (albeit at a much smaller gap on certain metrics than your cited numbers, which I suspect is due to zram/pmem difference).
There are two benchmarks that I focused on:
1. Usemem - the exact command I ran is: time ./usemem --init-time -O -y -x -n 1 56G
My host is 32GB, 52 processor(s) / x86_64.
Build real (s) vs base sys (s) tput (KB/s)
free_ms
baseline 175.6 +/- 3.6 — 121.9 +/- 3.3 391,941 +/-
8,333 6,992 +/- 204vss_v5 184.0 +/- 3.9 +4.8% 130.5 +/- 3.8 376,192 +/-
8,581 8,297 +/- 247
(I hope the formatting works, but let me know if it looks weird).
2. Memhog: time memhog 48G
My host for this one is 16 GB, 52 processors, x86_64 too.
Build real (s) vs base sys (s)
baseline 80.5 +/- 1.9 — 62.7 +/- 2.0vss_v5 83.0 +/- 1.8 +3.1% 65.7 +/- 1.8
On both benchmark, I enable MGLRU, to more closely match the setup you had.
Staring at the run logs (and double check with the logs you sent me to make sure it's not just on my system), there are some common patterns I noticed across these runs:
1. Kswapd is slower on the vswap side, which shifts work towards direct reclaim, and makes compaction have to run harder (which has a weird contention through zsmalloc - I can expand further, but this is not vswap-specific, just exacerbated by slower kswapd).
2. Higher swap readahead (albeit with higher hit rate) - this is more of an artifact of the fact that zero swap pages are no longer backed by zram swapfile, which skipped readahead in certain paths. We can ignore this for now, but worth assessing this for fast swap backends in general (zero swap pages, zswap, so on and so forth).
I spent sometimes perf-ing kswapd, and hack the usemem binary a bit so that I can perf the free stage of usemem separately. Most of the vswap-specific overhead lies in the xarray lookups. Some big offenders on top of my mind:
1. Right now, in the physical swap allocator, whenever we have an allocated slot in the range we're checking, we check if that slot is swap-cache-only (i.e no swap count), and if so we try to free it (if swapfile is almost full etc.). This check is cheap if all swap entry metadata live in physical swap layer only, but more expensive when you have to go through another layer of indirection :)
I fixed that by just taking one bit in the reverse map to track swap-cache-only state, which eliminates this without extra space overhead (on top of the existing design).
2. On the free path, in swap_pte_batch(), we check cgroup to make sure that the range we pass to free_swap_and_cache_nr() belongs to the same cgroup, which has a per-PTE overhead for going to the vswap layer. We can make this check once-per range instead, to reduce overhead. Even better - we can skip this check in swap_pte_batch() for the free case, and deferred this check to later on where we already enter vswap cluster lock context :)
With a bunch of changes like that, I closed the gap majorly:
usemem:
Build real (s) vs base sys (s) tput (KB/s)
free_ms
baseline 175.6 +/- 3.6 — 121.9 +/- 3.3 391,941 +/-
8,333 6,992 +/- 204new_opt_v2 179.8 +/- 3.0 +2.4% 126.1 +/- 2.9 382,536 +/-
6,662 7,105 +/- 183
memhog:
Build real (s) vs base sys (s)
baseline 80.5 +/- 1.9 — 62.7 +/- 2.0new_opt_v2 79.9 +/- 1.7 -0.8% 62.4 +/- 1.7
I would like to also point out that, some of this overhead is specific to the swapfile backend case, which is why we don't see this in zswap in the stats I included in V5. Zswap does not require this swap-cache-only dance, because in virtual swap, zswap only needs the virtual swap slot as the index (on top of much more negligible space overhead thanks to zswap tree merging into vswap cluster, no swap charging, no double allocation, etc.).
Anyway, still a small gap. The next idea that I have is inspired by TLB, which cache virtual->physical memory address translation. I added a per-CPU MRU virtual cluster. The idea is that a lot of consecutive swap operations operate on the same range of swap entries - merging these operations of course makes the most sense, but sometimes it's not convenient to do it. The non-vswap, old design sometimes lock the physical swap cluster and expose the swap cluster struct to callers to pass around, but I would like to avoid that if possible :)
With this change, we close the gap even further - exceeding the baseline in average in certain cases, but as you can see it's within noises so I wouldn't conclude too much out of it:
usemem:
Build real (s) vs base sys (s) tput (KB/s)
free_ms
baseline 175.6 +/- 3.6 — 121.9 +/- 3.3 391,941 +/-
8,333 6,992 +/- 204cc_v2 176.4 +/- 5.3 +0.4% 123.6 +/- 5.4 390,405 +/-
12,792 6,987 +/- 296
memhog:
Build real (s) vs base sys (s)
baseline 80.5 +/- 1.9 — 62.7 +/- 2.0cc_v2 79.9 +/- 0.9 -0.8% 62.1 +/- 1.5
The reclaim and compaction stats tell a similar story:
Reclaim / Compaction (usemem)
Metric baselinevss_v5 new_opt_v2 cc_v2
allocstall 167,787 +/- 10,292 170,532 +/-
15,185 169,782 +/- 9,903 168,635 +/- 13,526pgsteal_kswapd 6,932,143 +/- 186,411 6,965,962 +/-
288,323 6,968,188 +/- 286,383 7,038,513 +/- 202,696pgsteal_direct 9,759,350 +/- 480,674 9,978,721 +/-
765,543 9,899,698 +/- 480,781 9,845,668 +/- 544,319swap_ra 82.9 +/- 22.6 5994.8 +/-
2817.5 4976.8 +/- 1484.2 4718.2 +/- 1510.5
pgmigrate 1,029,901 +/- 428,416 1,687,072 +/-
399,505 1,260,451 +/- 202,603 1,144,560 +/- 490,177
Reclaim / Compaction (memhog)
Metric baselinevss_v5 new_opt_v2 cc_v2
allocstall 101,245 +/- 6,271 109,320 +/-
12,180 100,207 +/- 11,053 99,223 +/- 9,905pgsteal_kswapd 8,817,264 +/- 432,519 8,436,548 +/-
265,763 8,728,944 +/- 305,101 8,962,443 +/- 589,012pgsteal_direct 5,408,046 +/- 394,775 5,932,611 +/-
584,873 5,419,891 +/- 551,226 5,349,352 +/- 601,655swap_ra 66.5 +/- 22.8 8589.5 +/-
3325.1 8954.5 +/- 2661.9 8703.1 +/- 1746.6
pgmigrate 239,410 +/- 46,014 277,193 +/-
71,487 320,672 +/- 59,488 243,989 +/- 136,129
You can see that the latter versions gradually restore the behaviors of baseline in terms of reclaim dynamics :)
Some final remarks:
* I still think there's a good chance we can *significantly* close the gap overall between a design with virtual swap and a design without. It's a bit premature to commit to a vswap-optional route (which to be completely honest I'm still not confident is possible to satisfy all of our requirements).
* Regardless of the direction we take, these are all pitfalls that will be problematic for virtual swap design, and more generally some of them will affect any dynamic swap design (which has to go through some sort of indirection or a dynamic data structure like xarray that will induce some amount of lookup overhead). I hope my work here can be useful in this sense too, outside of this specific vswap direction :)
I will clean things up a bit and send you a v6 for further inspection. Once again, I'd like to express my gratitude for your engagement and feedback.
Nhat Pham
maintainerQuoted 6 lines · Nhat Pham
* I still think there's a good chance we can *significantly* close the gap overall between a design with virtual swap and a design without. It's a bit premature to commit to a vswap-optional route (which to be completely honest I'm still not confident is possible to satisfy all of our requirements).
And to further note - these benchmark measure, in effect, purely swap overhead. In a production environment with a lot of non-swap work, as long as the gap is close enough I think we would be fine, even for a hostile case like a fast swapfile-backend (I assume SSD swap's bottleneck will be the IO mostly).
I will stare at your responses to see if there is other benchmark I can play with, but it would be very helpful if you can share your full suite :)
Quoted 7 lines · Nhat Pham
Hi Kairui,
My apologies if I missed your response, but could you share with me your full benchmark suite? It would be hugely useful, not just for this series, but for all swap contributions in the future :) We should do as much homework ourselves as possible :P
Quoted 5 lines
And apologies for the delayed response. I kept having to back and forth between regression investigating, and figuring out what was going on with the build setups (I missed some of the CONFIGs you had originally), reducing variance on hosts, etc.
Hello Nhat!
No worries, I was also thinking about submitting some in tree test for that so testing will be easier, but got really busy with some other issues, series and the incommong LSFMM, will find some time to do that.
Quoted 5 lines
1. Kswapd is slower on the vswap side, which shifts work towards direct reclaim, and makes compaction have to run harder (which has a weird contention through zsmalloc - I can expand further, but this is not vswap-specific, just exacerbated by slower kswapd).
It might be related, e.g. could the dynamic alloc and RCU free of vswap data cause more fragmentation hence more pressure?
Quoted 5 lines
2. Higher swap readahead (albeit with higher hit rate) - this is more of an artifact of the fact that zero swap pages are no longer backed by zram swapfile, which skipped readahead in certain paths. We can ignore this for now, but worth assessing this for fast swap backends in general (zero swap pages, zswap, so on and so forth).
Hmm... That just brought up another question, you can't tell the backend type or properly do readahead until you look down through the virtual layer I guess?
Quoted 12 lines
I spent sometimes perf-ing kswapd, and hack the usemem binary a bit so that I can perf the free stage of usemem separately. Most of the vswap-specific overhead lies in the xarray lookups. Some big offenders on top of my mind:
1. Right now, in the physical swap allocator, whenever we have an allocated slot in the range we're checking, we check if that slot is swap-cache-only (i.e no swap count), and if so we try to free it (if swapfile is almost full etc.). This check is cheap if all swap entry metadata live in physical swap layer only, but more expensive when you have to go through another layer of indirection :)
Quoted 3 lines
I fixed that by just taking one bit in the reverse map to track swap-cache-only state, which eliminates this without extra space overhead (on top of the existing design).
Isn't that HAS_CACHE :) ?
Quoted 3 lines
2. On the free path, in
swap_pte_batch(), we check cgroup to make sure that the range we pass tofree_swap_and_cache_nr()belongs to the same cgroup, which has a per-PTE overhead for going to the vswap layer. We
This might be helpful:
https://lore.kernel.org/linux-mm/[email protected]/
I observed a similar but much smaller issue with the current swap too. Deferring the cgroup lookup to the swap-cache layer, where we already grab the cluster (in a later commit), should reduce a lot of overhead. It requires some unification of allocation though as shown in that series, things will be much easier after that :)
Quoted 2 lines
Anyway, still a small gap. The next idea that I have is inspired by TLB, which cache
virtual->physicalmemory address translation. I added
I think this is getting over complex... You got a mandatory virtual layer, which already comes with some cluster cache inside, and the lower physical allocator has its own cluster cache, and then a new set of cache on top of the virtual layer?
Quoted 8 lines
Some final remarks:
* I still think there's a good chance we can *significantly* close the gap overall between a design with virtual swap and a design without. It's a bit premature to commit to a vswap-optional route (which to be completely honest I'm still not confident is possible to satisfy all of our requirements).
Quoted 7 lines
* Regardless of the direction we take, these are all pitfalls that will be problematic for virtual swap design, and more generally some of them will affect any dynamic swap design (which has to go through some sort of indirection or a dynamic data structure like xarray that will induce some amount of lookup overhead). I hope my work here can be useful in this sense too, outside of this specific vswap direction :)
Glad to know things are getting better! We can definitely work something out. But besides the problem above, I think there are some other concerns that need to be solved too. Good part is I think everyone agrees that some kind of intermediate layer is needed.
Nhat Pham
maintainerQuoted 95 lines · Kairui Song
Quoted 7 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Quoted 9 lines
Changelog:
* v4 -> v5:
* Fix a deadlock inmemcg1_swapout(reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) withlockdep_assert_held(), and use guard(rcu) invswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).I tested the v5 (including the batched-free hotfix) and am still seeing significant regressions in both sequential and concurrent swap workloads
Thanks for the update as I can see It's a lot of thoughtful work. Actually I did run some tests already with your previously posted hotfix based on v3. I didn't update the result because very unfortunately, I still see a major performance regression even with a very simple setup.
BTW there seems a simpler way to reproduce that, just use memhog:
sudo mkswap/dev/pmem0; sudo swapon/dev/pmem0; time memhog 48G; sudo swapoff -aBefore:
(I'm using fish shell on that test machine so this is fish time format):
________________________________________________________Executed in 20.80 secs fish external usr time 5.14 secs 0.00 millis 5.14 secs sys time 15.65 secs 1.17 millis 15.65 secs________________________________________________________
Executed in 21.69 secs fish external
usr time 5.31 secs 725.00 micros 5.31 secs
sys time 16.36 secs 579.00 micros 16.36 secs
________________________________________________________Executed in 21.86 secs fish external usr time 5.39 secs 1.02 millis 5.39 secs sys time 16.46 secs 0.27 millis 16.46 secsAfter:
________________________________________________________
Executed in 30.77 secs fish external
usr time 5.16 secs 767.00 micros 5.16 secs
sys time 25.59 secs 580.00 micros 25.59 secs
________________________________________________________Executed in 37.47 secs fish external usr time 5.48 secs 0.00 micros 5.48 secs sys time 31.98 secs 674.00 micros 31.98 secs ________________________________________________________ Executed in 31.34 secs fish external usr time 5.22 secs 0.00 millis 5.22 secs sys time 26.09 secs 1.30 millis 26.09 secsIt's obviously a lot slower.
pmem may seem rare but SSDs are good at sequential, and memhog uses the same filled page and backend like ZRAM has extremely low overhead for same filled pages. Results with ZRAM are very similar, and many production workloads have massive amounts of samefill memory.
For example on the Android phone I'm using right now at this moment:
# cat /sys/block/zram0/mm_stat 4283899904 1317373036 1370259456 0 1475977216 116457 1991851 87273 1793760 ~450M of samefill page in ZRAM, we may see more on some server workload. And I'm seeing similar memhog results with ZRAM, pmem is just easier to setup and less noisy. also simulates high speed storage.I also ran the previous usemem matrix, which seems better than V3 but still pretty bad:
Test: usemem --init-time -O -n 1 56G, 16G mem, 48G swap, avgs of 8 run. Before:
Throughput (Sum): 528.98 MB/s Throughput (Mean): 526.113333 MB/s Free
Latency: 3037932.888889
After:
Throughput (Sum): 453.74 MB/s Throughput (Mean): 454.875000 MB/s Free
Latency: 5001144.500000 (~10%, 64% slower)I'm not sure why our results differ so much — perhaps different LRU settings, memory pressure ratios, or THP/mTHP configs? Here's my exact config in the attachment. Also includes the full log and info, with all debug options disabled for close to production. I ran it 8 times and just attached the first result log, it's all similar anyway, my test framework reboot the machine after each test run to reduce any potential noise.
Quoted 9 lines
And the above tests are only about sequential performance, concurrent ones seem worse:
Test: usemem --init-time -O -R -n 32 622M, 16G mem, 48G swap, avgs of 8 run. Before:
Throughput (Sum): 5467.51 MB/s Throughput (Mean): 170.04 MB/s Free
Latency: 28648.65
After:
Throughput (Sum): 4914.86 MB/s Throughput (Mean): 152.74 MB/s Free
Latency: 67789.81 (~10%, 230% slower)
For this test case, I took my 16G (a bit less than that technically) 52 cores host, using zram as the backend and MGLRU, for a spin.
Keeping the same parameters as your usemem command, unfortunately, led to massive thrashing (even with baseline kernel) - unfortunately zram still used physical memory so the overcommit level is too large (especially with random access pattern, i.e the -R flag).
I then tried reducing the 622M part to 480M, but the problem with that is VSS5 did not show any regression - probably because the overcommitting is too low, or not enough concurrency. I had to push the concurrency up to 52 workers, allocating 300M each (which is slightly more memory allocated overall than the 480 x 32 case), to finally show the regression you reported. Variance was very big with 8 runs though (what I normally use for usemem these days), so I had to do 20 runs per kernel - fortunately these runs are fast:
Metric baseline vss_v5 new_opt_v2 cc_v2 real (s) 15.0 +/- 0.8 18.3 +/- 1.8 15.1 +/- 1.0 14.7 +/- 1.0 sys (s) 396.4 +/- 31.1 511.9 +/- 60.3 404.1 +/- 34.5 392.4 +/- 39.9 tput (KB/s) 28188 +/- 6996 23287 +/- 6629 27999 +/- 6623 28744 +/- 7015 free (ms) 101.1 +/- 52.4 91.4 +/- 41.5 93.1 +/- 43.8 97.6 +/- 49.5 % real n/a +22.4% +0.7% -1.7% % sys n/a +29.1% +1.9% -1.0% % tput n/a -17.4% -0.7% +2.0% % free n/a -9.6% -7.9% -3.5%
(I realized I mangled the output last time of the "memory reclaim metrics table" table due to auto line break. Let's hope this is better).
Strangely, no free regression. Hmmm.
But real, sys, and throughput regression are real. The optimizations do close the gap to within noise level here too.
Yosry Ahmed
maintainerQuoted 45 lines · Nhat Pham
This patch series is based on 6.19. There are a couple more swap-related changes in mainline that I would need to coordinate with, but I still want to send this out as an update for the regressions reported by Kairui Song in [15]. It's probably easier to just build this thing rather than dig through that series of emails to get the fix patch :)
Changelog:
* v4 -> v5:
* Fix a deadlock inmemcg1_swapout(reported by syzbot [16]).
* Replace VM_WARN_ON(!spin_is_locked()) withlockdep_assert_held(), and use guard(rcu) invswap_cpu_dead
(reported by Peter Zijlstra [17]).
* v3 -> v4:
* Fix poor swap free batching behavior to alleviate a regression (reported by Kairui Song).
* Fix assorted kernel build errors reported by kernel test robots in the case ofCONFIG_SWAP=n.
* RFC v2 -> v3:
* Implement a cluster-based allocation algorithm for virtual swap slots, inspired by Kairui Song and Chris Li's implementation, as well as Johannes Weiner's suggestions. This eliminates the lock contention issues on the virtual swap layer.
* Re-use swap table for the reverse mapping.
* RemoveCONFIG_VIRTUAL_SWAP.
* Reducing the size of the swap descriptor from 48 bytes to 24 bytes, i.e another 50% reduction in memory overhead from v2.
* Remove swap cache and zswap tree and use the swap descriptor for this.
* Remove zeromap, and replace theswap_mapbytemap with 2 bitmaps (one for allocated slots, and one for bad slots).
* Rebase on top of 6.19 (7d0a66e4bb9081d75c82ec4957c50034cb0ea449)
* Update cover letter to include new benchmark results and discussion on overhead in various cases.
* RFC v1 -> RFC v2:
* Use a single atomic type (swap_refs) for reference counting purpose. This brings the size of the swap descriptor from 64 B down to 48 B (25% reduction). Suggested by Yosry Ahmed.
* Zeromap bitmap is removed in the virtual swap implementation. This saves one bit per physical swapfile slot.
* Rearrange the patches and the code change to make things more reviewable. Suggested by Johannes Weiner.
* Update the cover letter a bit.
Quoted 5 lines
This patch series implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).
Unfortuantely, I haven't been able to keep up with virtual swap and swap table development, as my time is mostly being spent elsewhere these days. I do have a question tho, which might have already been answered or is too naive/stupid -- so apologies in advance.
Given the recent advancements in the swap table and that most metadata and the swap cache are already being pulled into it, is it possible to use the swap table in the virtual swap layer instead of the xarray?
Basically pull the swap table one layer higher, and have it point to either a zswap entry or a physical swap slot (or others in the future)? If my understanding is correct, we kinda get the best of both worlds and reuse the integration already done by the swap table with the swap cache, as well as the lock paritioning.
In this world, the clusters would be in the virtual swap space, and we'd create the clusters on-demand as needed.
Does this even work or make the least amount of sense (I guess the question is for both Nhat and Kairui)?
Quoted 9 lines · Yosry Ahmed
Quoted 6 lines · Nhat Pham
This patch series implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).
Quoted 4 lines
Unfortuantely, I haven't been able to keep up with virtual swap and swap table development, as my time is mostly being spent elsewhere these days. I do have a question tho, which might have already been answered or is too naive/stupid -- so apologies in advance.
Hi Yosry,
Not a stupid question at all—it's actually spot on. :)
Quoted 11 lines
Given the recent advancements in the swap table and that most metadata and the swap cache are already being pulled into it, is it possible to use the swap table in the virtual swap layer instead of the xarray?
Basically pull the swap table one layer higher, and have it point to either a zswap entry or a physical swap slot (or others in the future)? If my understanding is correct, we kinda get the best of both worlds and reuse the integration already done by the swap table with the swap cache, as well as the lock paritioning.
Quoted 6 lines
In this world, the clusters would be in the virtual swap space, and we'd create the clusters on-demand as needed.
Does this even work or make the least amount of sense (I guess the question is for both Nhat and Kairui)?
Yes, this absolutely works. In fact, I previously posted a working RFC based on this idea. In that series, clusters are dynamically allocated, allowing the swap space to be dynamically sized (essentially infinite) while reusing all the existing infrastructure:
https://lore.kernel.org/all/[email protected]/
The only missing pieces are a few helpers like folio_realloc_swap() and folio_migrate_swap() for lower layer allocation and migration. I prototyped this locally and it wasn't difficult to implement. Furthermore, this approach works perfectly with YoungJun's tiering work with zero conflicts, the dynamic layer can be runtime or per-memcg optional.
To move this forward, I've stripped out the RFC features and memcg behavior changes, and recently sent a V3 that focuses purely on the infrastructure. It introduces no behavior changes or new features, just optimizations.
It cleans up a lot of allocation and ordering, as well as memcg swap lookups. Since some of these problems were also observed in the vss discussion, I think this will make things easier for all of us:
https://lore.kernel.org/all/[email protected]/
Yosry Ahmed
maintainerQuoted 37 lines · Kairui Song
Quoted 9 lines · Yosry Ahmed
Quoted 6 lines · Nhat Pham
This patch series implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).
Quoted 4 lines
Unfortuantely, I haven't been able to keep up with virtual swap and swap table development, as my time is mostly being spent elsewhere these days. I do have a question tho, which might have already been answered or is too naive/stupid -- so apologies in advance.
Hi Yosry,
Not a stupid question at all—it's actually spot on. :)
Quoted 11 lines
Given the recent advancements in the swap table and that most metadata and the swap cache are already being pulled into it, is it possible to use the swap table in the virtual swap layer instead of the xarray?
Basically pull the swap table one layer higher, and have it point to either a zswap entry or a physical swap slot (or others in the future)? If my understanding is correct, we kinda get the best of both worlds and reuse the integration already done by the swap table with the swap cache, as well as the lock paritioning.
Quoted 6 lines
In this world, the clusters would be in the virtual swap space, and we'd create the clusters on-demand as needed.
Does this even work or make the least amount of sense (I guess the question is for both Nhat and Kairui)?
Quoted 5 lines
Yes, this absolutely works. In fact, I previously posted a working RFC based on this idea. In that series, clusters are dynamically allocated, allowing the swap space to be dynamically sized (essentially infinite) while reusing all the existing infrastructure:
https://lore.kernel.org/all/[email protected]/
There are a few aspects that I don't agree with in this RFC, and I think Nhat and Johannes raised most of them. Mostly that I don't want to expose ghost swapfiles or similar to userspace.
I think userspace's view of swapfiles should remain the same and reflect the physical swap slots. The virtual swap layer should be completely transparent in this case. Userspace shouldn't need to configure it in any way.
In an ideal world, the only noticeable change from userspace is that with zswap, compressed pages would stop using slots in the swapfile and charging the memcg for them -- and that zswap would work even without a swapfile, by just enabling it. This is admittedly a user-visible behavioral change, but I am hoping that's a good one that we can live with.
If there are real concerns about this, we can discuss things like a knob or config option to keep charging zswap pages as swap slots (ew..) or only allow zswap with a real swapfile (double ew..). But I am really hoping we can get away with changing the semantics without doing this.
We can add extra interfaces for virtual swap as needed, e.g. virtual swapoff that you mentioned to clear the swap cache, or stats about the virtual swap space (which translates to memory overhead).
There are also a few missing pieces like different memcg charging, but these were already pointed out, and we can figure them out as we go.
Nhat/Johannes, WDYT? Am I missing somthing?
Quoted 13 lines
The only missing pieces are a few helpers like
folio_realloc_swap()andfolio_migrate_swap()for lower layer allocation and migration. I prototyped this locally and it wasn't difficult to implement. Furthermore, this approach works perfectly with YoungJun's tiering work with zero conflicts, the dynamic layer can be runtime or per-memcg optional.To move this forward, I've stripped out the RFC features and memcg behavior changes, and recently sent a V3 that focuses purely on the infrastructure. It introduces no behavior changes or new features, just optimizations.
Quoted 4 lines
It cleans up a lot of allocation and ordering, as well as memcg swap lookups. Since some of these problems were also observed in the vss discussion, I think this will make things easier for all of us:
https://lore.kernel.org/all/[email protected]/
Yeah I saw that (but didn't really have time to do anything else about it). Splitting this out is definitely the right thing to do, and the series looks great from a very high level. Awesome work, as usual :)
Quoted 45 lines · Yosry Ahmed
Quoted 37 lines · Kairui Song
Quoted 9 lines · Yosry Ahmed
Quoted 6 lines · Nhat Pham
This patch series implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).
Quoted 4 lines
Unfortuantely, I haven't been able to keep up with virtual swap and swap table development, as my time is mostly being spent elsewhere these days. I do have a question tho, which might have already been answered or is too naive/stupid -- so apologies in advance.
Hi Yosry,
Not a stupid question at all—it's actually spot on. :)
Quoted 11 lines
Given the recent advancements in the swap table and that most metadata and the swap cache are already being pulled into it, is it possible to use the swap table in the virtual swap layer instead of the xarray?
Basically pull the swap table one layer higher, and have it point to either a zswap entry or a physical swap slot (or others in the future)? If my understanding is correct, we kinda get the best of both worlds and reuse the integration already done by the swap table with the swap cache, as well as the lock paritioning.
Quoted 6 lines
In this world, the clusters would be in the virtual swap space, and we'd create the clusters on-demand as needed.
Does this even work or make the least amount of sense (I guess the question is for both Nhat and Kairui)?
Quoted 5 lines
Yes, this absolutely works. In fact, I previously posted a working RFC based on this idea. In that series, clusters are dynamically allocated, allowing the swap space to be dynamically sized (essentially infinite) while reusing all the existing infrastructure:
https://lore.kernel.org/all/[email protected]/
Quoted 8 lines
There are a few aspects that I don't agree with in this RFC, and I think Nhat and Johannes raised most of them. Mostly that I don't want to expose ghost swapfiles or similar to userspace.
I think userspace's view of swapfiles should remain the same and reflect the physical swap slots. The virtual swap layer should be completely transparent in this case. Userspace shouldn't need to configure it in any way.
That approach is definitely doable. For example, with that RFC we could simply drop the interface I introduced and enable it via a different knob, and that would be very close to it. :)
Using a swapfile to represent the virtual layer externally just made it more flexible. I agree that the RFC design was a bit confusing and could be improved. There is no technical difficulty in hiding it from userspace; it's mostly a design choice. And even if we don't use a swapfile to represent it internally, all the other infrastructure can still be reused without much modification.
Using a swapfile does have its benefits, though. For example, the virtual layer could act as an ordinary tier following YoungJun's design:
https://lore.kernel.org/linux-mm/[email protected]/
It also means we wouldn't need to introduce things like a new, virtual-specific swapoff mechanism.
Quoted 6 lines
In an ideal world, the only noticeable change from userspace is that with zswap, compressed pages would stop using slots in the swapfile and charging the memcg for them -- and that zswap would work even without a swapfile, by just enabling it. This is admittedly a user-visible behavioral change, but I am hoping that's a good one that we can live with.
Totally agree with the ideal end goal for zswap. just not sure if that's the right place to start for this usage, zswap doesn't always apply. For instance, we have SSDs with built-in compression, software-based storage stacks with built-in compression and deduplication, swap over RDMA, and, most notably, ZRAM users. They don't necessarily need zswap or a virtual layer, and the upper layer better be as much simplified as possible.
Quoted 8 lines
If there are real concerns about this, we can discuss things like a knob or config option to keep charging zswap pages as swap slots (ew..) or only allow zswap with a real swapfile (double ew..). But I am really hoping we can get away with changing the semantics without doing this.
We can add extra interfaces for virtual swap as needed, e.g. virtual swapoff that you mentioned to clear the swap cache, or stats about the virtual swap space (which translates to memory overhead).
Good suggestions.
Quoted 8 lines
Quoted 4 lines
It cleans up a lot of allocation and ordering, as well as memcg swap lookups. Since some of these problems were also observed in the vss discussion, I think this will make things easier for all of us:
https://lore.kernel.org/all/[email protected]/Yeah I saw that (but didn't really have time to do anything else about it). Splitting this out is definitely the right thing to do, and the series looks great from a very high level. Awesome work, as usual :)
Thanks!
Yosry Ahmed
maintainerQuoted 15 lines
Quoted 6 lines
Quoted 5 lines
Yes, this absolutely works. In fact, I previously posted a working RFC based on this idea. In that series, clusters are dynamically allocated, allowing the swap space to be dynamically sized (essentially infinite) while reusing all the existing infrastructure:
https://lore.kernel.org/all/[email protected]/Quoted 8 lines
There are a few aspects that I don't agree with in this RFC, and I think Nhat and Johannes raised most of them. Mostly that I don't want to expose ghost swapfiles or similar to userspace.
I think userspace's view of swapfiles should remain the same and reflect the physical swap slots. The virtual swap layer should be completely transparent in this case. Userspace shouldn't need to configure it in any way.
Quoted 6 lines
That approach is definitely doable. For example, with that RFC we could simply drop the interface I introduced and enable it via a different knob, and that would be very close to it. :)
Using a swapfile to represent the virtual layer externally just made it more flexible.
I think it makes it less flexible to be honest. Once it's exposed to userspace there's little we can change about it, and userspace needs to set it up.
Quoted 5 lines
I agree that the RFC design was a bit confusing and
could be improved. There is no technical difficulty in hiding it from userspace; it's mostly a design choice. And even if we don't use a swapfile to represent it internally, all the other infrastructure can still be reused without much modification.
Yeah that's what I was getting at. It doesn't even need to be a swapfile in the kernel, at the very least it should be named differently to avoid confusion with actual swapfiles.
Quoted 4 lines
Using a swapfile does have its benefits, though. For example, the virtual layer could act as an ordinary tier following YoungJun's design:
https://lore.kernel.org/linux-mm/[email protected]/
Hmm I didn't look too closely at this but I don't understand how making it a swapfile helps with tiering? If anything, I think it makes tiering more difficult. For tiering to work, we need an abstraction/redirection layer, such that we don't need to update the page tables (or shmem pagecache) if we demote/promote pages. That is exactly the use case for a virtual swap layer. The page tables point at a virtual swap ID and the backend could change transparently (e.g. for zswap writeback, or tiering).
If we make the virtual layer a swapfile, how do we demote/promote without updating page tables?
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
Quoted 2 lines
It also means we wouldn't need to introduce things like a new, virtual-specific swapoff mechanism.
We don't *need* to introduce this, at least not initially. Only if we have a good use case for it.
Quoted 7 lines
Quoted 6 lines
In an ideal world, the only noticeable change from userspace is that with zswap, compressed pages would stop using slots in the swapfile and charging the memcg for them -- and that zswap would work even without a swapfile, by just enabling it. This is admittedly a user-visible behavioral change, but I am hoping that's a good one that we can live with.
Quoted 7 lines
Totally agree with the ideal end goal for zswap. just not sure if that's the right place to start for this usage, zswap doesn't always apply. For instance, we have SSDs with built-in compression, software-based storage stacks with built-in compression and deduplication, swap over RDMA, and, most notably, ZRAM users. They don't necessarily need zswap or a virtual layer, and the upper layer better be as much simplified as possible.
Right, it's not necessarily zswap at all. As I mentioned above, the same logic applies for swap tiering. You can actually consider zswap one of the tiers (more-or-less). If you have one swapfile (or one tier) like the ones you mention above, the virtual layer just always points to a single backend (e.g. the slot in the swapfile). There might be some additional overhead, but I think it would be minimal if we use the cluster-based approach you have been pushing to eliminate static overhead and make it all dynamic based on actual usage.
At a high-level, if we have a single tier/swapfile, I think the only additional overhead would be the reverse mapping from the swap slot to the virtual swap layer, which would be 8 bytes or so for every swapped out entry, right?
I think this was discussed before but I still wonder if we really need a reverse mapping, if it's only to optimize swapoff then I don't think it's a requirement. We can still scan the virtual swap layer to look for slots to swapin. It would still be better than scanning the page tables as we do today. But I think there were other use cases for the reverse mapping, I just forgot what they were.
Gregory Price
reviewerQuoted 5 lines · Yosry Ahmed
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
Sorry to add to the fun, but i do think this is mildly relevant.
I've been testing hardware-compressed RAM as a swap tier (CRAM) w/ vswap.
Will hopefully be publishing soon - but was waiting to see how vswap would go first. But I think this is a good insertion point.
With vswap - this integration was so absurdly clean. We just add VSWAP_CRAM and being able to writeback the folio to zswap or regular swap was surprisingly straightforward.
The alternative was to inherit an absurd amount of boilerplate from zswap, and then the complexity explodes if you have to decide whether to go to backend X or backend Y.
So I just wanted to say, in support of this series, there is functional value in the virtualization here that isn't fully represented by just zswap/zram/swap interactions.
Quoted 6 lines
I think this was discussed before but I still wonder if we really need a reverse mapping, if it's only to optimize swapoff then I don't think it's a requirement. We can still scan the virtual swap layer to look for slots to swapin. It would still be better than scanning the page tables as we do today. But I think there were other use cases for the reverse mapping, I just forgot what they were.
For the sake of discussion - there may be value in the reverse map for CRAM, since it can soft-fault its folios into page tables read-only. In this case, you can have multiple mappers in various states (softleaf vs read-only).
In the case that you want to writeback a multi-state cram folio, the reverse mapping may be useful. Right now I'm using rmap, but maybe there's an optimization here.
Maybe not worth it "until something actually uses it" though.
~Gregory
Quoted 14 lines · Yosry Ahmed <[email protected]> 于 2026年4月24日周五 04:48写道:
Quoted 4 lines
Using a swapfile does have its benefits, though. For example, the virtual layer could act as an ordinary tier following YoungJun's design:
https://lore.kernel.org/linux-mm/[email protected]/Hmm I didn't look too closely at this but I don't understand how making it a swapfile helps with tiering? If anything, I think it makes tiering more difficult. For tiering to work, we need an abstraction/redirection layer, such that we don't need to update the page tables (or shmem pagecache) if we demote/promote pages. That is exactly the use case for a virtual swap layer. The page tables point at a virtual swap ID and the backend could change transparently (e.g. for zswap writeback, or tiering).
Quoted 6 lines
If we make the virtual layer a swapfile, how do we demote/promote without updating page tables?
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
That's exactly what I hoped, virtual layer being part of the tier. Tier could be set up per task / cgroup. So is the virtual tier.
A standalone implementation of the virtual layer is more heavy than being a swapfile. Actually I think at this point, it is the word "swapfile" is misleading now. We may rename it to "swap mapping" or something. A swap mapping could be physical or virtual. Virtual mapping can realloc from physical ones (redirect), and swapoff of physical ones just read its data into virtual mapping's swap cache.
I think it's actually functionally very similar to Nhat's design already from a high level, the only difference is we don't need standalone infra for virtual parts.
For swapoff or migration you don't need to touch the page table, same as in this series, just update the virtual swap mapping to be cached or update the entry, it's identical to what this series is doing.
Quoted 33 lines · Kairui Song
Quoted 14 lines · Yosry Ahmed <[email protected]> 于 2026年4月24日周五 04:48写道:
Quoted 4 lines
Using a swapfile does have its benefits, though. For example, the virtual layer could act as an ordinary tier following YoungJun's design:
https://lore.kernel.org/linux-mm/[email protected]/Hmm I didn't look too closely at this but I don't understand how making it a swapfile helps with tiering? If anything, I think it makes tiering more difficult. For tiering to work, we need an abstraction/redirection layer, such that we don't need to update the page tables (or shmem pagecache) if we demote/promote pages. That is exactly the use case for a virtual swap layer. The page tables point at a virtual swap ID and the backend could change transparently (e.g. for zswap writeback, or tiering).
Quoted 6 lines
If we make the virtual layer a swapfile, how do we demote/promote without updating page tables?
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
That's exactly what I hoped, virtual layer being part of the tier. Tier could be set up per task / cgroup. So is the virtual tier.
A standalone implementation of the virtual layer is more heavy than being a swapfile. Actually I think at this point, it is the word "swapfile" is misleading now. We may rename it to "swap mapping" or something. A swap mapping could be physical or virtual. Virtual mapping can realloc from physical ones (redirect), and swapoff of physical ones just read its data into virtual mapping's swap cache.
Quoted 7 lines
I think it's actually functionally very similar to Nhat's design already from a high level, the only difference is we don't need standalone infra for virtual parts.
For swapoff or migration you don't need to touch the page table, same as in this series, just update the virtual swap mapping to be cached or update the entry, it's identical to what this series is doing.
BTW it does look like file mapping. In the long term maybe we can merge part of the swap mapping with file mapping again, not sure though. Swap mapping is a bit different as it's integrated with allocator, and previously it was reusing file mapping, but we had to use a lot of strange techniques e.g. split the mapping to avoid lock contention / special lookup routine / synchronization / handling writeback in an entirely different way. Just an idea and reference here.
Nhat Pham
maintainerOn Thu, Apr 23, 2026 at 9:16 PM Kairui Song <[email protected]> wrote:
My apologies for delayed response - I'm cleaning things up, and fighting with some memsw issue. I changed the semantic of the memory.swap counter a bit, but that makes it diverge operationally from memsw. Need to be careful not double charging or double uncharging here.
Quoted 33 lines
Quoted 14 lines · Yosry Ahmed <[email protected]> 于 2026年4月24日周五 04:48写道:
Quoted 4 lines
Using a swapfile does have its benefits, though. For example, the virtual layer could act as an ordinary tier following YoungJun's design:
https://lore.kernel.org/linux-mm/[email protected]/Hmm I didn't look too closely at this but I don't understand how making it a swapfile helps with tiering? If anything, I think it makes tiering more difficult. For tiering to work, we need an abstraction/redirection layer, such that we don't need to update the page tables (or shmem pagecache) if we demote/promote pages. That is exactly the use case for a virtual swap layer. The page tables point at a virtual swap ID and the backend could change transparently (e.g. for zswap writeback, or tiering).
Quoted 6 lines
If we make the virtual layer a swapfile, how do we demote/promote without updating page tables?
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
That's exactly what I hoped, virtual layer being part of the tier. Tier could be set up per task / cgroup. So is the virtual tier.
A standalone implementation of the virtual layer is more heavy than being a swapfile. Actually I think at this point, it is the word "swapfile" is misleading now. We may rename it to "swap mapping" or something. A swap mapping could be physical or virtual. Virtual mapping can realloc from physical ones (redirect), and swapoff of physical ones just read its data into virtual mapping's swap cache.
Quoted 3 lines
I think it's actually functionally very similar to Nhat's design already from a high level, the only difference is we don't need standalone infra for virtual parts.
Well yeah, great minds think alike ;)
As you have noticed, I have also converged towards a lot of your metadata design and operational arrangement.
Case in point is the delaying of cgroup check merging with swap freeing - I did not notice that patch you had in your series, but I realized I had to do it as well after studying the regression for awhile.
(I did think about proposing that outside of the vswap series, but I was thinking it would not be a problem at all with the current code. But in hindsight, since you're also merging swap cgroup with swap table, it will have a similar implications, albeit less expensive due to no xarray indirection).
Hopefully we can iron out the rest of the differences. I have a couple more use cases in mind (compressed writeback from zswap, discontiguous fallback for swapout, etc.), but without virtualization they seem like a deadend :(
And Gregory's cram stuff too - I think it's not undoable without vswap, but it's just a lot hairier :(
Quoted 4 lines
For swapoff or migration you don't need to touch the page table, same as in this series, just update the virtual swap mapping to be cached or update the entry, it's identical to what this series is doing.
Yeah the swapoff is no big deal.
Quoted 8 lines · Nhat Pham
On Thu, Apr 23, 2026 at 9:16 PM Kairui Song <[email protected]> wrote:
My apologies for delayed response - I'm cleaning things up, and fighting with some memsw issue. I changed the semantic of the memory.swap counter a bit, but that makes it diverge operationally from memsw. Need to be careful not double charging or double uncharging here.
Hi Nhat,
No worries.
About memory.swap, I also thought about changing it a bit previously to make thing cleaner:
https://lore.kernel.org/linux-mm/[email protected]/
But I dropped that part so swap table series p4 can be reviewed without any behavior change. Not sure if related.
Quoted 4 lines
Quoted 3 lines
I think it's actually functionally very similar to Nhat's design already from a high level, the only difference is we don't need standalone infra for virtual parts.
Well yeah, great minds think alike ;)
:)
Quoted 9 lines
As you have noticed, I have also converged towards a lot of your metadata design and operational arrangement.
Case in point is the delaying of cgroup check merging with swap freeing - I did not notice that patch you had in your series, but I realized I had to do it as well after studying the regression for awhile.
Quoted 5 lines
(I did think about proposing that outside of the vswap series, but I was thinking it would not be a problem at all with the current code. But in hindsight, since you're also merging swap cgroup with swap table, it will have a similar implications, albeit less expensive due to no xarray indirection).
There are actually more issues behind that. Later we would also want to distinguish shmem / anon swap entries again, so swap cache allocation ensures there is no conflict between these two. That is also causing some real issues.
Quoted 2 lines
Hopefully we can iron out the rest of the differences. I have a couple
Yeah, definitely. I think things are already getting much cleaner as we keep unifying and simplify the swap infra. Consider the current swap file something like s swap mapping as an infra seems to make things easier to understand as well.
Quoted 6 lines
more use cases in mind (compressed writeback from zswap, discontiguous fallback for swapout, etc.), but without virtualization they seem like a deadend :(
And Gregory's cram stuff too - I think it's not undoable without vswap, but it's just a lot hairier :(
Ah, I'm not against a virtual layer at all, actually that's a shared goal, I mean we might not want something mandatory, and redo everything again with more overhead.
Yosry Ahmed
maintainerQuoted 19 lines · Kairui Song
Quoted 17 lines · Yosry Ahmed <[email protected]> 于 2026年4月24日周五 04:48写道:
Quoted 4 lines
Using a swapfile does have its benefits, though. For example, the virtual layer could act as an ordinary tier following YoungJun's design:
https://lore.kernel.org/linux-mm/[email protected]/Hmm I didn't look too closely at this but I don't understand how making it a swapfile helps with tiering? If anything, I think it makes tiering more difficult. For tiering to work, we need an abstraction/redirection layer, such that we don't need to update the page tables (or shmem pagecache) if we demote/promote pages. That is exactly the use case for a virtual swap layer. The page tables point at a virtual swap ID and the backend could change transparently (e.g. for zswap writeback, or tiering).
If we make the virtual layer a swapfile, how do we demote/promote without updating page tables?
Quoted 6 lines
Quoted 3 lines
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
That's exactly what I hoped, virtual layer being part of the tier. Tier could be set up per task / cgroup. So is the virtual tier.
Just to clarify. I don't think virtual swap should be one of the tiers. I think it should be the mechanism through which we implement tiering (see above). I am not sure if that's what you meant.
Quoted 7 lines
A standalone implementation of the virtual layer is more heavy than being a swapfile. Actually I think at this point, it is the word "swapfile" is misleading now. We may rename it to "swap mapping" or something. A swap mapping could be physical or virtual. Virtual mapping can realloc from physical ones (redirect), and swapoff of physical ones just read its data into virtual mapping's swap cache.
I don't understand this part, please clarify. In my mind, all references to swap entries from outside backend code should refer to a virtual swap ID, which could be pointing to physical swap or zswap or something else.
I *think* what you're saying is that we should make that optional, but I don't see how this would work. If a page table is pointing at a swap slot in a swapfile, we cannot do tiering or zswap writeback or anything dynamic without updating page tables. So even if the system starts off with one swapfile, we cannot assume we won't add more and set up tiering (or enable zswap) after that, right?
I guess we'll keep the swap table in the swapfile and then we'll have it point to a different backend, but I really don't like this design. It's unnecessarily complicated in my opinion. Page tables will either refer to a virtual swap ID or a physical swap slot.
I think we can simply have swap tables representing the virtual swap space and pointing at the backend directly, whether or not we have zswap or tiering set up or not. Is the overhead really that bad?
Quoted 25 lines · Yosry Ahmed
Quoted 23 lines · Kairui Song
Quoted 20 lines · Yosry Ahmed <[email protected]> 于 2026年4月24日周五 04:48写道:
Quoted 4 lines
Using a swapfile does have its benefits, though. For example, the virtual layer could act as an ordinary tier following YoungJun's design:
https://lore.kernel.org/linux-mm/[email protected]/Hmm I didn't look too closely at this but I don't understand how making it a swapfile helps with tiering? If anything, I think it makes tiering more difficult. For tiering to work, we need an abstraction/redirection layer, such that we don't need to update the page tables (or shmem pagecache) if we demote/promote pages. That is exactly the use case for a virtual swap layer. The page tables point at a virtual swap ID and the backend could change transparently (e.g. for zswap writeback, or tiering).
If we make the virtual layer a swapfile, how do we demote/promote without updating page tables?
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
Quoted 6 lines
Quoted 2 lines
That's exactly what I hoped, virtual layer being part of the tier. Tier could be set up per task / cgroup. So is the virtual tier.
Just to clarify. I don't think virtual swap should be one of the tiers. I think it should be the mechanism through which we implement tiering (see above). I am not sure if that's what you meant.
YoungJun's swap tier have been working pretty well without the virtual part:
https://lore.kernel.org/linux-mm/[email protected]/
Quoted 8 lines
Quoted 7 lines
A standalone implementation of the virtual layer is more heavy than being a swapfile. Actually I think at this point, it is the word "swapfile" is misleading now. We may rename it to "swap mapping" or something. A swap mapping could be physical or virtual. Virtual mapping can realloc from physical ones (redirect), and swapoff of physical ones just read its data into virtual mapping's swap cache.
Quoted 4 lines
I don't understand this part, please clarify. In my mind, all references to swap entries from outside backend code should refer to a virtual swap ID, which could be pointing to physical swap or zswap or something else.
For example just reserve a type (e.g. type 0) as the virtual type? (type is really a bad naming though).
The that swap file (or swap mapping) will be
I was trying that based on this:
https://lore.kernel.org/linux-mm/[email protected]/
It seems to work and the only thing we need is actually just something like this one in VSS:
https://lore.kernel.org/linux-mm/[email protected]/
This part:
+ /* fall back to physical swap device */
+ if (!vswap_alloc_swap_slot(folio)) {
We do a folio_realloc_swap if folio->swap have type 0.
Which means, if there is no virtual device / mapping / file / space (I'm not sure how to name it at this point :) ), the ordinary swap routine is just still there untouched.
If there is one, and it's being used, then, it is still the ordinary swap routine, just do an extra allocation (and the extra allocation strictly follows YoungJun's tier rule), which is same with VSS, but everything is reused. From a user or high level interface perspective, this can be designed with no difference as VSS. Just with a few
bonuses: being per memcg / task / runtime optional, zero overhead if not enabled, and reusing all the infra.
BTW this deferred allocation (in VSS or dynamic swap mapping, similar thing) is actually a bit concerning to me as well. It changes the common swapout routine and maybe worth reconsideration (e.g. activate_locked_split and mTHP stats is now ignored?), being optional for now also seems safer.
Quoted 11 lines
I *think* what you're saying is that we should make that optional, but I don't see how this would work. If a page table is pointing at a swap slot in a swapfile, we cannot do tiering or zswap writeback or anything dynamic without updating page tables. So even if the system starts off with one swapfile, we cannot assume we won't add more and set up tiering (or enable zswap) after that, right?
I guess we'll keep the swap table in the swapfile and then we'll have it point to a different backend, but I really don't like this design. It's unnecessarily complicated in my opinion. Page tables will either refer to a virtual swap ID or a physical swap slot.
Or in another word, they are all just swap entries, and the swap layer handles things internally.
Quoted 3 lines
I think we can simply have swap tables representing the virtual swap space and pointing at the backend directly, whether or not we have zswap or tiering set up or not. Is the overhead really that bad?
Right... I mean with two layers you will likely have >16 bytes overhead, and double lookup. And I have been thinking about cutting down the memory usage to 3 bytes. And you can't make the lower / physical layer just a bitmap if you want a reverse mapping, and so far many things do require that. If we make the reverse mapping optional it might be more complicated than the thing we discussed.
I don't think the thing I described above is that complicated reading all the code and solutions so far. Maybe some better abstraction can help?
I've seen some vendors doing swap using UFFD just to cut down the overhead or having a highly customized backend solution for swap, so I was hoping the kernel part could be as minimal as possible.
Yosry Ahmed
maintainerQuoted 7 lines
Quoted 7 lines
Quoted 6 lines
Quoted 3 lines
IOW, I think the whole reason we want a virtual layer is to separate the backends, which would facilitate tiering. If the virtual layer is itself a swapfile, wouldn't it become one of the tiers?
That's exactly what I hoped, virtual layer being part of the tier. Tier could be set up per task / cgroup. So is the virtual tier.
Quoted 6 lines
Quoted 3 lines
Just to clarify. I don't think virtual swap should be one of the tiers. I think it should be the mechanism through which we implement tiering (see above). I am not sure if that's what you meant.
YoungJun's swap tier have been working pretty well without the virtual part:
https://lore.kernel.org/linux-mm/[email protected]/
Does this do promotion/demotion of swap entries?
Quoted 42 lines
Quoted 11 lines
Quoted 6 lines
A standalone implementation of the virtual layer is more heavy than being a swapfile. Actually I think at this point, it is the word "swapfile" is misleading now. We may rename it to "swap mapping" or something. A swap mapping could be physical or virtual. Virtual mapping can realloc from physical ones (redirect), and swapoff of physical ones just read its data into virtual mapping's swap cache.
I don't understand this part, please clarify. In my mind, all references to swap entries from outside backend code should refer to a virtual swap ID, which could be pointing to physical swap or zswap or something else.
For example just reserve a type (e.g. type 0) as the virtual type? (type is really a bad naming though).
The that swap file (or swap mapping) will be
I was trying that based on this:
https://lore.kernel.org/linux-mm/[email protected]/It seems to work and the only thing we need is actually just something like this one in VSS:
https://lore.kernel.org/linux-mm/[email protected]/This part:
+ /* fall back to physical swap device */
+ if (!vswap_alloc_swap_slot(folio)) {We do a
folio_realloc_swapiffolio->swaphave type 0.Which means, if there is no virtual device / mapping / file / space (I'm not sure how to name it at this point :) ), the ordinary swap routine is just still there untouched.
If there is one, and it's being used, then, it is still the ordinary swap routine, just do an extra allocation (and the extra allocation strictly follows YoungJun's tier rule), which is same with VSS, but everything is reused. From a user or high level interface perspective, this can be designed with no difference as VSS. Just with a few
bonuses: being per memcg / task / runtime optional, zero overhead if not enabled, and reusing all the infra.
Quoted 5 lines
BTW this deferred allocation (in VSS or dynamic swap mapping, similar thing) is actually a bit concerning to me as well. It changes the common swapout routine and maybe worth reconsideration (e.g.
activate_locked_splitand mTHP stats is now ignored?), being optional for now also seems safer.
I am not sure if I understand you correctly. I think what you're proposing is:
- Page tables either point directly to a swap slot, or to a virtual swap entry.
- By default, page tables just point to swap slots maintaining current behavior.
- If we have multiple backends (e.g. zswap or tiering), we use virtual swap entry instead.
- The physical swapfile has clusters and swap tables (status quo).
- Virtual swap is implemented with clusters and swap tables in a virtual space, and each table entry points to an underlying swap slot or zswap entry.
- If a page table has a physical swap slot, and we need to do tiering, we basically "make it virtual" by making the swap table of the physical swapfile point at a virtual swap entry? or another physical swapfile? Not sure.
In this design we have swap tables in both the virtual swap space as well as the physical swapfile, right? How does this work? Where does the metadata/swapcache live?
I am not sure if I got it right, I am a bit confused.
Quoted 16 lines
Quoted 8 lines
I *think* what you're saying is that we should make that optional, but I don't see how this would work. If a page table is pointing at a swap slot in a swapfile, we cannot do tiering or zswap writeback or anything dynamic without updating page tables. So even if the system starts off with one swapfile, we cannot assume we won't add more and set up tiering (or enable zswap) after that, right?
Quoted 4 lines
I guess we'll keep the swap table in the swapfile and then we'll have it point to a different backend, but I really don't like this design. It's unnecessarily complicated in my opinion. Page tables will either refer to a virtual swap ID or a physical swap slot.
Or in another word, they are all just swap entries, and the swap layer handles things internally.
Quoted 6 lines
Quoted 3 lines
I think we can simply have swap tables representing the virtual swap space and pointing at the backend directly, whether or not we have zswap or tiering set up or not. Is the overhead really that bad?
Right... I mean with two layers you will likely have >16 bytes overhead, and double lookup.
Why >16 bytes? Do we need anything extra other than the reverse mapping? Also why do we need a double lookup?
Quoted 9 lines
And I have been thinking about cutting
down the memory usage to 3 bytes. And you can't make the lower / physical layer just a bitmap if you want a reverse mapping, and so far many things do require that. If we make the reverse mapping optional it might be more complicated than the thing we discussed.I don't think the thing I described above is that complicated reading all the code and solutions so far. Maybe some better abstraction can help?
I don't think I quite understand it yet, maybe I am the problem :)
Quoted 4 lines
I've seen some vendors doing swap using UFFD just to cut down the overhead or having a highly customized backend solution for swap, so I was hoping the kernel part could be as minimal as possible.
Interesting.
On Sat, Apr 25, 2026 at 3:12 AM Yosry Ahmed <[email protected]> wrote
Quoted 3 lines
Quoted 1 line
Does this do promotion/demotion of swap entries?
Not yet, let's do things step by step.
Quoted 36 lines
Quoted 30 lines
For example just reserve a type (e.g. type 0) as the virtual type? (type is really a bad naming though).
The that swap file (or swap mapping) will be
I was trying that based on this:
https://lore.kernel.org/linux-mm/[email protected]/It seems to work and the only thing we need is actually just something like this one in VSS:
https://lore.kernel.org/linux-mm/[email protected]/This part:
+ /* fall back to physical swap device */
+ if (!vswap_alloc_swap_slot(folio)) {We do a
folio_realloc_swapiffolio->swaphave type 0.Which means, if there is no virtual device / mapping / file / space (I'm not sure how to name it at this point :) ), the ordinary swap routine is just still there untouched.
If there is one, and it's being used, then, it is still the ordinary swap routine, just do an extra allocation (and the extra allocation strictly follows YoungJun's tier rule), which is same with VSS, but everything is reused. From a user or high level interface perspective, this can be designed with no difference as VSS. Just with a few
bonuses: being per memcg / task / runtime optional, zero overhead if not enabled, and reusing all the infra.Quoted 5 lines
BTW this deferred allocation (in VSS or dynamic swap mapping, similar thing) is actually a bit concerning to me as well. It changes the common swapout routine and maybe worth reconsideration (e.g.
activate_locked_splitand mTHP stats is now ignored?), being optional for now also seems safer.
Quoted 4 lines
I am not sure if I understand you correctly. I think what you're proposing is:
- Page tables either point directly to a swap slot, or to a virtual swap entry.
- By default, page tables just point to swap slots maintaining current behavior.
I mean, they are all swap entries, nothing special from the page table side. Swap subsystems handle things internally.
Quoted 2 lines
- If we have multiple backends (e.g. zswap or tiering), we use virtual swap entry instead.
Actually that can just follow the swap priority, or tier rule. Even if virtual mapping exists, it can be bypassed. e.g. you have a large NBD and don't care about either fragmentation or compression for offline workload cgroups, then why use a virtual layer for them which could double the kmem usage or spend more CPU? Setup is a different issue which can be discussed.
Quoted 8 lines
- The physical swapfile has clusters and swap tables (status quo).
- Virtual swap is implemented with clusters and swap tables in a virtual space, and each table entry points to an underlying swap slot or zswap entry.
- If a page table has a physical swap slot, and we need to do tiering, we basically "make it virtual" by making the swap table of the physical swapfile point at a virtual swap entry? or another physical swapfile? Not sure.
They are still ordinary swap entries, nothing special. The virtual space is also just a ordinary swap file (or swap mapping), which is easy to do:
https://lore.kernel.org/linux-mm/[email protected]/
Then its virtual_table will have a different set of swap entries. (I left that part undone though).
Quoted 5 lines
Quoted 2 lines
Right... I mean with two layers you will likely have >16 bytes overhead, and double lookup.
Why >16 bytes? Do we need anything extra other than the reverse mapping? Also why do we need a double lookup?
You will have to store at least the following info: memcg (2 bytes), shadow (8 bytes), count (at least 1 bytes), and revert mapping (8 bytes, since you have to address a full virtual swap space). And some type info is also needed. Part of them can be shrinked but still, scientifically, merging two layers into one is considered a kind of optimization.
You need lookup the virtual layer, then the lower layer for many decision making, is was discussed before to introduce more cache bit or things like that and I think that is getting over complex, reminds me of the slot cache or HAS_CACHE thing...:
https://lore.kernel.org/linux-mm/CAMgjq7DJrtE-jARik849kCufd0qNnZQs7C8fcyzVOKE14-O+Dw@mail.gmail.com/
Quoted 1 line
I don't think I quite understand it yet, maybe I am the problem :)
Haha, not at all! Blame me for the poor explanation. To be honest, the design is still evolving and there are definitely details that need to be improved. It's hard to discuss these abstractions purely in theory, so it's probably best just keep the works moving forward in a clean way, and make things simpler and better be opt-in first.
Yosry Ahmed
maintainerQuoted 92 lines · Kairui Song
On Sat, Apr 25, 2026 at 3:12 AM Yosry Ahmed <[email protected]> wrote
Quoted 3 lines
Quoted 1 line
Does this do promotion/demotion of swap entries?
Not yet, let's do things step by step.
Quoted 36 lines
Quoted 30 lines
For example just reserve a type (e.g. type 0) as the virtual type? (type is really a bad naming though).
The that swap file (or swap mapping) will be
I was trying that based on this:
https://lore.kernel.org/linux-mm/[email protected]/It seems to work and the only thing we need is actually just something like this one in VSS:
https://lore.kernel.org/linux-mm/[email protected]/This part:
+ /* fall back to physical swap device */
+ if (!vswap_alloc_swap_slot(folio)) {We do a
folio_realloc_swapiffolio->swaphave type 0.Which means, if there is no virtual device / mapping / file / space (I'm not sure how to name it at this point :) ), the ordinary swap routine is just still there untouched.
If there is one, and it's being used, then, it is still the ordinary swap routine, just do an extra allocation (and the extra allocation strictly follows YoungJun's tier rule), which is same with VSS, but everything is reused. From a user or high level interface perspective, this can be designed with no difference as VSS. Just with a few
bonuses: being per memcg / task / runtime optional, zero overhead if not enabled, and reusing all the infra.Quoted 5 lines
BTW this deferred allocation (in VSS or dynamic swap mapping, similar thing) is actually a bit concerning to me as well. It changes the common swapout routine and maybe worth reconsideration (e.g.
activate_locked_splitand mTHP stats is now ignored?), being optional for now also seems safer.Quoted 4 lines
I am not sure if I understand you correctly. I think what you're proposing is:
- Page tables either point directly to a swap slot, or to a virtual swap entry.
- By default, page tables just point to swap slots maintaining current behavior.I mean, they are all swap entries, nothing special from the page table side. Swap subsystems handle things internally.
Quoted 2 lines
- If we have multiple backends (e.g. zswap or tiering), we use virtual swap entry instead.
Actually that can just follow the swap priority, or tier rule. Even if virtual mapping exists, it can be bypassed. e.g. you have a large NBD and don't care about either fragmentation or compression for offline workload cgroups, then why use a virtual layer for them which could double the kmem usage or spend more CPU? Setup is a different issue which can be discussed.
Quoted 8 lines
- The physical swapfile has clusters and swap tables (status quo).
- Virtual swap is implemented with clusters and swap tables in a virtual space, and each table entry points to an underlying swap slot or zswap entry.
- If a page table has a physical swap slot, and we need to do tiering, we basically "make it virtual" by making the swap table of the physical swapfile point at a virtual swap entry? or another physical swapfile? Not sure.They are still ordinary swap entries, nothing special. The virtual space is also just a ordinary swap file (or swap mapping), which is easy to do:
https://lore.kernel.org/linux-mm/[email protected]/Then its
virtual_tablewill have a different set of swap entries. (I left that part undone though).Quoted 5 lines
Quoted 2 lines
Right... I mean with two layers you will likely have >16 bytes overhead, and double lookup.
Why >16 bytes? Do we need anything extra other than the reverse mapping? Also why do we need a double lookup?
You will have to store at least the following info: memcg (2 bytes), shadow (8 bytes), count (at least 1 bytes), and revert mapping (8 bytes, since you have to address a full virtual swap space). And some type info is also needed. Part of them can be shrinked but still, scientifically, merging two layers into one is considered a kind of optimization.
Quoted 5 lines
You need lookup the virtual layer, then the lower layer for many decision making, is was discussed before to introduce more cache bit or things like that and I think that is getting over complex, reminds me of the slot cache or
HAS_CACHEthing...:
https://lore.kernel.org/linux-mm/CAMgjq7DJrtE-jARik849kCufd0qNnZQs7C8fcyzVOKE14-O+Dw@mail.gmail.com/
I think that's where the disconnect is. You are considering these two separate layers, each with its own metadata. The metadata should only live in one place.
If we only have swap tables in the virtual swap layer (with the metadata), backends do not have to carry the metadata. In this case, backends should only have a reverse mapping (if needed), and some internal data structure (e.g. bitmaps) to track usage.
This is difficult to achieve if the virtual swap layer is optional, because then the metadata can live in different places. This is why I think we should have a virtual swap layer that all swap entries go through and all metadata live in (where today's swap tables would live). Backends then only carry backend-specific data (e.g. compression handles for zswap, slots bitmap of swapfiles, etc). In this world I *think* the reverse mapping could end up being optional, depending on what we need it for.
Quoted 20 lines · Yosry Ahmed
Quoted 12 lines · Kairui Song
On Sat, Apr 25, 2026 at 3:12 AM Yosry Ahmed <[email protected]> wrote
Quoted 2 lines
Why >16 bytes? Do we need anything extra other than the reverse mapping? Also why do we need a double lookup?
You will have to store at least the following info: memcg (2 bytes), shadow (8 bytes), count (at least 1 bytes), and revert mapping (8 bytes, since you have to address a full virtual swap space). And some type info is also needed. Part of them can be shrinked but still, scientifically, merging two layers into one is considered a kind of optimization.
Quoted 5 lines
You need lookup the virtual layer, then the lower layer for many decision making, is was discussed before to introduce more cache bit or things like that and I think that is getting over complex, reminds me of the slot cache or
HAS_CACHEthing...:
https://lore.kernel.org/linux-mm/CAMgjq7DJrtE-jARik849kCufd0qNnZQs7C8fcyzVOKE14-O+Dw@mail.gmail.com/
Quoted 8 lines
I think that's where the disconnect is. You are considering these two separate layers, each with its own metadata. The metadata should only live in one place.
If we only have swap tables in the virtual swap layer (with the metadata), backends do not have to carry the metadata. In this case, backends should only have a reverse mapping (if needed), and some internal data structure (e.g. bitmaps) to track usage.
Ah, you are right. This is currently an intermediate state, that problem might be gone if we unified everything.
Quoted 2 lines
This is difficult to achieve if the virtual swap layer is optional, because then the metadata can live in different places. This is why I
But that's not difficult to achieve at all with an optional layer, and actually will be achieved naturally without any design change with the RFC I posted. Swap count / cgroup / shadow all stay in the top layer, lower layer is "reverse map" only (the undone part though, it will require to move the cluster cache from global to device level, which is also required for YoungJun's tier or any functional tiering to work, we may run into more and more detail issue like this).
Might even be easier that way, it's pretty close to the unified states I think.
Yosry Ahmed
maintainerQuoted 37 lines · Kairui Song
Quoted 20 lines · Yosry Ahmed
Quoted 12 lines · Kairui Song
On Sat, Apr 25, 2026 at 3:12 AM Yosry Ahmed <[email protected]> wrote
Quoted 2 lines
Why >16 bytes? Do we need anything extra other than the reverse mapping? Also why do we need a double lookup?
You will have to store at least the following info: memcg (2 bytes), shadow (8 bytes), count (at least 1 bytes), and revert mapping (8 bytes, since you have to address a full virtual swap space). And some type info is also needed. Part of them can be shrinked but still, scientifically, merging two layers into one is considered a kind of optimization.
Quoted 5 lines
You need lookup the virtual layer, then the lower layer for many decision making, is was discussed before to introduce more cache bit or things like that and I think that is getting over complex, reminds me of the slot cache or
HAS_CACHEthing...:
https://lore.kernel.org/linux-mm/CAMgjq7DJrtE-jARik849kCufd0qNnZQs7C8fcyzVOKE14-O+Dw@mail.gmail.com/Quoted 8 lines
I think that's where the disconnect is. You are considering these two separate layers, each with its own metadata. The metadata should only live in one place.
If we only have swap tables in the virtual swap layer (with the metadata), backends do not have to carry the metadata. In this case, backends should only have a reverse mapping (if needed), and some internal data structure (e.g. bitmaps) to track usage.
Ah, you are right. This is currently an intermediate state, that problem might be gone if we unified everything.
Quoted 2 lines
This is difficult to achieve if the virtual swap layer is optional, because then the metadata can live in different places. This is why I
Quoted 7 lines
But that's not difficult to achieve at all with an optional layer, and actually will be achieved naturally without any design change with the RFC I posted. Swap count / cgroup / shadow all stay in the top layer, lower layer is "reverse map" only (the undone part though, it will require to move the cluster cache from global to device level, which is also required for YoungJun's tier or any functional tiering to work, we may run into more and more detail issue like this).
But then you have to deal with the swap entries in the page tables potentially being virtual swap entries or physical swap slots, and IIUC in your design, those physica swap slots could end up actually having a redirection to another swap entry like virtual ones (e.g. if we start with one tier then add another tier at runtime). Right?
Quoted 3 lines
Might even be easier that way, it's pretty close to the unified states I think.
Nhat Pham
maintainerQuoted 26 lines · Kairui Song
Quoted 24 lines · Yosry Ahmed
Quoted 12 lines · Kairui Song
On Sat, Apr 25, 2026 at 3:12 AM Yosry Ahmed <[email protected]> wrote
Quoted 2 lines
Why >16 bytes? Do we need anything extra other than the reverse mapping? Also why do we need a double lookup?
You will have to store at least the following info: memcg (2 bytes), shadow (8 bytes), count (at least 1 bytes), and revert mapping (8 bytes, since you have to address a full virtual swap space). And some type info is also needed. Part of them can be shrinked but still, scientifically, merging two layers into one is considered a kind of optimization.
Quoted 5 lines
You need lookup the virtual layer, then the lower layer for many decision making, is was discussed before to introduce more cache bit or things like that and I think that is getting over complex, reminds me of the slot cache or
HAS_CACHEthing...:
https://lore.kernel.org/linux-mm/CAMgjq7DJrtE-jARik849kCufd0qNnZQs7C8fcyzVOKE14-O+Dw@mail.gmail.com/I think that's where the disconnect is. You are considering these two separate layers, each with its own metadata. The metadata should only live in one place.
Quoted 7 lines
Quoted 4 lines
If we only have swap tables in the virtual swap layer (with the metadata), backends do not have to carry the metadata. In this case, backends should only have a reverse mapping (if needed), and some internal data structure (e.g. bitmaps) to track usage.
Ah, you are right. This is currently an intermediate state, that problem might be gone if we unified everything.
What do you mean here?
Quoted 12 lines
Quoted 3 lines
This is difficult to achieve if the virtual swap layer is optional, because then the metadata can live in different places. This is why I
But that's not difficult to achieve at all with an optional layer, and actually will be achieved naturally without any design change with the RFC I posted. Swap count / cgroup / shadow all stay in the top layer, lower layer is "reverse map" only (the undone part though, it will require to move the cluster cache from global to device level, which is also required for YoungJun's tier or any functional tiering to work, we may run into more and more detail issue like this).
Quoted 1 line
Might even be easier that way, it's pretty close to the unified states I think.
I feel like you're moving towards the other direction, no? Seems like you are unifying swap metadata, which is good (vswap will also want to do this), but the problem is, the lower layer will have to allocate memory for these metadata too...
Say vswap is optional and runtime enabled. How do you structure a physical swap device's metadata? Some of the slots might be directly mapped to PTEs, some might back vswap slots. These two cases require a two completely different set of metadata: the former needs reference count, swap cache, swap cgroup etc., whereas the latter only needs reverse mapping...
I don't think we should mix vswap and non vswap slots in the same type/address space.
Nhat Pham
maintainerQuoted 55 lines · Kairui Song
On Sat, Apr 25, 2026 at 3:12 AM Yosry Ahmed <[email protected]> wrote
Quoted 3 lines
Quoted 1 line
Does this do promotion/demotion of swap entries?
Not yet, let's do things step by step.
Quoted 36 lines
Quoted 30 lines
For example just reserve a type (e.g. type 0) as the virtual type? (type is really a bad naming though).
The that swap file (or swap mapping) will be
I was trying that based on this:
https://lore.kernel.org/linux-mm/[email protected]/It seems to work and the only thing we need is actually just something like this one in VSS:
https://lore.kernel.org/linux-mm/[email protected]/This part:
+ /* fall back to physical swap device */
+ if (!vswap_alloc_swap_slot(folio)) {We do a
folio_realloc_swapiffolio->swaphave type 0.Which means, if there is no virtual device / mapping / file / space (I'm not sure how to name it at this point :) ), the ordinary swap routine is just still there untouched.
If there is one, and it's being used, then, it is still the ordinary swap routine, just do an extra allocation (and the extra allocation strictly follows YoungJun's tier rule), which is same with VSS, but everything is reused. From a user or high level interface perspective, this can be designed with no difference as VSS. Just with a few
bonuses: being per memcg / task / runtime optional, zero overhead if not enabled, and reusing all the infra.Quoted 5 lines
BTW this deferred allocation (in VSS or dynamic swap mapping, similar thing) is actually a bit concerning to me as well. It changes the common swapout routine and maybe worth reconsideration (e.g.
activate_locked_splitand mTHP stats is now ignored?), being optional for now also seems safer.Quoted 4 lines
I am not sure if I understand you correctly. I think what you're proposing is:
- Page tables either point directly to a swap slot, or to a virtual swap entry.
- By default, page tables just point to swap slots maintaining current behavior.I mean, they are all swap entries, nothing special from the page table side. Swap subsystems handle things internally.
Quoted 2 lines
- If we have multiple backends (e.g. zswap or tiering), we use virtual swap entry instead.
Quoted 6 lines
Actually that can just follow the swap priority, or tier rule. Even if virtual mapping exists, it can be bypassed. e.g. you have a large NBD and don't care about either fragmentation or compression for offline workload cgroups, then why use a virtual layer for them which could double the kmem usage or spend more CPU? Setup is a different issue which can be discussed.
I assume NBD == network block device here?
If you use a NBD, I think vswap overhead is not going to be the bottleneck here :)
And, what about reliability. Say you allocate a slot on the NBD, unmap the page from the PTEs, then proceed to swap_writeout(). What if the NBD device is no longer available? What if IO fails? If you already encode the physical swap slot location in the PTEs, then it's very expensive to correct this mistake. Whereas with vswap, you can fall back to another device if you so choose, and all it takes is just a simple backend change at the vswap layer.
Another issue with the current physical swapfile allocator is that induces physical contiguity where it's absolutely not needed. I don't know if this is the case with an NBD, but for flash device for e.g, obviously contiguity makes thing more efficient, but it would be nice if we can fallback to discontiguous swapout as a fallback.
I feel like NBD is an argument FOR virtualization, not against.
Quoted 24 lines
Quoted 9 lines
- The physical swapfile has clusters and swap tables (status quo).
- Virtual swap is implemented with clusters and swap tables in a virtual space, and each table entry points to an underlying swap slot or zswap entry.
- If a page table has a physical swap slot, and we need to do tiering, we basically "make it virtual" by making the swap table of the physical swapfile point at a virtual swap entry? or another physical swapfile? Not sure.They are still ordinary swap entries, nothing special. The virtual space is also just a ordinary swap file (or swap mapping), which is easy to do:
https://lore.kernel.org/linux-mm/[email protected]/Then its
virtual_tablewill have a different set of swap entries. (I left that part undone though).Quoted 5 lines
Quoted 2 lines
Right... I mean with two layers you will likely have >16 bytes overhead, and double lookup.
Why >16 bytes? Do we need anything extra other than the reverse mapping? Also why do we need a double lookup?
Quoted 6 lines
You will have to store at least the following info: memcg (2 bytes), shadow (8 bytes), count (at least 1 bytes), and revert mapping (8 bytes, since you have to address a full virtual swap space). And some type info is also needed. Part of them can be shrinked but still, scientifically, merging two layers into one is considered a kind of optimization.
Optimization is always a worthwhile pursuit of course. But you have to gauge it with what we can buy with a more flexbility design, which might end up buying us more performance win down the line
In the immediate term, vswap buys you a dynamic compressed layer + maintain the ability to write back.
Looking a bit longer term, I don't think you can do the following without a layer of indirection here:
1. Compressed writeback.
2. Discontiguous swapouts. I think we need this as a fallback for THP swapping (see [1] for the discussion).
3. Mixed backend swapin.
4. Optimizing swap IO - if sequential patterns matter for example, you need the ability to delay or change backend allocation. The current model is way too inflexible to allow for that.
5. Adding new swap backends. We want to decouple what the MM subsystem needs (which is minimally captured in the virtual layer), with what the backend itself wants.
Youngjun's paper is a case study for what you can buy with virtualization:
[1]: https://lore.kernel.org/all/[email protected]/
[2]: https://ieeexplore.ieee.org/document/8662047
Quoted 14 lines
You need lookup the virtual layer, then the lower layer for many decision making, is was discussed before to introduce more cache bit or things like that and I think that is getting over complex, reminds me of the slot cache or
HAS_CACHEthing...:
https://lore.kernel.org/linux-mm/CAMgjq7DJrtE-jARik849kCufd0qNnZQs7C8fcyzVOKE14-O+Dw@mail.gmail.com/Quoted 1 line
I don't think I quite understand it yet, maybe I am the problem :)
Haha, not at all! Blame me for the poor explanation. To be honest, the design is still evolving and there are definitely details that need to be improved. It's hard to discuss these abstractions purely in theory, so it's probably best just keep the works moving forward in a clean way, and make things simpler and better be opt-in first.