Skip to contentSkip to conversation

Virtual Swap Space

RFC PATCH Superseded Nhat Pham 5 participants 35 messages Apr 7, 2025 – Apr 22, 2025 2 messages not in the archive

Subsystems (13)

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Nhat Pham

author maintainer
#0 lore raw

cover Virtual Swap Space

This RFC implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).

The code attached to this RFC is purely a prototype. It is not 100% merge-ready (see section VI for future work). I do, however, want to show people this prototype/RFC, including all the bells and whistles and a couple of actual use cases, so that folks can see what the end results will look like, and give me early feedback :)

I. Motivation

Currently, when an anon page is swapped out, a slot in a backing swap device is allocated and stored in the page table entries that refer to the original page. This slot is also used as the "key" to find the swapped out content, as well as the index to swap data structures, such as the swap cache, or the swap cgroup mapping. Tying a swap entry to its backing slot in this way is performant and efficient when swap is purely just disk space, and swapoff is rare.

However, the advent of many swap optimizations has exposed major drawbacks of this design. The first problem is that we occupy a physical slot in the swap space, even for pages that are NEVER expected to hit the disk: pages compressed and stored in the zswap pool, zero-filled pages, or pages rejected by both of these optimizations when zswap writeback is disabled. This is the arguably central shortcoming of zswap:
* In deployments when no disk space can be afforded for swap (such as mobile and embedded devices), users cannot adopt zswap, and are forced to use zram. This is confusing for users, and creates extra burdens for developers, having to develop and maintain similar features for two separate swap backends (writeback, cgroup charging, THP support, etc.). For instance, see the discussion in [4].
* Resource-wise, it is hugely wasteful in terms of disk usage, and limits the memory saving potentials of these optimizations by the static size of the swapfile, especially in high memory systems that can have up to terabytes worth of memory. It also creates significant challenges for users who rely on swap utilization as an early OOM signal.

Another motivation for a swap redesign is to simplify swapoff, which is complicated and expensive in the current design. Tight coupling between a swap entry and its backing storage means that it requires a whole page table walk to update all the page table entries that refer to this swap entry, as well as updating all the associated swap data structures (swap cache, etc.).

II. High Level Design Overview

To fix the aforementioned issues, we need an abstraction that separates a swap entry from its physical backing storage. IOW, we need to “virtualize” the swap space: swap clients will work with a dynamically allocated virtual swap slot, storing it in page table entries, and using it to index into various swap-related data structures. The backing storage is decoupled from the virtual swap slot, and the newly introduced layer will “resolve” the virtual swap slot to the actual storage. This layer also manages other metadata of the swap entry, such as its lifetime information (swap count), via a dynamically allocated per-swap-entry descriptor:

struct swp_desc {
	swp_entry_t vswap;
	union {
		swp_slot_t slot;
		struct folio *folio;
		struct zswap_entry *zswap_entry;
	};
	struct rcu_head rcu;

	rwlock_t lock;
	enum swap_type type;

	atomic_t memcgid;

	atomic_t in_swapcache;
	struct kref refcnt;
	atomic_t swap_count;
};

This design allows us to:
* Decouple zswap (and zeromapped swap entry) from backing swapfile:
simply associate the virtual swap slot with one of the supported
backends: a zswap entry, a zero-filled swap page, a slot on the swapfile, or an in-memory page .
* Simplify and optimize swapoff: we only have to fault the page in and have the virtual swap slot points to the page instead of the on-disk physical swap slot. No need to perform any page table walking.

Please see the attached patches for implementation details.

Note that I do not remove the old implementation for now. Users can select between the old and the new implementation via the CONFIG_VIRTUAL_SWAP build config. This will also allow us to land the new design, and iteratively optimize upon it (without having to include everything in an even more massive patch series).

III. Future Use Cases

Other than decoupling swap backends and optimizing swapoff, this new design allows us to implement the following more easily and efficiently:

* Multi-tier swapping (as mentioned in [5]), with transparent transferring (promotion/demotion) of pages across tiers (see [8] and [9]). Similar to swapoff, with the old design we would need to perform the expensive page table walk.
* Swapfile compaction to alleviate fragmentation (as proposed by Ying Huang in [6]).
* Mixed backing THP swapin (see [7]): Once you have pinned down the backing store of THPs, then you can dispatch each range of subpages to appropriate swapin handle.
* Swapping a folio out with discontiguous physical swap slots (see [10])

IV. Potential Issues

Here is a couple of issues I can think of, along with some potential solutions:

1. Space overhead: we need one swap descriptor per swap entry.
* Note that this overhead is dynamic, i.e only incurred when we actually need to swap a page out.
* It can be further offset by the reduction of swap map and the elimination of zeromapped bitmap.

2. Lock contention: since the virtual swap space is dynamic/unbounded, we cannot naively range partition it anymore. This can increase lock contention on swap-related data structures (swap cache, zswap’s xarray, etc.).
* The problem is slightly alleviated by the lockless nature of the new reference counting scheme, as well as the per-entry locking for backing store information.
* Johannes suggested that I can implement a dynamic partition scheme, in which new partitions (along with associated data structures) are allocated on demand. It is one extra layer of indirection, but global locking will only be done only on partition allocation, rather than on each access. All other accesses only take local (per-partition) locks, or are completely lockless (such as partition lookup).

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

2. Kernel building: zswap enabled, 52 workers (one per processor), memory.max = 3G.

Baseline:
real: 183.55s
user: 5119.01s
sys: 655.16s

New Design:
real: mean: 184.5s
user: mean: 5117.4s
sys: mean: 695.23s

New Design (Static Partition)
real: 183.95s
user: 5119.29s
sys: 664.24s

3. Swapoff: 32 GB swapfile, 50% full, with a process that mmap-ed a 128GB file.

Baseline:
real: 25.54s
user: 0.00s
sys: 11.48s

New Design:
real: 11.69s
user: 0.00s
sys: 9.96s

The new design reduces the kernel CPU time by about 13%. There is also reduction in real time, but this is mostly due to more asynchronous IO (rather than the design itself) :)

VI. TODO list

This RFC includes a feature-complete prototype on top of 6.14. Here are some action items:

Short-term: needs to be done before merging
* More clean-ups and stress-testing.
* Add more documentation of the new design and its API.

Medium-term: optimizations required to make virtual swap implementation the default:
* Swap map shrinking and zero map reduction when virtual swap is enabled.
* Range partition the virtual swap space.
* More benchmarking and experiments in a variety of use cases.

Long-term: removal of the old implementation and other non-blocking opportunities
* Remove the old implementation, when there are no major regressions and bottlenecks, etc remained with the new design.
* Merge more existing swap data structures into this layer - for instance, the MTE swap xarray.
* Adding new use cases :)

[1]: https://lore.kernel.org/all/CAJD7tkbCnXJ95Qow_aOjNX6NOMU5ovMSHRC+95U4wtW6cM+puw@mail.gmail.com/
[2]: https://lwn.net/Articles/932077/
[3]: https://www.youtube.com/watch?v=Hwqw_TBGEhg
[4]: https://lore.kernel.org/all/[email protected]/
[5]: https://lore.kernel.org/lkml/CAF8kJuN-4UE0skVHvjUzpGefavkLULMonjgkXUZSBVJrcGFXCA@mail.gmail.com/
[6]: https://lore.kernel.org/linux-mm/[email protected]/
[7]: https://lore.kernel.org/all/CAGsJ_4ysCN6f7qt=6gvee1x3ttbOnifGneqcRm9Hoeun=uFQ2w@mail.gmail.com/
[8]: https://lore.kernel.org/linux-mm/[email protected]/
[9]: https://lore.kernel.org/all/CA+ZsKJ7DCE8PMOSaVmsmYZL9poxK6rn0gvVXbjpqxMwxS2C9TQ@mail.gmail.com/
[10]: https://lore.kernel.org/all/CACePvbUkMYMencuKfpDqtG1Ej7LiUS87VRAXb8sBn1yANikEmQ@mail.gmail.com/

Nhat Pham (14):
swapfile: rearrange functions
mm: swap: add an abstract API for locking out swapoff
mm: swap: add a separate type for physical swap slots
mm: swap: swap cache support for virtualized swap
zswap: unify zswap tree for virtualized swap
mm: swap: allocate a virtual swap slot for each swapped out page
swap: implement the swap_cgroup API using virtual swap
swap: manage swap entry lifetime at the virtual swap layer
swap: implement locking out swapoff using virtual swap slot
mm: swap: decouple virtual swap slot from backing store
memcg: swap: only charge physical swap slots
vswap: support THP swapin and batch free_swap_and_cache
swap: simplify swapoff using virtual swap
zswap: do not start zswap shrinker if there is no physical swap slots

 MAINTAINERS                |    7 +
 include/linux/mm_types.h   |    7 +
 include/linux/shmem_fs.h   |    3 +
 include/linux/swap.h       |  280 +++++--
 include/linux/swap_slots.h |    2 +-
 include/linux/swapops.h    |   37 +
 kernel/power/swap.c        |    6 +-
 mm/Kconfig                 |   28 +
 mm/Makefile                |    3 +
 mm/huge_memory.c           |    5 +-
 mm/internal.h              |   25 +-
 mm/memcontrol.c            |  166 ++++-
 mm/memory.c                |   99 ++-
 mm/migrate.c               |    1 +
 mm/page_io.c               |   60 +-
 mm/shmem.c                 |   29 +-
 mm/swap.h                  |   45 +-
 mm/swap_cgroup.c           |   10 +-
 mm/swap_slots.c            |   28 +-
 mm/swap_state.c            |  144 +++-
 mm/swapfile.c              |  770 ++++++++++++-------
 mm/vmscan.c                |   26 +-
 mm/vswap.c                 | 1437 ++++++++++++++++++++++++++++++++++++
 mm/zswap.c                 |   80 +-
 24 files changed, 2807 insertions(+), 491 deletions(-)
 create mode 100644 mm/vswap.c

base-commit: 922ceb9d4bb4dae66c37e24621687e0b4991f5a4

Signature · 1 line
2.47.1
author maintainer
#1 lore raw

RFC PATCH 1/14 swapfile: rearrange functions

Rearrange some functions in preparation for the rest of the series. No functional change intended.

---
 mm/swapfile.c | 230 +++++++++++++++++++++++++-------------------------
 1 file changed, 115 insertions(+), 115 deletions(-)
mm/swapfile.c +115 -115
index df7c4e8b089c..27cf985e08ac 100644
@@ -124,11 +124,6 @@ static struct swap_info_struct *swap_type_to_swap_info(int type)
 	return READ_ONCE(swap_info[type]); /* rcu_dereference() */
 }
 
-static inline unsigned char swap_count(unsigned char ent)
-{
-	return ent & ~SWAP_HAS_CACHE;	/* may include COUNT_CONTINUED flag */
-}
-
 /*
  * Use the second highest bit of inuse_pages counter as the indicator
  * if one swap device is on the available plist, so the atomic can
@@ -161,6 +156,11 @@ static long swap_usage_in_pages(struct swap_info_struct *si)
 /* Reclaim directly, bypass the slot cache and don't touch device lock */
 #define TTRS_DIRECT		0x8
 
+static inline unsigned char swap_count(unsigned char ent)
+{
+	return ent & ~SWAP_HAS_CACHE;	/* may include COUNT_CONTINUED flag */
+}
+
 static bool swap_is_has_cache(struct swap_info_struct *si,
 			      unsigned long offset, int nr_pages)
 {
@@ -1326,46 +1326,6 @@ static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
 	return NULL;
 }
 
-static unsigned char __swap_entry_free_locked(struct swap_info_struct *si,
-					      unsigned long offset,
-					      unsigned char usage)
-{
-	unsigned char count;
-	unsigned char has_cache;
-
-	count = si->swap_map[offset];
-
-	has_cache = count & SWAP_HAS_CACHE;
-	count &= ~SWAP_HAS_CACHE;
-
-	if (usage == SWAP_HAS_CACHE) {
-		VM_BUG_ON(!has_cache);
-		has_cache = 0;
-	} else if (count == SWAP_MAP_SHMEM) {
-		/*
-		 * Or we could insist on shmem.c using a special
-		 * swap_shmem_free() and free_shmem_swap_and_cache()...
-		 */
-		count = 0;
-	} else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
-		if (count == COUNT_CONTINUED) {
-			if (swap_count_continued(si, offset, count))
-				count = SWAP_MAP_MAX | COUNT_CONTINUED;
-			else
-				count = SWAP_MAP_MAX;
-		} else
-			count--;
-	}
-
-	usage = count | has_cache;
-	if (usage)
-		WRITE_ONCE(si->swap_map[offset], usage);
-	else
-		WRITE_ONCE(si->swap_map[offset], SWAP_HAS_CACHE);
-
-	return usage;
-}
-
 /*
  * When we get a swap entry, if there aren't some other ways to
  * prevent swapoff, such as the folio in swap cache is locked, RCU
@@ -1432,6 +1392,46 @@ struct swap_info_struct *get_swap_device(swp_entry_t entry)
 	return NULL;
 }
 
+static unsigned char __swap_entry_free_locked(struct swap_info_struct *si,
+					      unsigned long offset,
+					      unsigned char usage)
+{
+	unsigned char count;
+	unsigned char has_cache;
+
+	count = si->swap_map[offset];
+
+	has_cache = count & SWAP_HAS_CACHE;
+	count &= ~SWAP_HAS_CACHE;
+
+	if (usage == SWAP_HAS_CACHE) {
+		VM_BUG_ON(!has_cache);
+		has_cache = 0;
+	} else if (count == SWAP_MAP_SHMEM) {
+		/*
+		 * Or we could insist on shmem.c using a special
+		 * swap_shmem_free() and free_shmem_swap_and_cache()...
+		 */
+		count = 0;
+	} else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
+		if (count == COUNT_CONTINUED) {
+			if (swap_count_continued(si, offset, count))
+				count = SWAP_MAP_MAX | COUNT_CONTINUED;
+			else
+				count = SWAP_MAP_MAX;
+		} else
+			count--;
+	}
+
+	usage = count | has_cache;
+	if (usage)
+		WRITE_ONCE(si->swap_map[offset], usage);
+	else
+		WRITE_ONCE(si->swap_map[offset], SWAP_HAS_CACHE);
+
+	return usage;
+}
+
 static unsigned char __swap_entry_free(struct swap_info_struct *si,
 				       swp_entry_t entry)
 {
@@ -1585,25 +1585,6 @@ void put_swap_folio(struct folio *folio, swp_entry_t entry)
 	unlock_cluster(ci);
 }
 
-void swapcache_free_entries(swp_entry_t *entries, int n)
-{
-	int i;
-	struct swap_cluster_info *ci;
-	struct swap_info_struct *si = NULL;
-
-	if (n <= 0)
-		return;
-
-	for (i = 0; i < n; ++i) {
-		si = _swap_info_get(entries[i]);
-		if (si) {
-			ci = lock_cluster(si, swp_offset(entries[i]));
-			swap_entry_range_free(si, ci, entries[i], 1);
-			unlock_cluster(ci);
-		}
-	}
-}
-
 int __swap_count(swp_entry_t entry)
 {
 	struct swap_info_struct *si = swp_swap_info(entry);
@@ -1717,57 +1698,6 @@ static bool folio_swapped(struct folio *folio)
 	return swap_page_trans_huge_swapped(si, entry, folio_order(folio));
 }
 
-static bool folio_swapcache_freeable(struct folio *folio)
-{
-	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
-
-	if (!folio_test_swapcache(folio))
-		return false;
-	if (folio_test_writeback(folio))
-		return false;
-
-	/*
-	 * Once hibernation has begun to create its image of memory,
-	 * there's a danger that one of the calls to folio_free_swap()
-	 * - most probably a call from __try_to_reclaim_swap() while
-	 * hibernation is allocating its own swap pages for the image,
-	 * but conceivably even a call from memory reclaim - will free
-	 * the swap from a folio which has already been recorded in the
-	 * image as a clean swapcache folio, and then reuse its swap for
-	 * another page of the image.  On waking from hibernation, the
-	 * original folio might be freed under memory pressure, then
-	 * later read back in from swap, now with the wrong data.
-	 *
-	 * Hibernation suspends storage while it is writing the image
-	 * to disk so check that here.
-	 */
-	if (pm_suspended_storage())
-		return false;
-
-	return true;
-}
-
-/**
- * folio_free_swap() - Free the swap space used for this folio.
- * @folio: The folio to remove.
- *
- * If swap is getting full, or if there are no more mappings of this folio,
- * then call folio_free_swap to free its swap space.
- *
- * Return: true if we were able to release the swap space.
- */
-bool folio_free_swap(struct folio *folio)
-{
-	if (!folio_swapcache_freeable(folio))
-		return false;
-	if (folio_swapped(folio))
-		return false;
-
-	delete_from_swap_cache(folio);
-	folio_set_dirty(folio);
-	return true;
-}
-
 /**
  * free_swap_and_cache_nr() - Release reference on range of swap entries and
  *                            reclaim their cache if no more references remain.
@@ -1842,6 +1772,76 @@ void free_swap_and_cache_nr(swp_entry_t entry, int nr)
 	put_swap_device(si);
 }
 
+void swapcache_free_entries(swp_entry_t *entries, int n)
+{
+	int i;
+	struct swap_cluster_info *ci;
+	struct swap_info_struct *si = NULL;
+
+	if (n <= 0)
+		return;
+
+	for (i = 0; i < n; ++i) {
+		si = _swap_info_get(entries[i]);
+		if (si) {
+			ci = lock_cluster(si, swp_offset(entries[i]));
+			swap_entry_range_free(si, ci, entries[i], 1);
+			unlock_cluster(ci);
+		}
+	}
+}
+
+static bool folio_swapcache_freeable(struct folio *folio)
+{
+	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
+
+	if (!folio_test_swapcache(folio))
+		return false;
+	if (folio_test_writeback(folio))
+		return false;
+
+	/*
+	 * Once hibernation has begun to create its image of memory,
+	 * there's a danger that one of the calls to folio_free_swap()
+	 * - most probably a call from __try_to_reclaim_swap() while
+	 * hibernation is allocating its own swap pages for the image,
+	 * but conceivably even a call from memory reclaim - will free
+	 * the swap from a folio which has already been recorded in the
+	 * image as a clean swapcache folio, and then reuse its swap for
+	 * another page of the image.  On waking from hibernation, the
+	 * original folio might be freed under memory pressure, then
+	 * later read back in from swap, now with the wrong data.
+	 *
+	 * Hibernation suspends storage while it is writing the image
+	 * to disk so check that here.
+	 */
+	if (pm_suspended_storage())
+		return false;
+
+	return true;
+}
+
+/**
+ * folio_free_swap() - Free the swap space used for this folio.
+ * @folio: The folio to remove.
+ *
+ * If swap is getting full, or if there are no more mappings of this folio,
+ * then call folio_free_swap to free its swap space.
+ *
+ * Return: true if we were able to release the swap space.
+ */
+bool folio_free_swap(struct folio *folio)
+{
+	if (!folio_swapcache_freeable(folio))
+		return false;
+	if (folio_swapped(folio))
+		return false;
+
+	delete_from_swap_cache(folio);
+	folio_set_dirty(folio);
+	return true;
+}
+
 #ifdef CONFIG_HIBERNATION
 
 swp_entry_t get_swap_page_of_type(int type)
Signature · 1 line
2.47.1
author maintainer
#2 lore raw

RFC PATCH 2/14 mm: swap: add an abstract API for locking out swapoff

In reply to Nhat Pham

Currently, we get a reference to the backing swap device in order to lock out swapoff and ensure its validity. This is no longer sufficient and/or doable when the swap entries are decoupled from their backing stores - a swap entry might not have any backing swap device at all.

In preparation for this decoupling work, abstract away the swapoff locking out behavior into a generic API (whose implementation will eventually differ between the old and the new swap implementation).

---
 include/linux/swap.h | 12 ++++++++++++
 mm/memory.c          | 13 +++++++------
 mm/shmem.c           |  7 +++----
 mm/swap_state.c      | 10 ++++------
 4 files changed, 26 insertions(+), 16 deletions(-)
include/linux/swap.h +12 -0
index b13b72645db3..e479fd31c6d6 100644
@@ -706,5 +706,17 @@ static inline bool mem_cgroup_swap_full(struct folio *folio)
 }
 #endif
 
+static inline bool trylock_swapoff(swp_entry_t entry,
+				struct swap_info_struct **si)
+{
+	return get_swap_device(entry);
+}
+
+static inline void unlock_swapoff(swp_entry_t entry,
+				struct swap_info_struct *si)
+{
+	put_swap_device(si);
+}
+
 #endif /* __KERNEL__*/
 #endif /* _LINUX_SWAP_H */
mm/memory.c +7 -6
index fb7b8dc75167..e92914df5ca7 100644
@@ -4305,6 +4305,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 	struct swap_info_struct *si = NULL;
 	rmap_t rmap_flags = RMAP_NONE;
 	bool need_clear_cache = false;
+	bool swapoff_locked = false;
 	bool exclusive = false;
 	swp_entry_t entry;
 	pte_t pte;
@@ -4365,8 +4366,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 	}
 
 	/* Prevent swapoff from happening to us. */
-	si = get_swap_device(entry);
-	if (unlikely(!si))
+	swapoff_locked = trylock_swapoff(entry, &si);
+	if (unlikely(!swapoff_locked))
 		goto out;
 
 	folio = swap_cache_get_folio(entry, vma, vmf->address);
@@ -4713,8 +4714,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 		if (waitqueue_active(&swapcache_wq))
 			wake_up(&swapcache_wq);
 	}
-	if (si)
-		put_swap_device(si);
+	if (swapoff_locked)
+		unlock_swapoff(entry, si);
 	return ret;
 out_nomap:
 	if (vmf->pte)
@@ -4732,8 +4733,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 		if (waitqueue_active(&swapcache_wq))
 			wake_up(&swapcache_wq);
 	}
-	if (si)
-		put_swap_device(si);
+	if (swapoff_locked)
+		unlock_swapoff(entry, si);
 	return ret;
 }
 
mm/shmem.c +3 -4
index 1ede0800e846..8ef72dcc592e 100644
@@ -2262,8 +2262,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
 	if (is_poisoned_swp_entry(swap))
 		return -EIO;
 
-	si = get_swap_device(swap);
-	if (!si) {
+	if (!trylock_swapoff(swap, &si)) {
 		if (!shmem_confirm_swap(mapping, index, swap))
 			return -EEXIST;
 		else
@@ -2411,7 +2410,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
 	}
 	folio_mark_dirty(folio);
 	swap_free_nr(swap, nr_pages);
-	put_swap_device(si);
+	unlock_swapoff(swap, si);
 
 	*foliop = folio;
 	return 0;
@@ -2428,7 +2427,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
 		folio_unlock(folio);
 		folio_put(folio);
 	}
-	put_swap_device(si);
+	unlock_swapoff(swap, si);
 
 	return error;
 }
mm/swap_state.c +4 -6
index ca42b2be64d9..81f69b2df550 100644
@@ -419,12 +419,11 @@ struct folio *filemap_get_incore_folio(struct address_space *mapping,
 	if (non_swap_entry(swp))
 		return ERR_PTR(-ENOENT);
 	/* Prevent swapoff from happening to us */
-	si = get_swap_device(swp);
-	if (!si)
+	if (!trylock_swapoff(swp, &si))
 		return ERR_PTR(-ENOENT);
 	index = swap_cache_index(swp);
 	folio = filemap_get_folio(swap_address_space(swp), index);
-	put_swap_device(si);
+	unlock_swapoff(swp, si);
 	return folio;
 }
 
@@ -439,8 +438,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
 	void *shadow = NULL;
 
 	*new_page_allocated = false;
-	si = get_swap_device(entry);
-	if (!si)
+	if (!trylock_swapoff(entry, &si))
 		return NULL;
 
 	for (;;) {
@@ -538,7 +536,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
 	put_swap_folio(new_folio, entry);
 	folio_unlock(new_folio);
 put_and_return:
-	put_swap_device(si);
+	unlock_swapoff(entry, si);
 	if (!(*new_page_allocated) && new_folio)
 		folio_put(new_folio);
 	return result;
Signature · 1 line
2.47.1
author maintainer
#3 lore raw

RFC PATCH 3/14 mm: swap: add a separate type for physical swap slots

In reply to Nhat Pham

In preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates:

1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type.

from:

2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type.

The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g). We also take this opportunity to re-arrange the header files (include/linux/swap.h and swapops.h), grouping the swap API into the following categories:

