Linux Documentation
 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 13/20] mm, swap: only charge physical swap entries
Date: Thu,  3 Dec 2026 14:00:03 -0800	[thread overview]
Message-ID: <20261203220010.1302207-14-nphamcs@gmail.com> (raw)
In-Reply-To: <20261203220010.1302207-1-nphamcs@gmail.com>

Zswap-backed and zero-filled pages occupy no swap space, but were charged
against memcg->swap, the memcg's swap cgroup counter, as though they did.

Charge memcg->swap when a vswap entry acquires physical backing rather
than when it is allocated.

With vswap enabled, this changes what the counter means and when the
charge can fail:

* Virtual swap entries count towards memory.swap.current only when
  backed by physical swap slots.
* A cgroup can reclaim its anon memory even with memory.swap.max set to 0,
  provided zswap is allowed for it.
* The charge can fail at writeback rather than at allocation.
  swap_writeout() returns AOP_WRITEPAGE_ACTIVATE and
  zswap_writeback_entry() returns -ENOMEM for a cgroup at its limit.
* The zswap shrinker skips such a cgroup rather than walking its LRUs.

Also refactor the swap memcg operations into separate get, record, charge,
uncharge and put helpers, since recording the owner and charging it no
longer happen at the same time.

Direct-mapped physical swap charging is unchanged. In cgroup v1, vswap
entries still count against memsw. MEMCG_SWAP counts physical slots,
including slots backing virtual entries, rather than virtual slots.

Suggested-by: Johannes Weiner <hannes@cmpxchg.org>
Signed-off-by: Nhat Pham <nphamcs@gmail.com>
---
 .../admin-guide/cgroup-v1/memcg_test.rst      |   2 +-
 Documentation/admin-guide/cgroup-v2.rst       |  51 ++---
 include/linux/swap.h                          |  74 ++++++-
 mm/memcontrol-v1.c                            |  43 +++-
 mm/memcontrol-v1.h                            |  19 ++
 mm/memcontrol.c                               | 185 ++++++++++++++----
 mm/swapfile.c                                 |  88 +++++++--
 mm/zswap.c                                    |  22 ++-
 8 files changed, 383 insertions(+), 101 deletions(-)

diff --git a/Documentation/admin-guide/cgroup-v1/memcg_test.rst b/Documentation/admin-guide/cgroup-v1/memcg_test.rst
index d9951c319ef5..8d3fcba13450 100644
--- a/Documentation/admin-guide/cgroup-v1/memcg_test.rst
+++ b/Documentation/admin-guide/cgroup-v1/memcg_test.rst
@@ -43,7 +43,7 @@ Please note that implementation details can be changed.
 	mem_cgroup_uncharge()
 	  Called when a page's refcount goes down to 0.
 
-	mem_cgroup_uncharge_swap()
+	mem_cgroup_dir_phys_swap_free()
 	  Called when swp_entry's refcnt goes down to 0. A charge against swap
 	  disappears.
 
diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index eeeaf635754c..cd965ddeaf9e 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -1630,7 +1630,8 @@ The following nested keys are defined.
 
 	  swapcached
 		Amount of swap cached in memory. The swapcache is accounted
-		against both memory and swap usage.
+		against memory usage, and against swap usage when the swap
+		entry has physical backing.
 
 	  anon_thp
 		Amount of memory used in anonymous mappings backed by
@@ -1861,16 +1862,17 @@ The following nested keys are defined.
 	A read-only single value file which exists on non-root
 	cgroups.
 
-	The total amount of swap currently being used by the cgroup
-	and its descendants.
+	The total amount of physical swap currently being used by the
+	cgroup and its descendants.
 
   memory.swap.high
 	A read-write single value file which exists on non-root
 	cgroups.  The default is "max".
 
-	Swap usage throttle limit.  If a cgroup's swap usage exceeds
-	this limit, all its further allocations will be throttled to
-	allow userspace to implement custom out-of-memory procedures.
+	Physical swap usage throttle limit.  If a cgroup's physical
+	swap usage exceeds this limit, all its further allocations will
+	be throttled to allow userspace to implement custom
+	out-of-memory procedures.
 
 	This limit marks a point of no return for the cgroup. It is NOT
 	designed to manage the amount of swapping a workload does
@@ -1883,8 +1885,9 @@ The following nested keys are defined.
   memory.swap.peak
 	A read-write single value file which exists on non-root cgroups.
 
