Skip to contentSkip to conversation

mm, swap: Virtual Swap Space (Swap Table Edition)

RFC PATCH Superseded Nhat Pham 3 participants 24 messages May 28 – Jun 3

Subsystems (10)

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Nhat Pham

author maintainer
#0 lore raw

cover mm, swap: Virtual Swap Space (Swap Table Edition)

Based on: mm-unstable @ 444fc9435e57 + swap-table phase IV v5 [2].

I manually adapted Kairui's ghost device implementation (from [4]) for my vswap device. I've credited him as Co-developed-by on Patch I since a substantial portion of the dynamic-cluster infrastructure is his (I did propose the idea of using xarray/radix tree for dynamic swap clusters allocation and management though :P).

From here on out, for simplicity, I will refer to swap table phase IV as "P4", and the older v6 virtual swap space implementation as "v6".

I. Context and Motivation

Virtual swap decouples PTE swap entries from physical swap backing, allowing pages to be compressed by zswap without pre-allocating a physical swap slot. See [1] for a more involved discussion on the motivation of swap virtualization, but in short, a swap virtualization scheme needs to satisfy 3 requirements, which are all driven by real pressing use cases of many parties using swap:

1. No backend coupling. For instance, a zswap entry should not require a physical swap slot to be allocated. This prevents wastage of coupled backend resources, and allows zswap to be used in systems that do not have enough storage capacity for physical swap (without having to resort to silly hacks). The same should hold for zero-filled swap pages, and swap cached folios too.

2. Dynamic swap space. The virtualization scheme should not require static provisioning, to accommodate dynamic and unpredictable swap usage. This massively simplifies operational provisioning, and allow the in-memory compression backend to be maximally utilized. It also makes sure we do not induce unbounded overhead on unused swap capacity.

3. Efficient backend transfer. The virtualization scheme should not introduces PTE/rmap walking overhead for backend transfer. This is crucial for systems that want to support multiple swap backends in a tiering fashion (for e.g zswap -> disk swap).

There are a lot of other future use cases as well - see [1] for more details.

This series reimplements the virtual swap space concept (see [1]) on top of Kairui Song's swap table infrastructure, on top of [2] and in accordance with his proposal in [3]. The proposal's idea is interesting, so I decided to give it a shot myself. I'm still not 100% sure that this is bug-proof, but hey, it compiles, and has not crashed in my simple stress testing :)

The prototype here is feature-complete relative to the swap-table P4 baseline — swapout, swapin, freeing, swapoff, zswap writeback, zswap shrinker, memcg charging, and THP swapin all work for both vswap and direct-physical entries — and satisfies all three requirements above: no backend coupling (zswap/zero entries hold no physical slot), dynamic swap space (clusters allocated on demand via xarray, no static provisioning), and efficient backend transfer (in-place vtable updates, no PTE/rmap walking).

II. Design

With vswap, pages are assigned virtual swap entries on a ghost device with no backing storage. These entries are backed by zswap, zero pages, or (lazily) physical swap slots. Physical backing is allocated only when needed — on zswap writeback or reclaim writeout, after the rmap step.

Compared to the standalone v6 implementation [1], which introduces a 24-byte per-entry swap descriptor and its own cluster allocator, this edition uses swap_table infrastructure, and share a lot of the allocator logic. Per-slot metadata is stored in a tag-encoded virtual_table (atomic_long_t, 8 bytes per slot), and physical clusters store Pointer-tagged rmap entries in the swap_table for reverse lookup back to the virtual cluster.

Here are some data layout diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +-------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)  |
                       | +--------------------+  |
                       | | swap_table         |  |
                       | |   PFN / Shadow     |  |
                       | | memcg_table        |  |
                       | | count,flags,order  |  |
                       | | lock, list         |  |
                       | +--------------------+  |
                       |                         |
                       | virtual_table           |
                       | +--------------------+  |
                       | | NONE               |  |
                       | | PHYS               |  |
                       | | ZERO               |  |
                       | | ZSWAP(entry*)      |  |
                       | | FOLIO(folio*)      |  |
                       | +--------------------+  |
                       +-------------------------+
                              |
                              | PHYS resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate backend types:

  NONE:   |----- 0000 ------|000|  free / unbacked
  PHYS:   |-- (type:5,off:N)|001|  on a physical swapfile (shifted)
  ZERO:   |----- 0000 ------|010|  zero-filled page
  ZSWAP:  |--- zswap_entry* |011|  compressed in zswap
  FOLIO:  |--- folio* ------|100|  in-memory folio

We still have room for 3 more future backend types, for e.g. CRAM, i.e compressed-CXL-as-swap, which is laid out in [10] and [11]. Worst case scenario, we can add more fields to this extended struct.

Other design points:
- Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens. All the common swap code paths — swapout, swapin, swap freeing, swapoff, zswap writeback, THP swapin, etc. work for both. When CONFIG_VSWAP=n, the vswap branches compile out and behavior should be identical to today's swap-table P4 (at least that is my intention).
- Pointer-tagged swap_table on physical clusters for rmap (physical -> virtual) lookup.
- Virtual swap slots not backed by physical swap are not charged to memcg swap counters — only physical backing is charged (I made the case for this in [7]).
- Careful separation of vswap and physical swap allocation paths and structures adds a lot of complexity, but is crucial to make sure both paths are efficient and do not conflict with each other (for correctness and performance). I do re-use a lot of the allocation logic wherever possible though.

An example of this is the per-cpu cluster caching. I have found that caching virtual and physical clusters in the same structure is a recipe for bugs and performance regressions :) For instance, zswap shrinker will invalidate the cached virtual cluster, and cache its physical cluster instead, which will be reverted by the next vswap allocation.

And a lot more of these random tidbits off the top of my head. See the patches for a proof-of-concept implementation.

III. Follow-ups:

In no particular order (and most of which can be done as follow-up patch series rather than shoving everything in the initial landing):

- More thorough stress testing is very much needed.

- Performance benchmarks to make sure I don't accidentally regress the vswap-less case, and that the vswap's case performance is good. I suspect I will have to port a lot of the optimizations I implemented in v6 over here - some of the inefficiencies are inherent in any swap virtualization, and would require the same fix (for e.g the MRU cluster caching for faster cluster lookup - see [8] and [9]).

- Runtime enable/disable of the vswap device. To be honest, I don't know if there is a value in this. My preference is vswap can be optimized to the point that any overhead is negligible. Failing that, maybe we can come up with some simple heuristics that automatically decides for users?

In this RFC, CONFIG_VSWAP=y means the vswap device is always created at boot, and CONFIG_VSWAP=n means the vswap device is never created. This *might* be enough just on its own.

Is a runtime knob (sysfs or sysctl) worth the complexity beyond these heuristics? I'm not sure yet. Maintaining both cases at runtime also has overhead for checking as well, and some of the checks are not cheap :)

Besides, what does swapon/swapoff buy us here? We do not want multiple vswap devices - they're identical performance-wise, so we will just fragment clusters unnecessarily. We do not care about sizing, since the metadata layer is completely dynamic. If we want to opt-out of vswap at runtime per-cgroup, maybe swap.tier by Youngjun (see [12]) is a better interface than swapon/swapoff?

- Defer per-cluster memcg_table and zeromap allocation on physical clusters. A physical swap cluster backing vswap entries only do not really need their memcg_table, but the current design forces us to allocate it anyway. This is a waste of memory, and is an overhead regression compared to my older design on the zswap-only case, which Johannes has pointed out multiple times (see [6]), and is one of the biggest reasons why I have not been satisfied with this approach thus far. It honestly is a bit of a deal-breaker...

That said, I think I might be able to allocate them on demand, i.e only when the first direct-mapped slot is allocated on that cluster. That will give us the best of BOTH worlds, for both the vswap and directly-mapped physical swap cases. No promises, but I will try (if this approach is good enough for all parties).

- Widen swap_info_struct->max to unsigned long. The vswap device's max is currently clamped to ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) (~16 TiB) to fit in unsigned int. 16 TiB is small for vswap, especially when we're getting increasingly big machines memory-wise.

- Supporting 32-bit architectures. I need to do the math carefully. But do we want to optimize for these architectures anyway? I think the only argument is if somehow virtual swap is so good that we can just get rid of the direct-mapped physical swap case entirely, so we need to support 32-bit architectures. I'm willing to have my mind changed though.

- Add some fat design doc (assuming this approach is acceptable to folks).

- Samefilled page handling is still doable BTW, if folks think this has value :)

This is an early RFC — I have only done basic functional testing so far, and still need to run more thorough stress tests and benchmarks. That said, I figure I should send this out early to get folks's feedback, before I get myself too deep in this rabbit hole - the complexity is already mounting...

[1]: https://lore.kernel.org/all/[email protected]/
[2]: https://lore.kernel.org/all/[email protected]/
[3]: https://lwn.net/Articles/1072657/
[4]: https://lore.kernel.org/all/[email protected]/
[5]: https://lore.kernel.org/all/aerrps94j70MkgdW@gourry-fedora-PF4VCD3F/
[6]: https://lore.kernel.org/all/[email protected]/
[7]: https://lore.kernel.org/linux-mm/CAKEwX=P4syV38jAVCWq198r2OHXXc=xA-fx1dk6+qYef6yzxWQ@mail.gmail.com/
[8]: https://lore.kernel.org/all/CAKEwX=NrUhUrAFx+8BYJEfaVKpCm-H9JhBzYSrqOQb-NW7QRug@mail.gmail.com/
[9]: https://lore.kernel.org/all/[email protected]/
[10]: https://lore.kernel.org/all/aerrps94j70MkgdW@gourry-fedora-PF4VCD3F/
[11]: https://lore.kernel.org/all/afIKxG5mJZE6QgpR@gourry-fedora-PF4VCD3F/
[12]: https://lore.kernel.org/all/[email protected]/

Nhat Pham (5):
mm, swap: add virtual swap device infrastructure mm, swap: support zswap and zeroswap as vswap backends mm, swap: support physical swap as a vswap backend mm, swap: only charge physical swap entries mm, swap: add debugfs counters for vswap

 MAINTAINERS           |    1 +
 include/linux/swap.h  |   71 +++
 include/linux/zswap.h |    3 +
 mm/Kconfig            |   10 +
 mm/internal.h         |   20 +-
 mm/madvise.c          |    2 +-
 mm/memcontrol.c       |  132 ++++-
 mm/memory.c           |   34 +-
 mm/page_io.c          |  195 ++++++--
 mm/swap.h             |   59 ++-
 mm/swap_state.c       |   51 +-
 mm/swap_table.h       |   56 +++
 mm/swapfile.c         | 1096 +++++++++++++++++++++++++++++++++++++----
 mm/vmscan.c           |    5 +-
 mm/vswap.h            |  445 +++++++++++++++++
 mm/zswap.c            |  167 +++++--
 16 files changed, 2108 insertions(+), 239 deletions(-)
 create mode 100644 mm/vswap.h

base-commit: 401c55d4eacd97ffd24a89829655baa43b2b308e

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

RFC PATCH 1/5 mm, swap: add virtual swap device infrastructure

Create a massive virtual swap device at boot, along with the dynamic cluster infrastructure that the rest of the vswap layer is built on:

- swap_cluster_info_dynamic: per-cluster dynamic info kept in an xarray, allowing arbitrary-size devices without the static cluster_info[] array.
- virtual_table: a per-slot side table for vswap backend metadata (tag-encoded in low bits). The field itself is added in the next patch; this commit only introduces the dynamic cluster container that will hold it.
- The size of the vswap device is ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) pages.

Gated by a new CONFIG_VSWAP (depends on SWAP && 64BIT). For now, the vswap device cannot be swapon'd or swapoff'd — it is created unconditionally at boot when CONFIG_VSWAP=y and lives for the lifetime of the kernel. The SWP_VSWAP flag and swap_is_vswap() helper let hot paths skip per-device bookkeeping that doesn't apply (avail-list management, percpu_ref get/put, hibernation target lookup, etc.).

This patch is pure scaffolding: it introduces the device, the dynamic-cluster machinery, and the general shape of a vswap allocator (with sanity checks), but does not hook the vswap device into any allocation path. folio_alloc_swap will not produce vswap entries until a subsequent patch wires it in. Backends (zswap, zero, physical disk) and the vswap-aware swap-out / swap-in / writeback paths arrive in subsequent patches.

---
 MAINTAINERS          |   1 +
 include/linux/swap.h |   4 +
 mm/Kconfig           |  10 ++
 mm/page_io.c         |  18 ++-
 mm/swap.h            |  46 ++++++--
 mm/swap_state.c      |  43 ++++---
 mm/swap_table.h      |   2 +
 mm/swapfile.c        | 264 +++++++++++++++++++++++++++++++++++++++----
 mm/vswap.h           |  29 +++++
 mm/zswap.c           |  10 +-
 10 files changed, 375 insertions(+), 52 deletions(-)
 create mode 100644 mm/vswap.h
MAINTAINERS +1 -0
index 9be179722d42..e96bd0bf6307 100644
@@ -17041,6 +17041,7 @@ F:	mm/swap.h
 F:	mm/swap_table.h
 F:	mm/swap_state.c
 F:	mm/swapfile.c
+F:	mm/vswap.h
 
 MEMORY MANAGEMENT - THP (TRANSPARENT HUGE PAGE)
 M:	Andrew Morton <[email protected]>
include/linux/swap.h +4 -0
index 6d72778e6cc3..ee9b1e76b058 100644
@@ -214,6 +214,7 @@ enum {
 	SWP_STABLE_WRITES = (1 << 11),	/* no overwrite PG_writeback pages */
 	SWP_SYNCHRONOUS_IO = (1 << 12),	/* synchronous IO is efficient */
 	SWP_HIBERNATION = (1 << 13),	/* pinned for hibernation */
+	SWP_VSWAP	= (1 << 14),	/* virtual swap device */
 					/* add others here before... */
 };
 
@@ -282,6 +283,7 @@ struct swap_info_struct {
 	struct work_struct reclaim_work; /* reclaim worker */
 	struct list_head discard_clusters; /* discard clusters list */
 	struct plist_node avail_list;   /* entry in swap_avail_head */
+	struct xarray cluster_info_pool; /* Xarray for vswap dynamic cluster info */
 };
 
 static inline swp_entry_t page_swap_entry(struct page *page)
@@ -473,6 +475,8 @@ void swap_free_hibernation_slot(swp_entry_t entry);
 
 static inline void put_swap_device(struct swap_info_struct *si)
 {
+	if (si->flags & SWP_VSWAP)
+		return;
 	percpu_ref_put(&si->users);
 }
 
mm/Kconfig +10 -0
index 776b67c66e82..fc395ae3dde8 100644
@@ -19,6 +19,16 @@ menuconfig SWAP
 	  used to provide more virtual memory than the actual RAM present
 	  in your computer.  If unsure say Y.
 
+config VSWAP
+	bool "Virtual swap device"
+	depends on SWAP && 64BIT
+	help
+	  Adds a virtual swap layer that decouples swap entries in page
+	  tables from physical backing storage. Swap entries are allocated
+	  from a virtual swap device and can be backed by zswap, a physical
+	  swapfile, or kept in memory — with the backing changeable at
+	  runtime without invalidating page table entries.
+
 config ZSWAP
 	bool "Compressed cache for swap pages"
 	depends on SWAP
mm/page_io.c +15 -3
index f2d8fe7fd057..8126be6e4cfb 100644
@@ -295,8 +295,7 @@ int swap_writeout(struct folio *folio, struct swap_iocb **swap_plug)
 	}
 	rcu_read_unlock();
 
-	__swap_writepage(folio, swap_plug);
-	return 0;
+	return __swap_writepage(folio, swap_plug);
 out_unlock:
 	folio_unlock(folio);
 	return ret;
@@ -458,11 +457,18 @@ static void swap_writepage_bdev_async(struct folio *folio,
 	submit_bio(bio);
 }
 