1. Virtual swap API (i.e functions on swp_entry_t type).

2. Swap cache API (mm/swap_state.c)

3. Swap slot cache API (mm/swap_slots.c)

4. Physical swap slots and device API (mm/swapfile.c).

Note that we have not made any behavioral change - the mapping between the two types is the identity mapping. In later patches, we shall dynamically allocate a virtual swap slot (of type swp_entry_t) for each swapped out page to store in the page table entry, and associate it with a backing store. A physical swap slot (i.e a slot on a physical swap device) is one of the backing options.

---
 include/linux/mm_types.h   |   7 ++
 include/linux/swap.h       | 124 +++++++++++++------
 include/linux/swap_slots.h |   2 +-
 include/linux/swapops.h    |  25 ++++
 kernel/power/swap.c        |   6 +-
 mm/internal.h              |  10 +-
 mm/memory.c                |   7 +-
 mm/page_io.c               |  33 +++--
 mm/shmem.c                 |  21 +++-
 mm/swap.h                  |  17 +--
 mm/swap_cgroup.c           |  10 +-
 mm/swap_slots.c            |  28 ++---
 mm/swap_state.c            |  26 +++-
 mm/swapfile.c              | 243 ++++++++++++++++++++-----------------
 14 files changed, 351 insertions(+), 208 deletions(-)
include/linux/mm_types.h +7 -0
index 0234f14f2aa6..7d93bb2c3dae 100644
@@ -283,6 +283,13 @@ typedef struct {
 	unsigned long val;
 } swp_entry_t;
 
+/*
+ * Physical (i.e disk-based) swap slot handle.
+ */
+typedef struct {
+	unsigned long val;
+} swp_slot_t;
+
 /**
  * struct folio - Represents a contiguous set of bytes.
  * @flags: Identical to the page flags.
include/linux/swap.h +85 -39

202 lines not on this page · raw message

include/linux/swap_slots.h +1 -1
index 840aec3523b2..1ac926d46389 100644
@@ -13,7 +13,7 @@
 struct swap_slots_cache {
 	bool		lock_initialized;
 	struct mutex	alloc_lock; /* protects slots, nr, cur */
-	swp_entry_t	*slots;
+	swp_slot_t	*slots;
 	int		nr;
 	int		cur;
 	int		n_ret;
include/linux/swapops.h +25 -0
index 96f26e29fefe..2a4101c9bba4 100644
@@ -618,5 +618,30 @@ static inline int non_swap_entry(swp_entry_t entry)
 	return swp_type(entry) >= MAX_SWAPFILES;
 }
 
+/* Physical swap slots operations */
+
+/*
+ * Store a swap device type + offset into a swp_slot_t handle.
+ */
+static inline swp_slot_t swp_slot(unsigned long type, pgoff_t offset)
+{
+	swp_slot_t ret;
+
+	ret.val = (type << SWP_TYPE_SHIFT) | (offset & SWP_OFFSET_MASK);
+	return ret;
+}
+
+/* Extract the `type' field from a swp_slot_t. */
+static inline unsigned swp_slot_type(swp_slot_t slot)
+{
+	return (slot.val >> SWP_TYPE_SHIFT);
+}
+
+/* Extract the `offset' field from a swp_slot_t. */
+static inline pgoff_t swp_slot_offset(swp_slot_t slot)
+{
+	return slot.val & SWP_OFFSET_MASK;
+}
+
 #endif /* CONFIG_MMU */
 #endif /* _LINUX_SWAPOPS_H */
kernel/power/swap.c +3 -3
index 82b884b67152..32b236a81dbb 100644
@@ -178,10 +178,10 @@ sector_t alloc_swapdev_block(int swap)
 {
 	unsigned long offset;
 
-	offset = swp_offset(get_swap_page_of_type(swap));
+	offset = swp_slot_offset(swap_slot_alloc_of_type(swap));
 	if (offset) {
 		if (swsusp_extents_insert(offset))
-			swap_free(swp_entry(swap, offset));
+			swap_slot_free_nr(swp_slot(swap, offset), 1);
 		else
 			return swapdev_block(swap, offset);
 	}
@@ -203,7 +203,7 @@ void free_all_swap_pages(int swap)
 
 		ext = rb_entry(node, struct swsusp_extent, node);
 		rb_erase(node, &swsusp_extents);
-		swap_free_nr(swp_entry(swap, ext->start),
+		swap_slot_free_nr(swp_slot(swap, ext->start),
 			     ext->end - ext->start + 1);
 
 		kfree(ext);
mm/internal.h +7 -3
index 20b3535935a3..2d63f6537e35 100644
@@ -275,9 +275,13 @@ static inline int folio_pte_batch(struct folio *folio, unsigned long addr,
  */
 static inline pte_t pte_move_swp_offset(pte_t pte, long delta)
 {
-	swp_entry_t entry = pte_to_swp_entry(pte);
-	pte_t new = __swp_entry_to_pte(__swp_entry(swp_type(entry),
-						   (swp_offset(entry) + delta)));
+	swp_entry_t entry = pte_to_swp_entry(pte), new_entry;
+	swp_slot_t slot = swp_entry_to_swp_slot(entry);
+	pte_t new;
+
+	new_entry = swp_slot_to_swp_entry(swp_slot(swp_slot_type(slot),
+			swp_slot_offset(slot) + delta));
+	new = swp_entry_to_pte(new_entry);
 
 	if (pte_swp_soft_dirty(pte))
 		new = pte_swp_mksoft_dirty(new);
mm/memory.c +5 -2
index e92914df5ca7..c44e845b5320 100644
@@ -4125,8 +4125,9 @@ static struct folio *__alloc_swap_folio(struct vm_fault *vmf)
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
 static inline int non_swapcache_batch(swp_entry_t entry, int max_nr)
 {
-	struct swap_info_struct *si = swp_swap_info(entry);
-	pgoff_t offset = swp_offset(entry);
+	swp_slot_t slot = swp_entry_to_swp_slot(entry);
+	struct swap_info_struct *si = swap_slot_swap_info(slot);
+	pgoff_t offset = swp_slot_offset(slot);
 	int i;
 
 	/*
@@ -4308,6 +4309,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 	bool swapoff_locked = false;
 	bool exclusive = false;
 	swp_entry_t entry;
+	swp_slot_t slot;
 	pte_t pte;
 	vm_fault_t ret = 0;
 	void *shadow = NULL;
@@ -4369,6 +4371,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 	swapoff_locked = trylock_swapoff(entry, &si);
 	if (unlikely(!swapoff_locked))
 		goto out;
+	slot = swp_entry_to_swp_slot(entry);
 
 	folio = swap_cache_get_folio(entry, vma, vmf->address);
 	if (folio)
mm/page_io.c +22 -11
index 9b983de351f9..182851c47f43 100644
@@ -204,14 +204,17 @@ static bool is_folio_zero_filled(struct folio *folio)
 static void swap_zeromap_folio_set(struct folio *folio)
 {
 	struct obj_cgroup *objcg = get_obj_cgroup_from_folio(folio);
-	struct swap_info_struct *sis = swp_swap_info(folio->swap);
+	struct swap_info_struct *sis =
+		swap_slot_swap_info(swp_entry_to_swp_slot(folio->swap));
 	int nr_pages = folio_nr_pages(folio);
 	swp_entry_t entry;
+	swp_slot_t slot;
 	unsigned int i;
 
 	for (i = 0; i < folio_nr_pages(folio); i++) {
 		entry = page_swap_entry(folio_page(folio, i));
-		set_bit(swp_offset(entry), sis->zeromap);
+		slot = swp_entry_to_swp_slot(entry);
+		set_bit(swp_slot_offset(slot), sis->zeromap);
 	}
 
 	count_vm_events(SWPOUT_ZERO, nr_pages);
@@ -223,13 +226,16 @@ static void swap_zeromap_folio_set(struct folio *folio)
 
 static void swap_zeromap_folio_clear(struct folio *folio)
 {
-	struct swap_info_struct *sis = swp_swap_info(folio->swap);
+	struct swap_info_struct *sis =
+		swap_slot_swap_info(swp_entry_to_swp_slot(folio->swap));
 	swp_entry_t entry;
+	swp_slot_t slot;
 	unsigned int i;
 
 	for (i = 0; i < folio_nr_pages(folio); i++) {
 		entry = page_swap_entry(folio_page(folio, i));
-		clear_bit(swp_offset(entry), sis->zeromap);
+		slot = swp_entry_to_swp_slot(entry);
+		clear_bit(swp_slot_offset(slot), sis->zeromap);
 	}
 }
 
@@ -358,7 +364,8 @@ static void sio_write_complete(struct kiocb *iocb, long ret)
 		 * messages.
 		 */
 		pr_err_ratelimited("Write error %ld on dio swapfile (%llu)\n",
-				   ret, swap_dev_pos(page_swap_entry(page)));
+				   ret,
+				   swap_slot_pos(swp_entry_to_swp_slot(page_swap_entry(page))));
 		for (p = 0; p < sio->pages; p++) {
 			page = sio->bvec[p].bv_page;
 			set_page_dirty(page);
@@ -374,10 +381,11 @@ static void sio_write_complete(struct kiocb *iocb, long ret)
 
 static void swap_writepage_fs(struct folio *folio, struct writeback_control *wbc)
 {
+	swp_slot_t slot = swp_entry_to_swp_slot(folio->swap);
 	struct swap_iocb *sio = NULL;
-	struct swap_info_struct *sis = swp_swap_info(folio->swap);
+	struct swap_info_struct *sis = swap_slot_swap_info(slot);
 	struct file *swap_file = sis->swap_file;
-	loff_t pos = swap_dev_pos(folio->swap);
+	loff_t pos = swap_slot_pos(slot);
 
 	count_swpout_vm_event(folio);
 	folio_start_writeback(folio);
@@ -452,7 +460,8 @@ static void swap_writepage_bdev_async(struct folio *folio,
 
 void __swap_writepage(struct folio *folio, struct writeback_control *wbc)
 {
-	struct swap_info_struct *sis = swp_swap_info(folio->swap);
+	struct swap_info_struct *sis =
+		swap_slot_swap_info(swp_entry_to_swp_slot(folio->swap));
 
 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
 	/*
@@ -543,9 +552,10 @@ static bool swap_read_folio_zeromap(struct folio *folio)
 
 static void swap_read_folio_fs(struct folio *folio, struct swap_iocb **plug)
 {
-	struct swap_info_struct *sis = swp_swap_info(folio->swap);
+	swp_slot_t slot = swp_entry_to_swp_slot(folio->swap);
+	struct swap_info_struct *sis = swap_slot_swap_info(slot);
 	struct swap_iocb *sio = NULL;
-	loff_t pos = swap_dev_pos(folio->swap);
+	loff_t pos = swap_slot_pos(slot);
 
 	if (plug)
 		sio = *plug;
@@ -614,7 +624,8 @@ static void swap_read_folio_bdev_async(struct folio *folio,
 
 void swap_read_folio(struct folio *folio, struct swap_iocb **plug)
 {
-	struct swap_info_struct *sis = swp_swap_info(folio->swap);
+	struct swap_info_struct *sis =
+		swap_slot_swap_info(swp_entry_to_swp_slot(folio->swap));
 	bool synchronous = sis->flags & SWP_SYNCHRONOUS_IO;
 	bool workingset = folio_test_workingset(folio);
 	unsigned long pflags;
mm/shmem.c +15 -6
index 8ef72dcc592e..f8efa49eb499 100644
@@ -1387,6 +1387,7 @@ static int shmem_find_swap_entries(struct address_space *mapping,
 	XA_STATE(xas, &mapping->i_pages, start);
 	struct folio *folio;
 	swp_entry_t entry;
+	swp_slot_t slot;
 
 	rcu_read_lock();
 	xas_for_each(&xas, folio, ULONG_MAX) {
@@ -1397,11 +1398,13 @@ static int shmem_find_swap_entries(struct address_space *mapping,
 			continue;
 
 		entry = radix_to_swp_entry(folio);
+		slot = swp_entry_to_swp_slot(entry);
+
 		/*
 		 * swapin error entries can be found in the mapping. But they're
 		 * deliberately ignored here as we've done everything we can do.
 		 */
-		if (swp_type(entry) != type)
+		if (swp_slot_type(slot) != type)
 			continue;
 
 		indices[folio_batch_count(fbatch)] = xas.xa_index;
@@ -1619,7 +1622,6 @@ static int shmem_writepage(struct page *page, struct writeback_control *wbc)
 	if (!swap.val) {
 		if (nr_pages > 1)
 			goto try_split;
-
 		goto redirty;
 	}
 
@@ -2164,6 +2166,7 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,
 	XA_STATE_ORDER(xas, &mapping->i_pages, index, 0);
 	void *alloced_shadow = NULL;
 	int alloced_order = 0, i;
+	swp_slot_t slot = swp_entry_to_swp_slot(swap);
 
 	/* Convert user data gfp flags to xarray node gfp flags */
 	gfp &= GFP_RECLAIM_MASK;
@@ -2202,11 +2205,14 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,
 			 */
 			for (i = 0; i < 1 << order; i++) {
 				pgoff_t aligned_index = round_down(index, 1 << order);
-				swp_entry_t tmp;
+				swp_entry_t tmp_entry;
+				swp_slot_t tmp_slot;
 
-				tmp = swp_entry(swp_type(swap), swp_offset(swap) + i);
+				tmp_slot =
+					swp_slot(swp_slot_type(slot), swp_slot_offset(slot) + i);
+				tmp_entry = swp_slot_to_swp_entry(tmp_slot);
 				__xa_store(&mapping->i_pages, aligned_index + i,
-					   swp_to_radix_entry(tmp), 0);
+					   swp_to_radix_entry(tmp_entry), 0);
 			}
 		}
 
@@ -2253,10 +2259,12 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
 	struct folio *folio = NULL;
 	bool skip_swapcache = false;
 	swp_entry_t swap;
+	swp_slot_t slot;
 	int error, nr_pages, order, split_order;
 
 	VM_BUG_ON(!*foliop || !xa_is_value(*foliop));
 	swap = radix_to_swp_entry(*foliop);
+	slot = swp_entry_to_swp_slot(swap);
 	*foliop = NULL;
 
 	if (is_poisoned_swp_entry(swap))
@@ -2328,7 +2336,8 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
 		if (split_order > 0) {
 			pgoff_t offset = index - round_down(index, 1 << split_order);
 
-			swap = swp_entry(swp_type(swap), swp_offset(swap) + offset);
+			swap = swp_slot_to_swp_entry(swp_slot(
+					swp_slot_type(slot), swp_slot_offset(slot) + offset));
 		}
 
 		/* Here we actually start the io */
mm/swap.h +9 -8
index ad2f121de970..d5f8effa8015 100644
@@ -32,12 +32,10 @@ extern struct address_space *swapper_spaces[];
 	(&swapper_spaces[swp_type(entry)][swp_offset(entry) \
 		>> SWAP_ADDRESS_SPACE_SHIFT])
 
-/*
- * Return the swap device position of the swap entry.
- */
-static inline loff_t swap_dev_pos(swp_entry_t entry)
+/* Return the swap device position of the swap slot. */
+static inline loff_t swap_slot_pos(swp_slot_t slot)
 {
-	return ((loff_t)swp_offset(entry)) << PAGE_SHIFT;
+	return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT;
 }
 
 /*
@@ -78,7 +76,9 @@ struct folio *swapin_readahead(swp_entry_t entry, gfp_t flag,
 
 static inline unsigned int folio_swap_flags(struct folio *folio)
 {
-	return swp_swap_info(folio->swap)->flags;
+	swp_slot_t swp_slot = swp_entry_to_swp_slot(folio->swap);
+
+	return swap_slot_swap_info(swp_slot)->flags;
 }
 
 /*
@@ -89,8 +89,9 @@ static inline unsigned int folio_swap_flags(struct folio *folio)
 static inline int swap_zeromap_batch(swp_entry_t entry, int max_nr,
 		bool *is_zeromap)
 {
-	struct swap_info_struct *sis = swp_swap_info(entry);
-	unsigned long start = swp_offset(entry);
+	swp_slot_t slot = swp_entry_to_swp_slot(entry);
+	struct swap_info_struct *sis = swap_slot_swap_info(slot);
+	unsigned long start = swp_slot_offset(slot);
 	unsigned long end = start + max_nr;
 	bool first_bit;
 
mm/swap_cgroup.c +6 -4
index 1007c30f12e2..5e4c91d694a0 100644
@@ -65,11 +65,12 @@ void swap_cgroup_record(struct folio *folio, unsigned short id,
 			swp_entry_t ent)
 {
 	unsigned int nr_ents = folio_nr_pages(folio);
+	swp_slot_t slot = swp_entry_to_swp_slot(ent);
 	struct swap_cgroup *map;
 	pgoff_t offset, end;
 	unsigned short old;
 
-	offset = swp_offset(ent);
+	offset = swp_slot_offset(slot);
 	end = offset + nr_ents;
 	map = swap_cgroup_ctrl[swp_type(ent)].map;
 
@@ -92,12 +93,12 @@ void swap_cgroup_record(struct folio *folio, unsigned short id,
  */
 unsigned short swap_cgroup_clear(swp_entry_t ent, unsigned int nr_ents)
 {
-	pgoff_t offset = swp_offset(ent);
+	swp_slot_t slot = swp_entry_to_swp_slot(ent);
+	pgoff_t offset = swp_slot_offset(slot);
 	pgoff_t end = offset + nr_ents;
 	struct swap_cgroup *map;
 	unsigned short old, iter = 0;
 
-	offset = swp_offset(ent);
 	end = offset + nr_ents;
 	map = swap_cgroup_ctrl[swp_type(ent)].map;
 
@@ -120,12 +121,13 @@ unsigned short swap_cgroup_clear(swp_entry_t ent, unsigned int nr_ents)
 unsigned short lookup_swap_cgroup_id(swp_entry_t ent)
 {
 	struct swap_cgroup_ctrl *ctrl;
+	swp_slot_t slot = swp_entry_to_swp_slot(ent);
 
 	if (mem_cgroup_disabled())
 		return 0;
 
 	ctrl = &swap_cgroup_ctrl[swp_type(ent)];
-	return __swap_cgroup_id_lookup(ctrl->map, swp_offset(ent));
+	return __swap_cgroup_id_lookup(ctrl->map, swp_slot_offset(slot));
 }
 
 int swap_cgroup_swapon(int type, unsigned long max_pages)
mm/swap_slots.c +12 -16
index 9c7c171df7ba..4ec2de0c2756 100644
@@ -111,14 +111,14 @@ static bool check_cache_active(void)
 static int alloc_swap_slot_cache(unsigned int cpu)
 {
 	struct swap_slots_cache *cache;
-	swp_entry_t *slots;
+	swp_slot_t *slots;
 
 	/*
 	 * Do allocation outside swap_slots_cache_mutex
 	 * as kvzalloc could trigger reclaim and folio_alloc_swap,
 	 * which can lock swap_slots_cache_mutex.
 	 */
-	slots = kvcalloc(SWAP_SLOTS_CACHE_SIZE, sizeof(swp_entry_t),
+	slots = kvcalloc(SWAP_SLOTS_CACHE_SIZE, sizeof(swp_slot_t),
 			 GFP_KERNEL);
 	if (!slots)
 		return -ENOMEM;
@@ -160,7 +160,7 @@ static void drain_slots_cache_cpu(unsigned int cpu, bool free_slots)
 	cache = &per_cpu(swp_slots, cpu);
 	if (cache->slots) {
 		mutex_lock(&cache->alloc_lock);
-		swapcache_free_entries(cache->slots + cache->cur, cache->nr);
+		swap_slot_cache_free_slots(cache->slots + cache->cur, cache->nr);
 		cache->cur = 0;
 		cache->nr = 0;
 		if (free_slots && cache->slots) {
@@ -238,22 +238,22 @@ static int refill_swap_slots_cache(struct swap_slots_cache *cache)
 
 	cache->cur = 0;
 	if (swap_slot_cache_active)
-		cache->nr = get_swap_pages(SWAP_SLOTS_CACHE_SIZE,
+		cache->nr = swap_slot_alloc(SWAP_SLOTS_CACHE_SIZE,
 					   cache->slots, 0);
 
 	return cache->nr;
 }
 
-swp_entry_t folio_alloc_swap(struct folio *folio)
+swp_slot_t folio_alloc_swap_slot(struct folio *folio)
 {
-	swp_entry_t entry;
+	swp_slot_t slot;
 	struct swap_slots_cache *cache;
 
-	entry.val = 0;
+	slot.val = 0;
 
 	if (folio_test_large(folio)) {
 		if (IS_ENABLED(CONFIG_THP_SWAP))
-			get_swap_pages(1, &entry, folio_order(folio));
+			swap_slot_alloc(1, &slot, folio_order(folio));
 		goto out;
 	}
 
@@ -273,7 +273,7 @@ swp_entry_t folio_alloc_swap(struct folio *folio)
 		if (cache->slots) {
 repeat:
 			if (cache->nr) {
-				entry = cache->slots[cache->cur];
+				slot = cache->slots[cache->cur];
 				cache->slots[cache->cur++].val = 0;
 				cache->nr--;
 			} else if (refill_swap_slots_cache(cache)) {
@@ -281,15 +281,11 @@ swp_entry_t folio_alloc_swap(struct folio *folio)
 			}
 		}
 		mutex_unlock(&cache->alloc_lock);
-		if (entry.val)
+		if (slot.val)
 			goto out;
 	}
 
-	get_swap_pages(1, &entry, 0);
+	swap_slot_alloc(1, &slot, 0);
 out:
-	if (mem_cgroup_try_charge_swap(folio, entry)) {
-		put_swap_folio(folio, entry);
-		entry.val = 0;
-	}
-	return entry;
+	return slot;
 }
mm/swap_state.c +20 -6
index 81f69b2df550..055e555d3382 100644
@@ -167,6 +167,19 @@ void __delete_from_swap_cache(struct folio *folio,
 	__lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr);
 }
 
+swp_entry_t folio_alloc_swap(struct folio *folio)
+{
+	swp_slot_t slot = folio_alloc_swap_slot(folio);
+	swp_entry_t entry = swp_slot_to_swp_entry(slot);
+
+	if (entry.val && mem_cgroup_try_charge_swap(folio, entry)) {
+		put_swap_folio(folio, entry);
+		entry.val = 0;
+	}
+
+	return entry;
+}
+
 /**
  * add_to_swap - allocate swap space for a folio
  * @folio: folio we want to move to swap
@@ -548,7 +561,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
  * A failure return means that either the page allocation failed or that
  * the swap entry is no longer in use.
  *
- * get/put_swap_device() aren't needed to call this function, because
+ * swap_slot_(get|put)_swap_info() aren't needed to call this function, because
  * __read_swap_cache_async() call them and swap_read_folio() holds the
  * swap cache folio lock.
  */
@@ -654,11 +667,12 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 				    struct mempolicy *mpol, pgoff_t ilx)
 {
 	struct folio *folio;
-	unsigned long entry_offset = swp_offset(entry);
-	unsigned long offset = entry_offset;
+	swp_slot_t slot = swp_entry_to_swp_slot(entry);
+	unsigned long slot_offset = swp_slot_offset(slot);
+	unsigned long offset = slot_offset;
 	unsigned long start_offset, end_offset;
 	unsigned long mask;
-	struct swap_info_struct *si = swp_swap_info(entry);
+	struct swap_info_struct *si = swap_slot_swap_info(slot);
 	struct blk_plug plug;
 	struct swap_iocb *splug = NULL;
 	bool page_allocated;
@@ -679,13 +693,13 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 	for (offset = start_offset; offset <= end_offset ; offset++) {
 		/* Ok, do the async read-ahead now */
 		folio = __read_swap_cache_async(
-				swp_entry(swp_type(entry), offset),
+				swp_slot_to_swp_entry(swp_slot(swp_slot_type(slot), offset)),
 				gfp_mask, mpol, ilx, &page_allocated, false);
 		if (!folio)
 			continue;
 		if (page_allocated) {
 			swap_read_folio(folio, &splug);
-			if (offset != entry_offset) {
+			if (offset != slot_offset) {
 				folio_set_readahead(folio);
 				count_vm_event(SWAP_RA);
 			}
mm/swapfile.c +134 -109

681 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#10 lore raw

RFC PATCH 4/14 mm: swap: swap cache support for virtualized swap

In reply to Nhat Pham

Currently, the swap cache code assumes that the swap space is of a fixed size. The virtual swap space is dynamically sized, so the existing partitioning code cannot be easily reused. A dynamic partitioning is planned, but for now keep the design simple and just use a flat swapcache for vswap.

Since the vswap's implementation has begun to diverge from the old implementation, we also introduce a new build config (CONFIG_VIRTUAL_SWAP). Users who do not select this config will get the old implementation, with no behavioral change.

---
 mm/Kconfig      | 13 ++++++++++
 mm/swap.h       | 22 ++++++++++------
 mm/swap_state.c | 68 +++++++++++++++++++++++++++++++++++++++++--------
 3 files changed, 85 insertions(+), 18 deletions(-)
mm/Kconfig +13 -0
index 1b501db06417..1a6acdb64333 100644
@@ -22,6 +22,19 @@ menuconfig SWAP
 	  used to provide more virtual memory than the actual RAM present
 	  in your computer.  If unsure say Y.
 
+config VIRTUAL_SWAP
+	bool "Swap space virtualization"
+	depends on SWAP
+	default n
+	help
+		When this is selected, the kernel is built with the new swap
+		design. This will allow us to decouple the swap backends
+		(zswap, on-disk swapfile, etc.), and save disk space when we
+		use zswap (or the zero-filled swap page optimization).
+
+		There might be more lock contentions with heavy swap use, since
+		the swap cache is no longer range partitioned.
+
 config ZSWAP
 	bool "Compressed cache for swap pages"
 	depends on SWAP
mm/swap.h +14 -8
index d5f8effa8015..06e20b1d79c4 100644
@@ -22,22 +22,27 @@ void swap_write_unplug(struct swap_iocb *sio);
 int swap_writepage(struct page *page, struct writeback_control *wbc);
 void __swap_writepage(struct folio *folio, struct writeback_control *wbc);
 
-/* linux/mm/swap_state.c */
-/* One swap address space for each 64M swap space */
+/* Return the swap device position of the swap slot. */
+static inline loff_t swap_slot_pos(swp_slot_t slot)
+{
+	return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT;
+}
+
 #define SWAP_ADDRESS_SPACE_SHIFT	14
 #define SWAP_ADDRESS_SPACE_PAGES	(1 << SWAP_ADDRESS_SPACE_SHIFT)
 #define SWAP_ADDRESS_SPACE_MASK		(SWAP_ADDRESS_SPACE_PAGES - 1)
+
+/* linux/mm/swap_state.c */
+#ifdef CONFIG_VIRTUAL_SWAP
+extern struct address_space *swap_address_space(swp_entry_t entry);
+#define swap_cache_index(entry) entry.val
+#else
+/* One swap address space for each 64M swap space */
 extern struct address_space *swapper_spaces[];
 #define swap_address_space(entry)			    \
 	(&swapper_spaces[swp_type(entry)][swp_offset(entry) \
 		>> SWAP_ADDRESS_SPACE_SHIFT])
 
-/* Return the swap device position of the swap slot. */
-static inline loff_t swap_slot_pos(swp_slot_t slot)
-{
-	return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT;
-}
-
 /*
  * Return the swap cache index of the swap entry.
  */
@@ -46,6 +51,7 @@ static inline pgoff_t swap_cache_index(swp_entry_t entry)
 	BUILD_BUG_ON((SWP_OFFSET_MASK | SWAP_ADDRESS_SPACE_MASK) != SWP_OFFSET_MASK);
 	return swp_offset(entry) & SWAP_ADDRESS_SPACE_MASK;
 }
+#endif
 
 void show_swap_cache_info(void);
 bool add_to_swap(struct folio *folio);
mm/swap_state.c +58 -10

115 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#14 lore raw

RFC PATCH 5/14 zswap: unify zswap tree for virtualized swap

In reply to Nhat Pham

Similar to swap cache, the zswap tree code, specifically the range partition logic, can no longer easily be reused for the new virtual swap space design. Use a simple unified zswap tree in the new implementation for now. As in the case of swap cache, range partitioning is planned as a follow up work.

---
 mm/zswap.c | 38 ++++++++++++++++++++++++++++++++------
 1 file changed, 32 insertions(+), 6 deletions(-)
mm/zswap.c +32 -6
index 23365e76a3ce..c1327569ce80 100644
@@ -203,8 +203,6 @@ struct zswap_entry {
 	struct list_head lru;
 };
 
-static struct xarray *zswap_trees[MAX_SWAPFILES];
-static unsigned int nr_zswap_trees[MAX_SWAPFILES];
 
 /* RCU-protected iteration */
 static LIST_HEAD(zswap_pools);
@@ -231,12 +229,28 @@ static bool zswap_has_pool;
 * helpers and fwd declarations
 **********************************/
 
+#ifdef CONFIG_VIRTUAL_SWAP
+static DEFINE_XARRAY(zswap_tree);
+
+static inline struct xarray *swap_zswap_tree(swp_entry_t swp)
+{
+	return &zswap_tree;
+}
+
+#define zswap_tree_index(entry)	entry.val
+#else
+static struct xarray *zswap_trees[MAX_SWAPFILES];
+static unsigned int nr_zswap_trees[MAX_SWAPFILES];
+
 static inline struct xarray *swap_zswap_tree(swp_entry_t swp)
 {
 	return &zswap_trees[swp_type(swp)][swp_offset(swp)
 		>> SWAP_ADDRESS_SPACE_SHIFT];
 }
 
+#define zswap_tree_index(entry)	swp_offset(entry)
+#endif
+
 #define zswap_pool_debug(msg, p)				\
 	pr_debug("%s pool %s/%s\n", msg, (p)->tfm_name,		\
 		 zpool_get_type((p)->zpool))
@@ -1047,7 +1061,7 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 				 swp_entry_t swpentry)
 {
 	struct xarray *tree;
-	pgoff_t offset = swp_offset(swpentry);
+	pgoff_t offset = zswap_tree_index(swpentry);
 	struct folio *folio;
 	struct mempolicy *mpol;
 	bool folio_was_allocated;
@@ -1463,7 +1477,7 @@ static bool zswap_store_page(struct page *page,
 		goto compress_failed;
 
 	old = xa_store(swap_zswap_tree(page_swpentry),
-		       swp_offset(page_swpentry),
+		       zswap_tree_index(page_swpentry),
 		       entry, GFP_KERNEL);
 	if (xa_is_err(old)) {
 		int err = xa_err(old);
@@ -1612,7 +1626,7 @@ bool zswap_store(struct folio *folio)
 bool zswap_load(struct folio *folio)
 {
 	swp_entry_t swp = folio->swap;
-	pgoff_t offset = swp_offset(swp);
+	pgoff_t offset = zswap_tree_index(swp);
 	bool swapcache = folio_test_swapcache(folio);
 	struct xarray *tree = swap_zswap_tree(swp);
 	struct zswap_entry *entry;
@@ -1670,7 +1684,7 @@ bool zswap_load(struct folio *folio)
 
 void zswap_invalidate(swp_entry_t swp)
 {
-	pgoff_t offset = swp_offset(swp);
+	pgoff_t offset = zswap_tree_index(swp);
 	struct xarray *tree = swap_zswap_tree(swp);
 	struct zswap_entry *entry;
 
@@ -1682,6 +1696,16 @@ void zswap_invalidate(swp_entry_t swp)
 		zswap_entry_free(entry);
 }
 
+#ifdef CONFIG_VIRTUAL_SWAP
+int zswap_swapon(int type, unsigned long nr_pages)
+{
+	return 0;
+}
+
+void zswap_swapoff(int type)
+{
+}
+#else
 int zswap_swapon(int type, unsigned long nr_pages)
 {
 	struct xarray *trees, *tree;
@@ -1718,6 +1742,8 @@ void zswap_swapoff(int type)
 	nr_zswap_trees[type] = 0;
 	zswap_trees[type] = NULL;
 }
+#endif /* CONFIG_VIRTUAL_SWAP */
+
 
 /*********************************
 * debugfs functions
Signature · 1 line
2.47.1
author maintainer
#15 lore raw

RFC PATCH 6/14 mm: swap: allocate a virtual swap slot for each swapped out page

In reply to Nhat Pham

For the new virtual swap space design, dynamically allocate a virtual slot (as well as an associated metadata structure) for each swapped out page, and associate it to the (physical) swap slot on the swapfile/swap partition.

For now, there is always a physical slot in the swapfile associated for each virtual swap slot (except those about to be freed). The virtual swap slot's lifetime is still tied to the lifetime of its physical swap slot.

We also maintain a backward map to look up the virtual swap slot from its associated physical swap slot on swapfile. This is used in cluster readahead, as well as several swapfile operations, such as the swap slot reclamation that happens when the swapfile is almost full. It will also be used in a future patch that simplifies swapoff.

---
 MAINTAINERS             |   7 +
 include/linux/swap.h    |  28 ++-
 include/linux/swapops.h |  12 ++
 mm/Kconfig              |   4 +
 mm/Makefile             |   1 +
 mm/internal.h           |  43 ++++-
 mm/shmem.c              |  10 +-
 mm/swap.h               |   2 +
 mm/swap_state.c         |  39 +++--
 mm/swapfile.c           |  18 +-
 mm/vswap.c              | 375 ++++++++++++++++++++++++++++++++++++++++
 11 files changed, 508 insertions(+), 31 deletions(-)
 create mode 100644 mm/vswap.c
MAINTAINERS +7 -0
index 00e94bec401e..65108bf2a5f1 100644
@@ -25290,6 +25290,13 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/iio/light/vishay,veml6030.yaml
 F:	drivers/iio/light/veml6030.c
 
+VIRTUAL SWAP SPACE
+M:	Nhat Pham <[email protected]>
+M:	Johannes Weiner <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	mm/vswap.c
+
 VISHAY VEML6075 UVA AND UVB LIGHT SENSOR DRIVER
 M:	Javier Carrasco <[email protected]>
 S:	Maintained
include/linux/swap.h +27 -1
index 674089bc4cd1..d32a2c300924 100644
@@ -455,7 +455,6 @@ extern void __meminit kswapd_stop(int nid);
 /* Virtual swap API */
 swp_entry_t folio_alloc_swap(struct folio *folio);
 bool folio_free_swap(struct folio *folio);
-void put_swap_folio(struct folio *folio, swp_entry_t entry);
 int add_swap_count_continuation(swp_entry_t, gfp_t);
 void swap_shmem_alloc(swp_entry_t, int);
 int swap_duplicate(swp_entry_t);
@@ -504,6 +503,7 @@ static inline long get_nr_swap_pages(void)
 }
 
 void si_swapinfo(struct sysinfo *);
+void swap_slot_put_folio(swp_slot_t slot, struct folio *folio);
 swp_slot_t swap_slot_alloc_of_type(int);
 int swap_slot_alloc(int n, swp_slot_t swp_slots[], int order);
 void swap_slot_free_nr(swp_slot_t slot, int nr_pages);
@@ -725,6 +725,26 @@ static inline bool mem_cgroup_swap_full(struct folio *folio)
 }
 #endif
 
+#ifdef CONFIG_VIRTUAL_SWAP
+int vswap_init(void);
+void vswap_exit(void);
+void vswap_free(swp_entry_t entry);
+swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry);
+swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot);
+#else
+static inline int vswap_init(void)
+{
+	return 0;
+}
+
+static inline void vswap_exit(void)
+{
+}
+
+static inline void vswap_free(swp_entry_t entry)
+{
+}
+
 /**
  * swp_entry_to_swp_slot - look up the physical swap slot corresponding to a
  *                         virtual swap slot.
@@ -748,6 +768,12 @@ static inline swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot)
 {
 	return (swp_entry_t) { slot.val };
 }
+#endif
+
+static inline void put_swap_folio(struct folio *folio, swp_entry_t entry)
+{
+	swap_slot_put_folio(swp_entry_to_swp_slot(entry), folio);
+}
 
 static inline bool trylock_swapoff(swp_entry_t entry,
 				struct swap_info_struct **si)
include/linux/swapops.h +12 -0
index 2a4101c9bba4..ba7364e1400a 100644
@@ -27,6 +27,18 @@
 #define SWP_TYPE_SHIFT	(BITS_PER_XA_VALUE - MAX_SWAPFILES_SHIFT)
 #define SWP_OFFSET_MASK	((1UL << SWP_TYPE_SHIFT) - 1)
 
+#ifdef CONFIG_VIRTUAL_SWAP
+#if SWP_TYPE_SHIFT > 32
+#define MAX_VSWAP	U32_MAX
+#else
+/*
+ * The range of virtual swap slots is the same as the range of physical swap
+ * slots.
+ */
+#define MAX_VSWAP	(((MAX_SWAPFILES - 1) << SWP_TYPE_SHIFT) | SWP_OFFSET_MASK)
+#endif
+#endif
+
 /*
  * Definitions only for PFN swap entries (see is_pfn_swap_entry()).  To
  * store PFN, we only need SWP_PFN_BITS bits.  Each of the pfn swap entries
mm/Kconfig +4 -0
index 1a6acdb64333..d578b8e6ab6a 100644
@@ -32,6 +32,10 @@ config VIRTUAL_SWAP
 		(zswap, on-disk swapfile, etc.), and save disk space when we
 		use zswap (or the zero-filled swap page optimization).
 
+		In this new design, for each swap entry, a virtual swap slot is
+		allocated and stored in the page table entry, rather than the
+		handle to the physical swap slot on the swap device itself.
+
 		There might be more lock contentions with heavy swap use, since
 		the swap cache is no longer range partitioned.
 
mm/Makefile +1 -0
index 850386a67b3e..b7216c714fa1 100644
@@ -76,6 +76,7 @@ ifdef CONFIG_MMU
 endif
 
 obj-$(CONFIG_SWAP)	+= page_io.o swap_state.o swapfile.o swap_slots.o
+obj-$(CONFIG_VIRTUAL_SWAP)	+= vswap.o
 obj-$(CONFIG_ZSWAP)	+= zswap.o
 obj-$(CONFIG_HAS_DMA)	+= dmapool.o
 obj-$(CONFIG_HUGETLBFS)	+= hugetlb.o
mm/internal.h +36 -7

55 lines not on this page · raw message

mm/shmem.c +2 -8
index f8efa49eb499..4c00b4673468 100644
@@ -2166,7 +2166,6 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,
 	XA_STATE_ORDER(xas, &mapping->i_pages, index, 0);
 	void *alloced_shadow = NULL;
 	int alloced_order = 0, i;
-	swp_slot_t slot = swp_entry_to_swp_slot(swap);
 
 	/* Convert user data gfp flags to xarray node gfp flags */
 	gfp &= GFP_RECLAIM_MASK;
@@ -2205,12 +2204,8 @@ static int shmem_split_large_entry(struct inode *inode, pgoff_t index,
 			 */
 			for (i = 0; i < 1 << order; i++) {
 				pgoff_t aligned_index = round_down(index, 1 << order);
-				swp_entry_t tmp_entry;
-				swp_slot_t tmp_slot;
+				swp_entry_t tmp_entry = swap_nth(swap, i);
 
-				tmp_slot =
-					swp_slot(swp_slot_type(slot), swp_slot_offset(slot) + i);
-				tmp_entry = swp_slot_to_swp_entry(tmp_slot);
 				__xa_store(&mapping->i_pages, aligned_index + i,
 					   swp_to_radix_entry(tmp_entry), 0);
 			}
@@ -2336,8 +2331,7 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
 		if (split_order > 0) {
 			pgoff_t offset = index - round_down(index, 1 << split_order);
 
-			swap = swp_slot_to_swp_entry(swp_slot(
-					swp_slot_type(slot), swp_slot_offset(slot) + offset));
+			swap = swap_nth(swap, offset);
 		}
 
 		/* Here we actually start the io */
mm/swap.h +2 -0
index 06e20b1d79c4..31c94671cb44 100644
@@ -36,6 +36,8 @@ static inline loff_t swap_slot_pos(swp_slot_t slot)
 #ifdef CONFIG_VIRTUAL_SWAP
 extern struct address_space *swap_address_space(swp_entry_t entry);
 #define swap_cache_index(entry) entry.val
+
+void virt_clear_shadow_from_swap_cache(swp_entry_t entry);
 #else
 /* One swap address space for each 64M swap space */
 extern struct address_space *swapper_spaces[];
mm/swap_state.c +27 -12
index 268338a0ea57..eb4cd6ba2068 100644
@@ -176,6 +176,7 @@ void __delete_from_swap_cache(struct folio *folio,
 	__lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr);
 }
 
+#ifndef CONFIG_VIRTUAL_SWAP
 swp_entry_t folio_alloc_swap(struct folio *folio)
 {
 	swp_slot_t slot = folio_alloc_swap_slot(folio);
@@ -188,6 +189,7 @@ swp_entry_t folio_alloc_swap(struct folio *folio)
 
 	return entry;
 }
+#endif
 
 /**
  * add_to_swap - allocate swap space for a folio
@@ -270,26 +272,30 @@ void delete_from_swap_cache(struct folio *folio)
 }
 
 #ifdef CONFIG_VIRTUAL_SWAP
-void clear_shadow_from_swap_cache(int type, unsigned long begin,
-				unsigned long end)
+/*
+ * In the virtual swap implementation, we index the swap cache by virtual swap
+ * slots rather than physical ones. As a result, we only clear the shadow when
+ * the virtual swap slot is freed (via virt_clear_shadow_from_swap_cache()),
+ * not when the physical swap slot is freed (via clear_shadow_from_swap_cache()
+ * in the old implementation, which is a no-op in the new implementation).
+ */
+void virt_clear_shadow_from_swap_cache(swp_entry_t entry)
 {
-	swp_slot_t slot = swp_slot(type, begin);
-	swp_entry_t entry = swp_slot_to_swp_entry(slot);
-	unsigned long index = swap_cache_index(entry);
 	struct address_space *address_space = swap_address_space(entry);
-	void *old;
+	pgoff_t index = swap_cache_index(entry);
 	XA_STATE(xas, &address_space->i_pages, index);
 
 	xas_set_update(&xas, workingset_update_node);
-
 	xa_lock_irq(&address_space->i_pages);
-	xas_for_each(&xas, old, entry.val + end - begin) {
-		if (!xa_is_value(old))
-			continue;
+	if (xa_is_value(xas_load(&xas)))
 		xas_store(&xas, NULL);
-	}
 	xa_unlock_irq(&address_space->i_pages);
 }
+
+void clear_shadow_from_swap_cache(int type, unsigned long begin,
+				unsigned long end)
+{
+}
 #else
 void clear_shadow_from_swap_cache(int type, unsigned long begin,
 				unsigned long end)
@@ -978,10 +984,17 @@ static int __init swap_init_sysfs(void)
 	init_swapper_space(&swapper_space);
 #endif
 
+	err = vswap_init();
+	if (err) {
+		pr_err("failed to initialize virtual swap space\n");
+		return err;
+	}
+
 	swap_kobj = kobject_create_and_add("swap", mm_kobj);
 	if (!swap_kobj) {
 		pr_err("failed to create swap kobject\n");
-		return -ENOMEM;
+		err = -ENOMEM;
+		goto vswap_exit;
 	}
 	err = sysfs_create_group(swap_kobj, &swap_attr_group);
 	if (err) {
@@ -992,6 +1005,8 @@ static int __init swap_init_sysfs(void)
 
 delete_obj:
 	kobject_put(swap_kobj);
+vswap_exit:
+	vswap_exit();
 	return err;
 }
 subsys_initcall(swap_init_sysfs);
mm/swapfile.c +15 -3
index a1dd7e998e90..533011c97e03 100644
@@ -1505,6 +1505,20 @@ static void swap_slot_range_free(struct swap_info_struct *si,
 	unsigned char *map = si->swap_map + offset;
 	unsigned char *map_end = map + nr_pages;
 	swp_entry_t entry = swp_slot_to_swp_entry(slot);
+	int i;
+
+#ifndef CONFIG_VIRTUAL_SWAP
+	/*
+	 * In the new (i.e virtual swap) implementation, we will let the virtual
+	 * swap layer handle the cgroup swap accounting and charging.
+	 */
+	mem_cgroup_uncharge_swap(entry, nr_pages);
+#endif
+	/* release all the associated (virtual) swap slots */
+	for (i = 0; i < nr_pages; i++) {
+		vswap_free(entry);
+		entry.val++;
+	}
 
 	/* It should never free entries across different clusters */
 	VM_BUG_ON(ci != offset_to_cluster(si, offset + nr_pages - 1));
@@ -1517,7 +1531,6 @@ static void swap_slot_range_free(struct swap_info_struct *si,
 		*map = 0;
 	} while (++map < map_end);
 
-	mem_cgroup_uncharge_swap(entry, nr_pages);
 	swap_range_free(si, offset, nr_pages);
 
 	if (!ci->count)
@@ -1571,9 +1584,8 @@ void swap_free_nr(swp_entry_t entry, int nr_pages)
 /*
  * Called after dropping swapcache to decrease refcnt to swap entries.
  */
-void put_swap_folio(struct folio *folio, swp_entry_t entry)
+void swap_slot_put_folio(swp_slot_t slot, struct folio *folio)
 {
-	swp_slot_t slot = swp_entry_to_swp_slot(entry);
 	unsigned long offset = swp_slot_offset(slot);
 	struct swap_cluster_info *ci;
 	struct swap_info_struct *si;
mm/vswap.c new file +375 -0

375 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#16 lore raw

RFC PATCH 7/14 swap: implement the swap_cgroup API using virtual swap

In reply to Nhat Pham

Once we decouple a swap entry from its backing store via the virtual swap, we can no longer statically allocate an array to store the swap entries' cgroup information. Move it to the swap descriptor.

---
 mm/Makefile |  2 ++
 mm/vswap.c  | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 73 insertions(+), 1 deletion(-)
mm/Makefile +2 -0
index b7216c714fa1..35f2f282c8da 100644
@@ -101,8 +101,10 @@ obj-$(CONFIG_PAGE_COUNTER) += page_counter.o
 obj-$(CONFIG_MEMCG_V1) += memcontrol-v1.o
 obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o
 ifdef CONFIG_SWAP
+ifndef CONFIG_VIRTUAL_SWAP
 obj-$(CONFIG_MEMCG) += swap_cgroup.o
 endif
+endif
 obj-$(CONFIG_CGROUP_HUGETLB) += hugetlb_cgroup.o
 obj-$(CONFIG_GUP_TEST) += gup_test.o
 obj-$(CONFIG_DMAPOOL_TEST) += dmapool_test.o
mm/vswap.c +71 -1

95 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#17 lore raw

RFC PATCH 8/14 swap: manage swap entry lifetime at the virtual swap layer

In reply to Nhat Pham

This patch moves the swap entry lifetime to the virtual swap layer (if we enable swap virtualization), by adding the following fields to the swap descriptor:

1. Whether the swap entry is in swap cache (or about to be added).
2. The swap count of the swap entry, which counts the number of page table entries at which the swap entry is inserted.
3. The reference count of the swap entry, which is the swap count of the swap entry, added one if the entry has been added to the swap cache.

We also re-implement all of the swap entry lifetime API (swap_duplicate(), swap_free_nr(), swapcache_prepare(), etc.) in the virtual swap layer.

Note that the swapfile's swap map can be now be reduced under the virtual swap implementation, as each slot can now only have 3 states: unallocated, allocated, and bad slot. However, I leave this simplification to future work, to minimize the amount of code change for review in this series of work.

---
 include/linux/swap.h |  33 ++--
 mm/memory.c          |   2 +
 mm/swapfile.c        | 128 +++++++++++---
 mm/vswap.c           | 400 ++++++++++++++++++++++++++++++++++++++++++-
 4 files changed, 522 insertions(+), 41 deletions(-)
include/linux/swap.h +21 -12
index d32a2c300924..1d8679bd57f3 100644
@@ -225,6 +225,11 @@ enum {
 #define SWAP_CLUSTER_MAX_SKIPPED (SWAP_CLUSTER_MAX << 10)
 #define COMPACT_CLUSTER_MAX SWAP_CLUSTER_MAX
 
+#ifdef CONFIG_VIRTUAL_SWAP
+/* Swapfile's swap map state*/
+#define SWAP_MAP_ALLOCATED	0x01	/* Page is allocated */
+#define SWAP_MAP_BAD	0x02	/* Page is bad */
+#else
 /* Bit flag in swap_map */
 #define SWAP_HAS_CACHE	0x40	/* Flag page is cached, in first swap_map */
 #define COUNT_CONTINUED	0x80	/* Flag swap_map continuation for full count */
@@ -236,6 +241,7 @@ enum {
 
 /* Special value in each swap_map continuation */
 #define SWAP_CONT_MAX	0x7f	/* Max count */
+#endif /* CONFIG_VIRTUAL_SWAP */
 
 /*
  * We use this to track usage of a cluster. A cluster is a block of swap disk
@@ -455,7 +461,6 @@ extern void __meminit kswapd_stop(int nid);
 /* Virtual swap API */
 swp_entry_t folio_alloc_swap(struct folio *folio);
 bool folio_free_swap(struct folio *folio);
-int add_swap_count_continuation(swp_entry_t, gfp_t);
 void swap_shmem_alloc(swp_entry_t, int);
 int swap_duplicate(swp_entry_t);
 int swapcache_prepare(swp_entry_t entry, int nr);
@@ -559,11 +564,6 @@ static inline void free_swap_cache(struct folio *folio)
 {
 }
 
-static inline int add_swap_count_continuation(swp_entry_t swp, gfp_t gfp_mask)
-{
-	return 0;
-}
-
 static inline void swap_shmem_alloc(swp_entry_t swp, int nr)
 {
 }
@@ -728,9 +728,13 @@ static inline bool mem_cgroup_swap_full(struct folio *folio)
 #ifdef CONFIG_VIRTUAL_SWAP
 int vswap_init(void);
 void vswap_exit(void);
-void vswap_free(swp_entry_t entry);
 swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry);
 swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot);
+bool folio_swapped(struct folio *folio);
+bool vswap_swapcache_only(swp_entry_t entry, int nr);
+int non_swapcache_batch(swp_entry_t entry, int nr);
+bool swap_free_nr_any_cache_only(swp_entry_t entry, int nr);
+void put_swap_folio(struct folio *folio, swp_entry_t entry);
 #else
 static inline int vswap_init(void)
 {
@@ -741,10 +745,6 @@ static inline void vswap_exit(void)
 {
 }
 
-static inline void vswap_free(swp_entry_t entry)
-{
-}
-
 /**
  * swp_entry_to_swp_slot - look up the physical swap slot corresponding to a
  *                         virtual swap slot.
@@ -768,12 +768,12 @@ static inline swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot)
 {
 	return (swp_entry_t) { slot.val };
 }
-#endif
 
 static inline void put_swap_folio(struct folio *folio, swp_entry_t entry)
 {
 	swap_slot_put_folio(swp_entry_to_swp_slot(entry), folio);
 }
+#endif
 
 static inline bool trylock_swapoff(swp_entry_t entry,
 				struct swap_info_struct **si)
@@ -790,5 +790,14 @@ static inline void unlock_swapoff(swp_entry_t entry,
 	swap_slot_put_swap_info(si);
 }
 
+#if defined(CONFIG_SWAP) && !defined(CONFIG_VIRTUAL_SWAP)
+int add_swap_count_continuation(swp_entry_t, gfp_t);
+#else
+static inline int add_swap_count_continuation(swp_entry_t swp, gfp_t gfp_mask)
+{
+	return 0;
+}
+#endif
+
 #endif /* __KERNEL__*/
 #endif /* _LINUX_SWAP_H */
mm/memory.c +2 -0
index c44e845b5320..a1d3631ad85f 100644
@@ -4123,6 +4123,7 @@ static struct folio *__alloc_swap_folio(struct vm_fault *vmf)
 }
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
+#ifndef CONFIG_VIRTUAL_SWAP
 static inline int non_swapcache_batch(swp_entry_t entry, int max_nr)
 {
 	swp_slot_t slot = swp_entry_to_swp_slot(entry);
@@ -4143,6 +4144,7 @@ static inline int non_swapcache_batch(swp_entry_t entry, int max_nr)
 
 	return i;
 }
+#endif
 
 /*
  * Check if the PTEs within a range are contiguous swap entries
mm/swapfile.c +105 -23

320 lines not on this page · raw message

mm/vswap.c +394 -6

479 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#18 lore raw

RFC PATCH 9/14 swap: implement locking out swapoff using virtual swap slot

In reply to Nhat Pham

In the old design, we obtain a reference to the swap device to maintain the validity of the device's metadata struct (i.e swap_info_struct), as well as the swap entry itself, before various operations.

In the new virtual swap space design, however, this is no longer necessary - we can simply acquire a reference to the virtual swap slot itself to ensure it remains valid.

Furthermore, once we decouple virtual swap slots from their backing, obtaining a reference to the backing swap device itself is not sufficient or even possible anyway, as the backing of a virtual swap slot can change under it.

---
 include/linux/swap.h | 24 +++++++++++++++++++++++-
 mm/vswap.c           | 36 ++++++++++++++++++++++++++++++++++++
 2 files changed, 59 insertions(+), 1 deletion(-)
include/linux/swap.h +23 -1
index 1d8679bd57f3..7f6200f1db33 100644
@@ -730,11 +730,33 @@ int vswap_init(void);
 void vswap_exit(void);
 swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry);
 swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot);
+bool vswap_tryget(swp_entry_t entry);
+void vswap_put(swp_entry_t entry);
 bool folio_swapped(struct folio *folio);
 bool vswap_swapcache_only(swp_entry_t entry, int nr);
 int non_swapcache_batch(swp_entry_t entry, int nr);
 bool swap_free_nr_any_cache_only(swp_entry_t entry, int nr);
 void put_swap_folio(struct folio *folio, swp_entry_t entry);
+
+static inline bool trylock_swapoff(swp_entry_t entry,
+				struct swap_info_struct **si)
+{
+	if (!vswap_tryget(entry))
+		return false;
+
+	/*
+	 * No need to hold a reference to the swap device. The virtual swap slot pins
+	 * the physical swap slot, which in turns pin the swap device.
+	 */
+	*si = swap_slot_swap_info(swp_entry_to_swp_slot(entry));
+	return true;
+}
+
+static inline void unlock_swapoff(swp_entry_t entry,
+				struct swap_info_struct *si)
+{
+	vswap_put(entry);
+}
 #else
 static inline int vswap_init(void)
 {
@@ -773,7 +795,6 @@ static inline void put_swap_folio(struct folio *folio, swp_entry_t entry)
 {
 	swap_slot_put_folio(swp_entry_to_swp_slot(entry), folio);
 }
-#endif
 
 static inline bool trylock_swapoff(swp_entry_t entry,
 				struct swap_info_struct **si)
@@ -789,6 +810,7 @@ static inline void unlock_swapoff(swp_entry_t entry,
 {
 	swap_slot_put_swap_info(si);
 }
+#endif
 
 #if defined(CONFIG_SWAP) && !defined(CONFIG_VIRTUAL_SWAP)
 int add_swap_count_continuation(swp_entry_t, gfp_t);
mm/vswap.c +36 -0
index 1b8cf894390c..8a518ebd20e4 100644
@@ -425,6 +425,42 @@ swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot)
 	return ret;
 }
 
+/**
+ * vswap_tryget - try to obtain an ephemeral reference to a virtual swap slot.
+ *
+ * @entry: the virtual swap slot.
+ *
+ * Return: true if the reference was obtained.
+ */
+bool vswap_tryget(swp_entry_t entry)
+{
+	struct swp_desc *desc;
+	bool ret;
+
+	rcu_read_lock();
+	desc = xa_load(&vswap_map, entry.val);
+	if (!desc) {
+		rcu_read_unlock();
+		return false;
+	}
+
+	ret = kref_get_unless_zero(&desc->refcnt);
+	rcu_read_unlock();
+	return ret;
+}
+
+/**
+ * vswap_put - release an ephemeral reference to the virtual swap slot.
+ *
+ * @entry: the virtual swap slot.
+ */
+void vswap_put(swp_entry_t entry)
+{
+	struct swp_desc *desc = xa_load(&vswap_map, entry.val);
+
+	kref_put(&desc->refcnt, vswap_ref_release);
+}
+
 /**
  * swap_free_nr_any_cache_only - decrease the swap count of nr contiguous swap
  *                               entries by 1 (when the swap entries are removed
Signature · 1 line
2.47.1
author maintainer
#19 lore raw

RFC PATCH 10/14 mm: swap: decouple virtual swap slot from backing store

In reply to Nhat Pham

This patch presents the first real use case of the new virtual swap design. It leverages the virtualization of the swap space to decouple a swap entry and its backing storage. A swap entry can now be backed by one of the following options:

1. A slot on a physical swapfile/swap partition.
2. A "zero swap page".
3. A compressed object in the zswap pool.
4. An in-memory page. This can happen when a page is loaded (exclusively) from the zswap pool, or if the page is rejected by zswap and zswap writeback is disabled.

This allows us to use zswap and the zero swap page optimization, without having to reserved a slot on a swapfile, or a swapfile at all.

Note that we disable THP swapin on virtual swap implementation, for now. Similarly, we only operates on one swap entry at a time when we zap a PTE range. There is no real reason why we cannot build support for this in the new design. It is simply to make the patch smaller and more manageable for reviewers - these capabilities will be restored in a following patch.

In the same vein, for now we still charge virtual swap slots towards the memcg's swap usage. In a following patch, we will change this behavior and only charge physical (i.e on swapfile) swap slots towards the memcg's swap usage.

---
 include/linux/swap.h |  71 +++++-
 mm/Kconfig           |  11 +
 mm/huge_memory.c     |   5 +-
 mm/internal.h        |  16 +-
 mm/memcontrol.c      |  70 ++++--
 mm/memory.c          |  73 ++++--
 mm/migrate.c         |   1 +
 mm/page_io.c         |  31 ++-
 mm/shmem.c           |   7 +-
 mm/swap.h            |  10 +
 mm/swap_state.c      |  23 +-
 mm/swapfile.c        |  20 +-
 mm/vmscan.c          |  26 ++-
 mm/vswap.c           | 531 ++++++++++++++++++++++++++++++++++++++-----
 mm/zswap.c           |  34 ++-
 15 files changed, 771 insertions(+), 158 deletions(-)
include/linux/swap.h +64 -7
index 7f6200f1db33..073835335667 100644
@@ -461,6 +461,7 @@ extern void __meminit kswapd_stop(int nid);
 /* Virtual swap API */
 swp_entry_t folio_alloc_swap(struct folio *folio);
 bool folio_free_swap(struct folio *folio);
+void put_swap_folio(struct folio *folio, swp_entry_t entry);
 void swap_shmem_alloc(swp_entry_t, int);
 int swap_duplicate(swp_entry_t);
 int swapcache_prepare(swp_entry_t entry, int nr);
@@ -508,7 +509,6 @@ static inline long get_nr_swap_pages(void)
 }
 
 void si_swapinfo(struct sysinfo *);
-void swap_slot_put_folio(swp_slot_t slot, struct folio *folio);
 swp_slot_t swap_slot_alloc_of_type(int);
 int swap_slot_alloc(int n, swp_slot_t swp_slots[], int order);
 void swap_slot_free_nr(swp_slot_t slot, int nr_pages);
@@ -725,9 +725,12 @@ static inline bool mem_cgroup_swap_full(struct folio *folio)
 }
 #endif
 
+struct zswap_entry;
+
 #ifdef CONFIG_VIRTUAL_SWAP
 int vswap_init(void);
 void vswap_exit(void);
+swp_slot_t vswap_alloc_swap_slot(struct folio *folio);
 swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry);
 swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot);
 bool vswap_tryget(swp_entry_t entry);
@@ -736,7 +739,13 @@ bool folio_swapped(struct folio *folio);
 bool vswap_swapcache_only(swp_entry_t entry, int nr);
 int non_swapcache_batch(swp_entry_t entry, int nr);
 bool swap_free_nr_any_cache_only(swp_entry_t entry, int nr);
-void put_swap_folio(struct folio *folio, swp_entry_t entry);
+bool vswap_disk_backed(swp_entry_t entry, int nr);
+void vswap_split_huge_page(struct folio *head, struct folio *subpage);
+void vswap_migrate(struct folio *src, struct folio *dst);
+bool vswap_folio_backed(swp_entry_t entry, int nr);
+void vswap_store_folio(swp_entry_t entry, struct folio *folio);
+void swap_zeromap_folio_set(struct folio *folio);
+void vswap_assoc_zswap(swp_entry_t entry, struct zswap_entry *zswap_entry);
 
 static inline bool trylock_swapoff(swp_entry_t entry,
 				struct swap_info_struct **si)
@@ -745,16 +754,33 @@ static inline bool trylock_swapoff(swp_entry_t entry,
 		return false;
 
 	/*
-	 * No need to hold a reference to the swap device. The virtual swap slot pins
-	 * the physical swap slot, which in turns pin the swap device.
+	 * Note that this function does not provide any guarantee that the virtual
+	 * swap slot's backing state will be stable, only that the slot itself will
+	 * not be freed. This has several implications:
+	 *
+	 * 1. If the virtual swap slot is backed by a physical swap slot, we need to
+	 * also acquire a reference to the swap device before returning it.
+	 * Otherwise, the virtual swap slot can change its backend, allowing swapoff
+	 * to free the swap device looked up here.
+	 *
+	 * 2. The swap device we are looking up here might be outdated by the time we
+	 * return to the caller. It is perfectly OK, if the swap_info_struct is only
+	 * used in a best-effort manner (i.e optimization). If we need the precise
+	 * backing state, we need to re-check after the entry is pinned in swap cache.
 	 */
-	*si = swap_slot_swap_info(swp_entry_to_swp_slot(entry));
+	if (vswap_disk_backed(entry, 1))
+		*si = swap_slot_tryget_swap_info(swp_entry_to_swp_slot(entry));
+	else
+		*si = NULL;
+
 	return true;
 }
 
 static inline void unlock_swapoff(swp_entry_t entry,
 				struct swap_info_struct *si)
 {
+	if (si)
+		swap_slot_put_swap_info(si);
 	vswap_put(entry);
 }
 #else
@@ -791,9 +817,32 @@ static inline swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot)
 	return (swp_entry_t) { slot.val };
 }
 
-static inline void put_swap_folio(struct folio *folio, swp_entry_t entry)
+static inline swp_slot_t vswap_alloc_swap_slot(struct folio *folio)
+{
+	return swp_entry_to_swp_slot(folio->swap);
+}
+
+static inline void vswap_split_huge_page(struct folio *head,
+				struct folio *subpage)
+{
+}
+
+static inline void vswap_migrate(struct folio *src, struct folio *dst)
+{
+}
+
+static inline bool vswap_folio_backed(swp_entry_t entry, int nr)
+{
+	return false;
+}
+
+static inline void vswap_store_folio(swp_entry_t entry, struct folio *folio)
+{
+}
+
+static inline void vswap_assoc_zswap(swp_entry_t entry,
+				struct zswap_entry *zswap_entry)
 {
-	swap_slot_put_folio(swp_entry_to_swp_slot(entry), folio);
 }
 
 static inline bool trylock_swapoff(swp_entry_t entry,
@@ -810,8 +859,16 @@ static inline void unlock_swapoff(swp_entry_t entry,
 {
 	swap_slot_put_swap_info(si);
 }
+
 #endif
 
+static inline struct swap_info_struct *vswap_get_device(swp_entry_t entry)
+{
+	swp_slot_t slot = swp_entry_to_swp_slot(entry);
+
+	return slot.val ? swap_slot_tryget_swap_info(slot) : NULL;
+}
+
 #if defined(CONFIG_SWAP) && !defined(CONFIG_VIRTUAL_SWAP)
 int add_swap_count_continuation(swp_entry_t, gfp_t);
 #else
mm/Kconfig +11 -0
index d578b8e6ab6a..e9abc33fe4b7 100644
@@ -35,6 +35,17 @@ config VIRTUAL_SWAP
 		In this new design, for each swap entry, a virtual swap slot is
 		allocated and stored in the page table entry, rather than the
 		handle to the physical swap slot on the swap device itself.
+		Swap entries that are:
+
+		1. Zero-filled
+
+		2. Stored in the zswap pool.
+
+		3. Rejected by zswap but cannot be written back to a backing
+		   swap device.
+
+		no longer take up any disk storage (i.e they do not occupy any
+		slot in the backing swap device).
 
 		There might be more lock contentions with heavy swap use, since
 		the swap cache is no longer range partitioned.
mm/huge_memory.c +4 -1
index 373781b21e5c..e6832ec2b07a 100644
@@ -3172,6 +3172,7 @@ static void __split_huge_page_tail(struct folio *folio, int tail,
 {
 	struct page *head = &folio->page;
 	struct page *page_tail = head + tail;
+
 	/*
 	 * Careful: new_folio is not a "real" folio before we cleared PageTail.
 	 * Don't pass it around before clear_compound_head().
@@ -3227,8 +3228,10 @@ static void __split_huge_page_tail(struct folio *folio, int tail,
 		VM_WARN_ON_ONCE_PAGE(true, page_tail);
 		page_tail->private = 0;
 	}
-	if (folio_test_swapcache(folio))
+	if (folio_test_swapcache(folio)) {
 		new_folio->swap.val = folio->swap.val + tail;
+		vswap_split_huge_page(folio, new_folio);
+	}
 
 	/* Page flags must be visible before we make the page non-compound. */
 	smp_wmb();
mm/internal.h +8 -8
index ca28729f822a..51061691a731 100644
@@ -268,17 +268,12 @@ static inline swp_entry_t swap_nth(swp_entry_t entry, long n)
 	return (swp_entry_t) { entry.val + n };
 }
 
-/* similar to swap_nth, but check the backing physical slots as well. */
+/* temporary disallow batched swap operations */
 static inline swp_entry_t swap_move(swp_entry_t entry, long delta)
 {
-	swp_slot_t slot = swp_entry_to_swp_slot(entry), next_slot;
-	swp_entry_t next_entry = swap_nth(entry, delta);
-
-	next_slot = swp_entry_to_swp_slot(next_entry);
-	if (swp_slot_type(slot) != swp_slot_type(next_slot) ||
-			swp_slot_offset(slot) + delta != swp_slot_offset(next_slot))
-		next_entry.val = 0;
+	swp_entry_t next_entry;
 
+	next_entry.val = 0;
 	return next_entry;
 }
 #else
@@ -349,6 +344,8 @@ static inline pte_t pte_next_swp_offset(pte_t pte)
  * max_nr must be at least one and must be limited by the caller so scanning
  * cannot exceed a single page table.
  *
+ * Note that for virtual swap space, we will not batch anything for now.
+ *
  * 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)
@@ -363,6 +360,9 @@ static inline int swap_pte_batch(pte_t *start_ptep, int max_nr, pte_t pte)
 	VM_WARN_ON(!is_swap_pte(pte));
 	VM_WARN_ON(non_swap_entry(entry));
 
+	if (IS_ENABLED(CONFIG_VIRTUAL_SWAP))
+		return 1;
+
 	cgroup_id = lookup_swap_cgroup_id(entry);
 	while (ptep < end_ptep) {
 		pte = ptep_get(ptep);
mm/memcontrol.c +46 -24

102 lines not on this page · raw message

mm/memory.c +48 -25

122 lines not on this page · raw message

mm/migrate.c +1 -0
index 97f0edf0c032..3a2cf62f47ea 100644
@@ -523,6 +523,7 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 	if (folio_test_swapcache(folio)) {
 		folio_set_swapcache(newfolio);
 		newfolio->private = folio_get_private(folio);
+		vswap_migrate(folio, newfolio);
 		entries = nr;
 	} else {
 		entries = 1;
mm/page_io.c +23 -8
index 182851c47f43..83fc4a466db8 100644
@@ -201,6 +201,12 @@ static bool is_folio_zero_filled(struct folio *folio)
 	return true;
 }
 
+#ifdef CONFIG_VIRTUAL_SWAP
+static void swap_zeromap_folio_clear(struct folio *folio)
+{
+	vswap_store_folio(folio->swap, folio);
+}
+#else
 static void swap_zeromap_folio_set(struct folio *folio)
 {
 	struct obj_cgroup *objcg = get_obj_cgroup_from_folio(folio);
@@ -238,6 +244,7 @@ static void swap_zeromap_folio_clear(struct folio *folio)
 		clear_bit(swp_slot_offset(slot), sis->zeromap);
 	}
 }
+#endif /* CONFIG_VIRTUAL_SWAP */
 
 /*
  * We may have stale swap cache pages in memory: notice
@@ -246,6 +253,7 @@ static void swap_zeromap_folio_clear(struct folio *folio)
 int swap_writepage(struct page *page, struct writeback_control *wbc)
 {
 	struct folio *folio = page_folio(page);
+	swp_slot_t slot;
 	int ret;
 
 	if (folio_free_swap(folio)) {
@@ -275,9 +283,8 @@ int swap_writepage(struct page *page, struct writeback_control *wbc)
 		return 0;
 	} else {
 		/*
-		 * Clear bits this folio occupies in the zeromap to prevent
-		 * zero data being read in from any previous zero writes that
-		 * occupied the same swap entries.
+		 * Clear the zeromap state to prevent zero data being read in from any
+		 * previous zero writes that occupied the same swap entries.
 		 */
 		swap_zeromap_folio_clear(folio);
 	}
@@ -291,6 +298,13 @@ int swap_writepage(struct page *page, struct writeback_control *wbc)
 		return AOP_WRITEPAGE_ACTIVATE;
 	}
 
+	/* fall back to physical swap device */
+	slot = vswap_alloc_swap_slot(folio);
+	if (!slot.val) {
+		folio_mark_dirty(folio);
+		return AOP_WRITEPAGE_ACTIVATE;
+	}
+
 	__swap_writepage(folio, wbc);
 	return 0;
 }
@@ -624,14 +638,11 @@ static void swap_read_folio_bdev_async(struct folio *folio,
 
 void swap_read_folio(struct folio *folio, struct swap_iocb **plug)
 {
-	struct swap_info_struct *sis =
-		swap_slot_swap_info(swp_entry_to_swp_slot(folio->swap));
-	bool synchronous = sis->flags & SWP_SYNCHRONOUS_IO;
-	bool workingset = folio_test_workingset(folio);
+	struct swap_info_struct *sis;
+	bool synchronous, workingset = folio_test_workingset(folio);
 	unsigned long pflags;
 	bool in_thrashing;
 
-	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio) && !synchronous, folio);
 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
 	VM_BUG_ON_FOLIO(folio_test_uptodate(folio), folio);
 
@@ -657,6 +668,10 @@ void swap_read_folio(struct folio *folio, struct swap_iocb **plug)
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
 
+	sis = swap_slot_swap_info(swp_entry_to_swp_slot(folio->swap));
+	synchronous = sis->flags & SWP_SYNCHRONOUS_IO;
+	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio) && !synchronous, folio);
+
 	if (data_race(sis->flags & SWP_FS_OPS)) {
 		swap_read_folio_fs(folio, plug);
 	} else if (synchronous) {
mm/shmem.c +4 -3
index 4c00b4673468..609971a2b365 100644
@@ -1404,7 +1404,7 @@ static int shmem_find_swap_entries(struct address_space *mapping,
 		 * swapin error entries can be found in the mapping. But they're
 		 * deliberately ignored here as we've done everything we can do.
 		 */
-		if (swp_slot_type(slot) != type)
+		if (!slot.val || swp_slot_type(slot) != type)
 			continue;
 
 		indices[folio_batch_count(fbatch)] = xas.xa_index;
@@ -1554,7 +1554,7 @@ static int shmem_writepage(struct page *page, struct writeback_control *wbc)
 	if ((info->flags & VM_LOCKED) || sbinfo->noswap)
 		goto redirty;
 
-	if (!total_swap_pages)
+	if (!IS_ENABLED(CONFIG_VIRTUAL_SWAP) && !total_swap_pages)
 		goto redirty;
 
 	/*
@@ -2295,7 +2295,8 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
 			fallback_order0 = true;
 
 		/* Skip swapcache for synchronous device. */
-		if (!fallback_order0 && data_race(si->flags & SWP_SYNCHRONOUS_IO)) {
+		if (!fallback_order0 && si &&
+				  data_race(si->flags & SWP_SYNCHRONOUS_IO)) {
 			folio = shmem_swap_alloc_folio(inode, vma, index, swap, order, gfp);
 			if (!IS_ERR(folio)) {
 				skip_swapcache = true;
mm/swap.h +10 -0
index 31c94671cb44..411282d08a15 100644
@@ -86,9 +86,18 @@ static inline unsigned int folio_swap_flags(struct folio *folio)
 {
 	swp_slot_t swp_slot = swp_entry_to_swp_slot(folio->swap);
 
+	/*
+	 * In the virtual swap implementation, the folio might not be backed by any
+	 * physical swap slots (for e.g zswap-backed only).
+	 */
+	if (!swp_slot.val)
+		return 0;
 	return swap_slot_swap_info(swp_slot)->flags;
 }
 
+#ifdef CONFIG_VIRTUAL_SWAP
+int swap_zeromap_batch(swp_entry_t entry, int max_nr, bool *is_zeromap);
+#else
 /*
  * Return the count of contiguous swap entries that share the same
  * zeromap status as the starting entry. If is_zeromap is not NULL,
@@ -114,6 +123,7 @@ static inline int swap_zeromap_batch(swp_entry_t entry, int max_nr,
 	else
 		return find_next_bit(sis->zeromap, end, start) - start;
 }
+#endif
 
 #else /* CONFIG_SWAP */
 struct swap_iocb;
mm/swap_state.c +22 -1
index eb4cd6ba2068..3a549c4583e9 100644
@@ -494,6 +494,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
 
 	for (;;) {
 		int err;
+
 		/*
 		 * First check the swap cache.  Since this is normally
 		 * called after swap_cache_get_folio() failed, re-calling
@@ -531,8 +532,20 @@ struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
 		 * Swap entry may have been freed since our caller observed it.
 		 */
 		err = swapcache_prepare(entry, 1);
-		if (!err)
+		if (!err) {
+			/* This might be invoked by swap_cluster_readahead(), which can
+			 * race with shmem_swapin_folio(). The latter might have already
+			 * called delete_from_swap_cache(), allowing swapcache_prepare()
+			 * to succeed here. This can lead to reading bogus data to populate
+			 * the page. To prevent this, skip folio-backed virtual swap slots,
+			 * and let caller retry if necessary.
+			 */
+			if (vswap_folio_backed(entry, 1)) {
+				swapcache_clear(si, entry, 1);
+				goto put_and_return;
+			}
 			break;
+		}
 		else if (err != -EEXIST)
 			goto put_and_return;
 
@@ -715,6 +728,14 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 	struct swap_iocb *splug = NULL;
 	bool page_allocated;
 
+	/*
+	 * If swap is virtualized, the swap entry might not be backed by any
+	 * physical swap slot. In that case, just skip readahead and bring in the
+	 * target entry.
+	 */
+	if (!slot.val)
+		goto skip;
+
 	mask = swapin_nr_pages(offset) - 1;
 	if (!mask)
 		goto skip;
mm/swapfile.c +9 -11
index babb545acffd..59b34d51b16b 100644
@@ -1165,16 +1165,22 @@ static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
 	unsigned long begin = offset;
 	unsigned long end = offset + nr_entries - 1;
 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
+#ifndef CONFIG_VIRTUAL_SWAP
 	unsigned int i;
 
 	/*
 	 * Use atomic clear_bit operations only on zeromap instead of non-atomic
 	 * bitmap_clear to prevent adjacent bits corruption due to simultaneous writes.
+	 *
+	 * Note that in the virtual swap implementation, we do not need to perform
+	 * these operations, since zswap and zero-filled pages are not backed by
+	 * physical swapfile.
 	 */
 	for (i = 0; i < nr_entries; i++) {
 		clear_bit(offset + i, si->zeromap);
 		zswap_invalidate(swp_slot_to_swp_entry(swp_slot(si->type, offset + i)));
 	}
+#endif
 
 	if (si->flags & SWP_BLKDEV)
 		swap_slot_free_notify =
@@ -1639,43 +1645,35 @@ void swap_free_nr(swp_entry_t entry, int nr_pages)
 {
 	swap_slot_free_nr(swp_entry_to_swp_slot(entry), nr_pages);
 }
-#endif
 
 /*
  * This should only be called in contexts in which the slot has
  * been allocated but not associated with any swap entries.
  */
-void swap_slot_put_folio(swp_slot_t slot, struct folio *folio)
+void put_swap_folio(struct folio *folio, swp_entry_t entry)
 {
+	swp_slot_t slot = swp_entry_to_swp_slot(entry);
 	unsigned long offset = swp_slot_offset(slot);
 	struct swap_cluster_info *ci;
 	struct swap_info_struct *si;
 	int size = 1 << swap_slot_order(folio_order(folio));
-	unsigned char usage;
 
 	si = _swap_info_get(slot);
 	if (!si)
 		return;
 
-#ifdef CONFIG_VIRTUAL_SWAP
-	usage = SWAP_MAP_ALLOCATED;
-#else
-	usage = SWAP_HAS_CACHE;
-#endif
-
 	ci = lock_cluster(si, offset);
 	if (swap_is_has_cache(si, offset, size))
 		swap_slot_range_free(si, ci, slot, size);
 	else {
 		for (int i = 0; i < size; i++, slot.val++) {
-			if (!__swap_slot_free_locked(si, offset + i, usage))
+			if (!__swap_slot_free_locked(si, offset + i, SWAP_HAS_CACHE))
 				swap_slot_range_free(si, ci, slot, 1);
 		}
 	}
 	unlock_cluster(ci);
 }
 
-#ifndef CONFIG_VIRTUAL_SWAP
 int __swap_count(swp_entry_t entry)
 {
 	swp_slot_t slot = swp_entry_to_swp_slot(entry);
mm/vmscan.c +17 -9
index c767d71c43d7..db4178bf5f6f 100644
@@ -341,10 +341,15 @@ static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
 {
 	if (memcg == NULL) {
 		/*
-		 * For non-memcg reclaim, is there
-		 * space in any swap device?
+		 * For non-memcg reclaim:
+		 *
+		 * If swap is virtualized, we can still use zswap even if there is no
+		 * space left in any swap file/partition.
+		 *
+		 * Otherwise, check if there is space in any swap device?
 		 */
-		if (get_nr_swap_pages() > 0)
+		if ((IS_ENABLED(CONFIG_VIRTUAL_SWAP) && zswap_is_enabled()) ||
+				get_nr_swap_pages() > 0)
 			return true;
 	} else {
 		/* Is the memcg below its swap limit? */
@@ -2611,12 +2616,15 @@ static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
 static bool can_age_anon_pages(struct pglist_data *pgdat,
 			       struct scan_control *sc)
 {
-	/* Aging the anon LRU is valuable if swap is present: */
-	if (total_swap_pages > 0)
-		return true;
-
-	/* Also valuable if anon pages can be demoted: */
-	return can_demote(pgdat->node_id, sc);
+	/*
+	 * Aging the anon LRU is valuable if:
+	 * 1. Swap is virtualized and zswap is enabled.
+	 * 2. There are physical swap slots available.
+	 * 3. Anon pages can be demoted
+	 */
+	return (IS_ENABLED(CONFIG_VIRTUAL_SWAP) && zswap_is_enabled()) ||
+			total_swap_pages > 0 ||
+			can_demote(pgdat->node_id, sc);
 }
 
 #ifdef CONFIG_LRU_GEN
mm/vswap.c +477 -54

632 lines not on this page · raw message

mm/zswap.c +27 -7
index c1327569ce80..15429825d667 100644
@@ -1068,6 +1068,8 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	struct writeback_control wbc = {
 		.sync_mode = WB_SYNC_NONE,
 	};
+	struct zswap_entry *new_entry;
+	swp_slot_t slot;
 
 	/* try to allocate swap cache folio */
 	mpol = get_task_policy(current);
@@ -1088,6 +1090,10 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 		return -EEXIST;
 	}
 
+	slot = vswap_alloc_swap_slot(folio);
+	if (!slot.val)
+		goto release_folio;
+
 	/*
 	 * folio is locked, and the swapcache is now secured against
 	 * concurrent swapping to and from the slot, and concurrent
@@ -1098,12 +1104,9 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	 * be dereferenced.
 	 */
 	tree = swap_zswap_tree(swpentry);
-	if (entry != xa_cmpxchg(tree, offset, entry, NULL, GFP_KERNEL)) {
-		delete_from_swap_cache(folio);
-		folio_unlock(folio);
-		folio_put(folio);
-		return -ENOMEM;
-	}
+	new_entry = xa_cmpxchg(tree, offset, entry, NULL, GFP_KERNEL);
+	if (entry != new_entry)
+		goto fail;
 
 	zswap_decompress(entry, folio);
 
@@ -1124,6 +1127,14 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	folio_put(folio);
 
 	return 0;
+
+fail:
+	vswap_assoc_zswap(swpentry, new_entry);
+release_folio:
+	delete_from_swap_cache(folio);
+	folio_unlock(folio);
+	folio_put(folio);
+	return -ENOMEM;
 }
 
 /*********************************
@@ -1487,6 +1498,8 @@ static bool zswap_store_page(struct page *page,
 		goto store_failed;
 	}
 
+	vswap_assoc_zswap(page_swpentry, entry);
+
 	/*
 	 * We may have had an existing entry that became stale when
 	 * the folio was redirtied and now the new version is being
@@ -1608,7 +1621,7 @@ bool zswap_store(struct folio *folio)
 	 */
 	if (!ret) {
 		unsigned type = swp_type(swp);
-		pgoff_t offset = swp_offset(swp);
+		pgoff_t offset = zswap_tree_index(swp);
 		struct zswap_entry *entry;
 		struct xarray *tree;
 
@@ -1618,6 +1631,12 @@ bool zswap_store(struct folio *folio)
 			if (entry)
 				zswap_entry_free(entry);
 		}
+
+		/*
+		 * We might have also partially associated some virtual swap slots with
+		 * zswap entries. Undo this.
+		 */
+		vswap_store_folio(swp, folio);
 	}
 
 	return ret;
@@ -1674,6 +1693,7 @@ bool zswap_load(struct folio *folio)
 		count_objcg_events(entry->objcg, ZSWPIN, 1);
 
 	if (swapcache) {
+		vswap_store_folio(swp, folio);
 		zswap_entry_free(entry);
 		folio_mark_dirty(folio);
 	}
Signature · 1 line
2.47.1
author maintainer
#20 lore raw

RFC PATCH 11/14 memcg: swap: only charge physical swap slots

In reply to Nhat Pham

Now that zswap and the zero-filled swap page optimization no longer takes up any physical swap space, we should not charge towards the swap usage and limits of the memcg in these case. We will only record the memcg id on virtual swap slot allocation, and defer physical swap charging (i.e towards memory.swap.current) until the virtual swap slot is backed by an actual physical swap slot (on zswap store failure fallback or zswap writeback).

---
 include/linux/swap.h |  17 ++++++++
 mm/memcontrol.c      | 102 ++++++++++++++++++++++++++++++++++---------
 mm/vswap.c           |  43 ++++++++----------
 3 files changed, 118 insertions(+), 44 deletions(-)
include/linux/swap.h +17 -0
index 073835335667..98cdfe0c1da7 100644
@@ -679,6 +679,23 @@ static inline void folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_SWAP)
 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry);
+
+void __mem_cgroup_record_swap(struct folio *folio, swp_entry_t entry);
+static inline void mem_cgroup_record_swap(struct folio *folio,
+		swp_entry_t entry)
+{
+	if (!mem_cgroup_disabled())
+		__mem_cgroup_record_swap(folio, entry);
+}
+
+void __mem_cgroup_unrecord_swap(swp_entry_t entry, unsigned int nr_pages);
+static inline void mem_cgroup_unrecord_swap(swp_entry_t entry,
+		unsigned int nr_pages)
+{
+	if (!mem_cgroup_disabled())
+		__mem_cgroup_unrecord_swap(entry, nr_pages);
+}
+
 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry);
 static inline int mem_cgroup_try_charge_swap(struct folio *folio,
 		swp_entry_t entry)
mm/memcontrol.c +82 -20

153 lines not on this page · raw message

mm/vswap.c +19 -24

84 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#21 lore raw

RFC PATCH 12/14 vswap: support THP swapin and batch free_swap_and_cache

In reply to Nhat Pham

This patch implements the required functionalities for THP swapin and batched free_swap_and_cache() in the virtual swap space design.

The central requirement is the range of entries we are working with must have no mixed backing states:

1. For now, zswap-backed entries are not supported for these batched operations.
2. All the entries must be backed by the same type.
3. If the swap entries in the batch are backed by in-memory folio, it must be the same folio (i.e they correspond to the subpages of that folio).
4. If the swap entries in the batch are backed by slots on swapfiles, it must be the same swapfile, and these physical swap slots must also be contiguous.

---
 include/linux/swap.h |  6 +++
 mm/internal.h        | 14 +------
 mm/memory.c          | 16 ++++++--
 mm/vswap.c           | 89 ++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 109 insertions(+), 16 deletions(-)
include/linux/swap.h +6 -0
index 98cdfe0c1da7..c3a10c952116 100644
@@ -763,6 +763,7 @@ bool vswap_folio_backed(swp_entry_t entry, int nr);
 void vswap_store_folio(swp_entry_t entry, struct folio *folio);
 void swap_zeromap_folio_set(struct folio *folio);
 void vswap_assoc_zswap(swp_entry_t entry, struct zswap_entry *zswap_entry);
+bool vswap_can_swapin_thp(swp_entry_t entry, int nr);
 
 static inline bool trylock_swapoff(swp_entry_t entry,
 				struct swap_info_struct **si)
@@ -862,6 +863,11 @@ static inline void vswap_assoc_zswap(swp_entry_t entry,
 {
 }
 
+static inline bool vswap_can_swapin_thp(swp_entry_t entry, int nr)
+{
+	return true;
+}
+
 static inline bool trylock_swapoff(swp_entry_t entry,
 				struct swap_info_struct **si)
 {
mm/internal.h +1 -13
index 51061691a731..6694e7a14745 100644
@@ -268,14 +268,7 @@ static inline swp_entry_t swap_nth(swp_entry_t entry, long n)
 	return (swp_entry_t) { entry.val + n };
 }
 
-/* temporary disallow batched swap operations */
-static inline swp_entry_t swap_move(swp_entry_t entry, long delta)
-{
-	swp_entry_t next_entry;
-
-	next_entry.val = 0;
-	return next_entry;
-}
+swp_entry_t swap_move(swp_entry_t entry, long delta);
 #else
 static inline swp_entry_t swap_nth(swp_entry_t entry, long n)
 {
@@ -344,8 +337,6 @@ static inline pte_t pte_next_swp_offset(pte_t pte)
  * max_nr must be at least one and must be limited by the caller so scanning
  * cannot exceed a single page table.
  *
- * Note that for virtual swap space, we will not batch anything for now.
- *
  * 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)
@@ -360,9 +351,6 @@ static inline int swap_pte_batch(pte_t *start_ptep, int max_nr, pte_t pte)
 	VM_WARN_ON(!is_swap_pte(pte));
 	VM_WARN_ON(non_swap_entry(entry));
 
-	if (IS_ENABLED(CONFIG_VIRTUAL_SWAP))
-		return 1;
-
 	cgroup_id = lookup_swap_cgroup_id(entry);
 	while (ptep < end_ptep) {
 		pte = ptep_get(ptep);
mm/memory.c +13 -3
index c5c34efafa81..5abb464913ef 100644
@@ -4226,10 +4226,8 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf)
 	 * 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.
-	 *
-	 * We also disable THP swapin on the virtual swap implementation, for now.
 	 */
-	if (!zswap_never_enabled() || IS_ENABLED(CONFIG_VIRTUAL_SWAP))
+	if (!zswap_never_enabled())
 		goto fallback;
 
 	entry = pte_to_swp_entry(vmf->orig_pte);
@@ -4419,6 +4417,18 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 				}
 				need_clear_cache = true;
 
+				/*
+				 * Recheck to make sure the entire range is still
+				 * THP-swapin-able. Note that before we call
+				 * swapcache_prepare(), entries in the range can
+				 * still have their backing status changed.
+				 */
+				if (IS_ENABLED(CONFIG_VIRTUAL_SWAP) &&
+						!vswap_can_swapin_thp(entry, nr_pages)) {
+					schedule_timeout_uninterruptible(1);
+					goto out_page;
+				}
+
 				mem_cgroup_swapin_uncharge_swap(entry, nr_pages);
 
 				shadow = get_shadow_from_swap_cache(entry);
mm/vswap.c +89 -0

101 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#22 lore raw

RFC PATCH 13/14 swap: simplify swapoff using virtual swap

In reply to Nhat Pham

This patch presents the second applications of virtual swap design - simplifying and optimizing swapoff.

With virtual swap slots stored at page table entries and used as indices to various swap-related data structures, we no longer have to perform a page table walk in swapoff. Simply iterate through all the allocated swap slots on the swapfile, invoke the backward map and fault them in.

This is significantly cleaner, as well as slightly more performant, especially when there are a lot of unrelated VMAs (since the old swapoff code would have to traverse through all of them).

In a simple benchmark, in which we swapoff a 32 GB swapfile that is 50% full, and in which there is a process that maps a 128GB file into memory:

Baseline:
real: 25.54s
user: 0.00s
sys: 11.48s

New Design:
real: 11.69s
user: 0.00s
sys: 9.96s

Disregarding the real time reduction (which is mostly due to more IO asynchrony), the new design reduces the kernel CPU time by about 13%.

---
 include/linux/shmem_fs.h |   3 +
 include/linux/swap.h     |   1 +
 mm/shmem.c               |   2 +
 mm/swapfile.c            | 189 ++++++++++++++++++++++++++++++++-------
 mm/vswap.c               |  61 +++++++++++++
 5 files changed, 225 insertions(+), 31 deletions(-)
include/linux/shmem_fs.h +3 -0
index 0b273a7b9f01..668b6add3b8f 100644
@@ -108,7 +108,10 @@ extern void shmem_unlock_mapping(struct address_space *mapping);
 extern struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
 					pgoff_t index, gfp_t gfp_mask);
 extern void shmem_truncate_range(struct inode *inode, loff_t start, loff_t end);
+
+#ifndef CONFIG_VIRTUAL_SWAP
 int shmem_unuse(unsigned int type);
+#endif
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
 unsigned long shmem_allowable_huge_orders(struct inode *inode,
include/linux/swap.h +1 -0
index c3a10c952116..177f6640a026 100644
@@ -764,6 +764,7 @@ void vswap_store_folio(swp_entry_t entry, struct folio *folio);
 void swap_zeromap_folio_set(struct folio *folio);
 void vswap_assoc_zswap(swp_entry_t entry, struct zswap_entry *zswap_entry);
 bool vswap_can_swapin_thp(swp_entry_t entry, int nr);
+void vswap_swapoff(swp_entry_t entry, struct folio *folio, swp_slot_t slot);
 
 static inline bool trylock_swapoff(swp_entry_t entry,
 				struct swap_info_struct **si)
mm/shmem.c +2 -0
index 609971a2b365..fa792769e422 100644
@@ -1380,6 +1380,7 @@ static void shmem_evict_inode(struct inode *inode)
 #endif
 }
 
+#ifndef CONFIG_VIRTUAL_SWAP
 static int shmem_find_swap_entries(struct address_space *mapping,
 				   pgoff_t start, struct folio_batch *fbatch,
 				   pgoff_t *indices, unsigned int type)
@@ -1525,6 +1526,7 @@ int shmem_unuse(unsigned int type)
 
 	return error;
 }
+#endif /* CONFIG_VIRTUAL_SWAP */
 
 /*
  * Move the page from the page cache to the swap cache.
mm/swapfile.c +158 -31

207 lines not on this page · raw message

mm/vswap.c +61 -0

67 lines not on this page · raw message

Signature · 1 line
2.47.1
author maintainer
#23 lore raw

RFC PATCH 14/14 zswap: do not start zswap shrinker if there is no physical swap slots

In reply to Nhat Pham

When swap is virtualized, we no longer pre-allocate a slot on swapfile for each zswap entry. Do not start the zswap shrinker if there is no physical swap slots available.

---
 mm/zswap.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/zswap.c +8 -0
index 15429825d667..f2f412cc1911 100644
@@ -1277,6 +1277,14 @@ static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
 	if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
 		return 0;
 
+	/*
+	 * When swap is virtualized, we do not have any swap slots on swapfile
+	 * preallocated for zswap objects. If there is no slot available, we
+	 * cannot writeback and should just bail out here.
+	 */
+	if (IS_ENABLED(CONFIG_VIRTUAL_SWAP) && !get_nr_swap_pages())
+		return 0;
+
 	/*
 	 * The shrinker resumes swap writeback, which will enter block
 	 * and may enter fs. XXX: Harmonize with vmscan.c __GFP_FS
Signature · 1 line
2.47.1
#24 lore raw
In reply to Nhat Pham
Quoted 61 lines · Nhat Pham

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

2. Kernel building: zswap enabled, 52 workers (one per processor), memory.max = 3G.

Baseline:
real: 183.55s
user: 5119.01s
sys: 655.16s

New Design:
real: mean: 184.5s
user: mean: 5117.4s
sys: mean: 695.23s

Quoted 5 lines

New Design (Static Partition)
real: 183.95s
user: 5119.29s
sys: 664.24s

Hi Nhat,

Thanks for the patches! I have glanced over a couple of them, but this was the main question that came to my mind.

Just wanted to check if you had a look at the memory regression during these benchmarks?

Also what is sizeof(swp_desc)? Maybe we can calculate the memory overhead as sizeof(swp_desc) * swap size/PAGE_SIZE?

For a 64G swap that is filled with private anon pages, the overhead in MB might be (sizeof(swp_desc) in bytes * 16M) - 16M (zerobitmap) - 16M*8 (swap map)?

This looks like a sizeable memory regression?

Thanks,
Usama

maintainer
#4 lore raw

Re: [RFC PATCH 03/14] mm: swap: add a separate type for physical swap slots

In reply to Nhat Pham
Quoted 18 lines · Nhat Pham

In preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates:

1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type.

from:

2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type.

The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g). We also take this opportunity to re-arrange the header files (include/linux/swap.h and swapops.h), grouping the swap API into the following categories:

Quoted 7 lines

1. Virtual swap API (i.e functions on swp_entry_t type).

2. Swap cache API (mm/swap_state.c)

3. Swap slot cache API (mm/swap_slots.c)

4. Physical swap slots and device API (mm/swapfile.c).

This all makes sense.

However,

Quoted 29 lines
include/linux/swap.h +6 -17
@@ -483,50 +503,37 @@ static inline long get_nr_swap_pages(void)
 	return atomic_long_read(&nr_swap_pages);
 }
 
-extern void si_swapinfo(struct sysinfo *);
-swp_entry_t folio_alloc_swap(struct folio *folio);
-bool folio_free_swap(struct folio *folio);
-void put_swap_folio(struct folio *folio, swp_entry_t entry);
-extern swp_entry_t get_swap_page_of_type(int);
-extern int get_swap_pages(int n, swp_entry_t swp_entries[], int order);
-extern int add_swap_count_continuation(swp_entry_t, gfp_t);
-extern void swap_shmem_alloc(swp_entry_t, int);
-extern int swap_duplicate(swp_entry_t);
-extern int swapcache_prepare(swp_entry_t entry, int nr);
-extern void swap_free_nr(swp_entry_t entry, int nr_pages);
-extern void swapcache_free_entries(swp_entry_t *entries, int n);
-extern void free_swap_and_cache_nr(swp_entry_t entry, int nr);
+void si_swapinfo(struct sysinfo *);
+swp_slot_t swap_slot_alloc_of_type(int);
+int swap_slot_alloc(int n, swp_slot_t swp_slots[], int order);
+void swap_slot_free_nr(swp_slot_t slot, int nr_pages);
+void swap_slot_cache_free_slots(swp_slot_t *slots, int n);
 int swap_type_of(dev_t device, sector_t offset);
+sector_t swapdev_block(int, pgoff_t);
 int find_first_swap(dev_t *device);
-extern unsigned int count_swap_pages(int, int);
-extern sector_t swapdev_block(int, pgoff_t);
-extern int __swap_count(swp_entry_t entry);
-extern int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry);

include/linux/swap.h static inline long get_nr_swap_pages(void) · line 518

Quoted 10 lines
include/linux/swap.h +3 -5
-extern int swp_swapcount(swp_entry_t entry);
-struct swap_info_struct *swp_swap_info(swp_entry_t entry);
+unsigned int count_swap_pages(int, int);
+struct swap_info_struct *swap_slot_swap_info(swp_slot_t slot);
 struct backing_dev_info;
-extern int init_swap_address_space(unsigned int type, unsigned long nr_pages);
-extern void exit_swap_address_space(unsigned int type);
-extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
+struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot_t slot);
 sector_t swap_folio_sector(struct folio *folio);

this is difficult to review.

Can you please split out:

1. Code moves / cut-and-paste

2. Renames

3. New code

into three separate steps

maintainer
#11 lore raw

Re: [RFC PATCH 04/14] mm: swap: swap cache support for virtualized swap

In reply to Nhat Pham
Quoted 47 lines · Nhat Pham

Currently, the swap cache code assumes that the swap space is of a fixed size. The virtual swap space is dynamically sized, so the existing partitioning code cannot be easily reused. A dynamic partitioning is planned, but for now keep the design simple and just use a flat swapcache for vswap.

Since the vswap's implementation has begun to diverge from the old implementation, we also introduce a new build config (CONFIG_VIRTUAL_SWAP). Users who do not select this config will get the old implementation, with no behavioral change.

---
 mm/Kconfig      | 13 ++++++++++
 mm/swap.h       | 22 ++++++++++------
 mm/swap_state.c | 68 +++++++++++++++++++++++++++++++++++++++++--------
 3 files changed, 85 insertions(+), 18 deletions(-)
mm/Kconfig +13 -0
index 1b501db06417..1a6acdb64333 100644
@@ -22,6 +22,19 @@ menuconfig SWAP
 	  used to provide more virtual memory than the actual RAM present
 	  in your computer.  If unsure say Y.
 
+config VIRTUAL_SWAP
+	bool "Swap space virtualization"
+	depends on SWAP
+	default n
+	help
+		When this is selected, the kernel is built with the new swap
+		design. This will allow us to decouple the swap backends
+		(zswap, on-disk swapfile, etc.), and save disk space when we
+		use zswap (or the zero-filled swap page optimization).
+
+		There might be more lock contentions with heavy swap use, since
+		the swap cache is no longer range partitioned.
+
 config ZSWAP
 	bool "Compressed cache for swap pages"
 	depends on SWAP
mm/swap.h +0 -0
index d5f8effa8015..06e20b1d79c4 100644

mm/swap.h void swap_write_unplug(struct swap_iocb *sio); · line 29

Quoted 10 lines
mm/swap.h +5 -2
@@ -22,22 +22,27 @@ void swap_write_unplug(struct swap_iocb *sio);
 int swap_writepage(struct page *page, struct writeback_control *wbc);
 void __swap_writepage(struct folio *folio, struct writeback_control *wbc);
 
-/* linux/mm/swap_state.c */
-/* One swap address space for each 64M swap space */
+/* Return the swap device position of the swap slot. */
+static inline loff_t swap_slot_pos(swp_slot_t slot)
+{
+	return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT;
+}

In the same vein as the previous email, please avoid mixing moves, renames and new code as much as possible. This makes it quite hard to follow what's going on.

I think it would be better if you structure the series as follows:

1. Prep patches. Separate patches for moves, renames, new code.

3. mm: vswap
- config VIRTUAL_SWAP
- mm/vswap.c with skeleton data structures, init/exit, Makefile hookup

4. (temporarily) flatten existing address spaces

IMO you can do the swapcache and zswap in one patch

5+. conversion patches

Grow mm/vswap.c as you add discrete components like the descriptor allocator, swapoff locking, the swap_cgroup tracker etc.

You're mostly doing this part already. But try to order them by complexity and on a "core to periphery" gradient. I.e. swapoff locking should probably come before cgroup stuff.

Insert move and rename patches at points where they make the most sense. I.e. if they can be understood in the current upstream code already, put them with step 1 prep patches. If you find a move or a rename can only be understood in the context of one of the components, put them in a prep patch right before that one.

Quoted 14 lines
mm/swap.h +10 -0
@@ -260,6 +269,28 @@ void delete_from_swap_cache(struct folio *folio)
 	folio_ref_sub(folio, folio_nr_pages(folio));
 }
 
+#ifdef CONFIG_VIRTUAL_SWAP
+void clear_shadow_from_swap_cache(int type, unsigned long begin,
+				unsigned long end)
+{
+	swp_slot_t slot = swp_slot(type, begin);
+	swp_entry_t entry = swp_slot_to_swp_entry(slot);
+	unsigned long index = swap_cache_index(entry);
+	struct address_space *address_space = swap_address_space(entry);
+	void *old;
+	XA_STATE(xas, &address_space->i_pages, index);

mm/swap.h void delete_from_swap_cache(struct folio *folio) · line 291

Quoted 10 lines
mm/swap.h +10 -0
+
+	xas_set_update(&xas, workingset_update_node);
+
+	xa_lock_irq(&address_space->i_pages);
+	xas_for_each(&xas, old, entry.val + end - begin) {
+		if (!xa_is_value(old))
+			continue;
+		xas_store(&xas, NULL);
+	}
+	xa_unlock_irq(&address_space->i_pages);

I don't think you need separate functions for this, init, exit etc. if you tweak the macros to resolve to one tree. The current code already works if swapfiles are smaller than SWAP_ADDRESS_SPACE_PAGES and there is only one tree, after all.

This would save a lot of duplication and keep ifdefs more confined.

author maintainer
#5 lore raw

Re: [RFC PATCH 03/14] mm: swap: add a separate type for physical swap slots

In reply to Johannes Weiner
Quoted 76 lines · Johannes Weiner
Quoted 18 lines · Nhat Pham

In preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates:

1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type.

from:

2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type.

The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g). We also take this opportunity to re-arrange the header files (include/linux/swap.h and swapops.h), grouping the swap API into the following categories:

Quoted 7 lines

1. Virtual swap API (i.e functions on swp_entry_t type).

2. Swap cache API (mm/swap_state.c)

3. Swap slot cache API (mm/swap_slots.c)

4. Physical swap slots and device API (mm/swapfile.c).

This all makes sense.

However,

Quoted 29 lines
include/linux/swap.h +6 -17
@@ -483,50 +503,37 @@ static inline long get_nr_swap_pages(void)
      return atomic_long_read(&nr_swap_pages);
 }
 
-extern void si_swapinfo(struct sysinfo *);
-swp_entry_t folio_alloc_swap(struct folio *folio);
-bool folio_free_swap(struct folio *folio);
-void put_swap_folio(struct folio *folio, swp_entry_t entry);
-extern swp_entry_t get_swap_page_of_type(int);
-extern int get_swap_pages(int n, swp_entry_t swp_entries[], int order);
-extern int add_swap_count_continuation(swp_entry_t, gfp_t);
-extern void swap_shmem_alloc(swp_entry_t, int);
-extern int swap_duplicate(swp_entry_t);
-extern int swapcache_prepare(swp_entry_t entry, int nr);
-extern void swap_free_nr(swp_entry_t entry, int nr_pages);
-extern void swapcache_free_entries(swp_entry_t *entries, int n);
-extern void free_swap_and_cache_nr(swp_entry_t entry, int nr);
+void si_swapinfo(struct sysinfo *);
+swp_slot_t swap_slot_alloc_of_type(int);
+int swap_slot_alloc(int n, swp_slot_t swp_slots[], int order);
+void swap_slot_free_nr(swp_slot_t slot, int nr_pages);
+void swap_slot_cache_free_slots(swp_slot_t *slots, int n);
 int swap_type_of(dev_t device, sector_t offset);
+sector_t swapdev_block(int, pgoff_t);
 int find_first_swap(dev_t *device);
-extern unsigned int count_swap_pages(int, int);
-extern sector_t swapdev_block(int, pgoff_t);
-extern int __swap_count(swp_entry_t entry);
-extern int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry);

include/linux/swap.h static inline long get_nr_swap_pages(void) · line 518

Quoted 10 lines
include/linux/swap.h +3 -5
-extern int swp_swapcount(swp_entry_t entry);
-struct swap_info_struct *swp_swap_info(swp_entry_t entry);
+unsigned int count_swap_pages(int, int);
+struct swap_info_struct *swap_slot_swap_info(swp_slot_t slot);
 struct backing_dev_info;
-extern int init_swap_address_space(unsigned int type, unsigned long nr_pages);
-extern void exit_swap_address_space(unsigned int type);
-extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
+struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot_t slot);
 sector_t swap_folio_sector(struct folio *folio);

this is difficult to review.

Can you please split out:

Quoted 7 lines

1. Code moves / cut-and-paste

2. Renames

3. New code

into three separate steps

Makes sense, yeah.

I will reorganize the series as follows:

1. Rearrange in the first patch (which I already did for mm/swapfile.c, but now I'll also rearrange the functions in header files as well).
2. One more patch to rename the function and add the new type.
3. The rest of the series (new API, new code, etc.).

author maintainer
#25 lore raw
In reply to Usama Arif
Quoted 71 lines · Usama Arif
Quoted 61 lines · Nhat Pham

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

2. Kernel building: zswap enabled, 52 workers (one per processor), memory.max = 3G.

Baseline:
real: 183.55s
user: 5119.01s
sys: 655.16s

New Design:
real: mean: 184.5s
user: mean: 5117.4s
sys: mean: 695.23s

Quoted 5 lines

New Design (Static Partition)
real: 183.95s
user: 5119.29s
sys: 664.24s

Quoted 7 lines

Hi Nhat,

Thanks for the patches! I have glanced over a couple of them, but this was the main question that came to my mind.

Just wanted to check if you had a look at the memory regression during these benchmarks?

Also what is sizeof(swp_desc)? Maybe we can calculate the memory overhead as sizeof(swp_desc) * swap size/PAGE_SIZE?

Yeah, it's pretty big right now (120 bytes). I haven't done any space optimization yet - I basically listed out all the required information, and add one field for each of them. A couple of optimizations I have in mind:
1. Merged swap_count and in_swapcache (suggested by Yosry).
2. Unionize the rcu field with other fields, because rcu head is only needed for the free paths (suggested by Shakeel for a different context, but should be applicable here). Or maybe just remove it and free the swap descriptors in-context.
3. The type field is really only 2 bits - might be able to squeeze it in one of the other fields as well.
4. The lock field might not be needed. I think the in_swapcache bit is already used as a form of "backing storage pinning" mechanism, which should allow pinners exclusive rights to the backing state.

etc. etc.

The code will get uglier though, so I wanna at least send out one version with everything separate for clarity sake, before optimizing them away :)