-	The max swap usage recorded for the cgroup and its descendants since
-	the creation of the cgroup or the most recent reset for that FD.
+	The max physical swap usage recorded for the cgroup and its
+	descendants since the creation of the cgroup or the most recent
+	reset for that FD.
 
 	A write of any non-empty string to this file resets it to the
 	current memory usage for subsequent reads through the same
@@ -1894,8 +1897,9 @@ The following nested keys are defined.
 	A read-write single value file which exists on non-root
 	cgroups.  The default is "max".
 
-	Swap usage hard limit.  If a cgroup's swap usage reaches this
-	limit, anonymous memory of the cgroup will not be swapped out.
+	Physical swap usage hard limit.  If a cgroup's physical swap
+	usage reaches this limit, anonymous memory of the cgroup will
+	not be swapped out to a physical swap device.
 
   memory.swap.events
 	A read-only flat-keyed file which exists on non-root cgroups.
@@ -1904,23 +1908,24 @@ The following nested keys are defined.
 	modified event.
 
 	  high
-		The number of times the cgroup's swap usage was over
-		the high threshold.
+		The number of times the cgroup's physical swap usage
+		was over the high threshold.
 
 	  max
-		The number of times the cgroup's swap usage was about
-		to go over the max boundary and swap allocation
-		failed.
+		The number of times the cgroup's physical swap usage
+		was about to go over the max boundary and physical
+		swap allocation failed.
 
 	  fail
-		The number of times swap allocation failed either
-		because of running out of swap system-wide or max
-		limit.
+		The number of failed physical swap allocation or charge
+		attempts. This includes physical backing allocation for
+		virtual swap entries.
 
-	When reduced under the current usage, the existing swap
-	entries are reclaimed gradually and the swap usage may stay
-	higher than the limit for an extended period of time.  This
-	reduces the impact on the workload and memory management.
+	When reduced under the current usage, the existing physical
+	swap entries are reclaimed gradually and the physical swap
+	usage may stay higher than the limit for an extended period of
+	time.  This reduces the impact on the workload and memory
+	management.
 
   memory.zswap.current
 	A read-only single value file which exists on non-root
@@ -1950,8 +1955,6 @@ The following nested keys are defined.
 	reclaim inefficiency after disabling writeback (because the same
 	pages might be rejected again and again).
 
-	Note that this is subtly different from setting memory.swap.max to
-	0, as it still allows for pages to be written to the zswap pool.
 	This setting has no effect if zswap is disabled, and swapping
 	is allowed unless memory.swap.max is set to 0.
 
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 0c78121e2887..ae2676627b07 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -535,20 +535,56 @@ static inline void folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
 #endif
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_SWAP)
-int __mem_cgroup_try_charge_swap(struct folio *folio);
-static inline int mem_cgroup_try_charge_swap(struct folio *folio)
+unsigned short __mem_cgroup_swap_get(struct folio *folio);
+static inline unsigned short mem_cgroup_swap_get(struct folio *folio)
 {
 	if (mem_cgroup_disabled())
 		return 0;
-	return __mem_cgroup_try_charge_swap(folio);
+	return __mem_cgroup_swap_get(folio);
 }
 
-extern void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages);
-static inline void mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
+void __mem_cgroup_swap_fail(unsigned short id);
+static inline void mem_cgroup_swap_fail(unsigned short id)
 {
 	if (mem_cgroup_disabled())
 		return;
-	__mem_cgroup_uncharge_swap(id, nr_pages);
+	__mem_cgroup_swap_fail(id);
+}
+
+int __mem_cgroup_swap_charge(unsigned short id, unsigned int nr_pages);
+static inline int mem_cgroup_swap_charge(unsigned short id,
+					 unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return 0;
+	return __mem_cgroup_swap_charge(id, nr_pages);
+}
+
+void __mem_cgroup_swap_record(struct folio *folio, unsigned short id);
+static inline void mem_cgroup_swap_record(struct folio *folio,
+					  unsigned short id)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_swap_record(folio, id);
+}
+
+void __mem_cgroup_dir_phys_swap_free(unsigned short id, unsigned int nr_pages);
+static inline void mem_cgroup_dir_phys_swap_free(unsigned short id,
+						 unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_dir_phys_swap_free(id, nr_pages);
+}
+
+void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages);
+static inline void mem_cgroup_swap_put(unsigned short id,
+				       unsigned int nr_pages)
+{
+	if (mem_cgroup_disabled())
+		return;
+	__mem_cgroup_swap_put(id, nr_pages);
 }
 
 long mem_cgroup_get_folio_swap_margin(const struct folio *folio);
@@ -556,13 +592,33 @@ 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)
+static inline unsigned short mem_cgroup_swap_get(struct folio *folio)
+{
+	return 0;
+}
+
+static inline void mem_cgroup_swap_fail(unsigned short id)
+{
+}
+
+static inline int mem_cgroup_swap_charge(unsigned short id,
+					 unsigned int nr_pages)
 {
 	return 0;
 }
 
-static inline void mem_cgroup_uncharge_swap(unsigned short id,
-					    unsigned int nr_pages)
+static inline void mem_cgroup_swap_record(struct folio *folio,
+					  unsigned short id)
+{
+}
+
+static inline void mem_cgroup_dir_phys_swap_free(unsigned short id,
+						 unsigned int nr_pages)
+{
+}
+
+static inline void mem_cgroup_swap_put(unsigned short id,
+				       unsigned int nr_pages)
 {
 }
 
diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
index b7f286888507..eb61ab797c38 100644
--- a/mm/memcontrol-v1.c
+++ b/mm/memcontrol-v1.c
@@ -15,6 +15,7 @@
 #include "internal.h"
 #include "swap.h"
 #include "swap_table.h"
+#include "vswap.h"
 #include "memcontrol-v1.h"
 
 /* for OOM */
@@ -270,7 +271,9 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
 {
 	struct mem_cgroup *memcg;
 	struct obj_cgroup *objcg;
-	unsigned int nr_entries;
+	struct swap_cluster_info_dynamic *ci_dyn;
+	unsigned int nr_entries, nr_swapfile;
+	unsigned int start, i;
 	unsigned short private_id;
 
 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
@@ -298,10 +301,21 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
 	 * if the ID refers to the root memcg.
 	 */
 	nr_entries = folio_nr_pages(folio);
+	start = swp_cluster_offset(folio->swap);
 	private_id = mem_cgroup_private_id_get(memcg, nr_entries);
-	mod_memcg_state(memcg, MEMCG_SWAP, nr_entries);
+	nr_swapfile = nr_entries;
+	if (is_vswap_entry(folio->swap)) {
+		nr_swapfile = 0;
+		ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+		for (i = start; i < start + nr_entries; i++)
+			if (vtable_type(__vtable_get(ci_dyn, i)) == VSWAP_SWAPFILE)
+				nr_swapfile++;
+	}
+
+	if (nr_swapfile)
+		mod_memcg_state(memcg, MEMCG_SWAP, nr_swapfile);
 
-	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_entries, private_id);
+	__swap_cgroup_set(ci, start, nr_entries, private_id);
 
 	folio_unqueue_deferred_split(folio);
 	folio->memcg_data = 0;
@@ -340,8 +354,11 @@ void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
 void memcg1_swapin(struct folio *folio)
 {
 	struct swap_cluster_info *ci;
+	struct swap_cluster_info_dynamic *ci_dyn;
 	unsigned long nr_pages;
+	unsigned int start, i, nr_swapfile = 0;
 	unsigned short id;
+	bool is_vswap;
 
 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
@@ -366,12 +383,26 @@ void memcg1_swapin(struct folio *folio)
 	 * let's not wait for it.  The page already received a
 	 * memory+swap charge, drop the swap entry duplicate.
 	 */
+	is_vswap = is_vswap_entry(folio->swap);
 	nr_pages = folio_nr_pages(folio);
+	start = swp_cluster_offset(folio->swap);
 	ci = swap_cluster_get_and_lock(folio);
-	id = __swap_cgroup_clear(ci, swp_cluster_offset(folio->swap),
-				 nr_pages);
+	id = __swap_cgroup_clear(ci, start, nr_pages);
+	if (id && is_vswap) {
+		ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+		for (i = start; i < start + nr_pages; i++)
+			if (vtable_type(__vtable_get(ci_dyn, i)) == VSWAP_SWAPFILE)
+				nr_swapfile++;
+	}
 	swap_cluster_unlock(ci);
-	mem_cgroup_uncharge_swap(id, nr_pages);
+	if (!id)
+		return;
+	if (is_vswap) {
+		mem_cgroup_swap_uncharge(id, nr_pages, nr_swapfile);
+		mem_cgroup_swap_put(id, nr_pages);
+	} else {
+		mem_cgroup_dir_phys_swap_free(id, nr_pages);
+	}
 }
 #endif
 