-void __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug)
+int __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug)
 {
 	struct swap_info_struct *sis = __swap_entry_to_info(folio->swap);
 
 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
+
+	if (sis->flags & SWP_VSWAP) {
+		/* Prevent the page from getting reclaimed. */
+		folio_set_dirty(folio);
+		return AOP_WRITEPAGE_ACTIVATE;
+	}
+
 	/*
 	 * ->flags can be updated non-atomically,
 	 * but that will never affect SWP_FS_OPS, so the data_race
@@ -479,6 +485,7 @@ void __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug)
 		swap_writepage_bdev_sync(folio, sis);
 	else
 		swap_writepage_bdev_async(folio, sis);
+	return 0;
 }
 
 void swap_write_unplug(struct swap_iocb *sio)
@@ -684,6 +691,11 @@ void swap_read_folio(struct folio *folio, struct swap_iocb **plug)
 	if (zswap_load(folio) != -ENOENT)
 		goto finish;
 
+	if (unlikely(sis->flags & SWP_VSWAP)) {
+		folio_unlock(folio);
+		goto finish;
+	}
+
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
 
mm/swap.h +39 -7

84 lines not on this page · raw message

mm/swap_state.c +28 -15

119 lines not on this page · raw message

mm/swap_table.h +2 -0
index e6613e62f8d0..fd7f0fb9836a 100644
@@ -255,6 +255,8 @@ static inline unsigned long swap_table_get(struct swap_cluster_info *ci,
 	unsigned long swp_tb;
 
 	VM_WARN_ON_ONCE(off >= SWAPFILE_CLUSTER);
+	if (!ci)
+		return SWP_TB_NULL;
 
 	rcu_read_lock();
 	table = rcu_dereference(ci->table);
mm/swapfile.c +239 -25

508 lines not on this page · raw message

mm/vswap.h new file +29 -0
new file mode 100644
index 000000000000..094ff16cb5a4
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Virtual swap space
+ *
+ * Copyright (C) 2026 Nhat Pham
+ */
+#ifndef _MM_VSWAP_H
+#define _MM_VSWAP_H
+
+#include <linux/swap.h>
+
+#ifdef CONFIG_VSWAP
+
+extern struct swap_info_struct *vswap_si;
+
+static inline bool swap_is_vswap(struct swap_info_struct *si)
+{
+	return si->flags & SWP_VSWAP;
+}
+
+#else
+
+static inline bool swap_is_vswap(struct swap_info_struct *si)
+{
+	return false;
+}
+
+#endif /* CONFIG_VSWAP */
+#endif /* _MM_VSWAP_H */
mm/zswap.c +8 -2
index 761cd699e0a3..993406074d58 100644
@@ -994,11 +994,16 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	struct swap_info_struct *si;
 	int ret = 0;
 
-	/* try to allocate swap cache folio */
 	si = get_swap_device(swpentry);
 	if (!si)
 		return -EEXIST;
 
+	if (si->flags & SWP_VSWAP) {
+		put_swap_device(si);
+		return -EINVAL;
+	}
+
+	/* try to allocate swap cache folio */
 	mpol = get_task_policy(current);
 	folio = swap_cache_alloc_folio(swpentry, GFP_KERNEL, BIT(0), NULL, mpol,
 				       NO_INTERLEAVE_INDEX);
@@ -1049,7 +1054,8 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	folio_set_reclaim(folio);
 
 	/* start writeback */
-	__swap_writepage(folio, NULL);
+	ret = __swap_writepage(folio, NULL);
+	WARN_ON_ONCE(ret);
 
 out:
 	if (ret) {
Signature · 1 line
2.53.0-Meta
author maintainer
#2 lore raw

RFC PATCH 2/5 mm, swap: support zswap and zeroswap as vswap backends

In reply to Nhat Pham

Build the virtual swap layer on top of the swap-table infrastructure. Virtual swap entries decouple PTE swap entries from physical backing, allowing pages to be compressed by zswap (or detected as zero-filled) without pre-allocating a physical swap slot.

This patch only supports zswap and zero-page backends. If zswap_store fails, the page stays dirty in the swap cache (AOP_WRITEPAGE_ACTIVATE) — physical disk backing fallback comes in the next patch. Zswap writeback of vswap-backed entries is also disabled — the shrinker skips when no physical swap pages are available.

---
 include/linux/zswap.h |   3 +
 mm/internal.h         |  20 ++-
 mm/madvise.c          |   2 +-
 mm/memcontrol.c       |   8 +-
 mm/memory.c           |  20 ++-
 mm/page_io.c          |  61 +++++--
 mm/swap.h             |   4 +-
 mm/swap_state.c       |   8 +
 mm/swap_table.h       |  53 ++++++
 mm/swapfile.c         | 375 +++++++++++++++++++++++++++++++++---------
 mm/vmscan.c           |   5 +-
 mm/vswap.h            | 292 +++++++++++++++++++++++++++++++-
 mm/zswap.c            | 106 +++++++-----
 13 files changed, 807 insertions(+), 150 deletions(-)
include/linux/zswap.h +3 -0
index 30c193a1207e..4b4f211f3301 100644
@@ -6,6 +6,7 @@
 #include <linux/mm_types.h>
 
 struct lruvec;
+struct zswap_entry;
 
 extern atomic_long_t zswap_stored_pages;
 
@@ -28,6 +29,7 @@ unsigned long zswap_total_pages(void);
 bool zswap_store(struct folio *folio);
 int zswap_load(struct folio *folio);
 void zswap_invalidate(swp_entry_t swp);
+void zswap_entry_free(struct zswap_entry *entry);
 int zswap_swapon(int type, unsigned long nr_pages);
 void zswap_swapoff(int type);
 void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg);
@@ -50,6 +52,7 @@ static inline int zswap_load(struct folio *folio)
 }
 
 static inline void zswap_invalidate(swp_entry_t swp) {}
+static inline void zswap_entry_free(struct zswap_entry *entry) {}
 static inline int zswap_swapon(int type, unsigned long nr_pages)
 {
 	return 0;
mm/internal.h +18 -2
index 7646ecb9d621..23ea4c8172df 100644
@@ -16,6 +16,7 @@
 #include <linux/pagewalk.h>
 #include <linux/rmap.h>
 #include <linux/swap.h>
+#include "vswap.h"
 #include <linux/leafops.h>
 #include <linux/tracepoint-defs.h>
 
@@ -436,6 +437,9 @@ 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: True when the batch is for a free path. Skips the
+ *              vswap uniform-backing check (which is only relevant
+ *              for swapin batches).
  *
  * Detect a batch of contiguous swap entries: consecutive (non-present) PTEs
  * containing swap entries all with consecutive offsets and targeting the same
@@ -446,11 +450,14 @@ 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;
 	pte_t *ptep = start_ptep + 1;
+	swp_entry_t entry __maybe_unused;
+	int nr;
 
 	VM_WARN_ON(max_nr < 1);
 	VM_WARN_ON(!softleaf_is_swap(softleaf_from_pte(pte)));
@@ -464,7 +471,16 @@ 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;
+#ifdef CONFIG_VSWAP
+	if (!free_batch) {
+		entry = softleaf_from_pte(ptep_get(start_ptep));
+		if (nr > 1 && swap_is_vswap(__swap_entry_to_info(entry)) &&
+		    !vswap_can_swapin_thp(entry, nr))
+			return 1;
+	}
+#endif
+	return nr;
 }
 #endif /* CONFIG_MMU */
 
mm/madvise.c +1 -1
index cd9bb077072c..75ec10fbd61a 100644
@@ -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;
 				swap_put_entries_direct(entry, nr);
 				clear_not_present_full_ptes(mm, addr, pte, nr, tlb->fullmm);
mm/memcontrol.c +7 -1
index 039e9bc8971c..a3ad83c229f7 100644
@@ -48,6 +48,7 @@
 #include <linux/rbtree.h>
 #include <linux/slab.h>
 #include <linux/swapops.h>
+#include <linux/zswap.h>
 #include <linux/spinlock.h>
 #include <linux/fs.h>
 #include <linux/seq_file.h>
@@ -5538,8 +5539,13 @@ void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
 
 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
 {
-	long nr_swap_pages = get_nr_swap_pages();
+	long nr_swap_pages;
 
+	/* vswap provides unbounded virtual swap when zswap is enabled */
+	if (IS_ENABLED(CONFIG_VSWAP) && zswap_is_enabled())
+		return PAGE_COUNTER_MAX;
+
+	nr_swap_pages = get_nr_swap_pages();
 	if (mem_cgroup_disabled() || do_memsw_account())
 		return nr_swap_pages;
 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
mm/memory.c +12 -8
index 7c020995eafc..c3050e49b086 100644
@@ -1764,7 +1764,7 @@ static inline int zap_nonpresent_ptes(struct mmu_gather *tlb,
 		if (!should_zap_cows(details))
 			return 1;
 
-		nr = swap_pte_batch(pte, max_nr, ptent);
+		nr = swap_pte_batch(pte, max_nr, ptent, true);
 		rss[MM_SWAPENTS] -= nr;
 		swap_put_entries_direct(entry, nr);
 	} else if (softleaf_is_migration(entry)) {
@@ -4630,7 +4630,7 @@ static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages)
 	 * from different backends. And they are likely corner cases. Similar
 	 * things might be added once zswap support large folios.
 	 */
-	if (swap_pte_batch(ptep, nr_pages, pte) != nr_pages)
+	if (swap_pte_batch(ptep, nr_pages, pte, false) != nr_pages)
 		return false;
 	return true;
 }
@@ -4675,15 +4675,19 @@ static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf)
 	if (unlikely(userfaultfd_armed(vma)))
 		return 0;
 
+	entry = softleaf_from_pte(vmf->orig_pte);
+
 	/*
-	 * A large swapped out folio could be partially or fully in zswap. We
-	 * lack handling for such cases, so fallback to swapping in order-0
-	 * folio.
+	 * A large swapped out folio could be partially or fully in zswap.
+	 * With vswap, vswap_can_swapin_thp() (via swap_pte_batch) lets
+	 * THP swapin through only for backings that don't need per-page
+	 * decompression. For non-vswap entries we still need the
+	 * zswap_never_enabled() bail — zswap_load rejects large folios
+	 * with -EINVAL, which would SIGBUS the fault.
 	 */
-	if (!zswap_never_enabled())
+	if (!swap_is_vswap(__swap_entry_to_info(entry)) && !zswap_never_enabled())
 		return 0;
 
-	entry = softleaf_from_pte(vmf->orig_pte);
 	/*
 	 * Get a list of all the (large) orders below PMD_ORDER that are enabled
 	 * and suitable for swapping THP.
@@ -4942,7 +4946,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 		folio_ptep = vmf->pte - idx;
 		folio_pte = ptep_get(folio_ptep);
 		if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
-		    swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
+		    swap_pte_batch(folio_ptep, nr, folio_pte, false) != nr)
 			goto check_folio;
 
 		page_idx = idx;
mm/page_io.c +48 -13

108 lines not on this page · raw message

mm/swap.h +3 -1
index 479ee5871cb9..640413e30880 100644
@@ -69,7 +69,9 @@ struct swap_cluster_info_dynamic {
 	struct swap_cluster_info ci;	/* Underlying cluster info */
 	unsigned int index;		/* for cluster_index() */
 	struct rcu_head rcu;		/* For kfree_rcu deferred free */
-	/* Backend pointers (virtual_table) added in a later patch. */
+#ifdef CONFIG_VSWAP
+	atomic_long_t *virtual_table;	/* Backing pointers for vswap slots */
+#endif
 };
 
 /* All on-list cluster must have a non-zero flag. */
mm/swap_state.c +8 -0
index b063c47138c5..6bfa185b7d0f 100644
@@ -25,6 +25,7 @@
 #include "internal.h"
 #include "swap_table.h"
 #include "swap.h"
+#include "vswap.h"
 
 /*
  * swapper_space is a fiction, retained to simplify the path through
@@ -692,6 +693,13 @@ struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders,
 	if (IS_ERR(folio))
 		return folio;
 
+	if (folio_test_large(folio) && swap_is_vswap(__swap_entry_to_info(folio->swap)) &&
+	    !vswap_can_swapin_thp(folio->swap, folio_nr_pages(folio))) {
+		folio_unlock(folio);
+		folio_put(folio);
+		return NULL;
+	}
+
 	swap_read_folio(folio, NULL);
 	return folio;
 }
mm/swap_table.h +53 -0

63 lines not on this page · raw message

mm/swapfile.c +293 -82

654 lines not on this page · raw message

mm/vmscan.c +4 -1
index ca4533eba701..94b6cfcc28ac 100644
@@ -350,6 +350,9 @@ static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
 		 */
 		if (get_nr_swap_pages() > 0)
 			return true;
+		/* vswap doesn't contribute to nr_swap_pages */
+		if (IS_ENABLED(CONFIG_VSWAP) && zswap_is_enabled())
+			return true;
 	} else {
 		/* Is the memcg below its swap limit? */
 		if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
@@ -2615,7 +2618,7 @@ static bool can_age_anon_pages(struct lruvec *lruvec,
 			       struct scan_control *sc)
 {
 	/* Aging the anon LRU is valuable if swap is present: */
-	if (total_swap_pages > 0)
+	if (total_swap_pages > 0 || (IS_ENABLED(CONFIG_VSWAP) && zswap_is_enabled()))
 		return true;
 
 	/* Also valuable if anon pages can be demoted: */
mm/vswap.h +288 -4

311 lines not on this page · raw message

mm/zswap.c +69 -37

183 lines not on this page · raw message

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

RFC PATCH 3/5 mm, swap: support physical swap as a vswap backend

In reply to Nhat Pham

Add physical swap as a backend for the virtual swap layer. Without this, vswap can only back entries with zswap or zero pages, and a zswap_store failure has nowhere to fall back to — the page stays dirty in swap cache (AOP_WRITEPAGE_ACTIVATE).

With physical swap backing, vswap can allocate a physical slot on demand when needed: as a fallback for zswap_store failures, or as the destination for zswap writeback.

Each vswap entry's physical slot is tracked via a Pointer-tagged swap_table entry on the physical cluster (rmap back to the vswap entry).

---
 include/linux/swap.h |  10 ++
 mm/memcontrol.c      |   8 +-
 mm/memory.c          |  14 +-
 mm/page_io.c         | 130 ++++++++++----
 mm/swap.h            |  11 ++
 mm/swap_table.h      |   1 +
 mm/swapfile.c        | 398 ++++++++++++++++++++++++++++++++++++++++---
 mm/vswap.h           | 138 ++++++++++++++-
 mm/zswap.c           |  79 ++++++---
 9 files changed, 698 insertions(+), 91 deletions(-)
include/linux/swap.h +10 -0
index ee9b1e76b058..3fb55485fc76 100644
@@ -449,6 +449,16 @@ extern int swp_swapcount(swp_entry_t entry);
 struct backing_dev_info;
 extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
 sector_t swap_folio_sector(struct folio *folio);
+sector_t swap_entry_sector(swp_entry_t entry);
+
+#ifdef CONFIG_VSWAP
+swp_entry_t folio_realloc_swap(struct folio *folio);
+#else
+static inline swp_entry_t folio_realloc_swap(struct folio *folio)
+{
+	return (swp_entry_t){};
+}
+#endif
 
 /*
  * If there is an existing swap slot reference (swap entry) and the caller
mm/memcontrol.c +7 -1
index a3ad83c229f7..7492879b3239 100644
@@ -5541,7 +5541,13 @@ long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
 {
 	long nr_swap_pages;
 
-	/* vswap provides unbounded virtual swap when zswap is enabled */
+	/*
+	 * vswap provides unbounded virtual swap when zswap is enabled.
+	 * (No per-memcg may_zswap check — mem_cgroup_may_zswap can sleep
+	 * via __mem_cgroup_flush_stats, but this is callable from
+	 * rcu_read_lock contexts like cachestat(2) → workingset_test_recent.
+	 * The per-memcg swap.max is still enforced at charge time.)
+	 */
 	if (IS_ENABLED(CONFIG_VSWAP) && zswap_is_enabled())
 		return PAGE_COUNTER_MAX;
 
mm/memory.c +11 -3
index c3050e49b086..d15c748d4f90 100644
@@ -89,6 +89,7 @@
 #include "pgalloc-track.h"
 #include "internal.h"
 #include "swap.h"
+#include "vswap.h"
 
 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
@@ -4523,7 +4524,14 @@ static inline bool should_try_to_free_swap(struct swap_info_struct *si,
 	 * are fast, and meanwhile, swap cache pinning the slot deferring the
 	 * release of metadata or fragmentation is a more critical issue.
 	 */
-	if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
+	if (swap_entry_backend_has_flag(si, folio->swap, SWP_SYNCHRONOUS_IO))
+		return true;
+	/*
+	 * Non-swapfile backends cannot be reused for future swapouts.
+	 * Free the swap slot unless backed by contiguous physical swap.
+	 */
+	if (swap_is_vswap(si) &&
+	    !vswap_swapfile_backed(folio->swap, folio_nr_pages(folio)))
 		return true;
 	if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
 	    folio_test_mlocked(folio))
@@ -4832,7 +4840,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 		swap_update_readahead(folio, vma, vmf->address);
 	if (!folio) {
 		/* Swapin bypasses readahead for SWP_SYNCHRONOUS_IO devices */
-		if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
+		if (swap_entry_backend_has_flag(si, entry, SWP_SYNCHRONOUS_IO))
 			folio = swapin_sync(entry, GFP_HIGHUSER_MOVABLE,
 					    thp_swapin_suitable_orders(vmf) | BIT(0),
 					    vmf, NULL, 0);
@@ -5007,7 +5015,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 			 */
 			exclusive = true;
 		} else if (exclusive && folio_test_writeback(folio) &&
-			  data_race(si->flags & SWP_STABLE_WRITES)) {
+			  swap_entry_backend_has_flag(si, entry, SWP_STABLE_WRITES)) {
 			/*
 			 * This is tricky: not all swap backends support
 			 * concurrent page modifications while under writeback.
mm/page_io.c +96 -34

229 lines not on this page · raw message

mm/swap.h +11 -0
index 640413e30880..50c90a35382c 100644
@@ -285,6 +285,17 @@ static inline void swap_read_unplug(struct swap_iocb *plug)
 void swap_write_unplug(struct swap_iocb *sio);
 int swap_writeout(struct folio *folio, struct swap_iocb **swap_plug);
 int __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug);
+#ifdef CONFIG_VSWAP
+int __swap_writepage_phys(struct folio *folio, struct swap_iocb **swap_plug,
+			  swp_entry_t phys_entry);
+#else
+static inline int __swap_writepage_phys(struct folio *folio,
+					struct swap_iocb **swap_plug,
+					swp_entry_t phys_entry)
+{
+	return -EINVAL;
+}
+#endif
 
 /* linux/mm/swap_state.c */
 extern struct address_space swap_space __read_mostly;
mm/swap_table.h +1 -0
index b0e7ef9c966b..814bc75597a0 100644
@@ -406,6 +406,7 @@ static inline swp_entry_t swp_tb_ptr_to_swp_entry(unsigned long swp_tb)
 	return entry;
 }
 #else
+#define SWP_RMAP_CACHE_ONLY	0UL
 static inline bool swp_tb_is_pointer(unsigned long swp_tb)
 {
 	return false;
mm/swapfile.c +372 -26

569 lines not on this page · raw message

mm/vswap.h +135 -3

191 lines not on this page · raw message

mm/zswap.c +55 -24

116 lines not on this page · raw message

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

RFC PATCH 4/5 mm, swap: only charge physical swap entries

In reply to Nhat Pham

Stop double-charging vswap entries against memcg->swap. Previously, the entry was charged once at vswap allocation (via mem_cgroup_try_charge_swap) and implicitly again when physical backing was allocated.

Split the lifecycle into four operations: record the memcg private ID at vswap alloc without charging; charge memcg->swap only when physical backing is allocated via folio_realloc_swap; uncharge in vswap_release_backing (only nr_swapfile entries on v2, all nr on v1 memsw); and drop the ID ref at __swap_cluster_free_entries without uncharging.

Direct-mapped physical swap charging is unchanged.

---
 include/linux/swap.h |  57 +++++++++++++++++++++
 mm/memcontrol.c      | 118 +++++++++++++++++++++++++++++++++++++++++++
 mm/swapfile.c        | 109 ++++++++++++++++++++++++++++++++++++---
 3 files changed, 276 insertions(+), 8 deletions(-)
include/linux/swap.h +57 -0
index 3fb55485fc76..6f18ecdf0bb8 100644
@@ -597,6 +597,43 @@ static inline int mem_cgroup_try_charge_swap(struct folio *folio)
 	return __mem_cgroup_try_charge_swap(folio);
 }
 
+extern void __mem_cgroup_record_swap(struct folio *folio);
+static inline void mem_cgroup_record_swap(struct folio *folio)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_record_swap(folio);
+}
+
+extern int __mem_cgroup_charge_backing_phys_swap(struct mem_cgroup *memcg,
+					 unsigned int nr_pages);
+static inline int mem_cgroup_charge_backing_phys_swap(struct mem_cgroup *memcg,
+					      unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return 0;
+	return __mem_cgroup_charge_backing_phys_swap(memcg, nr_pages);
+}
+
+extern void __mem_cgroup_uncharge_backing_phys_swap(struct mem_cgroup *memcg,
+					    unsigned int nr_pages);
+static inline void mem_cgroup_uncharge_backing_phys_swap(struct mem_cgroup *memcg,
+						 unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_uncharge_backing_phys_swap(memcg, nr_pages);
+}
+
+extern void __mem_cgroup_id_put_swap(unsigned short id, unsigned int nr_pages);
+static inline void mem_cgroup_id_put_swap(unsigned short id,
+					  unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_id_put_swap(id, nr_pages);
+}
+
 extern void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages);
 static inline void mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
 {
@@ -613,6 +650,26 @@ static inline int mem_cgroup_try_charge_swap(struct folio *folio)
 	return 0;
 }
 