Quoted 2 lines

For a 64G swap that is filled with private anon pages, the overhead in MB might be (sizeof(swp_desc) in bytes * 16M) - 16M (zerobitmap) - 16M*8 (swap map)?

That is true. I will note, however, that in the past the overhead was static (i.e it is incurred no matter how much swap space you are using). In fact, you have to often overprovision for swap, so the overhead goes beyond what you will (ever) need.

Now the overhead is (mostly) dynamic - only incurred on demand, and reduced when you don't need it.

Quoted 6 lines

This looks like a sizeable memory regression?

Thanks,
Usama

author maintainer
#12 lore raw

Re: [RFC PATCH 04/14] mm: swap: swap cache support for virtualized swap

In reply to Johannes Weiner
Quoted 85 lines · Johannes Weiner
Quoted 47 lines · Nhat Pham

Currently, the swap cache code assumes that the swap space is of a fixed size. The virtual swap space is dynamically sized, so the existing partitioning code cannot be easily reused. A dynamic partitioning is planned, but for now keep the design simple and just use a flat swapcache for vswap.

Since the vswap's implementation has begun to diverge from the old implementation, we also introduce a new build config (CONFIG_VIRTUAL_SWAP). Users who do not select this config will get the old implementation, with no behavioral change.

---
 mm/Kconfig      | 13 ++++++++++
 mm/swap.h       | 22 ++++++++++------
 mm/swap_state.c | 68 +++++++++++++++++++++++++++++++++++++++++--------
 3 files changed, 85 insertions(+), 18 deletions(-)
mm/Kconfig +13 -0
index 1b501db06417..1a6acdb64333 100644
@@ -22,6 +22,19 @@ menuconfig SWAP
        used to provide more virtual memory than the actual RAM present
        in your computer.  If unsure say Y.
 
+config VIRTUAL_SWAP
+     bool "Swap space virtualization"
+     depends on SWAP
+     default n
+     help
+             When this is selected, the kernel is built with the new swap
+             design. This will allow us to decouple the swap backends
+             (zswap, on-disk swapfile, etc.), and save disk space when we
+             use zswap (or the zero-filled swap page optimization).
+
+             There might be more lock contentions with heavy swap use, since
+             the swap cache is no longer range partitioned.
+
 config ZSWAP
      bool "Compressed cache for swap pages"
      depends on SWAP
mm/swap.h +0 -0
index d5f8effa8015..06e20b1d79c4 100644

mm/swap.h void swap_write_unplug(struct swap_iocb *sio); · line 29

Quoted 10 lines
mm/swap.h +5 -2
@@ -22,22 +22,27 @@ void swap_write_unplug(struct swap_iocb *sio);
 int swap_writepage(struct page *page, struct writeback_control *wbc);
 void __swap_writepage(struct folio *folio, struct writeback_control *wbc);
 
-/* linux/mm/swap_state.c */
-/* One swap address space for each 64M swap space */
+/* Return the swap device position of the swap slot. */
+static inline loff_t swap_slot_pos(swp_slot_t slot)
+{
+     return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT;
+}

In the same vein as the previous email, please avoid mixing moves, renames and new code as much as possible. This makes it quite hard to follow what's going on.

I think it would be better if you structure the series as follows:

1. Prep patches. Separate patches for moves, renames, new code.

3. mm: vswap
- config VIRTUAL_SWAP
- mm/vswap.c with skeleton data structures, init/exit, Makefile hookup

4. (temporarily) flatten existing address spaces

IMO you can do the swapcache and zswap in one patch

5+. conversion patches

Grow mm/vswap.c as you add discrete components like the descriptor allocator, swapoff locking, the swap_cgroup tracker etc.

You're mostly doing this part already. But try to order them by complexity and on a "core to periphery" gradient. I.e. swapoff locking should probably come before cgroup stuff.

Quoted 5 lines

Insert move and rename patches at points where they make the most sense. I.e. if they can be understood in the current upstream code already, put them with step 1 prep patches. If you find a move or a rename can only be understood in the context of one of the components, put them in a prep patch right before that one.

Makes sense, yeah! I'll try to avoid mixing moves/renames/new code as much as I can.

Quoted 22 lines
Quoted 22 lines
mm/swap.h +17 -0
@@ -260,6 +269,28 @@ void delete_from_swap_cache(struct folio *folio)
      folio_ref_sub(folio, folio_nr_pages(folio));
 }
 
+#ifdef CONFIG_VIRTUAL_SWAP
+void clear_shadow_from_swap_cache(int type, unsigned long begin,
+                             unsigned long end)
+{
+     swp_slot_t slot = swp_slot(type, begin);
+     swp_entry_t entry = swp_slot_to_swp_entry(slot);
+     unsigned long index = swap_cache_index(entry);
+     struct address_space *address_space = swap_address_space(entry);
+     void *old;
+     XA_STATE(xas, &address_space->i_pages, index);
+
+     xas_set_update(&xas, workingset_update_node);
+
+     xa_lock_irq(&address_space->i_pages);
+     xas_for_each(&xas, old, entry.val + end - begin) {
+             if (!xa_is_value(old))
+                     continue;
Quoted 8 lines

mm/swap.h void delete_from_swap_cache(struct folio *folio) · line 291

Quoted 3 lines
mm/swap.h +3 -0
+             xas_store(&xas, NULL);
+     }
+     xa_unlock_irq(&address_space->i_pages);

I don't think you need separate functions for this, init, exit etc. if you tweak the macros to resolve to one tree. The current code already works if swapfiles are smaller than SWAP_ADDRESS_SPACE_PAGES and there is only one tree, after all.

For clear_shadow_from_swap_cache(), I think I understand what you want
- keep clear_shadow_from_swap_cache() the same for two implementations, but at caller sites, have the callers themselves determine the range in swap cache (i.e (begin, end)).

I'm a bit confused with init and exit, but I assume there is a way to do it for them as well.

I will note though, that it might increase the number of ifdefs sections (or alternatively, IS_ENABLED() checks), because these functions are called in different contexts for the two implementations:

1. init and exit are called in swapon/swapoff in the old implementation. They are called in swap initialization in the virtual swap implementation.

2. Similarly, we clear swap cache shadows when we free physical swap slots in the old implementation, and when we free virtual swap slots in the new implementation,

I think it is good actually, because it makes the difference explicit rather than implicit. Also, it helps us know exactly which code block to target when we unify the two implementations :) Just putting it out there.

Quoted 2 lines

This would save a lot of duplication and keep ifdefs more confined.

author maintainer
#13 lore raw

Re: [RFC PATCH 04/14] mm: swap: swap cache support for virtualized swap

Quoted 144 lines · Nhat Pham
Quoted 85 lines · Johannes Weiner
Quoted 47 lines · Nhat Pham

Currently, the swap cache code assumes that the swap space is of a fixed size. The virtual swap space is dynamically sized, so the existing partitioning code cannot be easily reused. A dynamic partitioning is planned, but for now keep the design simple and just use a flat swapcache for vswap.

Since the vswap's implementation has begun to diverge from the old implementation, we also introduce a new build config (CONFIG_VIRTUAL_SWAP). Users who do not select this config will get the old implementation, with no behavioral change.

---
 mm/Kconfig      | 13 ++++++++++
 mm/swap.h       | 22 ++++++++++------
 mm/swap_state.c | 68 +++++++++++++++++++++++++++++++++++++++++--------
 3 files changed, 85 insertions(+), 18 deletions(-)
mm/Kconfig +13 -0
index 1b501db06417..1a6acdb64333 100644
@@ -22,6 +22,19 @@ menuconfig SWAP
        used to provide more virtual memory than the actual RAM present
        in your computer.  If unsure say Y.
 
+config VIRTUAL_SWAP
+     bool "Swap space virtualization"
+     depends on SWAP
+     default n
+     help
+             When this is selected, the kernel is built with the new swap
+             design. This will allow us to decouple the swap backends
+             (zswap, on-disk swapfile, etc.), and save disk space when we
+             use zswap (or the zero-filled swap page optimization).
+
+             There might be more lock contentions with heavy swap use, since
+             the swap cache is no longer range partitioned.
+
 config ZSWAP
      bool "Compressed cache for swap pages"
      depends on SWAP
mm/swap.h +0 -0
index d5f8effa8015..06e20b1d79c4 100644

mm/swap.h void swap_write_unplug(struct swap_iocb *sio); · line 29

Quoted 10 lines
mm/swap.h +5 -2
@@ -22,22 +22,27 @@ void swap_write_unplug(struct swap_iocb *sio);
 int swap_writepage(struct page *page, struct writeback_control *wbc);
 void __swap_writepage(struct folio *folio, struct writeback_control *wbc);
 
-/* linux/mm/swap_state.c */
-/* One swap address space for each 64M swap space */
+/* Return the swap device position of the swap slot. */
+static inline loff_t swap_slot_pos(swp_slot_t slot)
+{
+     return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT;
+}

In the same vein as the previous email, please avoid mixing moves, renames and new code as much as possible. This makes it quite hard to follow what's going on.

I think it would be better if you structure the series as follows:

1. Prep patches. Separate patches for moves, renames, new code.

3. mm: vswap
- config VIRTUAL_SWAP
- mm/vswap.c with skeleton data structures, init/exit, Makefile hookup

4. (temporarily) flatten existing address spaces

IMO you can do the swapcache and zswap in one patch

5+. conversion patches

Grow mm/vswap.c as you add discrete components like the descriptor allocator, swapoff locking, the swap_cgroup tracker etc.

You're mostly doing this part already. But try to order them by complexity and on a "core to periphery" gradient. I.e. swapoff locking should probably come before cgroup stuff.

Quoted 5 lines

Insert move and rename patches at points where they make the most sense. I.e. if they can be understood in the current upstream code already, put them with step 1 prep patches. If you find a move or a rename can only be understood in the context of one of the components, put them in a prep patch right before that one.

Makes sense, yeah! I'll try to avoid mixing moves/renames/new code as much as I can.

Quoted 22 lines
Quoted 22 lines
mm/swap.h +17 -0
@@ -260,6 +269,28 @@ void delete_from_swap_cache(struct folio *folio)
      folio_ref_sub(folio, folio_nr_pages(folio));
 }
 
+#ifdef CONFIG_VIRTUAL_SWAP
+void clear_shadow_from_swap_cache(int type, unsigned long begin,
+                             unsigned long end)
+{
+     swp_slot_t slot = swp_slot(type, begin);
+     swp_entry_t entry = swp_slot_to_swp_entry(slot);
+     unsigned long index = swap_cache_index(entry);
+     struct address_space *address_space = swap_address_space(entry);
+     void *old;
+     XA_STATE(xas, &address_space->i_pages, index);
+
+     xas_set_update(&xas, workingset_update_node);
+
+     xa_lock_irq(&address_space->i_pages);
+     xas_for_each(&xas, old, entry.val + end - begin) {
+             if (!xa_is_value(old))
+                     continue;
Quoted 8 lines

mm/swap.h void delete_from_swap_cache(struct folio *folio) · line 291

Quoted 3 lines
mm/swap.h +3 -0
+             xas_store(&xas, NULL);
+     }
+     xa_unlock_irq(&address_space->i_pages);

I don't think you need separate functions for this, init, exit etc. if you tweak the macros to resolve to one tree. The current code already works if swapfiles are smaller than SWAP_ADDRESS_SPACE_PAGES and there is only one tree, after all.

For clear_shadow_from_swap_cache(), I think I understand what you want
- keep clear_shadow_from_swap_cache() the same for two implementations, but at caller sites, have the callers themselves determine the range in swap cache (i.e (begin, end)).

I'm a bit confused with init and exit, but I assume there is a way to do it for them as well.

I will note though, that it might increase the number of ifdefs sections (or alternatively, IS_ENABLED() checks), because these functions are called in different contexts for the two implementations:

1. init and exit are called in swapon/swapoff in the old implementation. They are called in swap initialization in the virtual swap implementation.

Quoted 8 lines

2. Similarly, we clear swap cache shadows when we free physical swap slots in the old implementation, and when we free virtual swap slots in the new implementation,

I think it is good actually, because it makes the difference explicit rather than implicit. Also, it helps us know exactly which code block to target when we unify the two implementations :) Just putting it out there.

Actually, I think I was confused.

At this stage, we have no real difference in the implementations yet - it's purely single tree vs multiple trees. So you're right - we shouldn't even need two implementations of the code...

I'll fix this.

Quoted 3 lines
Quoted 3 lines

This would save a lot of duplication and keep ifdefs more confined.