diff --git a/mm/memcontrol-v1.h b/mm/memcontrol-v1.h
index 820139657184..3eeac14aeecf 100644
--- a/mm/memcontrol-v1.h
+++ b/mm/memcontrol-v1.h
@@ -124,4 +124,23 @@ static inline void memcg1_uncharge_skmem(struct mem_cgroup *memcg, unsigned int
 
 #endif	/* CONFIG_MEMCG_V1 */
 
+#if defined(CONFIG_MEMCG) && defined(CONFIG_SWAP)
+void __mem_cgroup_swap_uncharge(unsigned short id, unsigned int nr_pages,
+				unsigned int nr_swapfile);
+static inline void mem_cgroup_swap_uncharge(unsigned short id,
+					    unsigned int nr_pages,
+					    unsigned int nr_swapfile)
+{
+	if ((!nr_swapfile && !do_memsw_account()) || mem_cgroup_disabled())
+		return;
+	__mem_cgroup_swap_uncharge(id, nr_pages, nr_swapfile);
+}
+#else
+static inline void mem_cgroup_swap_uncharge(unsigned short id,
+					    unsigned int nr_pages,
+					    unsigned int nr_swapfile)
+{
+}
+#endif
+
 #endif	/* __MM_MEMCONTROL_V1_H */
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 978c47ad4b93..571f375b2e7f 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -66,6 +66,7 @@
 #include "internal.h"
 #include "swap.h"
 #include "swap_table.h"
+#include "vswap.h"
 #include <net/sock.h>
 #include <net/ip.h>
 #include "slab.h"
@@ -6050,18 +6051,27 @@ void memcg1_swapin_abort(struct folio *folio, struct swap_cluster_info *ci)
 {
 	unsigned int start = swp_cluster_offset(folio->swap);
 	unsigned int end = start + folio_nr_pages(folio);
-	unsigned int i, nr = 0;
+	unsigned int i, nr = 0, nr_swapfile = 0;
 	struct mem_cgroup *memcg;
 	struct obj_cgroup *objcg;
+	struct swap_cluster_info_dynamic *ci_dyn;
 	unsigned short id;
+	bool is_vswap = is_vswap_entry(folio->swap);
 
 	if (mem_cgroup_disabled() || !do_memsw_account())
 		return;
 
 	lockdep_assert_held(&ci->lock);
-	for (i = start; i < end; i++)
-		if (__swp_tb_get_count(__swap_table_get(ci, i)))
-			nr++;
+	if (is_vswap)
+		ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+	for (i = start; i < end; i++) {
+		if (!__swp_tb_get_count(__swap_table_get(ci, i)))
+			continue;
+		nr++;
+		if (!is_vswap ||
+		    vtable_type(__vtable_get(ci_dyn, i)) == VSWAP_SWAPFILE)
+			nr_swapfile++;
+	}
 	if (!nr)
 		return;
 
@@ -6076,7 +6086,8 @@ void memcg1_swapin_abort(struct folio *folio, struct swap_cluster_info *ci)
 	memcg = obj_cgroup_memcg(obj_cgroup_from_private_id(id));
 	if (!mem_cgroup_private_id_is_root(id))
 		page_counter_charge(&memcg->memsw, nr);
-	mod_memcg_state(memcg, MEMCG_SWAP, nr);
+	if (nr_swapfile)
+		mod_memcg_state(memcg, MEMCG_SWAP, nr_swapfile);
 
 	for (i = start; i < end; i++)
 		if (__swp_tb_get_count(__swap_table_get(ci, i)))
@@ -6085,21 +6096,20 @@ void memcg1_swapin_abort(struct folio *folio, struct swap_cluster_info *ci)
 #endif
 
 /**
- * __mem_cgroup_try_charge_swap - try charging swap space for a folio
+ * __mem_cgroup_swap_get - pin the memcg to account a folio's swap slots to
  * @folio: folio being added to swap
  *
- * Try to charge @folio's memcg for the swap space at folio->swap.
+ * Pins one live private ID ref per page of @folio. The caller charges and
+ * records using the returned ID, including when its owner is reparented.
  *
- * Returns 0 on success, -ENOMEM on failure.
+ * Return: the pinned private ID, or 0 if there is nothing to account. Drop
+ * the pins with __mem_cgroup_swap_put().
  */
-int __mem_cgroup_try_charge_swap(struct folio *folio)
+unsigned short __mem_cgroup_swap_get(struct folio *folio)
 {
 	unsigned int nr_pages = folio_nr_pages(folio);
-	struct swap_cluster_info *ci;
-	struct page_counter *counter;
 	struct mem_cgroup *memcg;
 	struct obj_cgroup *objcg;
-	unsigned short private_id;
 
 	if (do_memsw_account())
 		return 0;
@@ -6109,38 +6119,85 @@ int __mem_cgroup_try_charge_swap(struct folio *folio)
 	if (!objcg)
 		return 0;
 
-	scoped_guard(rcu) {
-		memcg = obj_cgroup_memcg(objcg);
-		if (!folio_test_swapcache(folio)) {
-			memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
-			return 0;
-		}
+	guard(rcu)();
+	memcg = obj_cgroup_memcg(objcg);
+	if (!folio_test_swapcache(folio)) {
+		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
+		return 0;
+	}
 
-		private_id = mem_cgroup_private_id_get(memcg, nr_pages);
+	return mem_cgroup_private_id_get(memcg, nr_pages);
+}
 
-		if (!mem_cgroup_private_id_is_root(private_id) &&
-		    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
-			memcg_memory_event(memcg, MEMCG_SWAP_MAX);
-			memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
-			mem_cgroup_private_id_put(private_id, nr_pages);
-			return -ENOMEM;
-		}
-		mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
+/**
+ * __mem_cgroup_swap_fail - report a failed physical swap allocation
+ * @id: the pinned private ID of the swap owner (may be 0)
+ */
+void __mem_cgroup_swap_fail(unsigned short id)
+{
+	struct mem_cgroup *memcg;
+
+	if (do_memsw_account() || !id)
+		return;
+
+	guard(rcu)();
+	memcg = obj_cgroup_memcg(obj_cgroup_from_private_id(id));
+	memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
+}
+
+/**
+ * __mem_cgroup_swap_charge - charge physical swap space
+ * @id: the private ID to charge (may be 0)
+ * @nr_pages: the amount of swap space to charge
+ *
+ * Return: 0 on success, -ENOMEM if memory.swap.max is exceeded.
+ */
+int __mem_cgroup_swap_charge(unsigned short id, unsigned int nr_pages)
+{
+	struct page_counter *counter;
+	struct mem_cgroup *memcg;
+
+	if (do_memsw_account() || !id)
+		return 0;
+
+	guard(rcu)();
+	memcg = obj_cgroup_memcg(obj_cgroup_from_private_id(id));
+	if (!mem_cgroup_private_id_is_root(id) &&
+	    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
+		memcg_memory_event(memcg, MEMCG_SWAP_MAX);
+		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
+		return -ENOMEM;
 	}
+	mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
+	return 0;
+}
+
+/**
+ * __mem_cgroup_swap_record - record the owner of a folio's swap slots
+ * @folio: folio being added to swap
+ * @id: the private ID pinned by __mem_cgroup_swap_get()
+ */
+void __mem_cgroup_swap_record(struct folio *folio, unsigned short id)
+{
+	struct swap_cluster_info *ci;
 
 	ci = swap_cluster_get_and_lock(folio);
-	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_pages, private_id);
+	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap),
+			  folio_nr_pages(folio), id);
 	swap_cluster_unlock(ci);
-
-	return 0;
 }
 
 /**
- * __mem_cgroup_uncharge_swap - uncharge swap space
+ * __mem_cgroup_dir_phys_swap_free - uncharge and drop the reference for
+ * directly mapped physical swap entries
  * @id: cgroup id to uncharge
- * @nr_pages: the amount of swap space to uncharge
+ * @nr_pages: number of directly mapped physical swap entries
+ *
+ * This is roughly equivalent to calling mem_cgroup_swap_uncharge()
+ * followed by mem_cgroup_swap_put(). Reuse the resolved owner to avoid
+ * a second lookup.
  */
-void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
+void __mem_cgroup_dir_phys_swap_free(unsigned short id, unsigned int nr_pages)
 {
 	struct obj_cgroup *objcg;
 	struct mem_cgroup *memcg;
@@ -6161,6 +6218,61 @@ void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
 	rcu_read_unlock();
 }
 
+/**
+ * __mem_cgroup_swap_uncharge - release cgroup charges for a vswap range
+ * @id: the private ID to uncharge (may be 0)
+ * @nr_pages: total number of pages in the range
+ * @nr_swapfile: number of pages in the range backed by physical swap
+ *
+ * MEMCG_SWAP counts physically backed slots attributed to the swap
+ * owner. Subtract @nr_swapfile from it in both cgroup hierarchies.
+ *
+ * In v1, uncharge @nr_pages from memsw because it covers the whole
+ * range. In v2, uncharge @nr_swapfile from the swap counter because
+ * it covers physical backing.
+ *
+ * In v1, __memcg1_swapout() records the owner when a folio leaves
+ * swapcache, and memcg1_swapin() clears it when the folio returns.
+ * Both changes happen under the cluster lock. Backing release on a
+ * cached folio sees no owner after the swap-in charge transfer.
+ *
+ * In v2, the owner is recorded at swap allocation and remains while
+ * the folio is cached. Backing release balances the charge taken by
+ * folio_realloc_swap().
+ *
+ * The caller releases the private ID references separately.
+ */
+void __mem_cgroup_swap_uncharge(unsigned short id, unsigned int nr_pages,
+				unsigned int nr_swapfile)
+{
+	struct mem_cgroup *memcg;
+
+	if (!id)
+		return;
+
+	guard(rcu)();
+	memcg = obj_cgroup_memcg(obj_cgroup_from_private_id(id));
+	if (!mem_cgroup_private_id_is_root(id)) {
+		if (do_memsw_account())
+			page_counter_uncharge(&memcg->memsw, nr_pages);
+		else if (nr_swapfile)
+			page_counter_uncharge(&memcg->swap, nr_swapfile);
+	}
+	if (nr_swapfile)
+		mod_memcg_state(memcg, MEMCG_SWAP, -nr_swapfile);
+}
+
+/**
+ * __mem_cgroup_swap_put - drop the private ID refs taken for swap slots
+ * @id: the pinned private ID
+ * @nr_pages: number of refs to drop
+ */
+void __mem_cgroup_swap_put(unsigned short id, unsigned int nr_pages)
+{
+	guard(rcu)();
+	mem_cgroup_private_id_put(id, nr_pages);
+}
+
 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg)
 {
 	long nr_swap_pages = get_nr_swap_pages();
@@ -6203,11 +6315,8 @@ long mem_cgroup_get_folio_swap_margin(const struct folio *folio)
  */
 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;
+	return mem_cgroup_can_vswap(memcg) ||
+	       mem_cgroup_get_nr_swap_pages(memcg) >= nr_pages;
 }
 
 bool mem_cgroup_swap_full(const struct folio *folio)
diff --git a/mm/swapfile.c b/mm/swapfile.c
index afc48d33cc40..a1eef85b9eb6 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -47,6 +47,7 @@
 
 #include <asm/tlbflush.h>
 #include <linux/leafops.h>
+#include "memcontrol-v1.h"
 #include "swap_table.h"
 #include "vswap.h"
 #include "internal.h"
@@ -2110,6 +2111,7 @@ static swp_entry_t folio_alloc_phys_swap(struct folio *folio)
 int folio_alloc_swap(struct folio *folio)
 {
 	unsigned int order = folio_order(folio);
+	unsigned short memcg_id;
 	unsigned int size = 1 << order;
 	bool may_vswap;
 
@@ -2139,10 +2141,20 @@ int folio_alloc_swap(struct folio *folio)
 	if (!may_vswap || !vswap_alloc(folio))
 		folio_alloc_phys_swap(folio);
 
-	/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */
-	if (unlikely(mem_cgroup_try_charge_swap(folio))) {
-		swap_cache_del_folio(folio);
-		goto failed;
+	/*
+	 * Need to call this even if allocation failed, for MEMCG_SWAP_FAIL.
+	 * A vswap entry has no physical swap yet, so only record the memcg.
+	 * folio_realloc_swap() charges it once backing is allocated.
+	 */
+	memcg_id = mem_cgroup_swap_get(folio);
+	if (memcg_id) {
+		if (!is_vswap_entry(folio->swap) &&
+		    unlikely(mem_cgroup_swap_charge(memcg_id, size))) {
+			mem_cgroup_swap_put(memcg_id, size);
+			swap_cache_del_folio(folio);
+		} else {
+			mem_cgroup_swap_record(folio, memcg_id);
+		}
 	}
 
 	if (unlikely(!folio_test_swapcache(folio)))
@@ -2153,7 +2165,7 @@ int folio_alloc_swap(struct folio *folio)
 failed:
 	if (get_nr_swap_pages() <= 0 && !may_vswap)
 		return -ENOSPC;
-	if (mem_cgroup_get_folio_swap_margin(folio) <= 0)
+	if (!may_vswap && mem_cgroup_get_folio_swap_margin(folio) <= 0)
 		return -ENOMEM;
 
 	return order ? -E2BIG : -ENOMEM;
@@ -2224,12 +2236,25 @@ void __vswap_release_backing(struct swap_cluster_info *ci,
 	unsigned int ci_off;
 	unsigned long vt;
 	swp_entry_t phys_first = {};
+	unsigned short batch_id, cur_id;
+	unsigned int batch_nr = 0, batch_nr_swapfile = 0;
 
 	lockdep_assert_held(&ci->lock);
 	ci_dyn = container_of(ci, struct swap_cluster_info_dynamic, ci);
+	batch_id = __swap_cgroup_get(ci, ci_start);
 
 	for (ci_off = ci_start; ci_off < ci_start + nr; ci_off++) {
 		vt = __vtable_get(ci_dyn, ci_off);
+		cur_id = __swap_cgroup_get(ci, ci_off);
+
+		if (cur_id != batch_id) {
+			mem_cgroup_swap_uncharge(batch_id, batch_nr,
+						 batch_nr_swapfile);
+			batch_id = cur_id;
+			batch_nr = 0;
+			batch_nr_swapfile = 0;
+		}
+		batch_nr++;
 
 		/* The free helper takes one contiguous run within one cluster. */
 		if (phys_off_start != phys_off_end &&
@@ -2247,6 +2272,7 @@ void __vswap_release_backing(struct swap_cluster_info *ci,
 
 		switch (vtable_type(vt)) {
 		case VSWAP_SWAPFILE:
+			batch_nr_swapfile++;
 			if (phys_off_start == phys_off_end) {
 				phys_first = vtable_to_phys(vt);
 				phys_off_start = swp_offset(phys_first);
@@ -2278,6 +2304,8 @@ void __vswap_release_backing(struct swap_cluster_info *ci,
 				phys_off_start % SWAPFILE_CLUSTER,
 				phys_off_end - phys_off_start);
 	}
+
+	mem_cgroup_swap_uncharge(batch_id, batch_nr, batch_nr_swapfile);
 }
 
 /**
@@ -2368,6 +2396,8 @@ swp_entry_t folio_realloc_swap(struct folio *folio)
 	struct swap_cluster_info *ci;
 	struct swap_cluster_info_dynamic *ci_dyn;
 	unsigned int voff;
+	unsigned long vt;
+	unsigned short memcg_id;
 	swp_entry_t phys_entry = {};
 	swp_entry_t pe;
 	int i, nr = folio_nr_pages(folio);
@@ -2376,18 +2406,33 @@ swp_entry_t folio_realloc_swap(struct 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;
+	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);
+	vt = __vtable_get(ci_dyn, voff);
+	if (vtable_type(vt) == VSWAP_SWAPFILE) {
+		spin_unlock(&ci->lock);
+		return vtable_to_phys(vt);
+	}
+	memcg_id = __swap_cgroup_get(ci, voff);
+	spin_unlock(&ci->lock);
 
 	phys_entry = folio_alloc_phys_swap(folio);
-	if (!phys_entry.val)
+	if (!phys_entry.val) {
+		mem_cgroup_swap_fail(memcg_id);
 		return (swp_entry_t){};
+	}
 
-	voff = swp_cluster_offset(vswap_entry);
+	if (mem_cgroup_swap_charge(memcg_id, nr)) {
+		__swap_cluster_free_phys_backing(__swap_entry_to_info(phys_entry),
+						 __swap_entry_to_cluster(phys_entry),
+						 swp_cluster_offset(phys_entry),
+						 nr);
+		return (swp_entry_t){};
+	}
 
-	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
@@ -2572,6 +2617,18 @@ static void __swap_cluster_free_phys_backing(struct swap_info_struct *psi,
 	swap_cluster_unlock(pci);
 }
 
+/*
+ * Release cgroup accounting for freed swap slots. Physical backing of
+ * vswap entries was already uncharged by __vswap_release_backing().
+ */
+static void memcg_swap_free(unsigned short id, unsigned int nr, bool is_vswap)
+{
+	if (is_vswap)
+		mem_cgroup_swap_put(id, nr);
+	else
+		mem_cgroup_dir_phys_swap_free(id, nr);
+}
+
 /*
  * 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).
@@ -2584,10 +2641,11 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 	unsigned short batch_id = 0, id_cur;
 	unsigned int ci_off = ci_start, ci_end = ci_start + nr_pages;
 	unsigned int batch_off = ci_off;
+	bool is_vswap = swap_is_vswap(si);
 
 	VM_WARN_ON(ci->count < nr_pages);
 
-	if (swap_is_vswap(si))
+	if (is_vswap)
 		__vswap_release_backing(ci, ci_start, nr_pages);
 
 	ci->count -= nr_pages;
@@ -2613,14 +2671,14 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 		id_cur = __swap_cgroup_clear(ci, ci_off, 1);
 		if (batch_id != id_cur) {
 			if (batch_id)
-				mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
+				memcg_swap_free(batch_id, ci_off - batch_off, is_vswap);
 			batch_id = id_cur;
 			batch_off = ci_off;
 		}
 	} while (++ci_off < ci_end);
 
 	if (batch_id)
-		mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
+		memcg_swap_free(batch_id, ci_off - batch_off, is_vswap);
 
 	__swap_cluster_finish_free(si, ci, ci_start, nr_pages);
 }
diff --git a/mm/zswap.c b/mm/zswap.c
index 54b4ddcf7d73..f1f0fdf3945d 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1220,11 +1220,17 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
  * With vswap disabled, all zswap entries use directly mapped physical swap
  * entries. With vswap enabled, such entries are rare.
  *
- * A zswap-backed vswap entry needs physical swap capacity for writeback.
+ * A zswap-backed vswap entry needs physical swap capacity for writeback
+ * and cgroup swap margin where applicable. @memcg may be NULL to check
+ * device capacity alone.
  */
-static bool zswap_writeback_possible(void)
+static bool zswap_writeback_possible(struct mem_cgroup *memcg)
 {
-	return !vswap_is_enabled() || get_nr_swap_pages() > 0;
+	if (!vswap_is_enabled())
+		return true;
+	if (!memcg)
+		return get_nr_swap_pages() > 0;
+	return mem_cgroup_get_nr_swap_pages(memcg) > 0;
 }
 
 /*
@@ -1372,7 +1378,7 @@ static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
 	if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
 		return 0;
 
-	if (!zswap_writeback_possible())
+	if (!zswap_writeback_possible(memcg))
 		return 0;
 
 	/*
@@ -1459,7 +1465,7 @@ static struct shrinker *zswap_alloc_shrinker(void)
  * writeback disabled, is a zombie cgroup, or has empty zswap LRUs.
  *
  * Also returns -ENOENT when vswap is enabled and there is no physical
- * swap to write back to.
+ * swap for @memcg to write back to.
  */
 static int shrink_memcg(struct mem_cgroup *memcg)
 {
@@ -1470,7 +1476,7 @@ static int shrink_memcg(struct mem_cgroup *memcg)
 	if (!mem_cgroup_zswap_writeback_enabled(memcg))
 		return -ENOENT;
 
-	if (!zswap_writeback_possible())
+	if (!zswap_writeback_possible(memcg))
 		return -ENOENT;
 
 	/*
@@ -1505,7 +1511,7 @@ static void shrink_worker(struct work_struct *w)
 	int ret, failures = 0, attempts = 0;
 	unsigned long thr;
 
-	if (!zswap_writeback_possible())
+	if (!zswap_writeback_possible(NULL))
 		return;
 
 	/* Reclaim down to the accept threshold */
@@ -1586,7 +1592,7 @@ static void shrink_worker(struct work_struct *w)
 			break;
 resched:
 		cond_resched();
-	} while (zswap_total_pages() > thr && zswap_writeback_possible());
+	} while (zswap_total_pages() > thr && zswap_writeback_possible(NULL));
 }
 
 /*********************************
-- 
2.53.1-Meta


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

Thread overview: 22+ 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 ` [PATCH v7 08/20] mm/swap: support physical swap as a vswap backend Nhat Pham
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 ` Nhat Pham [this message]
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

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-14-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