Linux-mm Archive on lore.kernel.org
 help / color / mirror / Atom feed
From: Nhat Pham <nphamcs@gmail.com>
To: linux-mm@kvack.org, linux-kernel@vger.kernel.org
Cc: "Andrew Morton" <akpm@linux-foundation.org>,
	"Chris Li" <chrisl@kernel.org>,
	"Kairui Song" <kasong@tencent.com>,
	"Kemeng Shi" <shikemeng@huaweicloud.com>,
	"Baoquan He" <baoquan.he@linux.dev>,
	"Barry Song" <baohua@kernel.org>,
	"Youngjun Park" <youngjun.park@lge.com>,
	"Johannes Weiner" <hannes@cmpxchg.org>,
	"Yosry Ahmed" <yosry@kernel.org>,
	"Chengming Zhou" <chengming.zhou@linux.dev>,
	"Qi Zheng" <qi.zheng@linux.dev>,
	"Shakeel Butt" <shakeel.butt@linux.dev>,
	"Axel Rasmussen" <axelrasmussen@google.com>,
	"Yuanchu Xie" <yuanchu@google.com>, "Wei Xu" <weixugc@google.com>,
	"Baolin Wang" <baolin.wang@linux.alibaba.com>,
	"Michal Hocko" <mhocko@kernel.org>,
	"David Hildenbrand" <david@kernel.org>,
	"Liam R. Howlett" <liam@infradead.org>,
	"Vlastimil Babka" <vbabka@kernel.org>,
	"Mike Rapoport" <rppt@kernel.org>,
	"Hugh Dickins" <hughd@google.com>,
	"Jonathan Corbet" <corbet@lwn.net>,
	"Shuah Khan" <skhan@linuxfoundation.org>,
	"Randy Dunlap" <rdunlap@infradead.org>,
	"Roman Gushchin" <roman.gushchin@linux.dev>,
	"Muchun Song" <muchun.song@linux.dev>,
	"Arnd Bergmann" <arnd@arndb.de>,
	"Karl Mehltretter" <kmehltretter@gmail.com>,
	"Dapeng Mi" <dapeng1.mi@linux.intel.com>,
	"Marco Elver" <elver@google.com>,
	"Ethan Nelson-Moore" <enelsonmoore@gmail.com>,
	"Borislav Petkov (AMD)" <bp@alien8.de>,
	"Jeff Layton" <jlayton@kernel.org>,
	linux-doc@vger.kernel.org, cgroups@vger.kernel.org,
	"Tejun Heo" <tj@kernel.org>, "Michal Koutný" <mkoutny@suse.com>
Subject: [PATCH v7 08/20] mm/swap: support physical swap as a vswap backend
Date: Thu,  3 Dec 2026 13:59:58 -0800	[thread overview]
Message-ID: <20261203220010.1302207-9-nphamcs@gmail.com> (raw)
In-Reply-To: <20261203220010.1302207-1-nphamcs@gmail.com>

Virtual entries need physical backing when zswap rejects a folio.
Allocate physical entries while keeping the virtual entry in the PTE,
and submit I/O with the physical entry.

Record physical slots' reverse maps to their virtual entries. Preserve
existing backing on later writes and release it through the shared
physical allocator.

Register the virtual device here, after allocation, reads and physical
swapoff are ready. Add the vswap boot parameter and VSWAP_DEFAULT_ON
setting. The default is off; either setting can select enablement at boot.

Allow anonymous reclaim and cgroup admission without a physical device
when compressed storage is available. Bound the virtual reservation for
32-bit and 64-bit entry formats.

Suggested-by: Kairui Song <kasong@tencent.com>
Link: https://lore.kernel.org/all/sashiko-outbox-181078@kernel.org/
Link: https://lore.kernel.org/all/sashiko-outbox-181079@kernel.org/
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
---
 .../admin-guide/kernel-parameters.txt         |   7 +
 include/linux/memcontrol.h                    |   6 +
 include/linux/swap.h                          |  13 +
 mm/Kconfig                                    |  20 ++
 mm/memcontrol.c                               |  58 ++--
 mm/page_io.c                                  |  21 +-
 mm/shmem.c                                    |   3 +-
 mm/swap_state.c                               |   6 +-
 mm/swap_table.h                               |   7 +
 mm/swapfile.c                                 | 292 +++++++++++++++++-
 mm/util.c                                     |  13 +-
 mm/vmscan.c                                   |  14 +-
 mm/vswap.h                                    |  13 +
 mm/workingset.c                               |   2 +-
 mm/zswap.c                                    |   2 +-
 15 files changed, 432 insertions(+), 45 deletions(-)

diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index dce9b8f3ae98..68b2d751439b 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -8421,6 +8421,13 @@ Kernel parameters
 			force		- force vulnerability detection even on
 					  unaffected processors
 
+	vswap=		[MM,EARLY]
+			Route swapouts through the virtual swap layer, which
+			allows zswap and zero-filled pages to be used without
+			a physical swap device.
+			Format: { on | off }
+			Default: on if CONFIG_VSWAP_DEFAULT_ON=y, else off.
+
 	vsyscall=	[X86-64,EARLY]
 			Controls the behavior of vsyscalls (i.e. calls to
 			fixed addresses of 0xffffffffff600x00 from legacy
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index 536375a32691..e20183a9c834 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -1922,6 +1922,7 @@ static inline void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_ZSWAP)
 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg);
+bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush);
 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size);
 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size);
 bool mem_cgroup_zswap_writeback_enabled(const struct mem_cgroup *memcg);
@@ -1930,6 +1931,11 @@ static inline bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
 {
 	return true;
 }
+
+static inline bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
+{
+	return true;
+}
 static inline void obj_cgroup_charge_zswap(struct obj_cgroup *objcg,
 					   size_t size)
 {
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 26f63356da82..0c78121e2887 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -370,6 +370,8 @@ extern void __meminit kswapd_stop(int nid);
 bool current_is_kswapd(void);
 
 #ifdef CONFIG_SWAP
+bool mem_cgroup_can_vswap(struct mem_cgroup *memcg);
+
 int add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
 		unsigned long nr_pages, sector_t start_block);
 int generic_swapfile_activate(struct swap_info_struct *, struct file *,
@@ -448,6 +450,11 @@ static inline void put_swap_device(struct swap_info_struct *si)
 
 #else /* CONFIG_SWAP */
 static inline void swap_writeback_dropbehind_folio(struct folio *folio) {}
+static inline bool mem_cgroup_can_vswap(struct mem_cgroup *memcg)
+{
+	return false;
+}
+
 static inline struct swap_info_struct *get_swap_device(swp_entry_t entry)
 {
 	return NULL;
@@ -546,6 +553,7 @@ static inline void mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_p
 
 long mem_cgroup_get_folio_swap_margin(const struct folio *folio);
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg);
+bool mem_cgroup_can_swap(struct mem_cgroup *memcg, long nr_pages);
 bool mem_cgroup_swap_full(const struct folio *folio);
 #else
 static inline int mem_cgroup_try_charge_swap(struct folio *folio)
@@ -568,6 +576,11 @@ static inline long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg)
 	return get_nr_swap_pages();
 }
 
+static inline bool mem_cgroup_can_swap(struct mem_cgroup *memcg, long nr_pages)
+{
+	return mem_cgroup_can_vswap(memcg) || get_nr_swap_pages() >= nr_pages;
+}
+
 static inline bool mem_cgroup_swap_full(const struct folio *folio)
 {
 	return vm_swap_full();
diff --git a/mm/Kconfig b/mm/Kconfig
index 18925ccb4adc..704d43fcd92b 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -19,6 +19,26 @@ menuconfig SWAP
 	  used to provide more virtual memory than the actual RAM present
 	  in your computer.  If unsure say Y.
 
+config VSWAP_DEFAULT_ON
+	bool "Route swapouts through virtual swap by default"
+	depends on SWAP
+	default n
+	help
+	  Virtual swap allows zswap and zero-filled pages to be used
+	  without swapping on a physical device first, and lets a page
+	  move between zswap and a swapfile without invalidating the page
+	  table entries that refer to it.
+
+	  Swap entries are handed out by a virtual swap device instead of
+	  naming a slot on a real one, so the backing can be chosen and
+	  changed after the entry exists.
+
+	  Say Y to make "vswap=on" the default, routing swapouts through
+	  the virtual swap layer from boot.
+
+	  Say N (default) to leave vswap off unless "vswap=on" is passed
+	  on the kernel command line.
+
 config ZSWAP
 	bool "Compressed cache for swap pages"
 	depends on SWAP
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index df02308bb80a..a3d065c594bc 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -6150,6 +6150,22 @@ long mem_cgroup_get_folio_swap_margin(const struct folio *folio)
 	return margin;
 }
 