maintainer
#26 lore raw
In reply to Usama Arif
Quoted 74 lines · Usama Arif
Quoted 61 lines · Nhat Pham

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

2. Kernel building: zswap enabled, 52 workers (one per processor), memory.max = 3G.

Baseline:
real: 183.55s
user: 5119.01s
sys: 655.16s

New Design:
real: mean: 184.5s
user: mean: 5117.4s
sys: mean: 695.23s

Quoted 5 lines

New Design (Static Partition)
real: 183.95s
user: 5119.29s
sys: 664.24s

Hi Nhat,

Thanks for the patches! I have glanced over a couple of them, but this was the main question that came to my mind.

Quoted 7 lines

Just wanted to check if you had a look at the memory regression during these benchmarks?

Also what is sizeof(swp_desc)? Maybe we can calculate the memory overhead as sizeof(swp_desc) * swap size/PAGE_SIZE?

For a 64G swap that is filled with private anon pages, the overhead in MB might be (sizeof(swp_desc) in bytes * 16M) - 16M (zerobitmap) - 16M*8 (swap map)?

This looks like a sizeable memory regression?

One thing to keep in mind is that the swap descriptor is currently blatantly explicit, and many conversions and optimizations have not been done yet. There are some tradeoffs made here regarding code reviewability, but I agree it makes it hard to see what this would look like fully realized.

I think what's really missing is an analysis of what the goal is and what the overhead will be then.

The swapin path currently consults the swapcache, then the zeromap, then zswap, and finally the backend. The external swap_cgroup array is consulted to determine who to charge for the new page.

With vswap, the descriptor is looked up and resolves to a type, location, cgroup ownership, a refcount. This means it replaces the swapcache, the zeromap, the cgroup map, and largely the swap_map.

Nhat was not quite sure yet if the swap_map can be a single bit per entry or two bits to represent bad slots. In any case, it's a large reduction in static swap space overhead, and eliminates the tricky swap count continuation code.

#29 lore raw
In reply to Nhat Pham
Quoted 74 lines · Nhat Pham

This RFC implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).

The code attached to this RFC is purely a prototype. It is not 100% merge-ready (see section VI for future work). I do, however, want to show people this prototype/RFC, including all the bells and whistles and a couple of actual use cases, so that folks can see what the end results will look like, and give me early feedback :)

I. Motivation

Currently, when an anon page is swapped out, a slot in a backing swap device is allocated and stored in the page table entries that refer to the original page. This slot is also used as the "key" to find the swapped out content, as well as the index to swap data structures, such as the swap cache, or the swap cgroup mapping. Tying a swap entry to its backing slot in this way is performant and efficient when swap is purely just disk space, and swapoff is rare.

However, the advent of many swap optimizations has exposed major drawbacks of this design. The first problem is that we occupy a physical slot in the swap space, even for pages that are NEVER expected to hit the disk: pages compressed and stored in the zswap pool, zero-filled pages, or pages rejected by both of these optimizations when zswap writeback is disabled. This is the arguably central shortcoming of zswap:
* In deployments when no disk space can be afforded for swap (such as mobile and embedded devices), users cannot adopt zswap, and are forced to use zram. This is confusing for users, and creates extra burdens for developers, having to develop and maintain similar features for two separate swap backends (writeback, cgroup charging, THP support, etc.). For instance, see the discussion in [4].
* Resource-wise, it is hugely wasteful in terms of disk usage, and limits the memory saving potentials of these optimizations by the static size of the swapfile, especially in high memory systems that can have up to terabytes worth of memory. It also creates significant challenges for users who rely on swap utilization as an early OOM signal.

Another motivation for a swap redesign is to simplify swapoff, which is complicated and expensive in the current design. Tight coupling between a swap entry and its backing storage means that it requires a whole page table walk to update all the page table entries that refer to this swap entry, as well as updating all the associated swap data structures (swap cache, etc.).

II. High Level Design Overview

To fix the aforementioned issues, we need an abstraction that separates a swap entry from its physical backing storage. IOW, we need to “virtualize” the swap space: swap clients will work with a dynamically allocated virtual swap slot, storing it in page table entries, and using it to index into various swap-related data structures. The backing storage is decoupled from the virtual swap slot, and the newly introduced layer will “resolve” the virtual swap slot to the actual storage. This layer also manages other metadata of the swap entry, such as its lifetime information (swap count), via a dynamically allocated per-swap-entry descriptor:

struct swp_desc {
        swp_entry_t vswap;
        union {
                swp_slot_t slot;
                struct folio *folio;
                struct zswap_entry *zswap_entry;
        };
        struct rcu_head rcu;

        rwlock_t lock;
Quoted 8 lines
        enum swap_type type;

        atomic_t memcgid;

        atomic_t in_swapcache;
        struct kref refcnt;
        atomic_t swap_count;
};

Thanks for sharing the code, my initial idea after the discussion at LSFMM is that there is a simple way to combine this with the "swap table" [1] design of mine to solve the performance issue of this
series: just store the pointer of this struct in the swap table. It's a bruteforce and glue like solution but the contention issue will be gone.

Of course it's not a good approach, ideally the data structure can be simplified to an entry type in the swap table. The swap table series handles locking and synchronizations using either cluster lock (reusing swap allocator and existing swap logics) or folio lock (kind of like page cache). So many parts can be much simplified, I think it will be at most ~32 bytes per page with a virtual device (including the intermediate pointers).Will require quite some work though.

The good side with that approach is we will have a much lower memory overhead and even better performance. And the virtual space part will be optional, for non virtual setup the memory consumption will be only 8 bytes per page and also dynamically allocated, as discussed at LSFMM.

So sorry that I still have a few parts undone, looking forward to posting in about one week, eg. After this weekend it goes well. I'll also try to check your series first to see how these can be collaborated better.

A draft version is available here though, just in case anyone is really anxious to see the code, I wouldn't recommend spend much effort check it though as it may change rapidly:
https://github.com/ryncsn/linux/tree/kasong/devel/swap-unification

But the good news is the total LOC should be reduced, or at least won't increase much, as it will unify a lot of swap infrastructures. So things might be easier to implement after that.

[1] https://lore.kernel.org/linux-mm/CAMgjq7DHFYWhm+Z0C5tR2U2a-N_mtmgB4+idD2S+-1438u-wWw@mail.gmail.com/T/

author maintainer
#27 lore raw
In reply to Johannes Weiner
Quoted 97 lines · Johannes Weiner
Quoted 74 lines · Usama Arif
Quoted 61 lines · Nhat Pham

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

2. Kernel building: zswap enabled, 52 workers (one per processor), memory.max = 3G.

Baseline:
real: 183.55s
user: 5119.01s
sys: 655.16s

New Design:
real: mean: 184.5s
user: mean: 5117.4s
sys: mean: 695.23s

Quoted 5 lines

New Design (Static Partition)
real: 183.95s
user: 5119.29s
sys: 664.24s

Hi Nhat,

Thanks for the patches! I have glanced over a couple of them, but this was the main question that came to my mind.

Quoted 7 lines

Just wanted to check if you had a look at the memory regression during these benchmarks?

Also what is sizeof(swp_desc)? Maybe we can calculate the memory overhead as sizeof(swp_desc) * swap size/PAGE_SIZE?

For a 64G swap that is filled with private anon pages, the overhead in MB might be (sizeof(swp_desc) in bytes * 16M) - 16M (zerobitmap) - 16M*8 (swap map)?

This looks like a sizeable memory regression?

One thing to keep in mind is that the swap descriptor is currently blatantly explicit, and many conversions and optimizations have not been done yet. There are some tradeoffs made here regarding code reviewability, but I agree it makes it hard to see what this would look like fully realized.

I think what's really missing is an analysis of what the goal is and what the overhead will be then.

The swapin path currently consults the swapcache, then the zeromap, then zswap, and finally the backend. The external swap_cgroup array is consulted to determine who to charge for the new page.

Quoted 8 lines

With vswap, the descriptor is looked up and resolves to a type, location, cgroup ownership, a refcount. This means it replaces the swapcache, the zeromap, the cgroup map, and largely the swap_map.

Nhat was not quite sure yet if the swap_map can be a single bit per entry or two bits to represent bad slots. In any case, it's a large reduction in static swap space overhead, and eliminates the tricky swap count continuation code.

You're right. I haven't touched the swapfile swap map and the zeromap bitmap at all, primarily because it's non-functional change (optimization only). It also adds more ifdefs to the final codebase :)

In the next version, I can tag on one patch to:

1. remove zeromap bitmap. This one is pretty much straightforward - we're not using it at all.

2. Swap map reduction. I'm like 70% sure we don't need SWAP_MAP_BAD state. With the vswap reverse map and the swapfile inuse counters, we should be able to convert the swapmap into a pure bitmap. If we can't, then it's 2 bits per physical swapfiles.

author maintainer
#28 lore raw
Quoted 8 lines · Nhat Pham

You're right. I haven't touched the swapfile swap map and the zeromap bitmap at all, primarily because it's non-functional change (optimization only). It also adds more ifdefs to the final codebase :)

In the next version, I can tag on one patch to:

Quoted 7 lines

1. remove zeromap bitmap. This one is pretty much straightforward - we're not using it at all.

2. Swap map reduction. I'm like 70% sure we don't need SWAP_MAP_BAD state. With the vswap reverse map and the swapfile inuse counters, we should be able to convert the swapmap into a pure bitmap. If we can't, then it's 2 bits per physical swapfiles.

s/physical swapfiles/physical swap slot (3 states - unallocated, allocated, bad slot. the latter two might be mergeable).

author maintainer
#30 lore raw
In reply to Kairui Song
Quoted 8 lines · Kairui Song

Thanks for sharing the code, my initial idea after the discussion at LSFMM is that there is a simple way to combine this with the "swap table" [1] design of mine to solve the performance issue of this
series: just store the pointer of this struct in the swap table. It's a bruteforce and glue like solution but the contention issue will be gone.

Was waiting for your submission, but I figured I should send what I had out first for immediate feedback :)

Johannes actually proposed something similar to your physical swap allocator for the virtual swap slots allocation logic, to solve our lock contention problem. My apologies - I should have name-dropped you in the RFC cover as well (the cover was a bit outdated, and I haven't updated the newest developments that came from the LSFMMBPF conversation in the cover letter).

Quoted 9 lines

Of course it's not a good approach, ideally the data structure can be simplified to an entry type in the swap table. The swap table series handles locking and synchronizations using either cluster lock (reusing swap allocator and existing swap logics) or folio lock (kind of like page cache). So many parts can be much simplified, I think it will be at most ~32 bytes per page with a virtual device (including the intermediate pointers).Will require quite some work though.

Quoted 5 lines

The good side with that approach is we will have a much lower memory overhead and even better performance. And the virtual space part will be optional, for non virtual setup the memory consumption will be only 8 bytes per page and also dynamically allocated, as discussed at LSFMM.

I think one problem with your design, which I alluded to at the conference, is that it doesn't quite work for our requirements - namely the separation of zswap from its underlying backend.

All the metadata HAVE to live at the virtual layer. For once, we are duplicating the logic if we push this to the backend.

But more than that, there are lifetime operations that HAVE to be backend-agnostic. For instance, on the swap out path, when we unmap the page from the page table, we do swap_duplicate() (i.,e increasing the swap count/reference count of the swap entries). At that point, we have not (and cannot) make a decision regarding the backend storage yet, and thus does not have any backend-specific places to hold this piece of information. If we couple all the backends then yeah sure we can store it at the physical swapfile level, but that defeats the purpose of swap virtualization :)

Quoted 5 lines

So sorry that I still have a few parts undone, looking forward to posting in about one week, eg. After this weekend it goes well. I'll also try to check your series first to see how these can be collaborated better.

Of course, I'm not against collaboration :) As I mentioned earlier, we need more work on the allocation part, which your physical swapfile allocator should either work, or serve as the inspiration for.

Cheers,
Nhat

#31 lore raw
Quoted 43 lines · Nhat Pham
Quoted 8 lines · Kairui Song

Thanks for sharing the code, my initial idea after the discussion at LSFMM is that there is a simple way to combine this with the "swap table" [1] design of mine to solve the performance issue of this
series: just store the pointer of this struct in the swap table. It's a bruteforce and glue like solution but the contention issue will be gone.

Was waiting for your submission, but I figured I should send what I had out first for immediate feedback :)

Johannes actually proposed something similar to your physical swap allocator for the virtual swap slots allocation logic, to solve our lock contention problem. My apologies - I should have name-dropped you in the RFC cover as well (the cover was a bit outdated, and I haven't updated the newest developments that came from the LSFMMBPF conversation in the cover letter).

Quoted 9 lines

Of course it's not a good approach, ideally the data structure can be simplified to an entry type in the swap table. The swap table series handles locking and synchronizations using either cluster lock (reusing swap allocator and existing swap logics) or folio lock (kind of like page cache). So many parts can be much simplified, I think it will be at most ~32 bytes per page with a virtual device (including the intermediate pointers).Will require quite some work though.

Quoted 5 lines

The good side with that approach is we will have a much lower memory overhead and even better performance. And the virtual space part will be optional, for non virtual setup the memory consumption will be only 8 bytes per page and also dynamically allocated, as discussed at LSFMM.

I think one problem with your design, which I alluded to at the conference, is that it doesn't quite work for our requirements - namely the separation of zswap from its underlying backend.

All the metadata HAVE to live at the virtual layer. For once, we are duplicating the logic if we push this to the backend.

Quoted 9 lines

But more than that, there are lifetime operations that HAVE to be backend-agnostic. For instance, on the swap out path, when we unmap the page from the page table, we do swap_duplicate() (i.,e increasing the swap count/reference count of the swap entries). At that point, we have not (and cannot) make a decision regarding the backend storage yet, and thus does not have any backend-specific places to hold this piece of information. If we couple all the backends then yeah sure we can store it at the physical swapfile level, but that defeats the purpose of swap virtualization :)

Ah, now I get why you have to store the data in the virtual layer.

I was thinking that doing it in the physical layer will make it easier to reuse what swap already has. But if you need to be completely backend-agnostic, then just keep it in the virtual layer. Seems not a foundunmentail issue, it could be worked out in some way I think. eg. using another table type. I'll check if that would work after I've done the initial parts.

Quoted 13 lines
Quoted 6 lines

So sorry that I still have a few parts undone, looking forward to posting in about one week, eg. After this weekend it goes well. I'll also try to check your series first to see how these can be collaborated better.

Of course, I'm not against collaboration :) As I mentioned earlier, we need more work on the allocation part, which your physical swapfile allocator should either work, or serve as the inspiration for.

Cheers,
Nhat

#6 lore raw

Re: [RFC PATCH 03/14] mm: swap: add a separate type for physical swap slots

In reply to Johannes Weiner
Quoted 75 lines · Johannes Weiner
Quoted 18 lines · Nhat Pham

In preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates:

1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type.

from:

2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type.

The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g). We also take this opportunity to re-arrange the header files (include/linux/swap.h and swapops.h), grouping the swap API into the following categories:

Quoted 7 lines

1. Virtual swap API (i.e functions on swp_entry_t type).

2. Swap cache API (mm/swap_state.c)

3. Swap slot cache API (mm/swap_slots.c)

4. Physical swap slots and device API (mm/swapfile.c).

This all makes sense.

However,

Quoted 29 lines
include/linux/swap.h +6 -17
@@ -483,50 +503,37 @@ static inline long get_nr_swap_pages(void)
 	return atomic_long_read(&nr_swap_pages);
 }
 
-extern void si_swapinfo(struct sysinfo *);
-swp_entry_t folio_alloc_swap(struct folio *folio);
-bool folio_free_swap(struct folio *folio);
-void put_swap_folio(struct folio *folio, swp_entry_t entry);
-extern swp_entry_t get_swap_page_of_type(int);
-extern int get_swap_pages(int n, swp_entry_t swp_entries[], int order);
-extern int add_swap_count_continuation(swp_entry_t, gfp_t);
-extern void swap_shmem_alloc(swp_entry_t, int);
-extern int swap_duplicate(swp_entry_t);
-extern int swapcache_prepare(swp_entry_t entry, int nr);
-extern void swap_free_nr(swp_entry_t entry, int nr_pages);
-extern void swapcache_free_entries(swp_entry_t *entries, int n);
-extern void free_swap_and_cache_nr(swp_entry_t entry, int nr);
+void si_swapinfo(struct sysinfo *);
+swp_slot_t swap_slot_alloc_of_type(int);
+int swap_slot_alloc(int n, swp_slot_t swp_slots[], int order);
+void swap_slot_free_nr(swp_slot_t slot, int nr_pages);
+void swap_slot_cache_free_slots(swp_slot_t *slots, int n);
 int swap_type_of(dev_t device, sector_t offset);
+sector_t swapdev_block(int, pgoff_t);
 int find_first_swap(dev_t *device);
-extern unsigned int count_swap_pages(int, int);
-extern sector_t swapdev_block(int, pgoff_t);
-extern int __swap_count(swp_entry_t entry);
-extern int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry);

include/linux/swap.h static inline long get_nr_swap_pages(void) · line 518

Quoted 10 lines
include/linux/swap.h +3 -5
-extern int swp_swapcount(swp_entry_t entry);
-struct swap_info_struct *swp_swap_info(swp_entry_t entry);
+unsigned int count_swap_pages(int, int);
+struct swap_info_struct *swap_slot_swap_info(swp_slot_t slot);
 struct backing_dev_info;
-extern int init_swap_address_space(unsigned int type, unsigned long nr_pages);
-extern void exit_swap_address_space(unsigned int type);
-extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
+struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot_t slot);
 sector_t swap_folio_sector(struct folio *folio);

this is difficult to review.

Can you please split out:

Quoted 7 lines

1. Code moves / cut-and-paste

2. Renames

3. New code

into three separate steps

+1, I agree with the fundamental change (and is something that I attempted before), but it's really difficult to parse :)

Also, weren't the swap slots scheduled for removal or is my brain making stuff up again?

#32 lore raw
In reply to Kairui Song
Quoted 54 lines · Kairui Song
Quoted 43 lines · Nhat Pham
Quoted 8 lines · Kairui Song

Thanks for sharing the code, my initial idea after the discussion at LSFMM is that there is a simple way to combine this with the "swap table" [1] design of mine to solve the performance issue of this
series: just store the pointer of this struct in the swap table. It's a bruteforce and glue like solution but the contention issue will be gone.

Was waiting for your submission, but I figured I should send what I had out first for immediate feedback :)

Johannes actually proposed something similar to your physical swap allocator for the virtual swap slots allocation logic, to solve our lock contention problem. My apologies - I should have name-dropped you in the RFC cover as well (the cover was a bit outdated, and I haven't updated the newest developments that came from the LSFMMBPF conversation in the cover letter).

Quoted 9 lines

Of course it's not a good approach, ideally the data structure can be simplified to an entry type in the swap table. The swap table series handles locking and synchronizations using either cluster lock (reusing swap allocator and existing swap logics) or folio lock (kind of like page cache). So many parts can be much simplified, I think it will be at most ~32 bytes per page with a virtual device (including the intermediate pointers).Will require quite some work though.

Quoted 5 lines

The good side with that approach is we will have a much lower memory overhead and even better performance. And the virtual space part will be optional, for non virtual setup the memory consumption will be only 8 bytes per page and also dynamically allocated, as discussed at LSFMM.

I think one problem with your design, which I alluded to at the conference, is that it doesn't quite work for our requirements - namely the separation of zswap from its underlying backend.

All the metadata HAVE to live at the virtual layer. For once, we are duplicating the logic if we push this to the backend.

Quoted 9 lines

But more than that, there are lifetime operations that HAVE to be backend-agnostic. For instance, on the swap out path, when we unmap the page from the page table, we do swap_duplicate() (i.,e increasing the swap count/reference count of the swap entries). At that point, we have not (and cannot) make a decision regarding the backend storage yet, and thus does not have any backend-specific places to hold this piece of information. If we couple all the backends then yeah sure we can store it at the physical swapfile level, but that defeats the purpose of swap virtualization :)

Quoted 8 lines

Ah, now I get why you have to store the data in the virtual layer.

I was thinking that doing it in the physical layer will make it easier to reuse what swap already has. But if you need to be completely backend-agnostic, then just keep it in the virtual layer. Seems not a foundunmentail issue, it could be worked out in some way I think. eg. using another table type. I'll check if that would work after I've done the initial parts.

Watching from the sidelines, I am happy to see Nhat's proposal materializing, and think there is definitely room for collaboration here with Kairui's. Overall, both proposals seem to be complimentary concepts, and we just need to figure out the right way to combine them :)

#33 lore raw
In reply to Nhat Pham
Quoted 73 lines · Nhat Pham

This RFC implements the virtual swap space idea, based on Yosry's proposals at LSFMMBPF 2023 (see [1], [2], [3]), as well as valuable inputs from Johannes Weiner. The same idea (with different implementation details) has been floated by Rik van Riel since at least 2011 (see [8]).

The code attached to this RFC is purely a prototype. It is not 100% merge-ready (see section VI for future work). I do, however, want to show people this prototype/RFC, including all the bells and whistles and a couple of actual use cases, so that folks can see what the end results will look like, and give me early feedback :)

I. Motivation

Currently, when an anon page is swapped out, a slot in a backing swap device is allocated and stored in the page table entries that refer to the original page. This slot is also used as the "key" to find the swapped out content, as well as the index to swap data structures, such as the swap cache, or the swap cgroup mapping. Tying a swap entry to its backing slot in this way is performant and efficient when swap is purely just disk space, and swapoff is rare.

However, the advent of many swap optimizations has exposed major drawbacks of this design. The first problem is that we occupy a physical slot in the swap space, even for pages that are NEVER expected to hit the disk: pages compressed and stored in the zswap pool, zero-filled pages, or pages rejected by both of these optimizations when zswap writeback is disabled. This is the arguably central shortcoming of zswap:
* In deployments when no disk space can be afforded for swap (such as mobile and embedded devices), users cannot adopt zswap, and are forced to use zram. This is confusing for users, and creates extra burdens for developers, having to develop and maintain similar features for two separate swap backends (writeback, cgroup charging, THP support, etc.). For instance, see the discussion in [4].
* Resource-wise, it is hugely wasteful in terms of disk usage, and limits the memory saving potentials of these optimizations by the static size of the swapfile, especially in high memory systems that can have up to terabytes worth of memory. It also creates significant challenges for users who rely on swap utilization as an early OOM signal.

Another motivation for a swap redesign is to simplify swapoff, which is complicated and expensive in the current design. Tight coupling between a swap entry and its backing storage means that it requires a whole page table walk to update all the page table entries that refer to this swap entry, as well as updating all the associated swap data structures (swap cache, etc.).

II. High Level Design Overview

To fix the aforementioned issues, we need an abstraction that separates a swap entry from its physical backing storage. IOW, we need to “virtualize” the swap space: swap clients will work with a dynamically allocated virtual swap slot, storing it in page table entries, and using it to index into various swap-related data structures. The backing storage is decoupled from the virtual swap slot, and the newly introduced layer will “resolve” the virtual swap slot to the actual storage. This layer also manages other metadata of the swap entry, such as its lifetime information (swap count), via a dynamically allocated per-swap-entry descriptor:

struct swp_desc {
	swp_entry_t vswap;
	union {
		swp_slot_t slot;
		struct folio *folio;
		struct zswap_entry *zswap_entry;
	};
	struct rcu_head rcu;

	rwlock_t lock;
Quoted 8 lines
	enum swap_type type;

	atomic_t memcgid;

	atomic_t in_swapcache;
	struct kref refcnt;
	atomic_t swap_count;
};

It's exciting to see this proposal materilizing :)

I didn't get a chance to look too closely at the code, but I have a few high-level comments.

Do we need separate refcnt and swap_count? I am aware that there are cases where we need to hold a reference to prevent the descriptor from going away, without an extra page table entry referencing the swap descriptor -- but I am wondering if we can get away by just incrementing the swap count in these cases too? Would this mess things up?

Quoted 10 lines

This design allows us to:
* Decouple zswap (and zeromapped swap entry) from backing swapfile:
simply associate the virtual swap slot with one of the supported
backends: a zswap entry, a zero-filled swap page, a slot on the swapfile, or an in-memory page .
* Simplify and optimize swapoff: we only have to fault the page in and have the virtual swap slot points to the page instead of the on-disk physical swap slot. No need to perform any page table walking.

Quoted 7 lines

Please see the attached patches for implementation details.

Note that I do not remove the old implementation for now. Users can select between the old and the new implementation via the CONFIG_VIRTUAL_SWAP build config. This will also allow us to land the new design, and iteratively optimize upon it (without having to include everything in an even more massive patch series).

I know this is easier, but honestly I'd prefer if we do an incremental replacement (if possible) rather than introducing a new implementation and slowly deprecating the old one, which historically doesn't seem to go well :P

Once the series is organized as Johannes suggested, and we have better insights into how this will be integrated with Kairui's work, it should be clearer whether it's possible to incrementally update the current implemetation rather than add a parallel implementation.

Quoted 83 lines

III. Future Use Cases

Other than decoupling swap backends and optimizing swapoff, this new design allows us to implement the following more easily and efficiently:

* Multi-tier swapping (as mentioned in [5]), with transparent transferring (promotion/demotion) of pages across tiers (see [8] and [9]). Similar to swapoff, with the old design we would need to perform the expensive page table walk.
* Swapfile compaction to alleviate fragmentation (as proposed by Ying Huang in [6]).
* Mixed backing THP swapin (see [7]): Once you have pinned down the backing store of THPs, then you can dispatch each range of subpages to appropriate swapin handle.
* Swapping a folio out with discontiguous physical swap slots (see [10])

IV. Potential Issues

Here is a couple of issues I can think of, along with some potential solutions:

1. Space overhead: we need one swap descriptor per swap entry.
* Note that this overhead is dynamic, i.e only incurred when we actually need to swap a page out.
* It can be further offset by the reduction of swap map and the elimination of zeromapped bitmap.

2. Lock contention: since the virtual swap space is dynamic/unbounded, we cannot naively range partition it anymore. This can increase lock contention on swap-related data structures (swap cache, zswap’s xarray, etc.).
* The problem is slightly alleviated by the lockless nature of the new reference counting scheme, as well as the per-entry locking for backing store information.
* Johannes suggested that I can implement a dynamic partition scheme, in which new partitions (along with associated data structures) are allocated on demand. It is one extra layer of indirection, but global locking will only be done only on partition allocation, rather than on each access. All other accesses only take local (per-partition) locks, or are completely lockless (such as partition lookup).

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

Quoted 8 lines

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

I thought there would be some improvements with the new design once the lock contention is gone, due to the colocation of all swap metadata. Do we know why this isn't the case?

Also, one missing key metric in this cover letter is disk space savings. It would be useful if you can give a realistic example about how much disk space is being provisioned and wasted today to effictively use zswap, and how much this can decrease with this design.

I believe the disk space savings are one of the main motivations so let's showcase that :)

author maintainer
#8 lore raw

Re: [RFC PATCH 03/14] mm: swap: add a separate type for physical swap slots

In reply to a message not in the archive
Quoted 83 lines · Yosry Ahmed
Quoted 81 lines · Johannes Weiner
Quoted 18 lines · Nhat Pham

In preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates:

1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type.

from:

2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type.

The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g). We also take this opportunity to re-arrange the header files (include/linux/swap.h and swapops.h), grouping the swap API into the following categories:

Quoted 7 lines

1. Virtual swap API (i.e functions on swp_entry_t type).

2. Swap cache API (mm/swap_state.c)

3. Swap slot cache API (mm/swap_slots.c)

4. Physical swap slots and device API (mm/swapfile.c).

This all makes sense.

However,

Quoted 29 lines
include/linux/swap.h +6 -17
@@ -483,50 +503,37 @@ static inline long get_nr_swap_pages(void)
    return atomic_long_read(&nr_swap_pages);
 }
 
-extern void si_swapinfo(struct sysinfo *);
-swp_entry_t folio_alloc_swap(struct folio *folio);
-bool folio_free_swap(struct folio *folio);
-void put_swap_folio(struct folio *folio, swp_entry_t entry);
-extern swp_entry_t get_swap_page_of_type(int);
-extern int get_swap_pages(int n, swp_entry_t swp_entries[], int order);
-extern int add_swap_count_continuation(swp_entry_t, gfp_t);
-extern void swap_shmem_alloc(swp_entry_t, int);
-extern int swap_duplicate(swp_entry_t);
-extern int swapcache_prepare(swp_entry_t entry, int nr);
-extern void swap_free_nr(swp_entry_t entry, int nr_pages);
-extern void swapcache_free_entries(swp_entry_t *entries, int n);
-extern void free_swap_and_cache_nr(swp_entry_t entry, int nr);
+void si_swapinfo(struct sysinfo *);
+swp_slot_t swap_slot_alloc_of_type(int);
+int swap_slot_alloc(int n, swp_slot_t swp_slots[], int order);
+void swap_slot_free_nr(swp_slot_t slot, int nr_pages);
+void swap_slot_cache_free_slots(swp_slot_t *slots, int n);
 int swap_type_of(dev_t device, sector_t offset);
+sector_t swapdev_block(int, pgoff_t);
 int find_first_swap(dev_t *device);
-extern unsigned int count_swap_pages(int, int);
-extern sector_t swapdev_block(int, pgoff_t);
-extern int __swap_count(swp_entry_t entry);
-extern int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry);

include/linux/swap.h static inline long get_nr_swap_pages(void) · line 518

Quoted 10 lines
include/linux/swap.h +3 -5
-extern int swp_swapcount(swp_entry_t entry);
-struct swap_info_struct *swp_swap_info(swp_entry_t entry);
+unsigned int count_swap_pages(int, int);
+struct swap_info_struct *swap_slot_swap_info(swp_slot_t slot);
 struct backing_dev_info;
-extern int init_swap_address_space(unsigned int type, unsigned long nr_pages);
-extern void exit_swap_address_space(unsigned int type);
-extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
+struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot_t slot);
 sector_t swap_folio_sector(struct folio *folio);

this is difficult to review.

Can you please split out:

1. Code moves / cut-and-paste

2. Renames

3. New code

Quoted 7 lines
Quoted 1 line

into three separate steps

+1, I agree with the fundamental change (and is something that I attempted before), but it's really difficult to parse :)

Also, weren't the swap slots scheduled for removal or is my brain making stuff up again?

You mean the swap slot cache? That's the one Kairui wants to remove (I think he removed a huge chunk of it already).

This "swap slot" is basically just a new type I introduced to separate the physical and virtual swap types.

Quoted 1 line
author maintainer
#35 lore raw
In reply to a message not in the archive
Quoted 4 lines · Yosry Ahmed

On Mon, Apr 07, 2025 at 04:42:01PM -0700, Nhat Pham wrote:
It's exciting to see this proposal materilizing :)

Quoted 8 lines

I didn't get a chance to look too closely at the code, but I have a few high-level comments.

Do we need separate refcnt and swap_count? I am aware that there are cases where we need to hold a reference to prevent the descriptor from going away, without an extra page table entry referencing the swap descriptor -- but I am wondering if we can get away by just incrementing the swap count in these cases too? Would this mess things up?

Actually, you're right - we might not even need a separate refcnt field at all :) Here's my original thought process:

1. We need something that keeps the virtual swap slot and its metadata data structure (the swap descriptor) valid while we work with it.

2. In the old design, this is all stored at the swap device, so we need to obtain a reference to the swap device itself.

3. In the new design, this is no longer even possible. The backend might change under us even! So the refcnting needs to be done at the virtual swap level.

3. The refcnting needs to be separate from the swap count field, because certain operations/optimizations do check for the actual swap count, and incrementing the swap count willy nilly like that might accidentally throw these off. Think readahead-induced swap reads, for example. So I need a separate refcnt field that takes into account 3
sources: PTE references (swap count), swap cache, and "ephemeral" (i.e temporary) references, that replace the role of the swap device reference in the old design.

However, I have thought more about it. I don't think I need to obtain any ephemeral reference. I do need a refcnting mechanism, but one atomic field (that stores both the swap count and swap cache pin) should suffice.

Refcnt + RCU should already guarantee the existence of the swap descriptor while I work with it. So there won't be any UAF issue, as long as I am disciplined and check if the swap descriptor still exists etc. in the virtual swap implementation, which I already am doing anyway.

This should be safe enough, even in the face of swapoff, because swapoff also relies on the same reference counting mechanism to free the virtual swap slot and its descriptor. It tries to swap_free() the virtual swap slot, as it unmaps the virtual swap slot from the page table entry, which will decrement the swap count. So we're all good on this front.

We DO need to obtain a reference to the swap device in certain places though, if we want to use it down the line for some sort of optimizations (for example, to look at its swap device flags to check if it is a SWP_SYNCHRONOUS_IO device - see do_swap_page()). But this is a separate matter.

The end result is I will reduce 4 fields:

1. swp_entry_t vswap
2. atomic_t in_swapcache
3. atomic_t swap_count
4. struct kref kref;

Into a single swap_refs field.

Quoted 19 lines
Quoted 11 lines

This design allows us to:
* Decouple zswap (and zeromapped swap entry) from backing swapfile:
simply associate the virtual swap slot with one of the supported
backends: a zswap entry, a zero-filled swap page, a slot on the swapfile, or an in-memory page .
* Simplify and optimize swapoff: we only have to fault the page in and have the virtual swap slot points to the page instead of the on-disk physical swap slot. No need to perform any page table walking.

Quoted 7 lines

Please see the attached patches for implementation details.

Note that I do not remove the old implementation for now. Users can select between the old and the new implementation via the CONFIG_VIRTUAL_SWAP build config. This will also allow us to land the new design, and iteratively optimize upon it (without having to include everything in an even more massive patch series).

Quoted 4 lines

I know this is easier, but honestly I'd prefer if we do an incremental replacement (if possible) rather than introducing a new implementation and slowly deprecating the old one, which historically doesn't seem to go well :P

I know, I know :P

Quoted 5 lines

Once the series is organized as Johannes suggested, and we have better insights into how this will be integrated with Kairui's work, it should be clearer whether it's possible to incrementally update the current implemetation rather than add a parallel implementation.

Will take a look at Kairui's work when it's available :)

Quoted 90 lines
Quoted 90 lines

III. Future Use Cases

Other than decoupling swap backends and optimizing swapoff, this new design allows us to implement the following more easily and efficiently:

* Multi-tier swapping (as mentioned in [5]), with transparent transferring (promotion/demotion) of pages across tiers (see [8] and [9]). Similar to swapoff, with the old design we would need to perform the expensive page table walk.
* Swapfile compaction to alleviate fragmentation (as proposed by Ying Huang in [6]).
* Mixed backing THP swapin (see [7]): Once you have pinned down the backing store of THPs, then you can dispatch each range of subpages to appropriate swapin handle.
* Swapping a folio out with discontiguous physical swap slots (see [10])

IV. Potential Issues

Here is a couple of issues I can think of, along with some potential solutions:

1. Space overhead: we need one swap descriptor per swap entry.
* Note that this overhead is dynamic, i.e only incurred when we actually need to swap a page out.
* It can be further offset by the reduction of swap map and the elimination of zeromapped bitmap.

2. Lock contention: since the virtual swap space is dynamic/unbounded, we cannot naively range partition it anymore. This can increase lock contention on swap-related data structures (swap cache, zswap’s xarray, etc.).
* The problem is slightly alleviated by the lockless nature of the new reference counting scheme, as well as the per-entry locking for backing store information.
* Johannes suggested that I can implement a dynamic partition scheme, in which new partitions (along with associated data structures) are allocated on demand. It is one extra layer of indirection, but global locking will only be done only on partition allocation, rather than on each access. All other accesses only take local (per-partition) locks, or are completely lockless (such as partition lookup).

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

Quoted 6 lines
Quoted 2 lines

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

I thought there would be some improvements with the new design once the lock contention is gone, due to the colocation of all swap metadata. Do we know why this isn't the case?

The lock contention is reduced on access, but increased on allocation and free step (because we have to go through a global lock now due to the loss of swap space partitioning).

Virtual swap allocation optimization will be the next step, or it can be done concurrently, if we can figure out a way to make Kairui's work compatible with this.

Quoted 8 lines

Also, one missing key metric in this cover letter is disk space savings. It would be useful if you can give a realistic example about how much disk space is being provisioned and wasted today to effictively use zswap, and how much this can decrease with this design.

I believe the disk space savings are one of the main motivations so let's showcase that :)

Will do - I'm more concerned about regressions, so I wanna throw it out there right away to get ideas/feedback.

Quoted 1 line
#9 lore raw

Re: [RFC PATCH 03/14] mm: swap: add a separate type for physical swap slots

In reply to Nhat Pham
Quoted 87 lines · Nhat Pham
Quoted 85 lines · Yosry Ahmed
Quoted 82 lines · Johannes Weiner
Quoted 18 lines · Nhat Pham

In preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates:

1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type.

from:

2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type.

The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g). We also take this opportunity to re-arrange the header files (include/linux/swap.h and swapops.h), grouping the swap API into the following categories:

Quoted 7 lines

1. Virtual swap API (i.e functions on swp_entry_t type).

2. Swap cache API (mm/swap_state.c)

3. Swap slot cache API (mm/swap_slots.c)

4. Physical swap slots and device API (mm/swapfile.c).

This all makes sense.

However,

Quoted 29 lines
include/linux/swap.h +6 -17
@@ -483,50 +503,37 @@ static inline long get_nr_swap_pages(void)
    return atomic_long_read(&nr_swap_pages);
 }
 
-extern void si_swapinfo(struct sysinfo *);
-swp_entry_t folio_alloc_swap(struct folio *folio);
-bool folio_free_swap(struct folio *folio);
-void put_swap_folio(struct folio *folio, swp_entry_t entry);
-extern swp_entry_t get_swap_page_of_type(int);
-extern int get_swap_pages(int n, swp_entry_t swp_entries[], int order);
-extern int add_swap_count_continuation(swp_entry_t, gfp_t);
-extern void swap_shmem_alloc(swp_entry_t, int);
-extern int swap_duplicate(swp_entry_t);
-extern int swapcache_prepare(swp_entry_t entry, int nr);
-extern void swap_free_nr(swp_entry_t entry, int nr_pages);
-extern void swapcache_free_entries(swp_entry_t *entries, int n);
-extern void free_swap_and_cache_nr(swp_entry_t entry, int nr);
+void si_swapinfo(struct sysinfo *);
+swp_slot_t swap_slot_alloc_of_type(int);
+int swap_slot_alloc(int n, swp_slot_t swp_slots[], int order);
+void swap_slot_free_nr(swp_slot_t slot, int nr_pages);
+void swap_slot_cache_free_slots(swp_slot_t *slots, int n);
 int swap_type_of(dev_t device, sector_t offset);
+sector_t swapdev_block(int, pgoff_t);
 int find_first_swap(dev_t *device);
-extern unsigned int count_swap_pages(int, int);
-extern sector_t swapdev_block(int, pgoff_t);
-extern int __swap_count(swp_entry_t entry);
-extern int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry);

include/linux/swap.h static inline long get_nr_swap_pages(void) · line 518

Quoted 10 lines
include/linux/swap.h +3 -5
-extern int swp_swapcount(swp_entry_t entry);
-struct swap_info_struct *swp_swap_info(swp_entry_t entry);
+unsigned int count_swap_pages(int, int);
+struct swap_info_struct *swap_slot_swap_info(swp_slot_t slot);
 struct backing_dev_info;
-extern int init_swap_address_space(unsigned int type, unsigned long nr_pages);
-extern void exit_swap_address_space(unsigned int type);
-extern struct swap_info_struct *get_swap_device(swp_entry_t entry);
+struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot_t slot);
 sector_t swap_folio_sector(struct folio *folio);

this is difficult to review.

Can you please split out:

1. Code moves / cut-and-paste

2. Renames

3. New code

into three separate steps

Quoted 8 lines
Quoted 5 lines

+1, I agree with the fundamental change (and is something that I attempted before), but it's really difficult to parse :)

Also, weren't the swap slots scheduled for removal or is my brain making stuff up again?

You mean the swap slot cache? That's the one Kairui wants to remove (I think he removed a huge chunk of it already).

Right, I wanted to remove it to simplify the code and it is already completely gone now, see 0ff67f990bd45726e0d9e91111d998e7a3595b32, it's in 6.14

And the whole HAS_CACHE pinning thing will be gone too after the swap table series if it went smoothly.

My bad, the series I promoted is still not posted yet :(, which is not as I planned... encountered several mysterious WARNs testing with the mm-unstable, some are related to swap table and recent unstable changes, so spent quite some time checking other components and revisiting the series for better debugging and sanity checks.

Good thing is there seems to be no more blocking issues now.

author maintainer
#36 lore raw
In reply to Nhat Pham
Quoted 202 lines · Nhat Pham
Quoted 4 lines · Yosry Ahmed

On Mon, Apr 07, 2025 at 04:42:01PM -0700, Nhat Pham wrote:
It's exciting to see this proposal materilizing :)

Quoted 8 lines

I didn't get a chance to look too closely at the code, but I have a few high-level comments.

Do we need separate refcnt and swap_count? I am aware that there are cases where we need to hold a reference to prevent the descriptor from going away, without an extra page table entry referencing the swap descriptor -- but I am wondering if we can get away by just incrementing the swap count in these cases too? Would this mess things up?

Actually, you're right - we might not even need a separate refcnt field at all :) Here's my original thought process:

1. We need something that keeps the virtual swap slot and its metadata data structure (the swap descriptor) valid while we work with it.

2. In the old design, this is all stored at the swap device, so we need to obtain a reference to the swap device itself.

3. In the new design, this is no longer even possible. The backend might change under us even! So the refcnting needs to be done at the virtual swap level.

3. The refcnting needs to be separate from the swap count field, because certain operations/optimizations do check for the actual swap count, and incrementing the swap count willy nilly like that might accidentally throw these off. Think readahead-induced swap reads, for example. So I need a separate refcnt field that takes into account 3
sources: PTE references (swap count), swap cache, and "ephemeral" (i.e temporary) references, that replace the role of the swap device reference in the old design.

However, I have thought more about it. I don't think I need to obtain any ephemeral reference. I do need a refcnting mechanism, but one atomic field (that stores both the swap count and swap cache pin) should suffice.

Refcnt + RCU should already guarantee the existence of the swap descriptor while I work with it. So there won't be any UAF issue, as long as I am disciplined and check if the swap descriptor still exists etc. in the virtual swap implementation, which I already am doing anyway.

This should be safe enough, even in the face of swapoff, because swapoff also relies on the same reference counting mechanism to free the virtual swap slot and its descriptor. It tries to swap_free() the virtual swap slot, as it unmaps the virtual swap slot from the page table entry, which will decrement the swap count. So we're all good on this front.

We DO need to obtain a reference to the swap device in certain places though, if we want to use it down the line for some sort of optimizations (for example, to look at its swap device flags to check if it is a SWP_SYNCHRONOUS_IO device - see do_swap_page()). But this is a separate matter.

The end result is I will reduce 4 fields:

1. swp_entry_t vswap
2. atomic_t in_swapcache
3. atomic_t swap_count
4. struct kref kref;

Into a single swap_refs field.

Quoted 19 lines
Quoted 11 lines

This design allows us to:
* Decouple zswap (and zeromapped swap entry) from backing swapfile:
simply associate the virtual swap slot with one of the supported
backends: a zswap entry, a zero-filled swap page, a slot on the swapfile, or an in-memory page .
* Simplify and optimize swapoff: we only have to fault the page in and have the virtual swap slot points to the page instead of the on-disk physical swap slot. No need to perform any page table walking.

Quoted 7 lines

Please see the attached patches for implementation details.

Note that I do not remove the old implementation for now. Users can select between the old and the new implementation via the CONFIG_VIRTUAL_SWAP build config. This will also allow us to land the new design, and iteratively optimize upon it (without having to include everything in an even more massive patch series).

Quoted 4 lines

I know this is easier, but honestly I'd prefer if we do an incremental replacement (if possible) rather than introducing a new implementation and slowly deprecating the old one, which historically doesn't seem to go well :P

I know, I know :P

Quoted 5 lines

Once the series is organized as Johannes suggested, and we have better insights into how this will be integrated with Kairui's work, it should be clearer whether it's possible to incrementally update the current implemetation rather than add a parallel implementation.

Will take a look at Kairui's work when it's available :)

Quoted 90 lines
Quoted 90 lines

III. Future Use Cases

Other than decoupling swap backends and optimizing swapoff, this new design allows us to implement the following more easily and efficiently:

* Multi-tier swapping (as mentioned in [5]), with transparent transferring (promotion/demotion) of pages across tiers (see [8] and [9]). Similar to swapoff, with the old design we would need to perform the expensive page table walk.
* Swapfile compaction to alleviate fragmentation (as proposed by Ying Huang in [6]).
* Mixed backing THP swapin (see [7]): Once you have pinned down the backing store of THPs, then you can dispatch each range of subpages to appropriate swapin handle.
* Swapping a folio out with discontiguous physical swap slots (see [10])

IV. Potential Issues

Here is a couple of issues I can think of, along with some potential solutions:

1. Space overhead: we need one swap descriptor per swap entry.
* Note that this overhead is dynamic, i.e only incurred when we actually need to swap a page out.
* It can be further offset by the reduction of swap map and the elimination of zeromapped bitmap.

2. Lock contention: since the virtual swap space is dynamic/unbounded, we cannot naively range partition it anymore. This can increase lock contention on swap-related data structures (swap cache, zswap’s xarray, etc.).
* The problem is slightly alleviated by the lockless nature of the new reference counting scheme, as well as the per-entry locking for backing store information.
* Johannes suggested that I can implement a dynamic partition scheme, in which new partitions (along with associated data structures) are allocated on demand. It is one extra layer of indirection, but global locking will only be done only on partition allocation, rather than on each access. All other accesses only take local (per-partition) locks, or are completely lockless (such as partition lookup).

V. Benchmarking

As a proof of concept, I run the prototype through some simple benchmarks:

1. usemem: 16 threads, 2G each, memory.max = 16G

I benchmarked the following usemem commands:

time usemem --init-time -w -O -s 10 -n 16 2g

Baseline:
real: 33.96s
user: 25.31s
sys: 341.09s
average throughput: 111295.45 KB/s
average free time: 2079258.68 usecs

New Design:
real: 35.87s
user: 25.15s
sys: 373.01s
average throughput: 106965.46 KB/s
average free time: 3192465.62 usecs

To root cause this regression, I ran perf on the usemem program, as well as on the following stress-ng program:

perf record -ag -e cycles -G perf_cg -- ./stress-ng/stress-ng --pageswap $(nproc) --pageswap-ops 100000

and observed the (predicted) increase in lock contention on swap cache accesses. This regression is alleviated if I put together the following hack: limit the virtual swap space to a sufficient size for the benchmark, range partition the swap-related data structures (swap cache, zswap tree, etc.) based on the limit, and distribute the allocation of virtual swap slotss among these partitions (on a per-CPU basis):

real: 34.94s
user: 25.28s
sys: 360.25s
average throughput: 108181.15 KB/s
average free time: 2680890.24 usecs

Quoted 6 lines
Quoted 2 lines

As mentioned above, I will implement proper dynamic swap range partitioning in a follow up work.

I thought there would be some improvements with the new design once the lock contention is gone, due to the colocation of all swap metadata. Do we know why this isn't the case?

Quoted 7 lines

The lock contention is reduced on access, but increased on allocation and free step (because we have to go through a global lock now due to the loss of swap space partitioning).

Virtual swap allocation optimization will be the next step, or it can be done concurrently, if we can figure out a way to make Kairui's work compatible with this.

To clarify a bit - what Kairui's proposal gives us (IIUC) is a dynamic clustered approach on swap slot allocation. It's already done at the physical level.

This is precisely what this RFC is missing. So if there is a way to combine the work, I think it will go a long way in reducing the regression.

That said, I haven't looked closely at his code yet, so I don't know how easy/hard it is to combine the efforts :)