+static inline void mem_cgroup_record_swap(struct folio *folio)
+{
+}
+
+static inline int mem_cgroup_charge_backing_phys_swap(struct mem_cgroup *memcg,
+					      unsigned int nr_pages)
+{
+	return 0;
+}
+
+static inline void mem_cgroup_uncharge_backing_phys_swap(struct mem_cgroup *memcg,
+						 unsigned int nr_pages)
+{
+}
+
+static inline void mem_cgroup_id_put_swap(unsigned short id,
+					  unsigned int nr_pages)
+{
+}
+
 static inline void mem_cgroup_uncharge_swap(unsigned short id,
 					    unsigned int nr_pages)
 {
mm/memcontrol.c +118 -0

124 lines not on this page · raw message

mm/swapfile.c +101 -8

189 lines not on this page · raw message

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

RFC PATCH 5/5 mm, swap: add debugfs counters for vswap

In reply to Nhat Pham

Add /sys/kernel/debug/vswap/ with two counters:

- used: number of virtual swap slots currently allocated
- alloc_reject: cumulative count of failed vswap allocations

---
 mm/swapfile.c | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
mm/swapfile.c +15 -1
index be901fb741e5..3740ab764405 100644
@@ -7,6 +7,7 @@
  */
 
 #include <linux/blkdev.h>
+#include <linux/debugfs.h>
 #include <linux/mm.h>
 #include <linux/sched/mm.h>
 #include <linux/sched/task.h>
@@ -132,6 +133,9 @@ static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) = {
 	.lock = INIT_LOCAL_LOCK(),
 };
 
+static atomic_t __maybe_unused vswap_used = ATOMIC_INIT(0);
+static atomic_t __maybe_unused vswap_alloc_reject = ATOMIC_INIT(0);
+
 #ifdef CONFIG_VSWAP
 struct percpu_vswap_cluster {
 	unsigned long offset[SWAP_NR_ORDERS];
@@ -1993,11 +1997,13 @@ static bool vswap_alloc(struct folio *folio)
 	if (folio_test_swapcache(folio)) {
 		/* alloc_swap_scan_cluster updated percpu offset already */
 		local_unlock(&percpu_vswap_cluster.lock);
+		atomic_add(folio_nr_pages(folio), &vswap_used);
 		return true;
 	}
 
 	this_cpu_write(percpu_vswap_cluster.offset[order], SWAP_ENTRY_INVALID);
 	local_unlock(&percpu_vswap_cluster.lock);
+	atomic_add(folio_nr_pages(folio), &vswap_alloc_reject);
 	return false;
 }
 #endif
@@ -2554,8 +2560,10 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 
 	VM_WARN_ON(ci->count < nr_pages);
 
-	if (is_vswap)
+	if (is_vswap) {
 		vswap_release_backing(ci, ci_start, nr_pages);
+		atomic_sub(nr_pages, &vswap_used);
+	}
 
 	ci->count -= nr_pages;
 	do {
@@ -4793,6 +4801,7 @@ struct swap_info_struct *vswap_si;
 static int __init vswap_init(void)
 {
 	struct swap_info_struct *si;
+	struct dentry *root;
 	unsigned long maxpages;
 	int err;
 
@@ -4819,6 +4828,11 @@ static int __init vswap_init(void)
 	mutex_unlock(&swapon_mutex);
 
 	vswap_si = si;
+
+	root = debugfs_create_dir("vswap", NULL);
+	debugfs_create_atomic_t("used", 0444, root, &vswap_used);
+	debugfs_create_atomic_t("alloc_reject", 0444, root, &vswap_alloc_reject);
+
 	pr_info("vswap: created virtual swap device (%lu pages)\n", maxpages);
 	return 0;
 
Signature · 1 line
2.53.0-Meta
#6 lore raw
In reply to Nhat Pham
Quoted 11 lines · Nhat Pham

Based on: mm-unstable @ 444fc9435e57 + swap-table phase IV v5 [2].

I manually adapted Kairui's ghost device implementation (from [4]) for my vswap device. I've credited him as Co-developed-by on Patch I since a substantial portion of the dynamic-cluster infrastructure is his (I did propose the idea of using xarray/radix tree for dynamic swap clusters allocation and management though :P).

Quoted 1 line

From here on out, for simplicity, I will refer to swap table phase IV

as "P4", and the older v6 virtual swap space implementation as "v6".

...

Quoted 97 lines

This series reimplements the virtual swap space concept (see [1]) on top of Kairui Song's swap table infrastructure, on top of [2] and in accordance with his proposal in [3]. The proposal's idea is interesting, so I decided to give it a shot myself. I'm still not 100% sure that this is bug-proof, but hey, it compiles, and has not crashed in my simple stress testing :)

The prototype here is feature-complete relative to the swap-table P4 baseline — swapout, swapin, freeing, swapoff, zswap writeback, zswap shrinker, memcg charging, and THP swapin all work for both vswap and direct-physical entries — and satisfies all three requirements above: no backend coupling (zswap/zero entries hold no physical slot), dynamic swap space (clusters allocated on demand via xarray, no static provisioning), and efficient backend transfer (in-place vtable updates, no PTE/rmap walking).

II. Design

With vswap, pages are assigned virtual swap entries on a ghost device with no backing storage. These entries are backed by zswap, zero pages, or (lazily) physical swap slots. Physical backing is allocated only when needed — on zswap writeback or reclaim writeout, after the rmap step.

Compared to the standalone v6 implementation [1], which introduces a 24-byte per-entry swap descriptor and its own cluster allocator, this edition uses swap_table infrastructure, and share a lot of the allocator logic. Per-slot metadata is stored in a tag-encoded virtual_table (atomic_long_t, 8 bytes per slot), and physical clusters store Pointer-tagged rmap entries in the swap_table for reverse lookup back to the virtual cluster.

Here are some data layout diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +-------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)  |
                       | +--------------------+  |
                       | | swap_table         |  |
                       | |   PFN / Shadow     |  |
                       | | memcg_table        |  |
                       | | count,flags,order  |  |
                       | | lock, list         |  |
                       | +--------------------+  |
                       |                         |
                       | virtual_table           |
                       | +--------------------+  |
                       | | NONE               |  |
                       | | PHYS               |  |
                       | | ZERO               |  |
                       | | ZSWAP(entry*)      |  |
                       | | FOLIO(folio*)      |  |
                       | +--------------------+  |
                       +-------------------------+
                              |
                              | PHYS resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate backend types:

Quoted 5 lines
  NONE:   |----- 0000 ------|000|  free / unbacked
  PHYS:   |-- (type:5,off:N)|001|  on a physical swapfile (shifted)
  ZERO:   |----- 0000 ------|010|  zero-filled page
  ZSWAP:  |--- zswap_entry* |011|  compressed in zswap
  FOLIO:  |--- folio* ------|100|  in-memory folio

Thanks for trying this approach!

For the format part, PHYS don't need that much bits I think, so by slightly adjust the format vswap device could be share mostly the same format with ordinary device.

For example typical modern system don't have a address space larger than 52 bit. (Even with full 64 bits used for addressing, shift it by 12 we get 52). Plus 5 for type, you get 57, so you can have a marker that should work as long as it shorter than 1000000 for PHYS, and shared for all table format since it's not in conflict with anything. You have also use a few extra bits so a single swap space can be 8 times larger than RAM space, and since we can help multiple swap type I think that should be far than enough?

Then you have Shadow back at 001, and zero bit in shadow. The only special one is Zswap, which will be 100 now, and that's exactly the reserved pointer format in current swap table format, on seeing si->flags & VSWAP && is_pointer(swp_tb) you know that's zswap :)

Folio / PFN can still be 010 as in the current swap table format.

Then everything seems clean and aligned, no more special handling for vswap needed, there are detailed to sort out, but it should work.

Quoted 2 lines

- Pointer-tagged swap_table on physical clusters for rmap (physical -> virtual) lookup.

Or reuse the PHYS format (rename it maybe) since point back to vswap is also pointing to a si.

Quoted 7 lines

III. Follow-ups:

In no particular order (and most of which can be done as follow-up patch series rather than shoving everything in the initial landing):

- More thorough stress testing is very much needed.

Quoted 7 lines

- Performance benchmarks to make sure I don't accidentally regress the vswap-less case, and that the vswap's case performance is good. I suspect I will have to port a lot of the optimizations I implemented in v6 over here - some of the inefficiencies are inherent in any swap virtualization, and would require the same fix (for e.g the MRU cluster caching for faster cluster lookup - see [8] and [9]).

This could be imporved by per-si percpu cluster. Both YoungJun's tiering and Baoquan's previous swap ops mentioned this is needed, and now vswap also need that. If the vswap is also a si, then it will make use of this too.

YoungJun posted this a few month before:
https://lore.kernel.org/linux-mm/[email protected]/

The concern is that some locking contention could be heavier, or maybe that's just a hypothetical problem though.

Quoted 7 lines

- Runtime enable/disable of the vswap device. To be honest, I don't know if there is a value in this. My preference is vswap can be optimized to the point that any overhead is negligible. Failing that, maybe we can come up with some simple heuristics that automatically decides for users?

Quoted 6 lines

In this RFC, CONFIG_VSWAP=y means the vswap device is always created at boot, and CONFIG_VSWAP=n means the vswap device is never created. This *might* be enough just on its own.

Is a runtime knob (sysfs or sysctl) worth the complexity beyond these heuristics? I'm not sure yet. Maintaining both cases

I checked the code and I think it's not hard to do, patch 1 already handling the meta data dynamically, everything will still just work even if you remove vswap at runtime. The rest of patches need adaption but might not end up being complex, it other comments here are considered.

For patch 2, a few routines like vswap_can_swapin_thp seems not needed or should be moved to __swap_cache_alloc? VSWAP_FOLIO is same as swap cache folio check, which is already covered. Same for zero checking, and VSWAP_NONE which is same as swap count check I think. That way we not only save a lot of code, we also no longer need to treat vswap specially.

If you keep the format compatible with what we already have as the earlier comment mentions, a large portion of this part might be unneeded.

Quoted 2 lines

at runtime also has overhead for checking as well, and some of the checks are not cheap :)

I also noticed the new introduced swap_read_folio_phys in patch 3, so this actually can be done using Baoquan's swapops idea which is now part of Christoph's swap batching:

https://lore.kernel.org/linux-mm/[email protected]/#r

That series is focusing on batching and better performance but swapops was also proposed as a way to solve the virtual layer, makes it possible to have vswap as one kind of swapops which is Chris talked a lot about:

https://lore.kernel.org/linux-mm/aZiFvzlBJiYBUDre@MiWiFi-R3L-srv/

Following this, we could have something like:

const struct swap_ops swap_vswap_ops = {
.submit_write = swap_vswap_submit_write,
.submit_read = swap_vswap_submit_read,
};

The move the folio_realloc_swap in swap_vswap_submit_write.

Merge of IO might be moved to lower phyiscal level for vswap.

Another gain is that the memory usage and CPU overhead will be lower with only one layer. As I'm recently trying to offload swap dataplane off CPU so the CPU won't touch the data at all, the overhead will be purely by swap itself, plus some mm overhead. Things like that and IO optimization above and could make swap subsystem more and more performance sensitive so we have cases that needs only one layer.

Quoted 11 lines

- Defer per-cluster memcg_table and zeromap allocation on physical clusters. A physical swap cluster backing vswap entries only do not really need their memcg_table, but the current design forces us to allocate it anyway. This is a waste of memory, and is an overhead regression compared to my older design on the zswap-only case, which Johannes has pointed out multiple times (see [6]), and is one of the biggest reasons why I have not been satisfied with this approach thus far. It honestly is a bit of a deal-breaker...

Quoted 5 lines

That said, I think I might be able to allocate them on demand, i.e only when the first direct-mapped slot is allocated on that cluster. That will give us the best of BOTH worlds, for both the vswap and directly-mapped physical swap cases. No promises, but I will try (if this approach is good enough for all parties).

Zero map is not really a problem when it's just a inlined bit I think. For memcg table allocation, on demand seems a good idea, and actually we are not far from there, I tried to generalize the alloc-then-retry-sleep-alloc in swap_alloc_table but still not generic enough I guess.. Good new is the allocation of the table is already kind of ondemand, just need to split the detection of these two kind of table.

Mean while I also remember we once discussed about splitting the accounting for vswap / physical swap? If we went that approach we don't need to treat memcg_table specially.

Quoted 4 lines

- Widen swap_info_struct->max to unsigned long. The vswap device's max is currently clamped to ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) (~16 TiB) to fit in unsigned int. 16 TiB is small for vswap, especially when we're getting increasingly big machines memory-wise.

This should be very easy to do, just replace unsigned int with unsigned long, a lot of place to touch though :)

author maintainer
#7 lore raw
Quoted 113 lines · Kairui Song
Quoted 11 lines · Nhat Pham

Based on: mm-unstable @ 444fc9435e57 + swap-table phase IV v5 [2].

I manually adapted Kairui's ghost device implementation (from [4]) for my vswap device. I've credited him as Co-developed-by on Patch I since a substantial portion of the dynamic-cluster infrastructure is his (I did propose the idea of using xarray/radix tree for dynamic swap clusters allocation and management though :P).

Quoted 1 line

From here on out, for simplicity, I will refer to swap table phase IV

as "P4", and the older v6 virtual swap space implementation as "v6".

...

Quoted 97 lines

This series reimplements the virtual swap space concept (see [1]) on top of Kairui Song's swap table infrastructure, on top of [2] and in accordance with his proposal in [3]. The proposal's idea is interesting, so I decided to give it a shot myself. I'm still not 100% sure that this is bug-proof, but hey, it compiles, and has not crashed in my simple stress testing :)

The prototype here is feature-complete relative to the swap-table P4 baseline — swapout, swapin, freeing, swapoff, zswap writeback, zswap shrinker, memcg charging, and THP swapin all work for both vswap and direct-physical entries — and satisfies all three requirements above: no backend coupling (zswap/zero entries hold no physical slot), dynamic swap space (clusters allocated on demand via xarray, no static provisioning), and efficient backend transfer (in-place vtable updates, no PTE/rmap walking).

II. Design

With vswap, pages are assigned virtual swap entries on a ghost device with no backing storage. These entries are backed by zswap, zero pages, or (lazily) physical swap slots. Physical backing is allocated only when needed — on zswap writeback or reclaim writeout, after the rmap step.

Compared to the standalone v6 implementation [1], which introduces a 24-byte per-entry swap descriptor and its own cluster allocator, this edition uses swap_table infrastructure, and share a lot of the allocator logic. Per-slot metadata is stored in a tag-encoded virtual_table (atomic_long_t, 8 bytes per slot), and physical clusters store Pointer-tagged rmap entries in the swap_table for reverse lookup back to the virtual cluster.

Here are some data layout diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +-------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)  |
                       | +--------------------+  |
                       | | swap_table         |  |
                       | |   PFN / Shadow     |  |
                       | | memcg_table        |  |
                       | | count,flags,order  |  |
                       | | lock, list         |  |
                       | +--------------------+  |
                       |                         |
                       | virtual_table           |
                       | +--------------------+  |
                       | | NONE               |  |
                       | | PHYS               |  |
                       | | ZERO               |  |
                       | | ZSWAP(entry*)      |  |
                       | | FOLIO(folio*)      |  |
                       | +--------------------+  |
                       +-------------------------+
                              |
                              | PHYS resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate backend types:

Quoted 7 lines
Quoted 5 lines
  NONE:   |----- 0000 ------|000|  free / unbacked
  PHYS:   |-- (type:5,off:N)|001|  on a physical swapfile (shifted)
  ZERO:   |----- 0000 ------|010|  zero-filled page
  ZSWAP:  |--- zswap_entry* |011|  compressed in zswap
  FOLIO:  |--- folio* ------|100|  in-memory folio

Thanks for trying this approach!

Thanks for the suggestions. I hope going forward we have sth concrete to tinker with, rather than abstractions :P

Quoted 14 lines

For the format part, PHYS don't need that much bits I think, so by slightly adjust the format vswap device could be share mostly the same format with ordinary device.

For example typical modern system don't have a address space larger than 52 bit. (Even with full 64 bits used for addressing, shift it by 12 we get 52). Plus 5 for type, you get 57, so you can have a marker that should work as long as it shorter than 1000000 for PHYS, and shared for all table format since it's not in conflict with anything. You have also use a few extra bits so a single swap space can be 8 times larger than RAM space, and since we can help multiple swap type I think that should be far than enough?

Quoted 4 lines

Then you have Shadow back at 001, and zero bit in shadow. The only special one is Zswap, which will be 100 now, and that's exactly the reserved pointer format in current swap table format, on seeing si->flags & VSWAP && is_pointer(swp_tb) you know that's zswap :)

Are you suggesting we merge the virtual table with main swap table?

Man, I'd love to do this. There is a problem though - we have a case where we occupy both backing physical swap AND swap cache. Do you think we can fit both the physical swap slot handle and the swap cache PFN into the same slot in virtual table? Maybe with some expanding...?

Another option is we can be a bit smart about it - if a virtual swap entry is in swap cache AND occupies physical swap slot, then put the folio at the physical swap's table, use folio->swap as the rmap.

(I think you recommend this approach somewhere but for the life of me I can't find the reference - apologies if I'm putting words into your mouth :))

But this is a bit more complicated - extra care is needed for rmap handling at the physical swap layer, and swap cache handling at the virtual swap layer. Maybe a follow-up? :)

Quoted 11 lines

Folio / PFN can still be 010 as in the current swap table format.

Then everything seems clean and aligned, no more special handling for vswap needed, there are detailed to sort out, but it should work.

Quoted 2 lines

- Pointer-tagged swap_table on physical clusters for rmap (physical -> virtual) lookup.

Or reuse the PHYS format (rename it maybe) since point back to vswap is also pointing to a si.

Noted. I'm just doing the simplest thing right now - working prototype. I mean, we have enough bits :)

Quoted 16 lines
Quoted 8 lines