+/**
+ * mem_cgroup_can_swap - can @memcg swap out at least @nr_pages more pages?
+ * @memcg: the memcg to query
+ * @nr_pages: the number of pages the caller wants to swap out
+ *
+ * Return: true if @memcg can swap out at least @nr_pages more pages.
+ */
+bool mem_cgroup_can_swap(struct mem_cgroup *memcg, long nr_pages)
+{
+	if (!mem_cgroup_disabled() && !do_memsw_account() &&
+	    page_counter_margin(&memcg->swap) < nr_pages)
+		return false;
+
+	return mem_cgroup_can_vswap(memcg) || get_nr_swap_pages() >= nr_pages;
+}
+
 bool mem_cgroup_swap_full(const struct folio *folio)
 {
 	struct mem_cgroup *memcg;
@@ -6313,8 +6329,10 @@ static struct cftype swap_files[] = {
 
 #ifdef CONFIG_ZSWAP
 /**
- * obj_cgroup_may_zswap - check if this cgroup can zswap
- * @objcg: the object cgroup
+ * mem_cgroup_may_zswap - check if this cgroup can zswap
+ * @memcg: the memcg to query
+ * @may_flush: force-flush stats for an accurate check (sleeps). Pass false
+ *             from atomic contexts; the check is then best-effort.
  *
  * Check if the hierarchical zswap limit has been reached.
  *
@@ -6324,36 +6342,38 @@ static struct cftype swap_files[] = {
  * spending cycles on compression when there is already no room left
  * or zswap is disabled altogether somewhere in the hierarchy.
  */
-bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
+bool mem_cgroup_may_zswap(struct mem_cgroup *memcg, bool may_flush)
 {
-	struct mem_cgroup *memcg, *original_memcg;
-	bool ret = true;
-
 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
 		return true;
 
-	original_memcg = get_mem_cgroup_from_objcg(objcg);
-	for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
-	     memcg = parent_mem_cgroup(memcg)) {
+	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
 		unsigned long max = READ_ONCE(memcg->zswap_max);
 		unsigned long pages;
 
 		if (max == PAGE_COUNTER_MAX)
 			continue;
-		if (max == 0) {
-			ret = false;
-			break;
-		}
+		if (max == 0)
+			return false;
 
 		/* Force flush to get accurate stats for charging */
-		__mem_cgroup_flush_stats(memcg, true);
+		if (may_flush)
+			__mem_cgroup_flush_stats(memcg, true);
 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
-		if (pages < max)
-			continue;
-		ret = false;
-		break;
+		if (pages >= max)
+			return false;
 	}
-	mem_cgroup_put(original_memcg);
+	return true;
+}
+
+bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
+{
+	struct mem_cgroup *memcg;
+	bool ret;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	ret = mem_cgroup_may_zswap(memcg, true);
+	mem_cgroup_put(memcg);
 	return ret;
 }
 
diff --git a/mm/page_io.c b/mm/page_io.c
index 956c3ffc1039..854b0b71581d 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -209,6 +209,7 @@ static void swap_zeromap_folio_clear(struct folio *folio)
  */
 int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 {
+	swp_entry_t phys = folio->swap;
 	int ret = 0;
 
 	if (folio_free_swap(folio))
@@ -252,8 +253,14 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	 */
 	swap_zeromap_folio_clear(folio);
 
+	/*
+	 * For vswap: release stale non-swapfile backings (e.g. ZSWAP from a
+	 * previous swapout cycle) so zswap_store or folio_realloc_swap
+	 * starts on clean slots. Contiguous PHYS backing is preserved for
+	 * reuse by folio_realloc_swap.
+	 */
 	if (is_vswap_entry(folio->swap))
-		folio_release_vswap_backing(folio);
+		folio_release_non_phys_swap_backing(folio);
 
 	if (zswap_store(folio)) {
 		count_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);
@@ -268,13 +275,21 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
-	/* A vswap folio has no physical slot to write to. */
 	if (is_vswap_entry(folio->swap)) {
+		phys = folio_realloc_swap(folio);
+		if (!phys.val) {
+			folio_mark_dirty(folio);
+			return AOP_WRITEPAGE_ACTIVATE;
+		}
+	}
+
+	if (ctx->nofs &&
+	    (__swap_entry_to_info(phys)->ops->flags & SWAP_OPS_F_REQUIRE_NOFS)) {
 		folio_mark_dirty(folio);
 		return AOP_WRITEPAGE_ACTIVATE;
 	}
 
-	__swap_writeout(ctx, folio, folio->swap);
+	__swap_writeout(ctx, folio, phys);
 	return 0;
 out_unlock:
 	folio_unlock(folio);
diff --git a/mm/shmem.c b/mm/shmem.c
index 5d6807518474..5d3695886ecd 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -1914,7 +1914,8 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 	if ((info->flags & SHMEM_F_LOCKED) || sbinfo->noswap)
 		goto redirty;
 
-	if (!total_swap_pages)
+	/* vswap doesn't contribute to total_swap_pages */
+	if (!total_swap_pages && !(vswap_is_enabled() && zswap_is_enabled()))
 		goto redirty;
 
 	/*
diff --git a/mm/swap_state.c b/mm/swap_state.c
index 110a0c095825..ae41730bc806 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -186,6 +186,9 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 		return -ENOENT;
 	ci_off = swp_cluster_offset(targ_entry);
 	old_tb = __swap_table_get(ci, ci_off);
+	/* Physical readahead can hit a vswap-backing rmap slot; skip it. */
+	if (swp_tb_is_vswap(old_tb))
+		return -ENOENT;
 	if (swp_tb_is_folio(old_tb))
 		return -EEXIST;
 	/*
@@ -215,7 +218,8 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,
 	ci_end = ci_off + nr;
 	do {
 		old_tb = __swap_table_get(ci, ci_off);
-		if (unlikely(!swp_tb_is_shadow(old_tb) ||
+		if (unlikely(swp_tb_is_vswap(old_tb) ||
+			     !swp_tb_is_shadow(old_tb) ||
 			     !__swp_tb_get_count(old_tb) ||
 			     is_zero != __swap_table_test_zero(ci, ci_off) ||
 			     (memcg_id && *memcg_id != __swap_cgroup_get(ci, ci_off))))
diff --git a/mm/swap_table.h b/mm/swap_table.h
index 36b17f03bd9b..a54cacbc2ade 100644
--- a/mm/swap_table.h
+++ b/mm/swap_table.h
@@ -428,6 +428,13 @@ static inline bool swp_tb_is_vswap(unsigned long swp_tb)
 }
 
 #ifdef CONFIG_SWAP
+static inline unsigned long swp_entry_to_swp_tb_vswap(swp_entry_t entry)
+{
+	BUILD_BUG_ON(SWP_OFFSET_MASK >
+		     (SWP_RMAP_ENTRY_MASK >> SWP_TB_VSWAP_MARK_BITS));
+	return (swp_offset(entry) << SWP_TB_VSWAP_MARK_BITS) | SWP_TB_VSWAP_MARK;
+}
+
 static inline swp_entry_t swp_tb_vswap_to_swp_entry(unsigned long swp_tb)
 {
 	unsigned long offset;
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 6933e069bd2e..3dca9bd55736 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -57,6 +57,10 @@ static bool folio_swapcache_freeable(struct folio *folio);
 static void move_cluster(struct swap_info_struct *si,
 			 struct swap_cluster_info *ci, struct list_head *list,
 			 enum swap_cluster_flags new_flags);
+static void __swap_cluster_free_phys_backing(struct swap_info_struct *psi,
+					     struct swap_cluster_info *pci,
+					     unsigned int ci_start,
+					     unsigned int nr_pages);
 
 /*
  * Protects the swap_info array, and the SWP_USED flag. swap_info contains
@@ -1020,6 +1024,8 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 {
 	unsigned int order;
 	unsigned long nr_pages;
+	swp_entry_t vswap_entry, v;
+	unsigned int i;
 
 	lockdep_assert_held(&ci->lock);
 
@@ -1029,8 +1035,8 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 	/*
 	 * All mm swap allocation starts with a folio (folio_alloc_swap),
 	 * it's also the only allocation path for large orders allocation.
-	 * Such swap slots starts with count == 0 and will be increased
-	 * upon folio unmap.
+	 * Slots used directly start with count == 0 and gain references
+	 * when the folio is unmapped.
 	 *
 	 * Else, it's a exclusive order 0 allocation for hibernation.
 	 * The slot carries no swap count and is freed by offset.
@@ -1039,8 +1045,26 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 		order = folio_order(folio);
 		nr_pages = 1 << order;
 		swap_cluster_assert_empty(ci, ci_off, nr_pages, false);
-		__swap_cache_add_folio(ci, folio, swp_entry(si->type,
-							    ci_off + cluster_offset(si, ci)));
+		if (folio_test_swapcache(folio)) {
+			/*
+			 * Folio already in the swap cache: we are allocating
+			 * physical backing for its vswap entry. Point each
+			 * physical slot back at its own vswap entry
+			 * (Vswap-tagged rmap).
+			 */
+			VM_WARN_ON(!is_vswap_entry(folio->swap));
+			vswap_entry = folio->swap;
+			for (i = 0; i < nr_pages; i++) {
+				v = vswap_entry;
+				v.val += i;
+				__swap_table_set(ci, ci_off + i,
+						 swp_entry_to_swp_tb_vswap(v));
+			}
+		} else {
+			__swap_cache_add_folio(ci, folio,
+				swp_entry(si->type,
+					  ci_off + cluster_offset(si, ci)));
+		}
 	} else if (IS_ENABLED(CONFIG_HIBERNATION)) {
 		order = 0;
 		nr_pages = 1;
@@ -1911,6 +1935,12 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 	return err;
 }
 