III. Follow-ups:

In no particular order (and most of which can be done as follow-up patch series rather than shoving everything in the initial landing):

- More thorough stress testing is very much needed.

Quoted 7 lines

- Performance benchmarks to make sure I don't accidentally regress the vswap-less case, and that the vswap's case performance is good. I suspect I will have to port a lot of the optimizations I implemented in v6 over here - some of the inefficiencies are inherent in any swap virtualization, and would require the same fix (for e.g the MRU cluster caching for faster cluster lookup - see [8] and [9]).

Quoted 4 lines

This could be imporved by per-si percpu cluster. Both YoungJun's tiering and Baoquan's previous swap ops mentioned this is needed, and now vswap also need that. If the vswap is also a si, then it will make use of this too.

Yeah I made the same recommendation when I review swap tier last week:

https://lore.kernel.org/all/CAKEwX=N2XcMHN1jatppOk6wnmz-Shab5XMtTtzgYOzRvU_6YFw@mail.gmail.com/

I like it, but yeah it will be complicated. That said, I think not fixing the fast path for tiering/vswap will seriously restrict their usefulness. We don't want to go back to the old swap allocator days :)

We can also revive the swap slot cache, but why do it if we can repurpose your proven design, and just extend it a bit for multiple tiers/swap devices? :)

Quoted 6 lines

YoungJun posted this a few month before:
https://lore.kernel.org/linux-mm/[email protected]/

The concern is that some locking contention could be heavier, or maybe that's just a hypothetical problem though.

I don't think it's hypothetical. At least with vswap, it's very easy to get into a state where the shared per-cpu cache gets invalidated constantly if phys swap and vswap allocation alternates (which is actually very possible under heavy memory pressure), hammering the slow paths...

Quoted 12 lines
Quoted 12 lines

- Runtime enable/disable of the vswap device. To be honest, I don't know if there is a value in this. My preference is vswap can be optimized to the point that any overhead is negligible. Failing that, maybe we can come up with some simple heuristics that automatically decides for users?

In this RFC, CONFIG_VSWAP=y means the vswap device is always created at boot, and CONFIG_VSWAP=n means the vswap device is never created. This *might* be enough just on its own.

Quoted 8 lines
Quoted 2 lines

Is a runtime knob (sysfs or sysctl) worth the complexity beyond these heuristics? I'm not sure yet. Maintaining both cases

I checked the code and I think it's not hard to do, patch 1 already handling the meta data dynamically, everything will still just work even if you remove vswap at runtime. The rest of patches need adaption but might not end up being complex, it other comments here are considered.

Yeah, it's not terribily hard to do. I'm more wondering if it's worth the effort, both for the implementer and the user :)

As I said here, if we want vswap, just enable it at boot time and get a vast (but dynamic) device. We can make it optional per-cgroup through Youngjun's interface, and that would be good enough?

Quoted 7 lines

For patch 2, a few routines like vswap_can_swapin_thp seems not needed or should be moved to __swap_cache_alloc? VSWAP_FOLIO is same as swap cache folio check, which is already covered. Same for zero checking, and VSWAP_NONE which is same as swap count check I think. That way we not only save a lot of code, we also no longer need to treat vswap specially.

Unfortunately, I think a lot of this complexity is still needed. Vswap adds a new layer, which means new complications :)

For instance, I think you still need vswap_can_swapin_thp. It basically enforces that the backend must be something swap_read_folio() can handle. That means:

1. No zswap.

2. No mixed backend.

3. If it's phys swap, it must be contiguous in the same device.

The vswap entries might look contiguous in the virtual address space, but completely unsuitable for the backend.... This is a new complication that does not previously exist for non-virtualized swap, so it needs more code to handle it...

I use vswap_can_swapin_thp() in two places - first when we try to find a candidate range of PTEs for swap in (swap_pte_batch). And then double check after we've added into swap cache, as the backend can change arbitrarily before swap cache folio is locked.

Similar for some of the other helpers. For instance, vswap_swapfile_backed() is needed in certain optimizations or for correctness's sake, etc.

The VSWAP_FOLIO is redundant, I agree. It's just for convenient. It represents the state of vswap where it's still in swap (swap cache), but only backed by the swap cache folio, and not any other backends. Technically, you can represent it with VSWAP_NONE + a check in the swap cache field to see if there is a folio there.

If it's not too much code in v2 I can try to remove it (while leaving behind a comment explains the state).

Quoted 11 lines

If you keep the format compatible with what we already have as the earlier comment mentions, a large portion of this part might be unneeded.

Quoted 2 lines

at runtime also has overhead for checking as well, and some of the checks are not cheap :)

I also noticed the new introduced swap_read_folio_phys in patch 3, so this actually can be done using Baoquan's swapops idea which is now part of Christoph's swap batching:

I'm actually trying to have swap_read_folio() work for both vswap and phys swpa just with a biiit of if-else. But yeah this might be cleaner :)

Quoted 20 lines

https://lore.kernel.org/linux-mm/[email protected]/#r

That series is focusing on batching and better performance but swapops was also proposed as a way to solve the virtual layer, makes it possible to have vswap as one kind of swapops which is Chris talked a lot about:

https://lore.kernel.org/linux-mm/aZiFvzlBJiYBUDre@MiWiFi-R3L-srv/

Following this, we could have something like:

const struct swap_ops swap_vswap_ops = {
.submit_write = swap_vswap_submit_write,
.submit_read = swap_vswap_submit_read,
};

The move the folio_realloc_swap in swap_vswap_submit_write.

Merge of IO might be moved to lower phyiscal level for vswap.

Quoted 7 lines

Another gain is that the memory usage and CPU overhead will be lower with only one layer. As I'm recently trying to offload swap dataplane off CPU so the CPU won't touch the data at all, the overhead will be purely by swap itself, plus some mm overhead. Things like that and IO optimization above and could make swap subsystem more and more performance sensitive so we have cases that needs only one layer.

Yeah I can take a look at this. This prototype purely based on your P4 and with just a bit of hackery to transfer my v6 implementation over. Not very clean - just a PoC. If everyone is happy I can put more time in :)

Quoted 12 lines
Quoted 12 lines

- Defer per-cluster memcg_table and zeromap allocation on physical clusters. A physical swap cluster backing vswap entries only do not really need their memcg_table, but the current design forces us to allocate it anyway. This is a waste of memory, and is an overhead regression compared to my older design on the zswap-only case, which Johannes has pointed out multiple times (see [6]), and is one of the biggest reasons why I have not been satisfied with this approach thus far. It honestly is a bit of a deal-breaker...

Quoted 7 lines
Quoted 5 lines

That said, I think I might be able to allocate them on demand, i.e only when the first direct-mapped slot is allocated on that cluster. That will give us the best of BOTH worlds, for both the vswap and directly-mapped physical swap cases. No promises, but I will try (if this approach is good enough for all parties).

Zero map is not really a problem when it's just a inlined bit I think.

Yeah no problemo indeed. I saw a zeromap field in struct phys swap cluster, so I put this in the plan as "to remove later", but I just took a look and realized it's only for cases where you cant fit the bit in swap table. I'm gating vswap for 64 bit for now, so should not be a problem.

Quoted 6 lines

For memcg table allocation, on demand seems a good idea, and actually we are not far from there, I tried to generalize the alloc-then-retry-sleep-alloc in swap_alloc_table but still not generic enough I guess.. Good new is the allocation of the table is already kind of ondemand, just need to split the detection of these two kind of table.

I have a prototype of this, but I have not tested, so I do not want to send it out. :)

TLDR is - I still want to record the memcg for vswap (just not charge it towards the counter). So we still need memcg_table at both level, generally - just not allocating until needed (basically if a physical swap slot in the cluster is directly mapped into PTE). You can kinda tell, since you pass the folio into the allocation path - with some care you can distinguish between:

1. Virtual swap, or directly maped physical swap -> need memcg_table

2. Physical swap, backing vswap -> does not memcg_table.

Another alternative is you can defer this allocation until the point where you have to do the charging action. But then you have to be careful with failure handling, and need to backoff ya di da di da. Funsies.

I think I did a mixed of these 2 strategies. Anyway, I'll include the patch in v2 (if folks like this approach).

Quoted 4 lines

Mean while I also remember we once discussed about splitting the accounting for vswap / physical swap? If we went that approach we don't need to treat memcg_table specially.

For the charging behavior, I already have a patch for it actually in this series (just not the dynamic allocation of the memcg_table field yet).

Basically:

1. For vswap entry, not backed by phys swap: record swap memcg, hold reference to pin the memcg, but not charging towards swap.current.

2. For phys swap backing vswap: charging towards swap.current, but does not record the memcg in its memcg_table, nor does it hold reference to memcg (its vswap entry holds the reference already)

2. For phys swap directly mapped to PTE: charges, records, and holds reference.

The motivation here is I do not want vswap entry to shares the same limit as phys swap counter. If we think of it as "infinite" or "dynamic", it should not be capped at all, but even if it is charged, it should be something separate.

Quoted 8 lines
Quoted 5 lines

- Widen swap_info_struct->max to unsigned long. The vswap device's max is currently clamped to ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) (~16 TiB) to fit in unsigned int. 16 TiB is small for vswap, especially when we're getting increasingly big machines memory-wise.

This should be very easy to do, just replace unsigned int with unsigned long, a lot of place to touch though :)

Agree. I'm just lazy, and this sounds like a simple patch as a follow-up. This RFC is already 2000 LoCs - I do not want to burden reviewers with extra useless details :)

author maintainer
#8 lore raw
Quoted 170 lines · Nhat Pham
Quoted 113 lines · Kairui Song
Quoted 11 lines · Nhat Pham

Based on: mm-unstable @ 444fc9435e57 + swap-table phase IV v5 [2].

I manually adapted Kairui's ghost device implementation (from [4]) for my vswap device. I've credited him as Co-developed-by on Patch I since a substantial portion of the dynamic-cluster infrastructure is his (I did propose the idea of using xarray/radix tree for dynamic swap clusters allocation and management though :P).

Quoted 1 line

From here on out, for simplicity, I will refer to swap table phase IV

as "P4", and the older v6 virtual swap space implementation as "v6".

...

Quoted 97 lines

This series reimplements the virtual swap space concept (see [1]) on top of Kairui Song's swap table infrastructure, on top of [2] and in accordance with his proposal in [3]. The proposal's idea is interesting, so I decided to give it a shot myself. I'm still not 100% sure that this is bug-proof, but hey, it compiles, and has not crashed in my simple stress testing :)

The prototype here is feature-complete relative to the swap-table P4 baseline — swapout, swapin, freeing, swapoff, zswap writeback, zswap shrinker, memcg charging, and THP swapin all work for both vswap and direct-physical entries — and satisfies all three requirements above: no backend coupling (zswap/zero entries hold no physical slot), dynamic swap space (clusters allocated on demand via xarray, no static provisioning), and efficient backend transfer (in-place vtable updates, no PTE/rmap walking).

II. Design

With vswap, pages are assigned virtual swap entries on a ghost device with no backing storage. These entries are backed by zswap, zero pages, or (lazily) physical swap slots. Physical backing is allocated only when needed — on zswap writeback or reclaim writeout, after the rmap step.

Compared to the standalone v6 implementation [1], which introduces a 24-byte per-entry swap descriptor and its own cluster allocator, this edition uses swap_table infrastructure, and share a lot of the allocator logic. Per-slot metadata is stored in a tag-encoded virtual_table (atomic_long_t, 8 bytes per slot), and physical clusters store Pointer-tagged rmap entries in the swap_table for reverse lookup back to the virtual cluster.

Here are some data layout diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +-------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)  |
                       | +--------------------+  |
                       | | swap_table         |  |
                       | |   PFN / Shadow     |  |
                       | | memcg_table        |  |
                       | | count,flags,order  |  |
                       | | lock, list         |  |
                       | +--------------------+  |
                       |                         |
                       | virtual_table           |
                       | +--------------------+  |
                       | | NONE               |  |
                       | | PHYS               |  |
                       | | ZERO               |  |
                       | | ZSWAP(entry*)      |  |
                       | | FOLIO(folio*)      |  |
                       | +--------------------+  |
                       +-------------------------+
                              |
                              | PHYS resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate backend types:

Quoted 7 lines
Quoted 5 lines
  NONE:   |----- 0000 ------|000|  free / unbacked
  PHYS:   |-- (type:5,off:N)|001|  on a physical swapfile (shifted)
  ZERO:   |----- 0000 ------|010|  zero-filled page
  ZSWAP:  |--- zswap_entry* |011|  compressed in zswap
  FOLIO:  |--- folio* ------|100|  in-memory folio

Thanks for trying this approach!

Thanks for the suggestions. I hope going forward we have sth concrete to tinker with, rather than abstractions :P

Quoted 14 lines

For the format part, PHYS don't need that much bits I think, so by slightly adjust the format vswap device could be share mostly the same format with ordinary device.

For example typical modern system don't have a address space larger than 52 bit. (Even with full 64 bits used for addressing, shift it by 12 we get 52). Plus 5 for type, you get 57, so you can have a marker that should work as long as it shorter than 1000000 for PHYS, and shared for all table format since it's not in conflict with anything. You have also use a few extra bits so a single swap space can be 8 times larger than RAM space, and since we can help multiple swap type I think that should be far than enough?

Quoted 4 lines

Then you have Shadow back at 001, and zero bit in shadow. The only special one is Zswap, which will be 100 now, and that's exactly the reserved pointer format in current swap table format, on seeing si->flags & VSWAP && is_pointer(swp_tb) you know that's zswap :)

Are you suggesting we merge the virtual table with main swap table?

Man, I'd love to do this. There is a problem though - we have a case where we occupy both backing physical swap AND swap cache. Do you think we can fit both the physical swap slot handle and the swap cache PFN into the same slot in virtual table? Maybe with some expanding...?

Another option is we can be a bit smart about it - if a virtual swap entry is in swap cache AND occupies physical swap slot, then put the folio at the physical swap's table, use folio->swap as the rmap.

(I think you recommend this approach somewhere but for the life of me I can't find the reference - apologies if I'm putting words into your mouth :))

But this is a bit more complicated - extra care is needed for rmap handling at the physical swap layer, and swap cache handling at the virtual swap layer. Maybe a follow-up? :)

Quoted 6 lines

Folio / PFN can still be 010 as in the current swap table format.

Then everything seems clean and aligned, no more special handling for vswap needed, there are detailed to sort out, but it should work.

Quoted 29 lines
Quoted 5 lines
Quoted 2 lines

- Pointer-tagged swap_table on physical clusters for rmap (physical -> virtual) lookup.

Or reuse the PHYS format (rename it maybe) since point back to vswap is also pointing to a si.

Noted. I'm just doing the simplest thing right now - working prototype. I mean, we have enough bits :)

Quoted 20 lines
Quoted 8 lines

III. Follow-ups:

In no particular order (and most of which can be done as follow-up patch series rather than shoving everything in the initial landing):

- More thorough stress testing is very much needed.

Quoted 7 lines

- Performance benchmarks to make sure I don't accidentally regress the vswap-less case, and that the vswap's case performance is good. I suspect I will have to port a lot of the optimizations I implemented in v6 over here - some of the inefficiencies are inherent in any swap virtualization, and would require the same fix (for e.g the MRU cluster caching for faster cluster lookup - see [8] and [9]).

This could be imporved by per-si percpu cluster. Both YoungJun's tiering and Baoquan's previous swap ops mentioned this is needed, and now vswap also need that. If the vswap is also a si, then it will make use of this too.

Oh and the MRU cluster caching I mentioned here is not the allocation caching. It's the lookup caching, basically to avoid doing the xa_load() to look up clusters for consecutive swap operations on the same vswap cluster (which is the common case with vswap). For v6, it massively reduces this indirection lookup overhead. Performance-wise it's an absolute winner, just more complexity (because I need to handle reference counting carefully).

I also just realized we'll induce the indirection overhead on allocation here too, even if the cached cluster still have slots for allocation, because we look up the cluster (which is basically free for static swap device, but not free for vswap devices). Might need to take care of that to maintain vswap performance (but it will then diverge from your existing code...).

#12 lore raw
In reply to Nhat Pham
Quoted 21 lines · Nhat Pham
Quoted 14 lines · Kairui Song

For the format part, PHYS don't need that much bits I think, so by slightly adjust the format vswap device could be share mostly the same format with ordinary device.

For example typical modern system don't have a address space larger than 52 bit. (Even with full 64 bits used for addressing, shift it by 12 we get 52). Plus 5 for type, you get 57, so you can have a marker that should work as long as it shorter than 1000000 for PHYS, and shared for all table format since it's not in conflict with anything. You have also use a few extra bits so a single swap space can be 8 times larger than RAM space, and since we can help multiple swap type I think that should be far than enough?

Quoted 4 lines

Then you have Shadow back at 001, and zero bit in shadow. The only special one is Zswap, which will be 100 now, and that's exactly the reserved pointer format in current swap table format, on seeing si->flags & VSWAP && is_pointer(swp_tb) you know that's zswap :)

Quoted 6 lines

Are you suggesting we merge the virtual table with main swap table?

Man, I'd love to do this. There is a problem though - we have a case where we occupy both backing physical swap AND swap cache. Do you think we can fit both the physical swap slot handle and the swap cache PFN into the same slot in virtual table? Maybe with some expanding...?

I don't really get why we would need to do that? If you put the PFN info in the virtual / upper layer, then the count info, locking, and all swap IO synchronization (via folio lock), dup (current protected by ci lock / folio lock), and allocation (folio_alloc_swap), are all handled in this layer.

The physical / lower layer will just hold a reverse entry on folio_realloc_swap, or no entry at all (no physical layer used, zswap, or after swap allocation but before IO) right?

Looking up the actual folio from the physical layer will be a bit slower since it needs to resolve the reverse entry, but the only place we need to do that is things like migrate, compaction (none of them exist yet) which seems totally fine?

Quoted 5 lines
Quoted 4 lines

This could be imporved by per-si percpu cluster. Both YoungJun's tiering and Baoquan's previous swap ops mentioned this is needed, and now vswap also need that. If the vswap is also a si, then it will make use of this too.

Quoted 7 lines

Yeah I made the same recommendation when I review swap tier last week:

https://lore.kernel.org/all/CAKEwX=N2XcMHN1jatppOk6wnmz-Shab5XMtTtzgYOzRvU_6YFw@mail.gmail.com/

I like it, but yeah it will be complicated. That said, I think not fixing the fast path for tiering/vswap will seriously restrict their usefulness. We don't want to go back to the old swap allocator days :)

Thanks. Not too complicated, actually our internal kernel implementation still using si->percpu cluster, and use a counter for the rotation and each order have a counter :P, it's a bit ugly but works fine. It still serves pretty well just like the global percpu cluster, YoungJun's previous per ci percpu cluster also still provides the fast path, many ways to do that.

Quoted 5 lines
Quoted 5 lines

YoungJun posted this a few month before:
https://lore.kernel.org/linux-mm/[email protected]/

Quoted 8 lines
Quoted 2 lines

The concern is that some locking contention could be heavier, or maybe that's just a hypothetical problem though.

I don't think it's hypothetical. At least with vswap, it's very easy to get into a state where the shared per-cpu cache gets invalidated constantly if phys swap and vswap allocation alternates (which is actually very possible under heavy memory pressure), hammering the slow paths...

I mean if the per-cpu cache is moved to si level, then whoever enters the allocation path of a si will almost always get a stable percpu cache to use, even if the last used si changes.

We might better have a more explicit per si fast path for that. The plist rotation should better be done in a different (will be even better if lockless) way.

Quoted 40 lines
Quoted 13 lines
Quoted 13 lines

- Runtime enable/disable of the vswap device. To be honest, I don't know if there is a value in this. My preference is vswap can be optimized to the point that any overhead is negligible. Failing that, maybe we can come up with some simple heuristics that automatically decides for users?

In this RFC, CONFIG_VSWAP=y means the vswap device is always created at boot, and CONFIG_VSWAP=n means the vswap device is never created. This *might* be enough just on its own.

Quoted 8 lines
Quoted 2 lines

Is a runtime knob (sysfs or sysctl) worth the complexity beyond these heuristics? I'm not sure yet. Maintaining both cases

I checked the code and I think it's not hard to do, patch 1 already handling the meta data dynamically, everything will still just work even if you remove vswap at runtime. The rest of patches need adaption but might not end up being complex, it other comments here are considered.

Yeah, it's not terribily hard to do. I'm more wondering if it's worth the effort, both for the implementer and the user :)

As I said here, if we want vswap, just enable it at boot time and get a vast (but dynamic) device. We can make it optional per-cgroup through Youngjun's interface, and that would be good enough?

Quoted 7 lines

For patch 2, a few routines like vswap_can_swapin_thp seems not needed or should be moved to __swap_cache_alloc? VSWAP_FOLIO is same as swap cache folio check, which is already covered. Same for zero checking, and VSWAP_NONE which is same as swap count check I think. That way we not only save a lot of code, we also no longer need to treat vswap specially.

Unfortunately, I think a lot of this complexity is still needed. Vswap adds a new layer, which means new complications :)

Quoted 7 lines

For instance, I think you still need vswap_can_swapin_thp. It basically enforces that the backend must be something swap_read_folio() can handle. That means:

1. No zswap.

2. No mixed backend.

If mixed backend means phys vs zero vs zswap, then we already have part of that covered with the current swap cache except for the phys part (zswap part seems very doable with fujunjie's work). swap_cache_alloc_folio will ensure there is no mixed zerobit, it can be easily extended to ensure there is no mixed zswap as well (according to what I've learned from fujunjie's code). Similar logic for phys detection I think.

Quoted 34 lines
Quoted 6 lines

For memcg table allocation, on demand seems a good idea, and actually we are not far from there, I tried to generalize the alloc-then-retry-sleep-alloc in swap_alloc_table but still not generic enough I guess.. Good new is the allocation of the table is already kind of ondemand, just need to split the detection of these two kind of table.

I have a prototype of this, but I have not tested, so I do not want to send it out. :)

TLDR is - I still want to record the memcg for vswap (just not charge it towards the counter). So we still need memcg_table at both level, generally - just not allocating until needed (basically if a physical swap slot in the cluster is directly mapped into PTE). You can kinda tell, since you pass the folio into the allocation path - with some care you can distinguish between:

1. Virtual swap, or directly maped physical swap -> need memcg_table

2. Physical swap, backing vswap -> does not memcg_table.

Another alternative is you can defer this allocation until the point where you have to do the charging action. But then you have to be careful with failure handling, and need to backoff ya di da di da. Funsies.

I think I did a mixed of these 2 strategies. Anyway, I'll include the patch in v2 (if folks like this approach).

Quoted 4 lines

Mean while I also remember we once discussed about splitting the accounting for vswap / physical swap? If we went that approach we don't need to treat memcg_table specially.

Quoted 8 lines

For the charging behavior, I already have a patch for it actually in this series (just not the dynamic allocation of the memcg_table field yet).

Basically:

1. For vswap entry, not backed by phys swap: record swap memcg, hold reference to pin the memcg, but not charging towards swap.current.

Maybe you don't need to record memcg here since folio->memcg already have that info?

I previously had a patch:
https://lore.kernel.org/linux-mm/[email protected]/

The defers the recording of memcg, the behavior is almost identical to before, but charging & recording should be cleaner and you don't need to record memcg at allocation time hence maybe reduce the possibility of pinning a memcg. I didn't include that in P4 just to reduce LOC, maybe can be resent or included.

Quoted 10 lines

2. For phys swap backing vswap: charging towards swap.current, but does not record the memcg in its memcg_table, nor does it hold reference to memcg (its vswap entry holds the reference already)

2. For phys swap directly mapped to PTE: charges, records, and holds reference.

The motivation here is I do not want vswap entry to shares the same limit as phys swap counter. If we think of it as "infinite" or "dynamic", it should not be capped at all, but even if it is charged, it should be something separate.

Good to know, it's not too messy to make everything dynamic, but if our ultimate goal is to account for them separately, maybe we can save some effort here.

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

- Widen swap_info_struct->max to unsigned long. The vswap device's max is currently clamped to ALIGN_DOWN(UINT_MAX, SWAPFILE_CLUSTER) (~16 TiB) to fit in unsigned int. 16 TiB is small for vswap, especially when we're getting increasingly big machines memory-wise.

Quoted 6 lines
Quoted 2 lines

This should be very easy to do, just replace unsigned int with unsigned long, a lot of place to touch though :)

Agree. I'm just lazy, and this sounds like a simple patch as a follow-up. This RFC is already 2000 LoCs - I do not want to burden reviewers with extra useless details :)

No problem, good to see progress here :)

#9 lore raw
In reply to Nhat Pham
Quoted 26 lines · Nhat Pham
Quoted 19 lines · Nhat Pham
Quoted 17 lines · Kairui Song
Quoted 14 lines · Nhat Pham

III. Follow-ups:

In no particular order (and most of which can be done as follow-up patch series rather than shoving everything in the initial landing):

- More thorough stress testing is very much needed.

- Performance benchmarks to make sure I don't accidentally regress the vswap-less case, and that the vswap's case performance is good. I suspect I will have to port a lot of the optimizations I implemented in v6 over here - some of the inefficiencies are inherent in any swap virtualization, and would require the same fix (for e.g the MRU cluster caching for faster cluster lookup - see [8] and [9]).

Quoted 4 lines
Quoted 4 lines

This could be imporved by per-si percpu cluster. Both YoungJun's tiering and Baoquan's previous swap ops mentioned this is needed, and now vswap also need that. If the vswap is also a si, then it will make use of this too.

Quoted 7 lines

Oh and the MRU cluster caching I mentioned here is not the allocation caching. It's the lookup caching, basically to avoid doing the xa_load() to look up clusters for consecutive swap operations on the same vswap cluster (which is the common case with vswap). For v6, it massively reduces this indirection lookup overhead. Performance-wise it's an absolute winner, just more complexity (because I need to handle reference counting carefully).

Ah alright, that's interesting. And I think we can keep things simple to start, since sensitive users is stil able tol use plain device this way.

BTW maintaining MRU is also an overhead, I'm not sure if the lookup pattern always follows that?

Quoted 6 lines

I also just realized we'll induce the indirection overhead on allocation here too, even if the cached cluster still have slots for allocation, because we look up the cluster (which is basically free for static swap device, but not free for vswap devices). Might need to take care of that to maintain vswap performance (but it will then diverge from your existing code...).

That part should be indeed coverable by the si->percpu cluster though, I think.

author maintainer
#13 lore raw
In reply to Kairui Song
Quoted 36 lines · Kairui Song
Quoted 21 lines · Nhat Pham
Quoted 14 lines · Kairui Song

For the format part, PHYS don't need that much bits I think, so by slightly adjust the format vswap device could be share mostly the same format with ordinary device.

For example typical modern system don't have a address space larger than 52 bit. (Even with full 64 bits used for addressing, shift it by 12 we get 52). Plus 5 for type, you get 57, so you can have a marker that should work as long as it shorter than 1000000 for PHYS, and shared for all table format since it's not in conflict with anything. You have also use a few extra bits so a single swap space can be 8 times larger than RAM space, and since we can help multiple swap type I think that should be far than enough?

Quoted 4 lines

Then you have Shadow back at 001, and zero bit in shadow. The only special one is Zswap, which will be 100 now, and that's exactly the reserved pointer format in current swap table format, on seeing si->flags & VSWAP && is_pointer(swp_tb) you know that's zswap :)

Quoted 6 lines

Are you suggesting we merge the virtual table with main swap table?

Man, I'd love to do this. There is a problem though - we have a case where we occupy both backing physical swap AND swap cache. Do you think we can fit both the physical swap slot handle and the swap cache PFN into the same slot in virtual table? Maybe with some expanding...?

I don't really get why we would need to do that? If you put the PFN info in the virtual / upper layer, then the count info, locking, and all swap IO synchronization (via folio lock), dup (current protected by ci lock / folio lock), and allocation (folio_alloc_swap), are all handled in this layer.

Quoted 8 lines

The physical / lower layer will just hold a reverse entry on folio_realloc_swap, or no entry at all (no physical layer used, zswap, or after swap allocation but before IO) right?

Looking up the actual folio from the physical layer will be a bit slower since it needs to resolve the reverse entry, but the only place we need to do that is things like migrate, compaction (none of them exist yet) which seems totally fine?

All of this is correct, but consider swaping in a vswap entry backed by pswap. There are cases where you still want to maintain the pswap slots around backing vswap entry, while having the swap cache folio as well.

For e.g, at swap in time, we add the folio into the swap cache. First of all, we need to hold on to the physical swap slot for IO step. But even after IO succeeds, there are cases where you would still like to keep physical swap slots around (for e.g, to avoid swapping out again if the folio is only speculatively fetched).

So you have to make sure we have space for both the physical swap slot, and the swap cache folio's PFN at the same time for each vswap entry. So we still need the vtable extension (well maybe the other approach I mentioned could work, but I'm not 100% sure).

Quoted 14 lines
Quoted 6 lines
Quoted 5 lines

This could be imporved by per-si percpu cluster. Both YoungJun's tiering and Baoquan's previous swap ops mentioned this is needed, and now vswap also need that. If the vswap is also a si, then it will make use of this too.

Quoted 7 lines

Yeah I made the same recommendation when I review swap tier last week:

https://lore.kernel.org/all/CAKEwX=N2XcMHN1jatppOk6wnmz-Shab5XMtTtzgYOzRvU_6YFw@mail.gmail.com/

I like it, but yeah it will be complicated. That said, I think not fixing the fast path for tiering/vswap will seriously restrict their usefulness. We don't want to go back to the old swap allocator days :)

Quoted 6 lines

Thanks. Not too complicated, actually our internal kernel implementation still using si->percpu cluster, and use a counter for the rotation and each order have a counter :P, it's a bit ugly but works fine. It still serves pretty well just like the global percpu cluster, YoungJun's previous per ci percpu cluster also still provides the fast path, many ways to do that.

Sounds like something that should be upstreamed? ;)

I was concerned that you might deem the overhead too high (so I came up with the per-tier percpu caching), but honestly I like it a lot.

Quoted 15 lines
Quoted 6 lines
Quoted 6 lines

YoungJun posted this a few month before:
https://lore.kernel.org/linux-mm/[email protected]/

Quoted 8 lines
Quoted 2 lines

The concern is that some locking contention could be heavier, or maybe that's just a hypothetical problem though.

I don't think it's hypothetical. At least with vswap, it's very easy to get into a state where the shared per-cpu cache gets invalidated constantly if phys swap and vswap allocation alternates (which is actually very possible under heavy memory pressure), hammering the slow paths...

Quoted 7 lines

I mean if the per-cpu cache is moved to si level, then whoever enters the allocation path of a si will almost always get a stable percpu cache to use, even if the last used si changes.

We might better have a more explicit per si fast path for that. The plist rotation should better be done in a different (will be even better if lockless) way.

Exactly! That's what I'm thinking too. Basically I'm special-casing for vswap here, but if you're happy with generalizing this for every si I'm happy with it.

Quoted 49 lines
Quoted 41 lines
Quoted 14 lines
Quoted 14 lines

- Runtime enable/disable of the vswap device. To be honest, I don't know if there is a value in this. My preference is vswap can be optimized to the point that any overhead is negligible. Failing that, maybe we can come up with some simple heuristics that automatically decides for users?

In this RFC, CONFIG_VSWAP=y means the vswap device is always created at boot, and CONFIG_VSWAP=n means the vswap device is never created. This *might* be enough just on its own.

Quoted 8 lines
Quoted 2 lines

Is a runtime knob (sysfs or sysctl) worth the complexity beyond these heuristics? I'm not sure yet. Maintaining both cases

I checked the code and I think it's not hard to do, patch 1 already handling the meta data dynamically, everything will still just work even if you remove vswap at runtime. The rest of patches need adaption but might not end up being complex, it other comments here are considered.

Yeah, it's not terribily hard to do. I'm more wondering if it's worth the effort, both for the implementer and the user :)

As I said here, if we want vswap, just enable it at boot time and get a vast (but dynamic) device. We can make it optional per-cgroup through Youngjun's interface, and that would be good enough?

Quoted 7 lines

For patch 2, a few routines like vswap_can_swapin_thp seems not needed or should be moved to __swap_cache_alloc? VSWAP_FOLIO is same as swap cache folio check, which is already covered. Same for zero checking, and VSWAP_NONE which is same as swap count check I think. That way we not only save a lot of code, we also no longer need to treat vswap specially.

Unfortunately, I think a lot of this complexity is still needed. Vswap adds a new layer, which means new complications :)

Quoted 7 lines

For instance, I think you still need vswap_can_swapin_thp. It basically enforces that the backend must be something swap_read_folio() can handle. That means:

1. No zswap.

2. No mixed backend.

Quoted 7 lines

If mixed backend means phys vs zero vs zswap, then we already have part of that covered with the current swap cache except for the phys part (zswap part seems very doable with fujunjie's work). swap_cache_alloc_folio will ensure there is no mixed zerobit, it can be easily extended to ensure there is no mixed zswap as well (according to what I've learned from fujunjie's code). Similar logic for phys detection I think.

Yeah it's basically generalizing that check, and handle the case where we can have indirection.

I mean I can open-code it, but it has to be there :) And I figure it might be useful to check this opportunistically (at swap_pte_batch, even if it's not guaranteed to be correct down the line) before we even attempt to allocate a large folio etc. to avoid large folio allocation.

Quoted 47 lines
Quoted 35 lines
Quoted 7 lines

For memcg table allocation, on demand seems a good idea, and actually we are not far from there, I tried to generalize the alloc-then-retry-sleep-alloc in swap_alloc_table but still not generic enough I guess.. Good new is the allocation of the table is already kind of ondemand, just need to split the detection of these two kind of table.

I have a prototype of this, but I have not tested, so I do not want to send it out. :)

TLDR is - I still want to record the memcg for vswap (just not charge it towards the counter). So we still need memcg_table at both level, generally - just not allocating until needed (basically if a physical swap slot in the cluster is directly mapped into PTE). You can kinda tell, since you pass the folio into the allocation path - with some care you can distinguish between:

1. Virtual swap, or directly maped physical swap -> need memcg_table

2. Physical swap, backing vswap -> does not memcg_table.

Another alternative is you can defer this allocation until the point where you have to do the charging action. But then you have to be careful with failure handling, and need to backoff ya di da di da. Funsies.

I think I did a mixed of these 2 strategies. Anyway, I'll include the patch in v2 (if folks like this approach).

Quoted 4 lines

Mean while I also remember we once discussed about splitting the accounting for vswap / physical swap? If we went that approach we don't need to treat memcg_table specially.

Quoted 8 lines

For the charging behavior, I already have a patch for it actually in this series (just not the dynamic allocation of the memcg_table field yet).

Basically:

1. For vswap entry, not backed by phys swap: record swap memcg, hold reference to pin the memcg, but not charging towards swap.current.

Maybe you don't need to record memcg here since folio->memcg already have that info?

Quoted 8 lines

I previously had a patch:
https://lore.kernel.org/linux-mm/[email protected]/

The defers the recording of memcg, the behavior is almost identical to before, but charging & recording should be cleaner and you don't need to record memcg at allocation time hence maybe reduce the possibility of pinning a memcg. I didn't include that in P4 just to reduce LOC, maybe can be resent or included.

That works-ish when the folio is sitll in swap cache, but say if it's vswap backed by zswap (and the swap cache folio has been reclaimed), you need a place to store the memcg, no?

Just seems cleaner to centralize this info at vswap layer when it is presented, for now anyway, rather than juggling this on a per-backend basis.

Quoted 7 lines
Quoted 7 lines

2. For phys swap backing vswap: charging towards swap.current, but does not record the memcg in its memcg_table, nor does it hold reference to memcg (its vswap entry holds the reference already)

2. For phys swap directly mapped to PTE: charges, records, and holds reference.

Quoted 8 lines
Quoted 4 lines

The motivation here is I do not want vswap entry to shares the same limit as phys swap counter. If we think of it as "infinite" or "dynamic", it should not be capped at all, but even if it is charged, it should be something separate.

Good to know, it's not too messy to make everything dynamic, but if our ultimate goal is to account for them separately, maybe we can save some effort here.

It's not terrible, TBH.

#14 lore raw
Quoted 32 lines · Nhat Pham
Quoted 16 lines · Kairui Song
Quoted 7 lines · Nhat Pham

Are you suggesting we merge the virtual table with main swap table?

Man, I'd love to do this. There is a problem though - we have a case where we occupy both backing physical swap AND swap cache. Do you think we can fit both the physical swap slot handle and the swap cache PFN into the same slot in virtual table? Maybe with some expanding...?

I don't really get why we would need to do that? If you put the PFN info in the virtual / upper layer, then the count info, locking, and all swap IO synchronization (via folio lock), dup (current protected by ci lock / folio lock), and allocation (folio_alloc_swap), are all handled in this layer.

Quoted 8 lines

The physical / lower layer will just hold a reverse entry on folio_realloc_swap, or no entry at all (no physical layer used, zswap, or after swap allocation but before IO) right?

Looking up the actual folio from the physical layer will be a bit slower since it needs to resolve the reverse entry, but the only place we need to do that is things like migrate, compaction (none of them exist yet) which seems totally fine?

All of this is correct, but consider swaping in a vswap entry backed by pswap. There are cases where you still want to maintain the pswap slots around backing vswap entry, while having the swap cache folio as well.

Quoted 5 lines

For e.g, at swap in time, we add the folio into the swap cache. First of all, we need to hold on to the physical swap slot for IO step. But even after IO succeeds, there are cases where you would still like to keep physical swap slots around (for e.g, to avoid swapping out again if the folio is only speculatively fetched).

A reverse entry is enough to hold the physical swap, just like how the current hibernation works with a fake shadow, you don't need a PFN just for holding that.

Quoted 5 lines

So you have to make sure we have space for both the physical swap slot, and the swap cache folio's PFN at the same time for each vswap entry. So we still need the vtable extension (well maybe the other approach I mentioned could work, but I'm not 100% sure).

Right, vtable extension is fine, there is no redundant data. I just mean you don't need to set the PFN twice (for vswap & pswap). So simply reusing the PFN format in the vswap layer and solving everything there should be enough.

Quoted 8 lines
Quoted 6 lines

Thanks. Not too complicated, actually our internal kernel implementation still using si->percpu cluster, and use a counter for the rotation and each order have a counter :P, it's a bit ugly but works fine. It still serves pretty well just like the global percpu cluster, YoungJun's previous per ci percpu cluster also still provides the fast path, many ways to do that.

Sounds like something that should be upstreamed? ;)

I'd love to :), there is a lot of work going on as you can see and people seem to have many different proposals about this so I didn't prioritize it. I'll try as things settle down.

Quoted 27 lines
Quoted 19 lines
Quoted 11 lines
Quoted 7 lines

For patch 2, a few routines like vswap_can_swapin_thp seems not needed or should be moved to __swap_cache_alloc? VSWAP_FOLIO is same as swap cache folio check, which is already covered. Same for zero checking, and VSWAP_NONE which is same as swap count check I think. That way we not only save a lot of code, we also no longer need to treat vswap specially.

Unfortunately, I think a lot of this complexity is still needed. Vswap adds a new layer, which means new complications :)

Quoted 7 lines

For instance, I think you still need vswap_can_swapin_thp. It basically enforces that the backend must be something swap_read_folio() can handle. That means:

1. No zswap.

2. No mixed backend.

Quoted 7 lines

If mixed backend means phys vs zero vs zswap, then we already have part of that covered with the current swap cache except for the phys part (zswap part seems very doable with fujunjie's work). swap_cache_alloc_folio will ensure there is no mixed zerobit, it can be easily extended to ensure there is no mixed zswap as well (according to what I've learned from fujunjie's code). Similar logic for phys detection I think.

Quoted 8 lines

Yeah it's basically generalizing that check, and handle the case where we can have indirection.

I mean I can open-code it, but it has to be there :) And I figure it might be useful to check this opportunistically (at swap_pte_batch, even if it's not guaranteed to be correct down the line) before we even attempt to allocate a large folio etc. to avoid large folio allocation.

Right, but swap_cache_alloc_folio with orders=<large order> won't attempt a large allocation if the batch check fails, so that's fine.

Quoted 17 lines
Quoted 8 lines
Quoted 4 lines

Basically:

1. For vswap entry, not backed by phys swap: record swap memcg, hold reference to pin the memcg, but not charging towards swap.current.

Maybe you don't need to record memcg here since folio->memcg already have that info?

Quoted 8 lines

I previously had a patch:
https://lore.kernel.org/linux-mm/[email protected]/

The defers the recording of memcg, the behavior is almost identical to before, but charging & recording should be cleaner and you don't need to record memcg at allocation time hence maybe reduce the possibility of pinning a memcg. I didn't include that in P4 just to reduce LOC, maybe can be resent or included.

Quoted 3 lines

That works-ish when the folio is sitll in swap cache, but say if it's vswap backed by zswap (and the swap cache folio has been reclaimed), you need a place to store the memcg, no?

"Backed by zswap" means the actual swapout already happened, which is the case where we always have to record the memcg info because the folio is gone, seems still fit in the model.

Quoted 3 lines

Just seems cleaner to centralize this info at vswap layer when it is presented, for now anyway, rather than juggling this on a per-backend basis.

Zswap charge could be merged with vswap I think but pswap we just discussed that we might want to charge it differently? And actually vswap charge is still quite different from zswap charge if you want to make vswap infinitely large? I think we can figure out this part as we progress; it's not a major problem at this point.

author maintainer
#15 lore raw
Quoted 50 lines · Kairui Song
Quoted 32 lines · Nhat Pham
Quoted 16 lines · Kairui Song
Quoted 7 lines · Nhat Pham

Are you suggesting we merge the virtual table with main swap table?

Man, I'd love to do this. There is a problem though - we have a case where we occupy both backing physical swap AND swap cache. Do you think we can fit both the physical swap slot handle and the swap cache PFN into the same slot in virtual table? Maybe with some expanding...?

I don't really get why we would need to do that? If you put the PFN info in the virtual / upper layer, then the count info, locking, and all swap IO synchronization (via folio lock), dup (current protected by ci lock / folio lock), and allocation (folio_alloc_swap), are all handled in this layer.

Quoted 8 lines

The physical / lower layer will just hold a reverse entry on folio_realloc_swap, or no entry at all (no physical layer used, zswap, or after swap allocation but before IO) right?

Looking up the actual folio from the physical layer will be a bit slower since it needs to resolve the reverse entry, but the only place we need to do that is things like migrate, compaction (none of them exist yet) which seems totally fine?

All of this is correct, but consider swaping in a vswap entry backed by pswap. There are cases where you still want to maintain the pswap slots around backing vswap entry, while having the swap cache folio as well.

Quoted 5 lines

For e.g, at swap in time, we add the folio into the swap cache. First of all, we need to hold on to the physical swap slot for IO step. But even after IO succeeds, there are cases where you would still like to keep physical swap slots around (for e.g, to avoid swapping out again if the folio is only speculatively fetched).

A reverse entry is enough to hold the physical swap, just like how the current hibernation works with a fake shadow, you don't need a PFN just for holding that.

Quoted 5 lines

So you have to make sure we have space for both the physical swap slot, and the swap cache folio's PFN at the same time for each vswap entry. So we still need the vtable extension (well maybe the other approach I mentioned could work, but I'm not 100% sure).

Quoted 4 lines

Right, vtable extension is fine, there is no redundant data. I just mean you don't need to set the PFN twice (for vswap & pswap). So simply reusing the PFN format in the vswap layer and solving everything there should be enough.

Ah yeah, then I might have misunderstood you here. I thought you were proposing a way to remove vtable :)

"don't need to set the PFN twice" completely agree. I'm pretty sure I did not here, but do let me know if I accidentally set it twice. I'm be sure to check this myself for the next version.

Quoted 8 lines
Quoted 8 lines
Quoted 7 lines

Thanks. Not too complicated, actually our internal kernel implementation still using si->percpu cluster, and use a counter for the rotation and each order have a counter :P, it's a bit ugly but works fine. It still serves pretty well just like the global percpu cluster, YoungJun's previous per ci percpu cluster also still provides the fast path, many ways to do that.

Quoted 5 lines
Quoted 1 line

Sounds like something that should be upstreamed? ;)

I'd love to :), there is a lot of work going on as you can see and people seem to have many different proposals about this so I didn't prioritize it. I'll try as things settle down.

Yeah understandable. It's a very volatile codebase, with a lot of folks trying to improve different aspects.

Hopefully we're close to a unified design :)

I'll keep my dedicated vswap per-cpu alloc caching for now, but I'll get rid of it whenever the per-CPU per-si cache is ready.

Quoted 57 lines
Quoted 28 lines
Quoted 20 lines
Quoted 12 lines
Quoted 8 lines

For patch 2, a few routines like vswap_can_swapin_thp seems not needed or should be moved to __swap_cache_alloc? VSWAP_FOLIO is same as swap cache folio check, which is already covered. Same for zero checking, and VSWAP_NONE which is same as swap count check I think. That way we not only save a lot of code, we also no longer need to treat vswap specially.

Unfortunately, I think a lot of this complexity is still needed. Vswap adds a new layer, which means new complications :)

Quoted 7 lines

For instance, I think you still need vswap_can_swapin_thp. It basically enforces that the backend must be something swap_read_folio() can handle. That means:

1. No zswap.

2. No mixed backend.

Quoted 7 lines

If mixed backend means phys vs zero vs zswap, then we already have part of that covered with the current swap cache except for the phys part (zswap part seems very doable with fujunjie's work). swap_cache_alloc_folio will ensure there is no mixed zerobit, it can be easily extended to ensure there is no mixed zswap as well (according to what I've learned from fujunjie's code). Similar logic for phys detection I think.

Quoted 8 lines

Yeah it's basically generalizing that check, and handle the case where we can have indirection.

I mean I can open-code it, but it has to be there :) And I figure it might be useful to check this opportunistically (at swap_pte_batch, even if it's not guaranteed to be correct down the line) before we even attempt to allocate a large folio etc. to avoid large folio allocation.

Right, but swap_cache_alloc_folio with orders=<large order> won't attempt a large allocation if the batch check fails, so that's fine.

Quoted 17 lines
Quoted 16 lines
Quoted 4 lines

Basically:

1. For vswap entry, not backed by phys swap: record swap memcg, hold reference to pin the memcg, but not charging towards swap.current.

Maybe you don't need to record memcg here since folio->memcg already have that info?

I previously had a patch:
https://lore.kernel.org/linux-mm/[email protected]/

The defers the recording of memcg, the behavior is almost identical to before, but charging & recording should be cleaner and you don't need to record memcg at allocation time hence maybe reduce the possibility of pinning a memcg. I didn't include that in P4 just to reduce LOC, maybe can be resent or included.

Quoted 7 lines
Quoted 3 lines

That works-ish when the folio is sitll in swap cache, but say if it's vswap backed by zswap (and the swap cache folio has been reclaimed), you need a place to store the memcg, no?

"Backed by zswap" means the actual swapout already happened, which is the case where we always have to record the memcg info because the folio is gone, seems still fit in the model.

Hmmm I might have misunderstood you in my last response here.

So what you are doing in that patch:

1. Charge towards folio->memcg when we allocate swap slots, but do not record or take reference yet.

2. Once we reclaimed the folio after swap out, then we record and acquire reference to pin.

You know what - this would simplify my usecase. For vswap entries not backing by pswap, it *basically* just means I skip step 1 for vswap backend. Step 2 is shared for all cases. Donezo.

You're right. This is simpler :) Let me brew on it a bit longer in case there might be something we're missing. but it does seem like this will reduce complexity (and with the added benefits of me not having to come up with names for helpers).

Quoted 10 lines
Quoted 4 lines

Just seems cleaner to centralize this info at vswap layer when it is presented, for now anyway, rather than juggling this on a per-backend basis.

Zswap charge could be merged with vswap I think but pswap we just discussed that we might want to charge it differently? And actually vswap charge is still quite different from zswap charge if you want to make vswap infinitely large? I think we can figure out this part as we progress; it's not a major problem at this point.

That was because I misunderstood your suggestions. My bad :)

Anyway, please keep the suggestions and recommendations coming :) I'm playing with some of your suggestions right now, and waiting for other folks' inputs as well. Will send out the next version at some point. If there is no fundamental design flaws, I will un-RFC once I've addressed all the main issues.

author maintainer
#10 lore raw
In reply to Kairui Song
Quoted 36 lines · Kairui Song
Quoted 26 lines · Nhat Pham
Quoted 19 lines · Nhat Pham
Quoted 17 lines · Kairui Song
Quoted 14 lines · Nhat Pham

III. Follow-ups:

In no particular order (and most of which can be done as follow-up patch series rather than shoving everything in the initial landing):

- More thorough stress testing is very much needed.

- Performance benchmarks to make sure I don't accidentally regress the vswap-less case, and that the vswap's case performance is good. I suspect I will have to port a lot of the optimizations I implemented in v6 over here - some of the inefficiencies are inherent in any swap virtualization, and would require the same fix (for e.g the MRU cluster caching for faster cluster lookup - see [8] and [9]).

Quoted 4 lines
Quoted 4 lines

This could be imporved by per-si percpu cluster. Both YoungJun's tiering and Baoquan's previous swap ops mentioned this is needed, and now vswap also need that. If the vswap is also a si, then it will make use of this too.

Quoted 7 lines

Oh and the MRU cluster caching I mentioned here is not the allocation caching. It's the lookup caching, basically to avoid doing the xa_load() to look up clusters for consecutive swap operations on the same vswap cluster (which is the common case with vswap). For v6, it massively reduces this indirection lookup overhead. Performance-wise it's an absolute winner, just more complexity (because I need to handle reference counting carefully).

Quoted 3 lines

Ah alright, that's interesting. And I think we can keep things simple to start, since sensitive users is stil able tol use plain device this way.

Of course. I'm hoping vswap-on-zswap will not be too terrible at a start. We can then optimize for the swapfile backend case later.

Quoted 3 lines

BTW maintaining MRU is also an overhead, I'm not sure if the lookup pattern always follows that?

Yeah I had to be a bit careful in v6 to make sure the cache (and cache invalidation) happens at the right time. I've had this idea for awhile
- there's a reason why I waited until v6 to implement it :)

For instance, when physical swap allocator runs out of slot for a cluster, we try to reclaim the swap-cache-only slots. That involves taking the rmap back to vswap layer, to check swap cache and swap count. This is a very random pattern, so it does not benefit from this lookup cache, and in fact invalidates the cache :) So I had to add some hint to avoid going back to the vswap layer to check for swap-cache-only state.

Quoted 9 lines
Quoted 7 lines

I also just realized we'll induce the indirection overhead on allocation here too, even if the cached cluster still have slots for allocation, because we look up the cluster (which is basically free for static swap device, but not free for vswap devices). Might need to take care of that to maintain vswap performance (but it will then diverge from your existing code...).

That part should be indeed coverable by the si->percpu cluster though, I think.

Yeah agree - we just need to be a bit craftier with it. The fundamental problem is in the current model, we're only storing offset and si, then look up cluster based on that. But for dynamic vswap, that look up takes the xa_load().

Once we move to per-si per-cpu cluster, then I think it becomes ok to store the cluster pointer directly, correct?

The reference counting needs to be carefully handled though. I think in my old vss design I did something fairly silly - just hold a reference to it while it's in cache, then add CPU offlining handler to clean up. Not the end of the world I suppose, but maybe there's a smarter scheme.

#11 lore raw
Quoted 11 lines · Nhat Pham
Quoted 3 lines · Kairui Song

That part should be indeed coverable by the si->percpu cluster though, I think.

Yeah agree - we just need to be a bit craftier with it. The fundamental problem is in the current model, we're only storing offset and si, then look up cluster based on that. But for dynamic vswap, that look up takes the xa_load().

Quoted 8 lines

Once we move to per-si per-cpu cluster, then I think it becomes ok to store the cluster pointer directly, correct?

The reference counting needs to be carefully handled though. I think in my old vss design I did something fairly silly - just hold a reference to it while it's in cache, then add CPU offlining handler to clean up. Not the end of the world I suppose, but maybe there's a smarter scheme.

Yeah... I'm not entirely sure about this at this point, maybe it can be sorted out as we process. Maybe we can also avoid the xa_load with other techniques too.

maintainer
#16 lore raw
In reply to Nhat Pham
Quoted 99 lines

II. Design

With vswap, pages are assigned virtual swap entries on a ghost device with no backing storage. These entries are backed by zswap, zero pages, or (lazily) physical swap slots. Physical backing is allocated only when needed — on zswap writeback or reclaim writeout, after the rmap step.

Compared to the standalone v6 implementation [1], which introduces a 24-byte per-entry swap descriptor and its own cluster allocator, this edition uses swap_table infrastructure, and share a lot of the allocator logic. Per-slot metadata is stored in a tag-encoded virtual_table (atomic_long_t, 8 bytes per slot), and physical clusters store Pointer-tagged rmap entries in the swap_table for reverse lookup back to the virtual cluster.

Here are some data layout diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +-------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)  |
                       | +--------------------+  |
                       | | swap_table         |  |
                       | |   PFN / Shadow     |  |
                       | | memcg_table        |  |
                       | | count,flags,order  |  |
                       | | lock, list         |  |
                       | +--------------------+  |
                       |                         |
                       | virtual_table           |
                       | +--------------------+  |
                       | | NONE               |  |
                       | | PHYS               |  |
                       | | ZERO               |  |
                       | | ZSWAP(entry*)      |  |
                       | | FOLIO(folio*)      |  |
                       | +--------------------+  |
                       +-------------------------+
                              |
                              | PHYS resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate backend types:

  NONE:   |----- 0000 ------|000|  free / unbacked
  PHYS:   |-- (type:5,off:N)|001|  on a physical swapfile (shifted)
  ZERO:   |----- 0000 ------|010|  zero-filled page
  ZSWAP:  |--- zswap_entry* |011|  compressed in zswap
  FOLIO:  |--- folio* ------|100|  in-memory folio

We still have room for 3 more future backend types, for e.g. CRAM, i.e compressed-CXL-as-swap, which is laid out in [10] and [11]. Worst case scenario, we can add more fields to this extended struct.

Other design points:
- Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens. All the common swap code paths — swapout, swapin, swap freeing, swapoff, zswap writeback, THP swapin, etc. work for both. When CONFIG_VSWAP=n, the vswap branches compile out and behavior should be identical to today's swap-table P4 (at least that is my intention).
- Pointer-tagged swap_table on physical clusters for rmap (physical -> virtual) lookup.

Quoted 8 lines

- Virtual swap slots not backed by physical swap are not charged to memcg swap counters — only physical backing is charged (I made the case for this in [7]).
- Careful separation of vswap and physical swap allocation paths and structures adds a lot of complexity, but is crucial to make sure both paths are efficient and do not conflict with each other (for correctness and performance). I do re-use a lot of the allocation logic wherever possible though.

Thanks for working on this! I mostly looked at the high-level design and the zswap parts, as the swap code has changed a lot since I was familiar with it :)

It seems like the direction being taken here is that we have one (massive) vswap swap device, and we keep normal physical swap devices around as well.

A vswap entry can point at a physical swap entry, or zswap, or zeromap. If a vswap entry points at a physical swap entry, then the physical swap entry points back at the vswap entry (a reverse mapping).

I assume the main reason here is to avoid the extra overhead if everything uses vswap, which would mainly be the reverse mapping overhead? I guess there's also some simplicity that comes from reusing the swap info infra as a whole, including the swap table.

I don't like that the code bifurcates for vswap vs. normal swap entries though. Not sure if this is an issue that can be fixed with proper abstractions to hide it, or if the design needs modifications. I was honestly really hoping we don't end up with this. I was hoping that the physical swap device no longer uses a full swap table and all, and everything goes through vswap.

I hoping that if redirection isn't needed (e.g. zswap is disabled), vswap can directly encode the physical swap slot so that the reverse mapping isn't needed -- so we avoid the overhead without keeping the physical swap device using a fully-fledged swap table.

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

I at least hope that, the current design is not painting us into a corner (e.g. through userspace interfaces), and we can still achieve a vswap-for-all implementation in the future (maybe that's what you have in mind already?).

Aside from the swap code, the only sticking point for me is the logic bifurcation in zswap. Why does zswap need to handle vswap vs. not vswap? I thought the point of the design is to use vswap when zswap is used, and otherwise use a normal swap table. In a way, one of the goals is to make zswap a first class swap citizen, but it doesn't seem like we are achieving that?

author maintainer
#17 lore raw
Quoted 109 lines · Yosry Ahmed
Quoted 100 lines

II. Design

With vswap, pages are assigned virtual swap entries on a ghost device with no backing storage. These entries are backed by zswap, zero pages, or (lazily) physical swap slots. Physical backing is allocated only when needed — on zswap writeback or reclaim writeout, after the rmap step.

Compared to the standalone v6 implementation [1], which introduces a 24-byte per-entry swap descriptor and its own cluster allocator, this edition uses swap_table infrastructure, and share a lot of the allocator logic. Per-slot metadata is stored in a tag-encoded virtual_table (atomic_long_t, 8 bytes per slot), and physical clusters store Pointer-tagged rmap entries in the swap_table for reverse lookup back to the virtual cluster.

Here are some data layout diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +-------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)  |
                       | +--------------------+  |
                       | | swap_table         |  |
                       | |   PFN / Shadow     |  |
                       | | memcg_table        |  |
                       | | count,flags,order  |  |
                       | | lock, list         |  |
                       | +--------------------+  |
                       |                         |
                       | virtual_table           |
                       | +--------------------+  |
                       | | NONE               |  |
                       | | PHYS               |  |
                       | | ZERO               |  |
                       | | ZSWAP(entry*)      |  |
                       | | FOLIO(folio*)      |  |
                       | +--------------------+  |
                       +-------------------------+
                              |
                              | PHYS resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate backend types:

  NONE:   |----- 0000 ------|000|  free / unbacked
  PHYS:   |-- (type:5,off:N)|001|  on a physical swapfile (shifted)
  ZERO:   |----- 0000 ------|010|  zero-filled page
  ZSWAP:  |--- zswap_entry* |011|  compressed in zswap
  FOLIO:  |--- folio* ------|100|  in-memory folio

We still have room for 3 more future backend types, for e.g. CRAM, i.e compressed-CXL-as-swap, which is laid out in [10] and [11]. Worst case scenario, we can add more fields to this extended struct.

Other design points:
- Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens. All the common swap code paths — swapout, swapin, swap freeing, swapoff, zswap writeback, THP swapin, etc. work for both. When CONFIG_VSWAP=n, the vswap branches compile out and behavior should be identical to today's swap-table P4 (at least that is my intention).
- Pointer-tagged swap_table on physical clusters for rmap (physical -> virtual) lookup.

Quoted 8 lines

- Virtual swap slots not backed by physical swap are not charged to memcg swap counters — only physical backing is charged (I made the case for this in [7]).
- Careful separation of vswap and physical swap allocation paths and structures adds a lot of complexity, but is crucial to make sure both paths are efficient and do not conflict with each other (for correctness and performance). I do re-use a lot of the allocation logic wherever possible though.

Quoted 1 line

Thanks for working on this! I mostly looked at the high-level design and

Thank you for initiating this effort in LSFMMBPF 2023 (god, time flies). I was very excited by your presentation and decided to take a stab at it :)

(I'll be sure to mention the full context in a non-RFC version - it has a lot of gems in our technical discussions).

Quoted 2 lines

the zswap parts, as the swap code has changed a lot since I was familiar with it :)

It has changed a lot since 6.19, when I was working on v6. Very exciting time to be a (z)swap developer right now - we have new ideas and new features every other week :) Reviewing code has been quite a joy (albeit a lot of work).

Quoted 4 lines

It seems like the direction being taken here is that we have one (massive) vswap swap device, and we keep normal physical swap devices around as well.

Yep.

Quoted 4 lines

A vswap entry can point at a physical swap entry, or zswap, or zeromap. If a vswap entry points at a physical swap entry, then the physical swap entry points back at the vswap entry (a reverse mapping).

Yep.

Quoted 5 lines

I assume the main reason here is to avoid the extra overhead if everything uses vswap, which would mainly be the reverse mapping overhead? I guess there's also some simplicity that comes from reusing the swap info infra as a whole, including the swap table.

Yeah it helps a lot that we don't have to rewrite the whole allocator and swap entry reference counting logic again :)

Quoted 8 lines

I don't like that the code bifurcates for vswap vs. normal swap entries though. Not sure if this is an issue that can be fixed with proper abstractions to hide it, or if the design needs modifications. I was honestly really hoping we don't end up with this. I was hoping that the physical swap device no longer uses a full swap table and all, and everything goes through vswap.

Quoted 4 lines

I hoping that if redirection isn't needed (e.g. zswap is disabled), vswap can directly encode the physical swap slot so that the reverse mapping isn't needed -- so we avoid the overhead without keeping the physical swap device using a fully-fledged swap table.

Can you expand on "vswap can directly encode the physical swap slot"? I'm not sure I follow here.

Quoted 8 lines

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

In terms of the space overhead I do agree, FWIW :)

I think the other concern is the indirection overhead with going through the xarray for every swap operation, hence the per-CPU vswap cluster lookup caching idea:

https://lore.kernel.org/all/[email protected]/

Quoted 5 lines

I at least hope that, the current design is not painting us into a corner (e.g. through userspace interfaces), and we can still achieve a vswap-for-all implementation in the future (maybe that's what you have in mind already?).

That's still my plan. Operationally speaking, I want to make this completely transparent to users, with minimal to no performance overhead.

The next action item is to optimize for vswap-on-fast-swapfile case - that was Kairui's main concerns regarding performance. I spent a lot of time perfing and fixing issues for this case in v6. The issues with the most egregious effects and simplest fix (vswap-less swap-cache-only check for e.g) are already fixed in this new design, and eventually I will move the rest (lookup caching) and more to here.

Quoted 7 lines

Aside from the swap code, the only sticking point for me is the logic bifurcation in zswap. Why does zswap need to handle vswap vs. not vswap? I thought the point of the design is to use vswap when zswap is used, and otherwise use a normal swap table. In a way, one of the goals is to make zswap a first class swap citizen, but it doesn't seem like we are achieving that?

We already have all the machinery to make zswap completely independent. Right now, if you use vswap, you'll skip the zswap's internal xarray entirely, and just store a zswap entry in the virtual swap cluster's vtable.

I just haven't removed the old code for 2 reasons:

1. Reduce the delta on this RFC, to ease the burden for reviewers (and definitely not because I'm lazy :P)

2. The only other practical reason is so that we can let users compile with !CONFIG_VSWAP and still uses zswap on top of the old swapfile setup during the transition/experimentation period for now.

But logically and conceptually speaking, there is no reason I can come up with to use zswap on without vswap. The CPU indirection overhead is already partially there (since zswap uses an xarray) and further optimized (cluster loopup caching etc.), as well as the space overhead (vswap replaces the zswap xarray). I actually wrote a whole paragraph about how we should always go for vswap if we're using zswap, but then decide to remove it since there's no code for it yet.

If folks like it, what I can do is have CONFIG_ZSWAP depends on CONFIG_VSWAP, removes all the non-vswap logic, and call it a day? :) Then, on the swap allocation side, if vswap allocation fail and zswap writeback is disabled, we can error out early.

author maintainer
#18 lore raw
Quoted 185 lines · Nhat Pham
Quoted 109 lines · Yosry Ahmed
Quoted 100 lines

II. Design

With vswap, pages are assigned virtual swap entries on a ghost device with no backing storage. These entries are backed by zswap, zero pages, or (lazily) physical swap slots. Physical backing is allocated only when needed — on zswap writeback or reclaim writeout, after the rmap step.

Compared to the standalone v6 implementation [1], which introduces a 24-byte per-entry swap descriptor and its own cluster allocator, this edition uses swap_table infrastructure, and share a lot of the allocator logic. Per-slot metadata is stored in a tag-encoded virtual_table (atomic_long_t, 8 bytes per slot), and physical clusters store Pointer-tagged rmap entries in the swap_table for reverse lookup back to the virtual cluster.

Here are some data layout diagrams:

Case 1: vswap entry (virtualized)

  PTE                  swap_cluster_info_dynamic
  vswap_entry          +-------------------------+
  (swp_entry_t) ------>| swap_cluster_info (ci)  |
                       | +--------------------+  |
                       | | swap_table         |  |
                       | |   PFN / Shadow     |  |
                       | | memcg_table        |  |
                       | | count,flags,order  |  |
                       | | lock, list         |  |
                       | +--------------------+  |
                       |                         |
                       | virtual_table           |
                       | +--------------------+  |
                       | | NONE               |  |
                       | | PHYS               |  |
                       | | ZERO               |  |
                       | | ZSWAP(entry*)      |  |
                       | | FOLIO(folio*)      |  |
                       | +--------------------+  |
                       +-------------------------+
                              |
                              | PHYS resolves to

v
PHYSICAL CLUSTER (swap_cluster_info)
+--------------------------+
| swap_table per-slot: |
| NULL - free |
| PFN - cached folio |
| Shadow - swapped out |
| Pointer- vswap rmap |
| Bad - unusable |
| |
| Vswap-backing slot: |
| Pointer(C|swp_entry_t) |
| rmap back to vswap |
+--------------------------+

Case 2: direct-mapped physical entry (no vswap)

  PTE                  PHYSICAL CLUSTER (swap_cluster_info)
  phys_entry           +--------------------------+
  (swp_entry_t) ------>| swap_table per-slot:     |
                       |   NULL   - free          |
                       |   PFN    - cached folio  |
                       |   Shadow - swapped out   |
                       |   Bad    - unusable      |
                       +--------------------------+

struct swap_cluster_info_dynamic {

    struct swap_cluster_info ci;       /* swap_table, lock, etc. */
    unsigned int index;                /* position in xarray */
    struct rcu_head rcu;               /* kfree_rcu deferred free */
    atomic_long_t *virtual_table;      /* backend info, 8 B/slot */

};

Each vswap cluster (swap_cluster_info_dynamic) extends the classic swap_cluster_info struct with a virtual_table array that stores the backend information for each virtual swap entry in the cluster. Each entry is tag-encoded in the low 3 bits to indicate backend types:

  NONE:   |----- 0000 ------|000|  free / unbacked
  PHYS:   |-- (type:5,off:N)|001|  on a physical swapfile (shifted)
  ZERO:   |----- 0000 ------|010|  zero-filled page
  ZSWAP:  |--- zswap_entry* |011|  compressed in zswap
  FOLIO:  |--- folio* ------|100|  in-memory folio

We still have room for 3 more future backend types, for e.g. CRAM, i.e compressed-CXL-as-swap, which is laid out in [10] and [11]. Worst case scenario, we can add more fields to this extended struct.

Other design points:
- Both vswap entries (Case 1) and directly-mapped physical entries (Case 2) coexist as first-class citizens. All the common swap code paths — swapout, swapin, swap freeing, swapoff, zswap writeback, THP swapin, etc. work for both. When CONFIG_VSWAP=n, the vswap branches compile out and behavior should be identical to today's swap-table P4 (at least that is my intention).
- Pointer-tagged swap_table on physical clusters for rmap (physical -> virtual) lookup.

Quoted 8 lines

- Virtual swap slots not backed by physical swap are not charged to memcg swap counters — only physical backing is charged (I made the case for this in [7]).
- Careful separation of vswap and physical swap allocation paths and structures adds a lot of complexity, but is crucial to make sure both paths are efficient and do not conflict with each other (for correctness and performance). I do re-use a lot of the allocation logic wherever possible though.

Quoted 1 line

Thanks for working on this! I mostly looked at the high-level design and

Thank you for initiating this effort in LSFMMBPF 2023 (god, time flies). I was very excited by your presentation and decided to take a stab at it :)

(I'll be sure to mention the full context in a non-RFC version - it has a lot of gems in our technical discussions).

Quoted 2 lines

the zswap parts, as the swap code has changed a lot since I was familiar with it :)

It has changed a lot since 6.19, when I was working on v6. Very exciting time to be a (z)swap developer right now - we have new ideas and new features every other week :) Reviewing code has been quite a joy (albeit a lot of work).

Quoted 4 lines

It seems like the direction being taken here is that we have one (massive) vswap swap device, and we keep normal physical swap devices around as well.

Yep.

Quoted 4 lines

A vswap entry can point at a physical swap entry, or zswap, or zeromap. If a vswap entry points at a physical swap entry, then the physical swap entry points back at the vswap entry (a reverse mapping).

Yep.

Quoted 5 lines

I assume the main reason here is to avoid the extra overhead if everything uses vswap, which would mainly be the reverse mapping overhead? I guess there's also some simplicity that comes from reusing the swap info infra as a whole, including the swap table.

Yeah it helps a lot that we don't have to rewrite the whole allocator and swap entry reference counting logic again :)

Quoted 8 lines

I don't like that the code bifurcates for vswap vs. normal swap entries though. Not sure if this is an issue that can be fixed with proper abstractions to hide it, or if the design needs modifications. I was honestly really hoping we don't end up with this. I was hoping that the physical swap device no longer uses a full swap table and all, and everything goes through vswap.

Quoted 4 lines

I hoping that if redirection isn't needed (e.g. zswap is disabled), vswap can directly encode the physical swap slot so that the reverse mapping isn't needed -- so we avoid the overhead without keeping the physical swap device using a fully-fledged swap table.

Can you expand on "vswap can directly encode the physical swap slot"? I'm not sure I follow here.

Quoted 8 lines

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

In terms of the space overhead I do agree, FWIW :)

I think the other concern is the indirection overhead with going through the xarray for every swap operation, hence the per-CPU vswap cluster lookup caching idea:

https://lore.kernel.org/all/[email protected]/

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

I at least hope that, the current design is not painting us into a corner (e.g. through userspace interfaces), and we can still achieve a vswap-for-all implementation in the future (maybe that's what you have in mind already?).

That's still my plan. Operationally speaking, I want to make this completely transparent to users, with minimal to no performance overhead.

I do want to add that, even without achieving this, the current design already enables a lot of use cases. I think it is a good compromise to maintain both virtual and directly mapped physical swap entries for now, and revisit the conversation of whether we can afford a mandatory vswap layer once all the optimizations have been done :)

We should strive to simplify the codebase, and it will naturally happen when the original overhead concern is no longer there. A swap-related example: a few years ago, everyone thought swap slot cache was needed. But then, Kairui optimized the swap allocator's lock contention issue away, and that swap slot cache is suddenly redundant. That finally allowed us to get rid of it. Similar thing happened (or is happening?) with the SWP_SYNCHRONOUS_IO swapcache-skipping heuristics.

maintainer
#20 lore raw
In reply to Nhat Pham
Quoted 7 lines
Quoted 4 lines

I assume the main reason here is to avoid the extra overhead if everything uses vswap, which would mainly be the reverse mapping overhead? I guess there's also some simplicity that comes from reusing the swap info infra as a whole, including the swap table.

Yeah it helps a lot that we don't have to rewrite the whole allocator and swap entry reference counting logic again :)

I specifically meant using a full swap info thing for the physical swap device even when it's behind vswap. That seems like an overkill, and we don't need things like the swap entry reference coutning. We probably just need a bitmap and a reverse mapping.

So I am assuming the main reason why we are not doing that (at least for now) is simplicity?

Quoted 8 lines
Quoted 8 lines

I don't like that the code bifurcates for vswap vs. normal swap entries though. Not sure if this is an issue that can be fixed with proper abstractions to hide it, or if the design needs modifications. I was honestly really hoping we don't end up with this. I was hoping that the physical swap device no longer uses a full swap table and all, and everything goes through vswap.

Quoted 7 lines
Quoted 4 lines

I hoping that if redirection isn't needed (e.g. zswap is disabled), vswap can directly encode the physical swap slot so that the reverse mapping isn't needed -- so we avoid the overhead without keeping the physical swap device using a fully-fledged swap table.

Can you expand on "vswap can directly encode the physical swap slot"? I'm not sure I follow here.

I meant that if redirection is not needed (e.g. zswap is disabled), then instead of having a vswap device pointing at a physical swap device, we can just the data (e.g. phyiscal swap slot) in the vswap device directly. Then we don't need a full swap info thing and swap table for the physical swap device.

This directly ties into my question above, about why we have a fully-fledged swap info thing for the physical swap device when using vswap.

Quoted 9 lines
Quoted 8 lines

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

Quoted 7 lines

In terms of the space overhead I do agree, FWIW :)

I think the other concern is the indirection overhead with going through the xarray for every swap operation, hence the per-CPU vswap cluster lookup caching idea:

https://lore.kernel.org/all/[email protected]/

Right, but we should already avoid the xarray with the swap table design, right? We just have one swap table pointing to another essentially?

Quoted 9 lines
Quoted 5 lines

I at least hope that, the current design is not painting us into a corner (e.g. through userspace interfaces), and we can still achieve a vswap-for-all implementation in the future (maybe that's what you have in mind already?).

That's still my plan. Operationally speaking, I want to make this completely transparent to users, with minimal to no performance overhead.

So if CONFIG_VSWAP is set all swap devices are vswap by default, right? Would it help with testing if it's controlled by a boot param?

Quoted 7 lines

The next action item is to optimize for vswap-on-fast-swapfile case - that was Kairui's main concerns regarding performance. I spent a lot of time perfing and fixing issues for this case in v6. The issues with the most egregious effects and simplest fix (vswap-less swap-cache-only check for e.g) are already fixed in this new design, and eventually I will move the rest (lookup caching) and more to here.

So is the end goal to have vswap be the default rather than a special swap device? It would certainly help to include some details about that.

Quoted 30 lines
Quoted 7 lines

Aside from the swap code, the only sticking point for me is the logic bifurcation in zswap. Why does zswap need to handle vswap vs. not vswap? I thought the point of the design is to use vswap when zswap is used, and otherwise use a normal swap table. In a way, one of the goals is to make zswap a first class swap citizen, but it doesn't seem like we are achieving that?

We already have all the machinery to make zswap completely independent. Right now, if you use vswap, you'll skip the zswap's internal xarray entirely, and just store a zswap entry in the virtual swap cluster's vtable.

I just haven't removed the old code for 2 reasons:

1. Reduce the delta on this RFC, to ease the burden for reviewers (and definitely not because I'm lazy :P)

2. The only other practical reason is so that we can let users compile with !CONFIG_VSWAP and still uses zswap on top of the old swapfile setup during the transition/experimentation period for now.

But logically and conceptually speaking, there is no reason I can come up with to use zswap on without vswap. The CPU indirection overhead is already partially there (since zswap uses an xarray) and further optimized (cluster loopup caching etc.), as well as the space overhead (vswap replaces the zswap xarray). I actually wrote a whole paragraph about how we should always go for vswap if we're using zswap, but then decide to remove it since there's no code for it yet.

Quoted 4 lines

If folks like it, what I can do is have CONFIG_ZSWAP depends on CONFIG_VSWAP, removes all the non-vswap logic, and call it a day? :) Then, on the swap allocation side, if vswap allocation fail and zswap writeback is disabled, we can error out early.

Hmm maybe we can keep it around for now and do that after vswap stabilizes? It ultimately depend on how much complexity we maintain by allowing both.

I think another problem is 32-bit, technically zswap can be used on 32-bit now, right? So vswap not supporitng 32-bit is a problem.

General question (for both zswap and general swap code), would a boot param make implementation simpler? Right now we seem to key off the swap device having the "vswap" flag, would it help if it was a runtime constant?

maintainer
#19 lore raw
In reply to Nhat Pham
Quoted 48 lines
Quoted 33 lines
Quoted 11 lines

I don't like that the code bifurcates for vswap vs. normal swap entries though. Not sure if this is an issue that can be fixed with proper abstractions to hide it, or if the design needs modifications. I was honestly really hoping we don't end up with this. I was hoping that the physical swap device no longer uses a full swap table and all, and everything goes through vswap.

I hoping that if redirection isn't needed (e.g. zswap is disabled), vswap can directly encode the physical swap slot so that the reverse mapping isn't needed -- so we avoid the overhead without keeping the physical swap device using a fully-fledged swap table.

Can you expand on "vswap can directly encode the physical swap slot"? I'm not sure I follow here.

Quoted 8 lines

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

In terms of the space overhead I do agree, FWIW :)

I think the other concern is the indirection overhead with going through the xarray for every swap operation, hence the per-CPU vswap cluster lookup caching idea:

https://lore.kernel.org/all/[email protected]/

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

I at least hope that, the current design is not painting us into a corner (e.g. through userspace interfaces), and we can still achieve a vswap-for-all implementation in the future (maybe that's what you have in mind already?).

That's still my plan. Operationally speaking, I want to make this completely transparent to users, with minimal to no performance overhead.

I do want to add that, even without achieving this, the current design already enables a lot of use cases. I think it is a good compromise to maintain both virtual and directly mapped physical swap entries for now, and revisit the conversation of whether we can afford a mandatory vswap layer once all the optimizations have been done :)

Quoted 8 lines

We should strive to simplify the codebase, and it will naturally happen when the original overhead concern is no longer there. A swap-related example: a few years ago, everyone thought swap slot cache was needed. But then, Kairui optimized the swap allocator's lock contention issue away, and that swap slot cache is suddenly redundant. That finally allowed us to get rid of it. Similar thing happened (or is happening?) with the SWP_SYNCHRONOUS_IO swapcache-skipping heuristics.

I agree, I just want to make sure we have a line of sight (or at least no blockers) to having a unified vswap layer in the future.

author maintainer
#21 lore raw
In reply to Yosry Ahmed
Quoted 9 lines · Yosry Ahmed
Quoted 8 lines
Quoted 5 lines

I assume the main reason here is to avoid the extra overhead if everything uses vswap, which would mainly be the reverse mapping overhead? I guess there's also some simplicity that comes from reusing the swap info infra as a whole, including the swap table.

Yeah it helps a lot that we don't have to rewrite the whole allocator and swap entry reference counting logic again :)

Quoted 7 lines

I specifically meant using a full swap info thing for the physical swap device even when it's behind vswap. That seems like an overkill, and we don't need things like the swap entry reference coutning. We probably just need a bitmap and a reverse mapping.

So I am assuming the main reason why we are not doing that (at least for now) is simplicity?

Mostly.

FWIW, we're pretty close to full deduplication. Right now, physical swap clusters have a couple of fields that are not needed when they're backing a vswap cluster:

1. The main swap table (which houses swap cache, swap shadow, and reference counting): I repurpose it for the rmap :) It's an array of unsigned long, which works for rmap.

2. memcg_table: still duplicated, but I think I can make sure this is not allocated if physical swap clusters only back vswap entries. I have a prototype that I'm testing for this.

3. The zeromap field: this is actually not allocated in 64 bit architecture, IIUC, which is what I'm gating CONFIG_VSWAP on. If we extend vswap to supporting 32 bits, this can also be dynamically allocated.

4. Extend table - this is for the swap count overfills, and already dynamically allocated.

Quoted 23 lines
Quoted 9 lines
Quoted 9 lines

I don't like that the code bifurcates for vswap vs. normal swap entries though. Not sure if this is an issue that can be fixed with proper abstractions to hide it, or if the design needs modifications. I was honestly really hoping we don't end up with this. I was hoping that the physical swap device no longer uses a full swap table and all, and everything goes through vswap.

Quoted 7 lines
Quoted 4 lines

I hoping that if redirection isn't needed (e.g. zswap is disabled), vswap can directly encode the physical swap slot so that the reverse mapping isn't needed -- so we avoid the overhead without keeping the physical swap device using a fully-fledged swap table.

Can you expand on "vswap can directly encode the physical swap slot"? I'm not sure I follow here.

I meant that if redirection is not needed (e.g. zswap is disabled), then instead of having a vswap device pointing at a physical swap device, we can just the data (e.g. phyiscal swap slot) in the vswap device directly. Then we don't need a full swap info thing and swap table for the physical swap device.

Quoted 3 lines

This directly ties into my question above, about why we have a fully-fledged swap info thing for the physical swap device when using vswap.

See above.

Quoted 16 lines
Quoted 16 lines
Quoted 9 lines

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

In terms of the space overhead I do agree, FWIW :)

I think the other concern is the indirection overhead with going through the xarray for every swap operation, hence the per-CPU vswap cluster lookup caching idea:

Quoted 5 lines
Quoted 1 line

https://lore.kernel.org/all/[email protected]/

Right, but we should already avoid the xarray with the swap table design, right? We just have one swap table pointing to another essentially?

Hmmm, I don't quite follow your suggestion here.

For normal swap devices, we organize the space into clusters, and maintain them in various lists (free, nonfull, full etc.). The only difference with a vswap device is we do not have a free list, and have the clusters themselves dynamically allocated.

If we're using vswap, we will incur the xarray overhead. There's no avoiding that if we want a dynamic indirection layer. We can of course revisit this data structure design later.

So yes, it will be one swap table (vswap cluster) pointing to another swap table (pswap cluster). But to get to the first swap table, you will have to go through xarray still.

Quoted 22 lines
Quoted 10 lines
Quoted 6 lines

I at least hope that, the current design is not painting us into a corner (e.g. through userspace interfaces), and we can still achieve a vswap-for-all implementation in the future (maybe that's what you have in mind already?).

That's still my plan. Operationally speaking, I want to make this completely transparent to users, with minimal to no performance overhead.

So if CONFIG_VSWAP is set all swap devices are vswap by default, right? Would it help with testing if it's controlled by a boot param?

Quoted 7 lines

The next action item is to optimize for vswap-on-fast-swapfile case - that was Kairui's main concerns regarding performance. I spent a lot of time perfing and fixing issues for this case in v6. The issues with the most egregious effects and simplest fix (vswap-less swap-cache-only check for e.g) are already fixed in this new design, and eventually I will move the rest (lookup caching) and more to here.

Quoted 2 lines

So is the end goal to have vswap be the default rather than a special swap device? It would certainly help to include some details about that.

That is my preference - I did allude to it in "Runtime enable/disable of the vswap device" follow-up section :) I'm a sucker for unified paths. It kinda depends on whether we can optimize most of vswap overhead away though - if not, then we have to maintain both paths. Kairui, how do you feel about this?

Quoted 36 lines
Quoted 31 lines
Quoted 8 lines

Aside from the swap code, the only sticking point for me is the logic bifurcation in zswap. Why does zswap need to handle vswap vs. not vswap? I thought the point of the design is to use vswap when zswap is used, and otherwise use a normal swap table. In a way, one of the goals is to make zswap a first class swap citizen, but it doesn't seem like we are achieving that?

We already have all the machinery to make zswap completely independent. Right now, if you use vswap, you'll skip the zswap's internal xarray entirely, and just store a zswap entry in the virtual swap cluster's vtable.

I just haven't removed the old code for 2 reasons:

1. Reduce the delta on this RFC, to ease the burden for reviewers (and definitely not because I'm lazy :P)

2. The only other practical reason is so that we can let users compile with !CONFIG_VSWAP and still uses zswap on top of the old swapfile setup during the transition/experimentation period for now.

But logically and conceptually speaking, there is no reason I can come up with to use zswap on without vswap. The CPU indirection overhead is already partially there (since zswap uses an xarray) and further optimized (cluster loopup caching etc.), as well as the space overhead (vswap replaces the zswap xarray). I actually wrote a whole paragraph about how we should always go for vswap if we're using zswap, but then decide to remove it since there's no code for it yet.

Quoted 4 lines

If folks like it, what I can do is have CONFIG_ZSWAP depends on CONFIG_VSWAP, removes all the non-vswap logic, and call it a day? :) Then, on the swap allocation side, if vswap allocation fail and zswap writeback is disabled, we can error out early.

Quoted 6 lines

Hmm maybe we can keep it around for now and do that after vswap stabilizes? It ultimately depend on how much complexity we maintain by allowing both.

I think another problem is 32-bit, technically zswap can be used on 32-bit now, right? So vswap not supporitng 32-bit is a problem.

Ah shoot I forgot about that. Hmmm.

It's not impossible to make vswap support 32-bit. I did that for v6 after all. It just needs extra fields because we have fewer bits to leverage in pointers etc., complicating the logic a bit. Follow-up work? :)

Quoted 5 lines

General question (for both zswap and general swap code), would a boot param make implementation simpler? Right now we seem to key off the swap device having the "vswap" flag, would it help if it was a runtime constant?

Hmmm, even if it's a runtime constant, both branches still have to be there, no? Does the boot param simplify it somehow?

maintainer
#22 lore raw
Quoted 33 lines · Nhat Pham
Quoted 9 lines · Yosry Ahmed
Quoted 8 lines
Quoted 5 lines

I assume the main reason here is to avoid the extra overhead if everything uses vswap, which would mainly be the reverse mapping overhead? I guess there's also some simplicity that comes from reusing the swap info infra as a whole, including the swap table.

Yeah it helps a lot that we don't have to rewrite the whole allocator and swap entry reference counting logic again :)

Quoted 7 lines

I specifically meant using a full swap info thing for the physical swap device even when it's behind vswap. That seems like an overkill, and we don't need things like the swap entry reference coutning. We probably just need a bitmap and a reverse mapping.

So I am assuming the main reason why we are not doing that (at least for now) is simplicity?

Mostly.

FWIW, we're pretty close to full deduplication. Right now, physical swap clusters have a couple of fields that are not needed when they're backing a vswap cluster:

1. The main swap table (which houses swap cache, swap shadow, and reference counting): I repurpose it for the rmap :) It's an array of unsigned long, which works for rmap.

2. memcg_table: still duplicated, but I think I can make sure this is not allocated if physical swap clusters only back vswap entries. I have a prototype that I'm testing for this.

Quoted 7 lines

3. The zeromap field: this is actually not allocated in 64 bit architecture, IIUC, which is what I'm gating CONFIG_VSWAP on. If we extend vswap to supporting 32 bits, this can also be dynamically allocated.

4. Extend table - this is for the swap count overfills, and already dynamically allocated.

I see.

Quoted 27 lines
Quoted 14 lines
Quoted 14 lines
Quoted 7 lines

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

In terms of the space overhead I do agree, FWIW :)

I think the other concern is the indirection overhead with going through the xarray for every swap operation, hence the per-CPU vswap cluster lookup caching idea:

Quoted 5 lines
Quoted 1 line

https://lore.kernel.org/all/[email protected]/

Right, but we should already avoid the xarray with the swap table design, right? We just have one swap table pointing to another essentially?

Hmmm, I don't quite follow your suggestion here.

For normal swap devices, we organize the space into clusters, and maintain them in various lists (free, nonfull, full etc.). The only difference with a vswap device is we do not have a free list, and have the clusters themselves dynamically allocated.

Quoted 7 lines

If we're using vswap, we will incur the xarray overhead. There's no avoiding that if we want a dynamic indirection layer. We can of course revisit this data structure design later.

So yes, it will be one swap table (vswap cluster) pointing to another swap table (pswap cluster). But to get to the first swap table, you will have to go through xarray still.

Why the xarray? Don't page tables (and shmem page cache) just point directly to the vswap entry the same way they point to swap entries today?

*looks at the code*

Oh, it's to find the actual cluster because the vswap file can be sparse? Hmm yeah I guess we can revisit the data structure here later, but IIRC xarrays aren't particularly good for sparse data. Maybe it's usually not sprase in practice.

Maybe a maple tree? :)

Quoted 12 lines
Quoted 11 lines
Quoted 4 lines

If folks like it, what I can do is have CONFIG_ZSWAP depends on CONFIG_VSWAP, removes all the non-vswap logic, and call it a day? :) Then, on the swap allocation side, if vswap allocation fail and zswap writeback is disabled, we can error out early.

Hmm maybe we can keep it around for now and do that after vswap stabilizes? It ultimately depend on how much complexity we maintain by allowing both.

I think another problem is 32-bit, technically zswap can be used on 32-bit now, right? So vswap not supporitng 32-bit is a problem.

Quoted 6 lines

Ah shoot I forgot about that. Hmmm.

It's not impossible to make vswap support 32-bit. I did that for v6 after all. It just needs extra fields because we have fewer bits to leverage in pointers etc., complicating the logic a bit. Follow-up work? :)

Yeah we can do that, but it's a blocker for zswap only using vswap.

Quoted 7 lines
Quoted 4 lines

General question (for both zswap and general swap code), would a boot param make implementation simpler? Right now we seem to key off the swap device having the "vswap" flag, would it help if it was a runtime constant?

Hmmm, even if it's a runtime constant, both branches still have to be there, no? Does the boot param simplify it somehow?

Maybe it doesn't simplify the code, but if the branching causes performance overhead we can use static keys. I guess we can still use static keys per-swapfile, but it would be more complicated.

Anyway, not super important now.

author maintainer
#23 lore raw
Quoted 36 lines · Yosry Ahmed
Quoted 28 lines
Quoted 15 lines
Quoted 15 lines
Quoted 8 lines

All that being said, perhaps I am too out of touch with the code to realize it's simply not possible.

Honestly, if the main reason we can't have a single swap table for vswap is saving 8 bytes on the reverse mapping, it sounds like a weak-ish argument, even if we can't optimize the reverse mapping away. But maybe I am also out of touch with RAM prices :)

In terms of the space overhead I do agree, FWIW :)

I think the other concern is the indirection overhead with going through the xarray for every swap operation, hence the per-CPU vswap cluster lookup caching idea:

Quoted 5 lines
Quoted 1 line

https://lore.kernel.org/all/[email protected]/

Right, but we should already avoid the xarray with the swap table design, right? We just have one swap table pointing to another essentially?

Hmmm, I don't quite follow your suggestion here.

For normal swap devices, we organize the space into clusters, and maintain them in various lists (free, nonfull, full etc.). The only difference with a vswap device is we do not have a free list, and have the clusters themselves dynamically allocated.

Quoted 7 lines

If we're using vswap, we will incur the xarray overhead. There's no avoiding that if we want a dynamic indirection layer. We can of course revisit this data structure design later.

So yes, it will be one swap table (vswap cluster) pointing to another swap table (pswap cluster). But to get to the first swap table, you will have to go through xarray still.

Quoted 8 lines

Why the xarray? Don't page tables (and shmem page cache) just point directly to the vswap entry the same way they point to swap entries today?

*looks at the code*

Oh, it's to find the actual cluster because the vswap file can be sparse? Hmm yeah I guess we can revisit the data structure here later,

Less sparsity, and more dynamicity :) It might be dense for all we know - we just don't really know (or want to figure out) the size statically.

Quoted 4 lines

but IIRC xarrays aren't particularly good for sparse data. Maybe it's usually not sprase in practice.

Maybe a maple tree? :)

Maybe :)

Quoted 13 lines
Quoted 13 lines
Quoted 12 lines
Quoted 5 lines

If folks like it, what I can do is have CONFIG_ZSWAP depends on CONFIG_VSWAP, removes all the non-vswap logic, and call it a day? :) Then, on the swap allocation side, if vswap allocation fail and zswap writeback is disabled, we can error out early.

Hmm maybe we can keep it around for now and do that after vswap stabilizes? It ultimately depend on how much complexity we maintain by allowing both.

I think another problem is 32-bit, technically zswap can be used on 32-bit now, right? So vswap not supporitng 32-bit is a problem.

Quoted 8 lines
Quoted 6 lines

Ah shoot I forgot about that. Hmmm.

It's not impossible to make vswap support 32-bit. I did that for v6 after all. It just needs extra fields because we have fewer bits to leverage in pointers etc., complicating the logic a bit. Follow-up work? :)

Yeah we can do that, but it's a blocker for zswap only using vswap.

Yeah we can table that. FWIW, if you enable vswap, then zswap should go through vswap already. It's just code complexity (hopefully for a short while).

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

General question (for both zswap and general swap code), would a boot param make implementation simpler? Right now we seem to key off the swap device having the "vswap" flag, would it help if it was a runtime constant?

Quoted 8 lines
Quoted 2 lines

Hmmm, even if it's a runtime constant, both branches still have to be there, no? Does the boot param simplify it somehow?

Maybe it doesn't simplify the code, but if the branching causes performance overhead we can use static keys. I guess we can still use static keys per-swapfile, but it would be more complicated.

Anyway, not super important now.

Ahhh I see what you mean. Yeah we can optimize this later.