+bool mem_cgroup_can_vswap(struct mem_cgroup *memcg)
+{
+	return vswap_is_enabled() && zswap_is_enabled() &&
+	       (!memcg || mem_cgroup_may_zswap(memcg, false));
+}
+
 static bool folio_may_vswap(struct folio *folio)
 {
 	struct obj_cgroup *objcg;
@@ -2061,8 +2091,11 @@ void __vswap_release_backing(struct swap_cluster_info *ci,
 			     unsigned int ci_start, unsigned int nr)
 {
 	struct swap_cluster_info_dynamic *ci_dyn;
+	struct swap_info_struct *psi;
+	unsigned long phys_off_start = 0, phys_off_end = 0;
 	unsigned int ci_off;
 	unsigned long vt;
+	swp_entry_t phys_first = {};
 
 	lockdep_assert_held(&ci->lock);
 	ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
@@ -2070,7 +2103,30 @@ void __vswap_release_backing(struct swap_cluster_info *ci,
 	for (ci_off = ci_start; ci_off < ci_start + nr; ci_off++) {
 		vt = __vtable_get(ci_dyn, ci_off);
 
+		/* The free helper takes one contiguous run within one cluster. */
+		if (phys_off_start != phys_off_end &&
+		    (vtable_type(vt) != VSWAP_SWAPFILE ||
+		     swp_type(vtable_to_phys(vt)) != swp_type(phys_first) ||
+		     swp_offset(vtable_to_phys(vt)) != phys_off_end ||
+		     phys_off_end % SWAPFILE_CLUSTER == 0)) {
+			psi = __swap_entry_to_info(phys_first);
+			__swap_cluster_free_phys_backing(psi,
+					__swap_entry_to_cluster(phys_first),
+					phys_off_start % SWAPFILE_CLUSTER,
+					phys_off_end - phys_off_start);
+			phys_off_start = phys_off_end = 0;
+		}
+
 		switch (vtable_type(vt)) {
+		case VSWAP_SWAPFILE:
+			if (phys_off_start == phys_off_end) {
+				phys_first = vtable_to_phys(vt);
+				phys_off_start = swp_offset(phys_first);
+				phys_off_end = phys_off_start + 1;
+			} else {
+				phys_off_end++;
+			}
+			break;
 		case VSWAP_ZSWAP:
 			zswap_entry_free(vtable_to_zswap(vt));
 			break;
@@ -2086,6 +2142,14 @@ void __vswap_release_backing(struct swap_cluster_info *ci,
 		if (__swap_table_test_zero(ci, ci_off))
 			__swap_table_clear_zero(ci, ci_off);
 	}
+
+	if (phys_off_start != phys_off_end) {
+		psi = __swap_entry_to_info(phys_first);
+		__swap_cluster_free_phys_backing(psi,
+				__swap_entry_to_cluster(phys_first),
+				phys_off_start % SWAPFILE_CLUSTER,
+				phys_off_end - phys_off_start);
+	}
 }
 
 /**
@@ -2113,6 +2177,103 @@ void folio_release_vswap_backing(struct folio *folio)
 	spin_unlock(&ci->lock);
 }
 
+/**
+ * folio_release_non_phys_swap_backing() - Drop a folio's non-physical vswap backing.
+ * @folio: the folio, occupying a virtual swap entry.
+ *
+ * Release the zswap backing recorded for @folio's virtual swap entry,
+ * leaving the slots empty so the writeout path can install fresh physical
+ * backing. Does nothing when the entry is already backed by physical
+ * swapfile slots, which are kept for reuse, or when it has no backing
+ * beyond the swap cache folio itself.
+ *
+ * Context: Caller must hold the folio lock; @folio must be in the swap cache
+ * and occupy a virtual swap entry.
+ */
+void folio_release_non_phys_swap_backing(struct folio *folio)
+{
+	struct swap_cluster_info *ci;
+	struct swap_cluster_info_dynamic *ci_dyn;
+	int nr = folio_nr_pages(folio);
+	unsigned int voff;
+	unsigned long vt;
+	enum vswap_backing_type type;
+
+	ci = __swap_entry_to_cluster(folio->swap);
+	ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+	voff = swp_cluster_offset(folio->swap);
+
+	spin_lock(&ci->lock);
+	/*
+	 * A folio's slots cannot mix swapfile with other backends, except
+	 * mid-backend-change, which always starts from slot 0.
+	 */
+	vt = __vtable_get(ci_dyn, voff);
+	type = vtable_type(vt);
+
+	if (type == VSWAP_SWAPFILE || type == VSWAP_NONE) {
+		spin_unlock(&ci->lock);
+		return;
+	}
+
+	__vswap_release_backing(ci, voff, nr);
+	spin_unlock(&ci->lock);
+}
+
+/**
+ * folio_realloc_swap() - Back a virtual swap folio with a physical swap slot.
+ * @folio: the folio, occupying a virtual swap entry.
+ *
+ * Ensure @folio's virtual swap entry has physical (swapfile) backing,
+ * allocating a physical slot on demand if it has none. If @folio is
+ * already physically backed, the existing physical entry is returned
+ * unchanged.
+ *
+ * Context: Caller must hold the folio lock; @folio must be in the swap cache
+ * and occupy a virtual swap entry.
+ * Return: The physical swap entry now backing @folio, or an empty entry
+ * (.val == 0) on failure.
+ */
+swp_entry_t folio_realloc_swap(struct folio *folio)
+{
+	swp_entry_t vswap_entry = folio->swap;
+	struct swap_cluster_info *ci;
+	struct swap_cluster_info_dynamic *ci_dyn;
+	unsigned int voff;
+	swp_entry_t phys_entry = {};
+	swp_entry_t pe;
+	int i, nr = folio_nr_pages(folio);
+
+	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
+	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
+	VM_WARN_ON(!is_vswap_entry(vswap_entry));
+
+	phys_entry = vswap_to_phys(vswap_entry);
+	if (phys_entry.val)
+		return phys_entry;
+
+	phys_entry = folio_alloc_phys_swap(folio);
+	if (!phys_entry.val)
+		return (swp_entry_t){};
+
+	voff = swp_cluster_offset(vswap_entry);
+
+	ci = __swap_entry_to_cluster(vswap_entry);
+	ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+	spin_lock(&ci->lock);
+	/*
+	 * Install PHYS backing without freeing any prior contents of the
+	 * vtable. Releasing the old backing is the caller's job.
+	 */
+	for (i = 0; i < nr; i++) {
+		pe.val = phys_entry.val + i;
+		__vtable_set(ci_dyn, voff + i, vtable_mk_phys(pe));
+	}
+	spin_unlock(&ci->lock);
+
+	return phys_entry;
+}
+
 /**
  * folio_dup_swap() - Increase swap count of swap entries of a folio.
  * @folio: folio with swap entries bounded.
@@ -2242,6 +2403,47 @@ struct swap_info_struct *get_swap_device(swp_entry_t entry)
 	return ERR_PTR(-EIO);
 }
 
+/*
+ * Common tail for freeing swap slots: device-level accounting
+ * and cluster list management.
+ */
+static void __swap_cluster_finish_free(struct swap_info_struct *si,
+				       struct swap_cluster_info *ci,
+				       unsigned int ci_start,
+				       unsigned int nr_pages)
+{
+	lockdep_assert_held(&ci->lock);
+	swap_range_free(si, cluster_offset(si, ci) + ci_start, nr_pages);
+	swap_cluster_assert_empty(ci, ci_start, nr_pages, false);
+
+	if (!ci->count)
+		free_cluster(si, ci);
+	else
+		partial_free_cluster(si, ci);
+}
+
+/*
+ * Free physical swap slots that were backing vswap entries (Vswap-tagged).
+ */
+static void __swap_cluster_free_phys_backing(struct swap_info_struct *psi,
+					     struct swap_cluster_info *pci,
+					     unsigned int ci_start,
+					     unsigned int nr_pages)
+{
+	unsigned int ci_off;
+
+	spin_lock_nested(&pci->lock, SINGLE_DEPTH_NESTING);
+	VM_WARN_ON(pci->count < nr_pages);
+	pci->count -= nr_pages;
+	for (ci_off = ci_start; ci_off < ci_start + nr_pages; ci_off++) {
+		__swap_table_set(pci, ci_off, null_to_swp_tb());
+		if (!SWAP_TABLE_HAS_ZEROFLAG)
+			__swap_table_clear_zero(pci, ci_off);
+	}
+	__swap_cluster_finish_free(psi, pci, ci_start, nr_pages);
+	swap_cluster_unlock(pci);
+}
+
 /*
  * Free a set of swap slots after their swap count dropped to zero, or will be
  * zero after putting the last ref (saves one __swap_cluster_put_entry call).
@@ -2253,7 +2455,6 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 	unsigned long old_tb;
 	unsigned short batch_id = 0, id_cur;
 	unsigned int ci_off = ci_start, ci_end = ci_start + nr_pages;
-	unsigned long ci_head = cluster_offset(si, ci);
 	unsigned int batch_off = ci_off;
 
 	VM_WARN_ON(ci->count < nr_pages);
@@ -2293,13 +2494,7 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 	if (batch_id)
 		mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
 
-	swap_range_free(si, ci_head + ci_start, nr_pages);
-	swap_cluster_assert_empty(ci, ci_start, nr_pages, false);
-
-	if (!ci->count)
-		free_cluster(si, ci);
-	else
-		partial_free_cluster(si, ci);
+	__swap_cluster_finish_free(si, ci, ci_start, nr_pages);
 }
 
 int __swap_count(swp_entry_t entry)
@@ -4515,3 +4710,76 @@ subsys_initcall(swapfile_init);
 
 struct swap_info_struct *vswap_si;
 DEFINE_STATIC_KEY_FALSE(vswap_key);
+
+static bool vswap_enabled_early __initdata = IS_ENABLED(CONFIG_VSWAP_DEFAULT_ON);
+
+static int __init early_vswap(char *buf)
+{
+	return kstrtobool(buf, &vswap_enabled_early);
+}
+early_param("vswap", early_vswap);
+
+/* vswap does no IO on its own. */
+static const struct swap_ops vswap_ops = { };
+
+static int __init vswap_init(void)
+{
+	struct swap_info_struct *si;
+	unsigned long maxpages;
+	int err;
+
+	if (!vswap_enabled_early)
+		return 0;
+
+	si = alloc_swap_info();
+	if (IS_ERR(si)) {
+		pr_warn("vswap: alloc_swap_info failed (%ld); vswap disabled, swapout falls back to direct physical swap\n",
+			PTR_ERR(si));
+		return 0;
+	}
+
+	/*
+	 * Each swapped page holds a reference on its cgroup's
+	 * objcg->private_id_ref, a 32-bit refcount_t, so a cgroup that swaps
+	 * REFCOUNT_MAX pages saturates it and leaks the objcg until reboot.
+	 * Cap the device there.
+	 */
+	maxpages = min(swapfile_maximum_size,
+		       ALIGN_DOWN((unsigned long)REFCOUNT_MAX, SWAPFILE_CLUSTER));
+	/*
+	 * SWP_WRITEOK enables slot allocation. SWP_SOLIDSTATE selects
+	 * per-CPU cluster allocation; vswap has no si->global_cluster.
+	 */
+	si->flags |= SWP_VSWAP | SWP_SOLIDSTATE | SWP_WRITEOK;
+	si->ops = &vswap_ops;
+	si->bdev = NULL;
+	si->max = maxpages;
+	si->pages = maxpages - 1;
+
+	INIT_WORK(&si->discard_work, swap_discard_work);
+	INIT_WORK(&si->reclaim_work, swap_reclaim_work);
+
+	err = setup_swap_clusters_info(si, NULL, maxpages);
+	if (err)
+		goto fail;
+
+	mutex_lock(&swapon_mutex);
+	enable_swap_info(si);
+	mutex_unlock(&swapon_mutex);
+
+	vswap_si = si;
+	pr_info("vswap: created virtual swap device (%lu pages)\n", maxpages);
+
+	/* Last: everything above must be visible before routing starts. */
+	static_branch_enable(&vswap_key);
+	return 0;
+
+fail:
+	pr_warn("vswap: setup_swap_clusters_info failed (%d); vswap disabled, swapout falls back to direct physical swap\n",
+		err);
+	spin_lock(&swap_lock);
+	si->flags = 0;
+	spin_unlock(&swap_lock);
+	return 0;
+}
+late_initcall(vswap_init);
diff --git a/mm/util.c b/mm/util.c
index 80f6c714844f..47c4cf7400cf 100644
--- a/mm/util.c
+++ b/mm/util.c
@@ -33,6 +33,7 @@
 
 #include "internal.h"
 #include "swap.h"
+#include "vswap.h"
 
 /**
  * kfree_const - conditionally free memory
@@ -983,7 +984,17 @@ int __vm_enough_memory(const struct mm_struct *mm, long pages, int cap_sys_admin
 		return 0;
 
 	if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
-		if (pages > totalram_pages() + total_swap_pages)
+		allowed = totalram_pages() + total_swap_pages;
+		/*
+		 * Vswap is in neither term, so with no swapfile the bound
+		 * would collapse to RAM alone even though zswap can absorb
+		 * more. Compression swap is backed by memory, so budget a 3x
+		 * compression ratio, typical of most workloads. Anything that
+		 * compresses better can use OVERCOMMIT_ALWAYS.
+		 */
+		if (vswap_is_enabled() && zswap_is_enabled())
+			allowed += 2 * totalram_pages();
+		if (pages > allowed)
 			goto error;
 		return 0;
 	}
diff --git a/mm/vmscan.c b/mm/vmscan.c
index 5bf20b57fe45..77aefadc24f9 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -302,10 +302,12 @@ 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?
-		 * And under GFP_NOIO, is there enough swapcached anon to make
-		 * scanning anon worthwhile?
+		 * vswap does not contribute to nr_swap_pages. And under
+		 * GFP_NOIO, is there enough swapcached anon to make scanning
+		 * anon worthwhile?
 		 */
-		if (get_nr_swap_pages() > 0 &&
+		if ((get_nr_swap_pages() > 0 ||
+		     (vswap_is_enabled() && zswap_is_enabled())) &&
 		    !reclaimable_anon_is_low(memcg, nid, sc))
 			return true;
 	} else {
@@ -313,7 +315,7 @@ static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
 		 * Is the memcg below its swap limit, and under GFP_NOIO does
 		 * it have enough swapcached anon to make scanning worthwhile?
 		 */
-		if (mem_cgroup_get_nr_swap_pages(memcg) > 0 &&
+		if (mem_cgroup_can_swap(memcg, 1) &&
 		    !reclaimable_anon_is_low(memcg, nid, sc))
 			return true;
 	}
@@ -2752,7 +2754,7 @@ static bool can_age_anon_pages(struct lruvec *lruvec,
 			       struct scan_control *sc)
 {
 	/* Aging the anon LRU is valuable if swap is present: */
-	if (total_swap_pages > 0)
+	if (total_swap_pages > 0 || (vswap_is_enabled() && zswap_is_enabled()))
 		return true;
 
 	/* Also valuable if anon pages can be demoted: */
@@ -2827,7 +2829,7 @@ static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
 		return 0;
 
 	if (!can_demote(pgdat->node_id, sc, memcg) &&
-	    mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
+	    !mem_cgroup_can_swap(memcg, MIN_LRU_BATCH))
 		return 0;
 
 	return swappiness;
diff --git a/mm/vswap.h b/mm/vswap.h
index c4f0670c9b5c..080e4bec8280 100644
--- a/mm/vswap.h
+++ b/mm/vswap.h
@@ -29,6 +29,10 @@ enum vswap_backing_type {
 #include "swap_table.h"
 DECLARE_STATIC_KEY_FALSE(vswap_key);
 
+/*
+ * Only true once vswap_init() has published vswap_si, so callers never
+ * see the device half built.
+ */
 static inline bool vswap_is_enabled(void)
 {
 	return static_branch_unlikely(&vswap_key);
@@ -88,6 +92,13 @@ static inline enum vswap_backing_type vtable_type(unsigned long vt)
 	return vt ? VSWAP_ZSWAP : VSWAP_NONE;
 }
 
+static inline unsigned long vtable_mk_phys(swp_entry_t entry)
+{
+	BUILD_BUG_ON(BITS_PER_XA_VALUE + VTABLE_TAG_BITS > BITS_PER_LONG);
+	VM_WARN_ON_ONCE(entry.val >> BITS_PER_XA_VALUE);
+	return (entry.val << VTABLE_TAG_BITS) | VTABLE_TAG_MASK;
+}
+
 static inline swp_entry_t vtable_to_phys(unsigned long vt)
 {
 	VM_WARN_ON(vtable_type(vt) != VSWAP_SWAPFILE);
@@ -212,6 +223,8 @@ static inline struct zswap_entry *vswap_zswap_load(swp_entry_t entry)
 }
 
 void folio_release_vswap_backing(struct folio *folio);
+swp_entry_t folio_realloc_swap(struct folio *folio);
+void folio_release_non_phys_swap_backing(struct folio *folio);
 
 /*
  * Walk nr vtable slots starting at voff in ci_dyn. Returns the prefix
diff --git a/mm/workingset.c b/mm/workingset.c
index 87d5e55dd684..283cf0d150bc 100644
--- a/mm/workingset.c
+++ b/mm/workingset.c
@@ -523,7 +523,7 @@ bool workingset_test_recent(void *shadow, bool file, bool *workingset,
 		workingset_size += lruvec_page_state(eviction_lruvec,
 						     NR_INACTIVE_FILE);
 	}
-	if (mem_cgroup_get_nr_swap_pages(eviction_memcg) > 0) {
+	if (mem_cgroup_can_swap(eviction_memcg, 1)) {
 		workingset_size += lruvec_page_state(eviction_lruvec,
 						     NR_ACTIVE_ANON);
 		if (file) {
diff --git a/mm/zswap.c b/mm/zswap.c
index aab8ec782d03..be68ffa1f554 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1720,7 +1720,7 @@ bool zswap_store(struct folio *folio)
 	 */
 	if (is_vswap_entry(swp)) {
 		if (index > 0)
-			folio_release_vswap_backing(folio);
+			folio_release_non_phys_swap_backing(folio);
 	} else {
 		zswap_invalidate(swp_type(swp), swp_offset(swp), nr_pages);
 	}
-- 
2.53.1-Meta



  parent reply	other threads:[~2026-12-03 22:01 UTC|newest]

Thread overview: 25+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-03 21:59 [PATCH v7 00/20] mm: mandatory virtual swap Nhat Pham
2026-12-03 21:59 ` [PATCH v7 01/20] mm/swap: prepare dynamic clusters for vswap Nhat Pham
2026-12-03 21:59 ` [PATCH v7 02/20] mm, swap: prepare the swap IO path " Nhat Pham
2026-12-03 21:59 ` [PATCH v7 03/20] mm/swap: prepare zswap and zero storage for virtual entries Nhat Pham
2026-12-03 21:59 ` [PATCH v7 04/20] mm/swap: allocate virtual swap slots Nhat Pham
2026-12-03 21:59 ` [PATCH v7 05/20] mm/swap: return physical entries from the swap allocator Nhat Pham
2026-12-03 21:59 ` [PATCH v7 06/20] mm/swap: resolve physical backing for reads and device flags Nhat Pham
2026-12-03 21:59 ` [PATCH v7 07/20] mm/swap: prepare physical swapoff for virtual backing Nhat Pham
2026-12-03 21:59 ` Nhat Pham [this message]
2026-12-03 21:59 ` [PATCH v7 09/20] mm, swap: enable THP swapin for vswap entries Nhat Pham
2026-12-03 22:00 ` [PATCH v7 10/20] mm, swap: write back vswap zswap entries to physical swap Nhat Pham
2026-12-03 22:00 ` [PATCH v7 11/20] mm, swap: reclaim physical slots backing cache-only vswap entries Nhat Pham
2026-12-03 22:00 ` [PATCH v7 12/20] mm, swap: add debugfs counters for vswap Nhat Pham
2026-12-03 22:00 ` [PATCH v7 13/20] mm, swap: only charge physical swap entries Nhat Pham
2026-12-03 22:00 ` [PATCH v7 14/20] mm, swap: defer memcg_table allocation for physical swap clusters Nhat Pham
2026-12-03 22:00 ` [PATCH v7 15/20] mm, swap: add vmstat and memcg counters for vswap Nhat Pham
2026-12-03 22:00 ` [PATCH v7 16/20] mm/swap: make vswap mandatory Nhat Pham
2026-12-03 22:00 ` [PATCH v7 17/20] mm/swap: drop direct physical swapcache handling Nhat Pham
2026-12-03 22:00 ` [PATCH v7 18/20] mm/zswap: store compressed entries only in the vtable Nhat Pham
2026-12-03 22:00 ` [PATCH v7 19/20] mm/swap: reclaim physical backing through reverse mappings Nhat Pham
2026-12-03 22:00 ` [PATCH v7 20/20] mm/swap: move virtual swap metadata into vswap clusters Nhat Pham
2026-12-03 22:14 ` [PATCH v7 00/20] mm: mandatory virtual swap Yosry Ahmed
2026-12-03 23:00   ` Nhat Pham
2026-12-03 23:05     ` Yosry Ahmed
2026-12-03 23:14       ` Nhat Pham

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261203220010.1302207-9-nphamcs@gmail.com \
    --to=nphamcs@gmail.com \
    --cc=akpm@linux-foundation.org \
    --cc=arnd@arndb.de \
    --cc=axelrasmussen@google.com \
    --cc=baohua@kernel.org \
    --cc=baolin.wang@linux.alibaba.com \
    --cc=baoquan.he@linux.dev \
    --cc=bp@alien8.de \
    --cc=cgroups@vger.kernel.org \
    --cc=chengming.zhou@linux.dev \
    --cc=chrisl@kernel.org \
    --cc=corbet@lwn.net \
    --cc=dapeng1.mi@linux.intel.com \
    --cc=david@kernel.org \
    --cc=elver@google.com \
    --cc=enelsonmoore@gmail.com \
    --cc=hannes@cmpxchg.org \
    --cc=hughd@google.com \
    --cc=jlayton@kernel.org \
    --cc=kasong@tencent.com \
    --cc=kmehltretter@gmail.com \
    --cc=liam@infradead.org \
    --cc=linux-doc@vger.kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-mm@kvack.org \
    --cc=mhocko@kernel.org \
    --cc=mkoutny@suse.com \
    --cc=muchun.song@linux.dev \
    --cc=qi.zheng@linux.dev \
    --cc=rdunlap@infradead.org \
    --cc=roman.gushchin@linux.dev \
    --cc=rppt@kernel.org \
    --cc=shakeel.butt@linux.dev \
    --cc=shikemeng@huaweicloud.com \
    --cc=skhan@linuxfoundation.org \
    --cc=tj@kernel.org \
    --cc=vbabka@kernel.org \
    --cc=weixugc@google.com \
    --cc=yosry@kernel.org \
    --cc=youngjun.park@lge.com \
    --cc=yuanchu@google.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox