Skip to contentSkip to conversation

Eliminate Dying Memory Cgroup

PATCH Superseded Qi Zheng 12 participants 107 messages Oct 28, 2025 – Dec 2, 2025

Subsystems (18)
Memory management VFS MM core Tracing +14 more subsystems

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Qi Zheng

author reviewer
#0 lore raw

cover Eliminate Dying Memory Cgroup

From: Qi Zheng <[email protected]>

Hi all,

This series aims to eliminate the problem of dying memory cgroup. It completes the adaptation to the MGLRU scenarios based on the Muchun Song's patchset[1].

The adaptation method was discussed with Harry Yoo. For more details, please refer to the commit message of [PATCH v1 23/26].

The changes are as follows:
- drop [PATCH RFC 02/28]
- drop THP split queue related part, which has been merged as a separate patchset[2]
- prevent memory cgroup release in folio_split_queue_lock{_irqsave}() in [PATCH v1 16/26]
- Separate the reparenting function of traditional LRU folios to [PATCH v1 22/26]
- adapted to the MGLRU scenarios in [PATCH v1 23/26]
- refactor memcg_reparent_objcgs() in [PATCH v1 24/26]
- collect Acked-bys and Reviewed-bys
- rebase onto the next-20251028

Comments and suggestions are welcome!

Thanks,
Qi

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

Muchun Song (22):
mm: memcontrol: remove dead code of checking parent memory cgroup
mm: workingset: use folio_lruvec() in workingset_refault()
mm: rename unlock_page_lruvec_irq and its variants
mm: vmscan: refactor move_folios_to_lru()
mm: memcontrol: allocate object cgroup for non-kmem case
mm: memcontrol: return root object cgroup for root memory cgroup
mm: memcontrol: prevent memory cgroup release in
get_mem_cgroup_from_folio()
buffer: prevent memory cgroup release in folio_alloc_buffers()
writeback: prevent memory cgroup release in writeback module
mm: memcontrol: prevent memory cgroup release in
count_memcg_folio_events()
mm: page_io: prevent memory cgroup release in page_io module
mm: migrate: prevent memory cgroup release in folio_migrate_mapping()
mm: mglru: prevent memory cgroup release in mglru
mm: memcontrol: prevent memory cgroup release in
mem_cgroup_swap_full()
mm: workingset: prevent memory cgroup release in lru_gen_eviction()
mm: workingset: prevent lruvec release in workingset_refault()
mm: zswap: prevent lruvec release in zswap_folio_swapin()
mm: swap: prevent lruvec release in swap module
mm: workingset: prevent lruvec release in workingset_activation()
mm: memcontrol: prepare for reparenting LRU pages for lruvec lock
mm: memcontrol: eliminate the problem of dying memory cgroup for LRU
folios
mm: lru: add VM_WARN_ON_ONCE_FOLIO to lru maintenance helpers

Qi Zheng (4):
mm: thp: prevent memory cgroup release in
folio_split_queue_lock{_irqsave}()
mm: vmscan: prepare for reparenting traditional LRU folios
mm: vmscan: prepare for reparenting MGLRU folios
mm: memcontrol: refactor memcg_reparent_objcgs()

 fs/buffer.c                      |   4 +-
 fs/fs-writeback.c                |  22 +-
 include/linux/memcontrol.h       | 159 ++++++------
 include/linux/mm_inline.h        |   6 +
 include/linux/mmzone.h           |  20 ++
 include/trace/events/writeback.h |   3 +
 mm/compaction.c                  |  43 +++-
 mm/huge_memory.c                 |  18 +-
 mm/memcontrol-v1.c               |  15 +-
 mm/memcontrol.c                  | 405 ++++++++++++++++++-------------
 mm/migrate.c                     |   2 +
 mm/mlock.c                       |   2 +-
 mm/page_io.c                     |   8 +-
 mm/percpu.c                      |   2 +-
 mm/shrinker.c                    |   6 +-
 mm/swap.c                        |  20 +-
 mm/vmscan.c                      | 198 ++++++++++++---
 mm/workingset.c                  |  26 +-
 mm/zswap.c                       |   2 +
 19 files changed, 612 insertions(+), 349 deletions(-)
Signature · 1 line
2.20.1
author reviewer
#1 lore raw

PATCH 1/26 mm: memcontrol: remove dead code of checking parent memory cgroup

From: Muchun Song <[email protected]>

Since the no-hierarchy mode has been deprecated after the commit:

commit bef8620cd8e0 ("mm: memcg: deprecate the non-hierarchical mode").

As a result, parent_mem_cgroup() will not return NULL except when passing the root memcg, and the root memcg cannot be offline. Hence, it's safe to remove the check on the returned value of parent_mem_cgroup(). Remove the corresponding dead code.

---
 mm/memcontrol.c | 5 -----
 mm/shrinker.c   | 6 +-----
 2 files changed, 1 insertion(+), 10 deletions(-)
mm/memcontrol.c +0 -5
index 93f7c76f0ce96..d5257465c9d75 100644
@@ -3339,9 +3339,6 @@ static void memcg_offline_kmem(struct mem_cgroup *memcg)
 		return;
 
 	parent = parent_mem_cgroup(memcg);
-	if (!parent)
-		parent = root_mem_cgroup;
-
 	memcg_reparent_list_lrus(memcg, parent);
 
 	/*
@@ -3632,8 +3629,6 @@ struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
 			break;
 		}
 		memcg = parent_mem_cgroup(memcg);
-		if (!memcg)
-			memcg = root_mem_cgroup;
 	}
 	return memcg;
 }
mm/shrinker.c +1 -5
index 4a93fd433689a..e8e092a2f7f41 100644
@@ -286,14 +286,10 @@ void reparent_shrinker_deferred(struct mem_cgroup *memcg)
 {
 	int nid, index, offset;
 	long nr;
-	struct mem_cgroup *parent;
+	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
 	struct shrinker_info *child_info, *parent_info;
 	struct shrinker_info_unit *child_unit, *parent_unit;
 
-	parent = parent_mem_cgroup(memcg);
-	if (!parent)
-		parent = root_mem_cgroup;
-
 	/* Prevent from concurrent shrinker_info expand */
 	mutex_lock(&shrinker_mutex);
 	for_each_node(nid) {
Signature · 1 line
2.20.1
author reviewer
#4 lore raw

PATCH 2/26 mm: workingset: use folio_lruvec() in workingset_refault()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

Use folio_lruvec() to simplify the code.

---
 mm/workingset.c | 7 +------
 1 file changed, 1 insertion(+), 6 deletions(-)
mm/workingset.c +1 -6
index 68a76a91111f4..8cad8ee6dec6a 100644
@@ -534,8 +534,6 @@ bool workingset_test_recent(void *shadow, bool file, bool *workingset,
 void workingset_refault(struct folio *folio, void *shadow)
 {
 	bool file = folio_is_file_lru(folio);
-	struct pglist_data *pgdat;
-	struct mem_cgroup *memcg;
 	struct lruvec *lruvec;
 	bool workingset;
 	long nr;
@@ -557,10 +555,7 @@ void workingset_refault(struct folio *folio, void *shadow)
 	 * locked to guarantee folio_memcg() stability throughout.
 	 */
 	nr = folio_nr_pages(folio);
-	memcg = folio_memcg(folio);
-	pgdat = folio_pgdat(folio);
-	lruvec = mem_cgroup_lruvec(memcg, pgdat);
-
+	lruvec = folio_lruvec(folio);
 	mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + file, nr);
 
 	if (!workingset_test_recent(shadow, file, &workingset, true))
Signature · 1 line
2.20.1
author reviewer
#6 lore raw

PATCH 3/26 mm: rename unlock_page_lruvec_irq and its variants

In reply to Qi Zheng

From: Muchun Song <[email protected]>

It is inappropriate to use folio_lruvec_lock() variants in conjunction with unlock_page_lruvec() variants, as this involves the inconsistent operation of locking a folio while unlocking a page. To rectify this, the functions unlock_page_lruvec{_irq, _irqrestore} are renamed to lruvec_unlock{_irq,_irqrestore}.

---
 include/linux/memcontrol.h | 10 +++++-----
 mm/compaction.c            | 14 +++++++-------
 mm/huge_memory.c           |  2 +-
 mm/mlock.c                 |  2 +-
 mm/swap.c                  | 12 ++++++------
 mm/vmscan.c                |  4 ++--
 6 files changed, 22 insertions(+), 22 deletions(-)
include/linux/memcontrol.h +5 -5
index 8d2e250535a8a..6185d8399a54e 100644
@@ -1493,17 +1493,17 @@ static inline struct lruvec *parent_lruvec(struct lruvec *lruvec)
 	return mem_cgroup_lruvec(memcg, lruvec_pgdat(lruvec));
 }
 
-static inline void unlock_page_lruvec(struct lruvec *lruvec)
+static inline void lruvec_unlock(struct lruvec *lruvec)
 {
 	spin_unlock(&lruvec->lru_lock);
 }
 
-static inline void unlock_page_lruvec_irq(struct lruvec *lruvec)
+static inline void lruvec_unlock_irq(struct lruvec *lruvec)
 {
 	spin_unlock_irq(&lruvec->lru_lock);
 }
 
-static inline void unlock_page_lruvec_irqrestore(struct lruvec *lruvec,
+static inline void lruvec_unlock_irqrestore(struct lruvec *lruvec,
 		unsigned long flags)
 {
 	spin_unlock_irqrestore(&lruvec->lru_lock, flags);
@@ -1525,7 +1525,7 @@ static inline struct lruvec *folio_lruvec_relock_irq(struct folio *folio,
 		if (folio_matches_lruvec(folio, locked_lruvec))
 			return locked_lruvec;
 
-		unlock_page_lruvec_irq(locked_lruvec);
+		lruvec_unlock_irq(locked_lruvec);
 	}
 
 	return folio_lruvec_lock_irq(folio);
@@ -1539,7 +1539,7 @@ static inline void folio_lruvec_relock_irqsave(struct folio *folio,
 		if (folio_matches_lruvec(folio, *lruvecp))
 			return;
 
-		unlock_page_lruvec_irqrestore(*lruvecp, *flags);
+		lruvec_unlock_irqrestore(*lruvecp, *flags);
 	}
 
 	*lruvecp = folio_lruvec_lock_irqsave(folio, flags);
mm/compaction.c +7 -7
index 8760d10bd0b32..4dce180f699b4 100644
@@ -913,7 +913,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 		 */
 		if (!(low_pfn % COMPACT_CLUSTER_MAX)) {
 			if (locked) {
-				unlock_page_lruvec_irqrestore(locked, flags);
+				lruvec_unlock_irqrestore(locked, flags);
 				locked = NULL;
 			}
 
@@ -964,7 +964,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 			}
 			/* for alloc_contig case */
 			if (locked) {
-				unlock_page_lruvec_irqrestore(locked, flags);
+				lruvec_unlock_irqrestore(locked, flags);
 				locked = NULL;
 			}
 
@@ -1053,7 +1053,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 			if (unlikely(page_has_movable_ops(page)) &&
 			    !PageMovableOpsIsolated(page)) {
 				if (locked) {
-					unlock_page_lruvec_irqrestore(locked, flags);
+					lruvec_unlock_irqrestore(locked, flags);
 					locked = NULL;
 				}
 
@@ -1158,7 +1158,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 		/* If we already hold the lock, we can skip some rechecking */
 		if (lruvec != locked) {
 			if (locked)
-				unlock_page_lruvec_irqrestore(locked, flags);
+				lruvec_unlock_irqrestore(locked, flags);
 
 			compact_lock_irqsave(&lruvec->lru_lock, &flags, cc);
 			locked = lruvec;
@@ -1226,7 +1226,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 isolate_fail_put:
 		/* Avoid potential deadlock in freeing page under lru_lock */
 		if (locked) {
-			unlock_page_lruvec_irqrestore(locked, flags);
+			lruvec_unlock_irqrestore(locked, flags);
 			locked = NULL;
 		}
 		folio_put(folio);
@@ -1242,7 +1242,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 		 */
 		if (nr_isolated) {
 			if (locked) {
-				unlock_page_lruvec_irqrestore(locked, flags);
+				lruvec_unlock_irqrestore(locked, flags);
 				locked = NULL;
 			}
 			putback_movable_pages(&cc->migratepages);
@@ -1274,7 +1274,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 
 isolate_abort:
 	if (locked)
-		unlock_page_lruvec_irqrestore(locked, flags);
+		lruvec_unlock_irqrestore(locked, flags);
 	if (folio) {
 		folio_set_lru(folio);
 		folio_put(folio);
mm/huge_memory.c +1 -1
index 0a826b6e6aa7f..9d3594df6eedf 100644
@@ -4014,7 +4014,7 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
 		expected_refs = folio_expected_ref_count(folio) + 1;
 		folio_ref_unfreeze(folio, expected_refs);
 
-		unlock_page_lruvec(lruvec);
+		lruvec_unlock(lruvec);
 
 		if (ci)
 			swap_cluster_unlock(ci);
mm/mlock.c +1 -1
index bb0776f5ef7ca..5a81de8dd4875 100644
@@ -205,7 +205,7 @@ static void mlock_folio_batch(struct folio_batch *fbatch)
 	}
 
 	if (lruvec)
-		unlock_page_lruvec_irq(lruvec);
+		lruvec_unlock_irq(lruvec);
 	folios_put(fbatch);
 }
 
mm/swap.c +6 -6
index 2260dcd2775e7..ec0c654e128dc 100644
@@ -91,7 +91,7 @@ static void page_cache_release(struct folio *folio)
 
 	__page_cache_release(folio, &lruvec, &flags);
 	if (lruvec)
-		unlock_page_lruvec_irqrestore(lruvec, flags);
+		lruvec_unlock_irqrestore(lruvec, flags);
 }
 
 void __folio_put(struct folio *folio)
@@ -175,7 +175,7 @@ static void folio_batch_move_lru(struct folio_batch *fbatch, move_fn_t move_fn)
 	}
 
 	if (lruvec)
-		unlock_page_lruvec_irqrestore(lruvec, flags);
+		lruvec_unlock_irqrestore(lruvec, flags);
 	folios_put(fbatch);
 }
 
@@ -349,7 +349,7 @@ void folio_activate(struct folio *folio)
 
 	lruvec = folio_lruvec_lock_irq(folio);
 	lru_activate(lruvec, folio);
-	unlock_page_lruvec_irq(lruvec);
+	lruvec_unlock_irq(lruvec);
 	folio_set_lru(folio);
 }
 #endif
@@ -963,7 +963,7 @@ void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
 
 		if (folio_is_zone_device(folio)) {
 			if (lruvec) {
-				unlock_page_lruvec_irqrestore(lruvec, flags);
+				lruvec_unlock_irqrestore(lruvec, flags);
 				lruvec = NULL;
 			}
 			if (folio_ref_sub_and_test(folio, nr_refs))
@@ -977,7 +977,7 @@ void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
 		/* hugetlb has its own memcg */
 		if (folio_test_hugetlb(folio)) {
 			if (lruvec) {
-				unlock_page_lruvec_irqrestore(lruvec, flags);
+				lruvec_unlock_irqrestore(lruvec, flags);
 				lruvec = NULL;
 			}
 			free_huge_folio(folio);
@@ -991,7 +991,7 @@ void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
 		j++;
 	}
 	if (lruvec)
-		unlock_page_lruvec_irqrestore(lruvec, flags);
+		lruvec_unlock_irqrestore(lruvec, flags);
 	if (!j) {
 		folio_batch_reinit(folios);
 		return;
mm/vmscan.c +2 -2
index c922bad2b8fd4..3a1044ce30f1e 100644
@@ -1829,7 +1829,7 @@ bool folio_isolate_lru(struct folio *folio)
 		folio_get(folio);
 		lruvec = folio_lruvec_lock_irq(folio);
 		lruvec_del_folio(lruvec, folio);
-		unlock_page_lruvec_irq(lruvec);
+		lruvec_unlock_irq(lruvec);
 		ret = true;
 	}
 
@@ -7849,7 +7849,7 @@ void check_move_unevictable_folios(struct folio_batch *fbatch)
 	if (lruvec) {
 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
-		unlock_page_lruvec_irq(lruvec);
+		lruvec_unlock_irq(lruvec);
 	} else if (pgscanned) {
 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
 	}
Signature · 1 line
2.20.1
author reviewer
#9 lore raw

PATCH 4/26 mm: vmscan: refactor move_folios_to_lru()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In a subsequent patch, we'll reparent the LRU folios. The folios that are moved to the appropriate LRU list can undergo reparenting during the move_folios_to_lru() process. Hence, it's incorrect for the caller to hold a lruvec lock. Instead, we should utilize the more general interface of folio_lruvec_relock_irq() to obtain the correct lruvec lock.

This patch involves only code refactoring and doesn't introduce any functional changes.

---
 mm/vmscan.c | 46 +++++++++++++++++++++++-----------------------
 1 file changed, 23 insertions(+), 23 deletions(-)
mm/vmscan.c +23 -23
index 3a1044ce30f1e..660cd40cfddd4 100644
@@ -1883,24 +1883,27 @@ static bool too_many_isolated(struct pglist_data *pgdat, int file,
 /*
  * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
  *
- * Returns the number of pages moved to the given lruvec.
+ * Returns the number of pages moved to the appropriate lruvec.
+ *
+ * Note: The caller must not hold any lruvec lock.
  */
-static unsigned int move_folios_to_lru(struct lruvec *lruvec,
-		struct list_head *list)
+static unsigned int move_folios_to_lru(struct list_head *list)
 {
 	int nr_pages, nr_moved = 0;
+	struct lruvec *lruvec = NULL;
 	struct folio_batch free_folios;
 
 	folio_batch_init(&free_folios);
 	while (!list_empty(list)) {
 		struct folio *folio = lru_to_folio(list);
 
+		lruvec = folio_lruvec_relock_irq(folio, lruvec);
 		VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
 		list_del(&folio->lru);
 		if (unlikely(!folio_evictable(folio))) {
-			spin_unlock_irq(&lruvec->lru_lock);
+			lruvec_unlock_irq(lruvec);
 			folio_putback_lru(folio);
-			spin_lock_irq(&lruvec->lru_lock);
+			lruvec = NULL;
 			continue;
 		}
 
@@ -1922,19 +1925,15 @@ static unsigned int move_folios_to_lru(struct lruvec *lruvec,
 
 			folio_unqueue_deferred_split(folio);
 			if (folio_batch_add(&free_folios, folio) == 0) {
-				spin_unlock_irq(&lruvec->lru_lock);
+				lruvec_unlock_irq(lruvec);
 				mem_cgroup_uncharge_folios(&free_folios);
 				free_unref_folios(&free_folios);
-				spin_lock_irq(&lruvec->lru_lock);
+				lruvec = NULL;
 			}
 
 			continue;
 		}
 
-		/*
-		 * All pages were isolated from the same lruvec (and isolation
-		 * inhibits memcg migration).
-		 */
 		VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
 		lruvec_add_folio(lruvec, folio);
 		nr_pages = folio_nr_pages(folio);
@@ -1943,11 +1942,12 @@ static unsigned int move_folios_to_lru(struct lruvec *lruvec,
 			workingset_age_nonresident(lruvec, nr_pages);
 	}
 
+	if (lruvec)
+		lruvec_unlock_irq(lruvec);
+
 	if (free_folios.nr) {
-		spin_unlock_irq(&lruvec->lru_lock);
 		mem_cgroup_uncharge_folios(&free_folios);
 		free_unref_folios(&free_folios);
-		spin_lock_irq(&lruvec->lru_lock);
 	}
 
 	return nr_moved;
@@ -2016,9 +2016,9 @@ static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
 	nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false,
 					 lruvec_memcg(lruvec));
 
-	spin_lock_irq(&lruvec->lru_lock);
-	move_folios_to_lru(lruvec, &folio_list);
+	move_folios_to_lru(&folio_list);
 
+	spin_lock_irq(&lruvec->lru_lock);
 	__mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc),
 					stat.nr_demoted);
 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
@@ -2166,11 +2166,10 @@ static void shrink_active_list(unsigned long nr_to_scan,
 	/*
 	 * Move folios back to the lru list.
 	 */
-	spin_lock_irq(&lruvec->lru_lock);
-
-	nr_activate = move_folios_to_lru(lruvec, &l_active);
-	nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
+	nr_activate = move_folios_to_lru(&l_active);
+	nr_deactivate = move_folios_to_lru(&l_inactive);
 
+	spin_lock_irq(&lruvec->lru_lock);
 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
 	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
 
@@ -4735,14 +4734,15 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
 			set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active));
 	}
 
-	spin_lock_irq(&lruvec->lru_lock);
-
-	move_folios_to_lru(lruvec, &list);
+	move_folios_to_lru(&list);
 
+	local_irq_disable();
 	walk = current->reclaim_state->mm_walk;
 	if (walk && walk->batched) {
 		walk->lruvec = lruvec;
+		spin_lock(&lruvec->lru_lock);
 		reset_batch_size(walk);
+		spin_unlock(&lruvec->lru_lock);
 	}
 
 	__mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc),
@@ -4754,7 +4754,7 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
 	count_memcg_events(memcg, item, reclaimed);
 	__count_vm_events(PGSTEAL_ANON + type, reclaimed);
 
-	spin_unlock_irq(&lruvec->lru_lock);
+	local_irq_enable();
 
 	list_splice_init(&clean, &list);
 
Signature · 1 line
2.20.1
author reviewer
#32 lore raw

PATCH 5/26 mm: memcontrol: allocate object cgroup for non-kmem case

In reply to Qi Zheng

From: Muchun Song <[email protected]>

Pagecache pages are charged at allocation time and hold a reference to the original memory cgroup until reclaimed. Depending on memory pressure, page sharing patterns between different cgroups and cgroup creation/destruction rates, many dying memory cgroups can be pinned by pagecache pages, reducing page reclaim efficiency and wasting memory. Converting LRU folios and most other raw memory cgroup pins to the object cgroup direction can fix this long-living problem.

As a result, the objcg infrastructure is no longer solely applicable to the kmem case. In this patch, we extend the scope of the objcg infrastructure beyond the kmem case, enabling LRU folios to reuse it for folio charging purposes.

It should be noted that LRU folios are not accounted for at the root level, yet the folio->memcg_data points to the root_mem_cgroup. Hence, the folio->memcg_data of LRU folios always points to a valid pointer. However, the root_mem_cgroup does not possess an object cgroup. Therefore, we also allocate an object cgroup for the root_mem_cgroup.

---
 mm/memcontrol.c | 51 +++++++++++++++++++++++--------------------------
 1 file changed, 24 insertions(+), 27 deletions(-)
mm/memcontrol.c +24 -27
index d5257465c9d75..2afd7f99ca101 100644
@@ -204,10 +204,10 @@ static struct obj_cgroup *obj_cgroup_alloc(void)
 	return objcg;
 }
 
-static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
-				  struct mem_cgroup *parent)
+static void memcg_reparent_objcgs(struct mem_cgroup *memcg)
 {
 	struct obj_cgroup *objcg, *iter;
+	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
 
 	objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
 
@@ -3302,30 +3302,17 @@ unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
 	return val;
 }
 
-static int memcg_online_kmem(struct mem_cgroup *memcg)
+static void memcg_online_kmem(struct mem_cgroup *memcg)
 {
-	struct obj_cgroup *objcg;
-
 	if (mem_cgroup_kmem_disabled())
-		return 0;
+		return;
 
 	if (unlikely(mem_cgroup_is_root(memcg)))
-		return 0;
-
-	objcg = obj_cgroup_alloc();
-	if (!objcg)
-		return -ENOMEM;
-
-	objcg->memcg = memcg;
-	rcu_assign_pointer(memcg->objcg, objcg);
-	obj_cgroup_get(objcg);
-	memcg->orig_objcg = objcg;
+		return;
 
 	static_branch_enable(&memcg_kmem_online_key);
 
 	memcg->kmemcg_id = memcg->id.id;
-
-	return 0;
 }
 
 static void memcg_offline_kmem(struct mem_cgroup *memcg)
@@ -3340,12 +3327,6 @@ static void memcg_offline_kmem(struct mem_cgroup *memcg)
 
 	parent = parent_mem_cgroup(memcg);
 	memcg_reparent_list_lrus(memcg, parent);
-
-	/*
-	 * Objcg's reparenting must be after list_lru's, make sure list_lru
-	 * helpers won't use parent's list_lru until child is drained.
-	 */
-	memcg_reparent_objcgs(memcg, parent);
 }
 
 #ifdef CONFIG_CGROUP_WRITEBACK
@@ -3862,9 +3843,9 @@ mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
 {
 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
+	struct obj_cgroup *objcg;
 
-	if (memcg_online_kmem(memcg))
-		goto remove_id;
+	memcg_online_kmem(memcg);
 
 	/*
 	 * A memcg must be visible for expand_shrinker_info()
@@ -3874,6 +3855,15 @@ static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
 	if (alloc_shrinker_info(memcg))
 		goto offline_kmem;
 
+	objcg = obj_cgroup_alloc();
+	if (!objcg)
+		goto free_shrinker;
+
+	objcg->memcg = memcg;
+	rcu_assign_pointer(memcg->objcg, objcg);
+	obj_cgroup_get(objcg);
+	memcg->orig_objcg = objcg;
+
 	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
 		queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
 				   FLUSH_TIME);
@@ -3896,9 +3886,10 @@ static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
 	xa_store(&mem_cgroup_ids, memcg->id.id, memcg, GFP_KERNEL);
 
 	return 0;
+free_shrinker:
+	free_shrinker_info(memcg);
 offline_kmem:
 	memcg_offline_kmem(memcg);
-remove_id:
 	mem_cgroup_id_remove(memcg);
 	return -ENOMEM;
 }
@@ -3916,6 +3907,12 @@ static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
 
 	memcg_offline_kmem(memcg);
 	reparent_deferred_split_queue(memcg);
+	/*
+	 * The reparenting of objcg must be after the reparenting of the
+	 * list_lru and deferred_split_queue above, which ensures that they will
+	 * not mistakenly get the parent list_lru and deferred_split_queue.
+	 */
+	memcg_reparent_objcgs(memcg);
 	reparent_shrinker_deferred(memcg);
 	wb_memcg_offline(memcg);
 	lru_gen_offline_memcg(memcg);
Signature · 1 line
2.20.1
author reviewer
#36 lore raw

PATCH 6/26 mm: memcontrol: return root object cgroup for root memory cgroup

In reply to Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
 include/linux/memcontrol.h | 29 +++++++++++++++++-------
 mm/memcontrol.c            | 45 ++++++++++++++++++++------------------
 mm/percpu.c                |  2 +-
 3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +21 -8
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
 #define MEMCG_CHARGE_BATCH 64U
 
 extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
 
 enum page_memcg_data_flags {
 	/* page->memcg_data is a pointer to an slabobj_ext vector */
@@ -549,6 +550,11 @@ static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
 	return (memcg == root_mem_cgroup);
 }
 
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+	return objcg == root_obj_cgroup;
+}
+
 static inline bool mem_cgroup_disabled(void)
 {
 	return !cgroup_subsys_enabled(memory_cgrp_subsys);
@@ -773,23 +779,26 @@ struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *css){
 
 static inline bool obj_cgroup_tryget(struct obj_cgroup *objcg)
 {
+	if (obj_cgroup_is_root(objcg))
+		return true;
 	return percpu_ref_tryget(&objcg->refcnt);
 }
 
-static inline void obj_cgroup_get(struct obj_cgroup *objcg)
+static inline void obj_cgroup_get_many(struct obj_cgroup *objcg,
+				       unsigned long nr)
 {
-	percpu_ref_get(&objcg->refcnt);
+	if (!obj_cgroup_is_root(objcg))
+		percpu_ref_get_many(&objcg->refcnt, nr);
 }
 
-static inline void obj_cgroup_get_many(struct obj_cgroup *objcg,
-				       unsigned long nr)
+static inline void obj_cgroup_get(struct obj_cgroup *objcg)
 {
-	percpu_ref_get_many(&objcg->refcnt, nr);
+	obj_cgroup_get_many(objcg, 1);
 }
 
 static inline void obj_cgroup_put(struct obj_cgroup *objcg)
 {
-	if (objcg)
+	if (objcg && !obj_cgroup_is_root(objcg))
 		percpu_ref_put(&objcg->refcnt);
 }
 
@@ -1094,6 +1103,11 @@ static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
 	return true;
 }
 
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+	return true;
+}
+
 static inline bool mem_cgroup_disabled(void)
 {
 	return true;
@@ -1710,8 +1724,7 @@ static inline struct obj_cgroup *get_obj_cgroup_from_current(void)
 {
 	struct obj_cgroup *objcg = current_obj_cgroup();
 
-	if (objcg)
-		obj_cgroup_get(objcg);
+	obj_cgroup_get(objcg);
 
 	return objcg;
 }
mm/memcontrol.c +24 -21

119 lines not on this page · raw message

mm/percpu.c +1 -1
index 81462ce5866e1..78bdffe1fcb57 100644
@@ -1616,7 +1616,7 @@ static bool pcpu_memcg_pre_alloc_hook(size_t size, gfp_t gfp,
 		return true;
 
 	objcg = current_obj_cgroup();
-	if (!objcg)
+	if (obj_cgroup_is_root(objcg))
 		return true;
 
 	if (obj_cgroup_charge(objcg, gfp, pcpu_obj_full_size(size)))
Signature · 1 line
2.20.1
author reviewer
#46 lore raw

PATCH 7/26 mm: memcontrol: prevent memory cgroup release in get_mem_cgroup_from_folio()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in get_mem_cgroup_from_folio().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/memcontrol.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
mm/memcontrol.c +8 -3
index d484b632c790f..1da3ad77054d3 100644
@@ -973,14 +973,19 @@ struct mem_cgroup *get_mem_cgroup_from_current(void)
  */
 struct mem_cgroup *get_mem_cgroup_from_folio(struct folio *folio)
 {
-	struct mem_cgroup *memcg = folio_memcg(folio);
+	struct mem_cgroup *memcg;
 
 	if (mem_cgroup_disabled())
 		return NULL;
 
+	if (!folio_memcg_charged(folio))
+		return root_mem_cgroup;
+
 	rcu_read_lock();
-	if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
-		memcg = root_mem_cgroup;
+retry:
+	memcg = folio_memcg(folio);
+	if (unlikely(!css_tryget(&memcg->css)))
+		goto retry;
 	rcu_read_unlock();
 	return memcg;
 }
Signature · 1 line
2.20.1
author reviewer
#49 lore raw

PATCH 8/26 buffer: prevent memory cgroup release in folio_alloc_buffers()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the function get_mem_cgroup_from_folio() is employed to safeguard against the release of the memory cgroup. This serves as a preparatory measure for the reparenting of the LRU pages.

---
 fs/buffer.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/buffer.c +2 -2
index 6a8752f7bbedb..bc93d0b1d0c30 100644
@@ -925,8 +925,7 @@ struct buffer_head *folio_alloc_buffers(struct folio *folio, unsigned long size,
 	long offset;
 	struct mem_cgroup *memcg, *old_memcg;
 
-	/* The folio lock pins the memcg */
-	memcg = folio_memcg(folio);
+	memcg = get_mem_cgroup_from_folio(folio);
 	old_memcg = set_active_memcg(memcg);
 
 	head = NULL;
@@ -947,6 +946,7 @@ struct buffer_head *folio_alloc_buffers(struct folio *folio, unsigned long size,
 	}
 out:
 	set_active_memcg(old_memcg);
+	mem_cgroup_put(memcg);
 	return head;
 /*
  * In case anything failed, we just free everything we got.
Signature · 1 line
2.20.1
author reviewer
#51 lore raw

PATCH 9/26 writeback: prevent memory cgroup release in writeback module

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the function get_mem_cgroup_css_from_folio() and the rcu read lock are employed to safeguard against the release of the memory cgroup.

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 fs/fs-writeback.c                | 22 +++++++++++-----------
 include/linux/memcontrol.h       |  9 +++++++--
 include/trace/events/writeback.h |  3 +++
 mm/memcontrol.c                  | 14 ++++++++------
 4 files changed, 29 insertions(+), 19 deletions(-)
fs/fs-writeback.c +11 -11
index 2b35e80037fee..afd81fb8100cb 100644
@@ -269,15 +269,13 @@ void __inode_attach_wb(struct inode *inode, struct folio *folio)
 	if (inode_cgwb_enabled(inode)) {
 		struct cgroup_subsys_state *memcg_css;
 
-		if (folio) {
-			memcg_css = mem_cgroup_css_from_folio(folio);
-			wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
-		} else {
-			/* must pin memcg_css, see wb_get_create() */
+		/* must pin memcg_css, see wb_get_create() */
+		if (folio)
+			memcg_css = get_mem_cgroup_css_from_folio(folio);
+		else
 			memcg_css = task_get_css(current, memory_cgrp_id);
-			wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
-			css_put(memcg_css);
-		}
+		wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
+		css_put(memcg_css);
 	}
 
 	if (!wb)
@@ -968,16 +966,16 @@ void wbc_account_cgroup_owner(struct writeback_control *wbc, struct folio *folio
 	if (!wbc->wb || wbc->no_cgroup_owner)
 		return;
 
-	css = mem_cgroup_css_from_folio(folio);
+	css = get_mem_cgroup_css_from_folio(folio);
 	/* dead cgroups shouldn't contribute to inode ownership arbitration */
 	if (!(css->flags & CSS_ONLINE))
-		return;
+		goto out;
 
 	id = css->id;
 
 	if (id == wbc->wb_id) {
 		wbc->wb_bytes += bytes;
-		return;
+		goto out;
 	}
 
 	if (id == wbc->wb_lcand_id)
@@ -990,6 +988,8 @@ void wbc_account_cgroup_owner(struct writeback_control *wbc, struct folio *folio
 		wbc->wb_tcand_bytes += bytes;
 	else
 		wbc->wb_tcand_bytes -= min(bytes, wbc->wb_tcand_bytes);
+out:
+	css_put(css);
 }
 EXPORT_SYMBOL_GPL(wbc_account_cgroup_owner);
 
include/linux/memcontrol.h +7 -2
index 9fdbd4970021d..174e52d8e7039 100644
@@ -895,7 +895,7 @@ static inline bool mm_match_cgroup(struct mm_struct *mm,
 	return match;
 }
 
-struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio);
+struct cgroup_subsys_state *get_mem_cgroup_css_from_folio(struct folio *folio);
 ino_t page_cgroup_ino(struct page *page);
 
 static inline bool mem_cgroup_online(struct mem_cgroup *memcg)
@@ -1577,9 +1577,14 @@ static inline void mem_cgroup_track_foreign_dirty(struct folio *folio,
 	if (mem_cgroup_disabled())
 		return;
 
+	if (!folio_memcg_charged(folio))
+		return;
+
+	rcu_read_lock();
 	memcg = folio_memcg(folio);
-	if (unlikely(memcg && &memcg->css != wb->memcg_css))
+	if (unlikely(&memcg->css != wb->memcg_css))
 		mem_cgroup_track_foreign_dirty_slowpath(folio, wb);
+	rcu_read_unlock();
 }
 
 void mem_cgroup_flush_foreign(struct bdi_writeback *wb);
include/trace/events/writeback.h +3 -0
index c08aff044e807..3680828727f23 100644
@@ -295,7 +295,10 @@ TRACE_EVENT(track_foreign_dirty,
 		__entry->ino		= inode ? inode->i_ino : 0;
 		__entry->memcg_id	= wb->memcg_css->id;
 		__entry->cgroup_ino	= __trace_wb_assign_cgroup(wb);
+
+		rcu_read_lock();
 		__entry->page_cgroup_ino = cgroup_ino(folio_memcg(folio)->css.cgroup);
+		rcu_read_unlock();
 	),
 
 	TP_printk("bdi %s[%llu]: ino=%lu memcg_id=%u cgroup_ino=%lu page_cgroup_ino=%lu",
mm/memcontrol.c +8 -6
index 1da3ad77054d3..aa8945c4ee383 100644
@@ -241,7 +241,7 @@ DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
 EXPORT_SYMBOL(memcg_bpf_enabled_key);
 
 /**
- * mem_cgroup_css_from_folio - css of the memcg associated with a folio
+ * get_mem_cgroup_css_from_folio - acquire a css of the memcg associated with a folio
  * @folio: folio of interest
  *
  * If memcg is bound to the default hierarchy, css of the memcg associated
@@ -251,14 +251,16 @@ EXPORT_SYMBOL(memcg_bpf_enabled_key);
  * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
  * is returned.
  */
-struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
+struct cgroup_subsys_state *get_mem_cgroup_css_from_folio(struct folio *folio)
 {
-	struct mem_cgroup *memcg = folio_memcg(folio);
+	struct mem_cgroup *memcg;
 
-	if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
-		memcg = root_mem_cgroup;
+	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
+		return &root_mem_cgroup->css;
 
-	return &memcg->css;
+	memcg = get_mem_cgroup_from_folio(folio);
+
+	return memcg ? &memcg->css : &root_mem_cgroup->css;
 }
 
 /**
Signature · 1 line
2.20.1
author reviewer
#53 lore raw

PATCH 10/26 mm: memcontrol: prevent memory cgroup release in count_memcg_folio_events()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in count_memcg_folio_events().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 include/linux/memcontrol.h | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
include/linux/memcontrol.h +8 -3
index 174e52d8e7039..ca8d4e09cbe7d 100644
@@ -984,10 +984,15 @@ void count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
 static inline void count_memcg_folio_events(struct folio *folio,
 		enum vm_event_item idx, unsigned long nr)
 {
-	struct mem_cgroup *memcg = folio_memcg(folio);
+	struct mem_cgroup *memcg;
 
-	if (memcg)
-		count_memcg_events(memcg, idx, nr);
+	if (!folio_memcg_charged(folio))
+		return;
+
+	rcu_read_lock();
+	memcg = folio_memcg(folio);
+	count_memcg_events(memcg, idx, nr);
+	rcu_read_unlock();
 }
 
 static inline void count_memcg_events_mm(struct mm_struct *mm,
Signature · 1 line
2.20.1
author reviewer
#55 lore raw

PATCH 11/26 mm: page_io: prevent memory cgroup release in page_io module

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in swap_writepage() and bio_associate_blkg_from_page().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/page_io.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
mm/page_io.c +6 -2
index 3c342db77ce38..ec7720762042c 100644
@@ -276,10 +276,14 @@ int swap_writeout(struct folio *folio, struct swap_iocb **swap_plug)
 		count_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);
 		goto out_unlock;
 	}
+
+	rcu_read_lock();
 	if (!mem_cgroup_zswap_writeback_enabled(folio_memcg(folio))) {
+		rcu_read_unlock();
 		folio_mark_dirty(folio);
 		return AOP_WRITEPAGE_ACTIVATE;
 	}
+	rcu_read_unlock();
 
 	__swap_writepage(folio, swap_plug);
 	return 0;
@@ -307,11 +311,11 @@ static void bio_associate_blkg_from_page(struct bio *bio, struct folio *folio)
 	struct cgroup_subsys_state *css;
 	struct mem_cgroup *memcg;
 
-	memcg = folio_memcg(folio);
-	if (!memcg)
+	if (!folio_memcg_charged(folio))
 		return;
 
 	rcu_read_lock();
+	memcg = folio_memcg(folio);
 	css = cgroup_e_css(memcg->css.cgroup, &io_cgrp_subsys);
 	bio_associate_blkg_from_css(bio, css);
 	rcu_read_unlock();
Signature · 1 line
2.20.1
author reviewer
#58 lore raw

PATCH 12/26 mm: migrate: prevent memory cgroup release in folio_migrate_mapping()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in folio_migrate_mapping().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/migrate.c | 2 ++
 1 file changed, 2 insertions(+)
mm/migrate.c +2 -0
index ceee354ef2152..cdab1b652c530 100644
@@ -664,6 +664,7 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 		struct lruvec *old_lruvec, *new_lruvec;
 		struct mem_cgroup *memcg;
 
+		rcu_read_lock();
 		memcg = folio_memcg(folio);
 		old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
 		new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
@@ -691,6 +692,7 @@ static int __folio_migrate_mapping(struct address_space *mapping,
 			__mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
 			__mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
 		}
+		rcu_read_unlock();
 	}
 	local_irq_enable();
 
Signature · 1 line
2.20.1
author reviewer
#60 lore raw

PATCH 13/26 mm: mglru: prevent memory cgroup release in mglru

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in mglru.

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/vmscan.c | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
mm/vmscan.c +17 -6
index 660cd40cfddd4..676e6270e5b45 100644
@@ -3445,8 +3445,10 @@ static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
 	if (folio_nid(folio) != pgdat->node_id)
 		return NULL;
 
+	rcu_read_lock();
 	if (folio_memcg(folio) != memcg)
-		return NULL;
+		folio = NULL;
+	rcu_read_unlock();
 
 	return folio;
 }
@@ -4203,12 +4205,12 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
 	unsigned long addr = pvmw->address;
 	struct vm_area_struct *vma = pvmw->vma;
 	struct folio *folio = pfn_folio(pvmw->pfn);
-	struct mem_cgroup *memcg = folio_memcg(folio);
+	struct mem_cgroup *memcg;
 	struct pglist_data *pgdat = folio_pgdat(folio);
-	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
-	struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
-	DEFINE_MAX_SEQ(lruvec);
-	int gen = lru_gen_from_seq(max_seq);
+	struct lruvec *lruvec;
+	struct lru_gen_mm_state *mm_state;
+	unsigned long max_seq;
+	int gen;
 
 	lockdep_assert_held(pvmw->ptl);
 	VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
@@ -4243,6 +4245,13 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
 		}
 	}
 
+	rcu_read_lock();
+	memcg = folio_memcg(folio);
+	lruvec = mem_cgroup_lruvec(memcg, pgdat);
+	max_seq = READ_ONCE((lruvec)->lrugen.max_seq);
+	gen = lru_gen_from_seq(max_seq);
+	mm_state = get_mm_state(lruvec);
+
 	arch_enter_lazy_mmu_mode();
 
 	pte -= (addr - start) / PAGE_SIZE;
@@ -4279,6 +4288,8 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
 
 	arch_leave_lazy_mmu_mode();
 
+	rcu_read_unlock();
+
 	/* feedback from rmap walkers to page table walkers */
 	if (mm_state && suitable_to_scan(i, young))
 		update_bloom_filter(mm_state, max_seq, pvmw->pmd);
Signature · 1 line
2.20.1
author reviewer
#63 lore raw

PATCH 14/26 mm: memcontrol: prevent memory cgroup release in mem_cgroup_swap_full()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in mem_cgroup_swap_full().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/memcontrol.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
mm/memcontrol.c +7 -3
index aa8945c4ee383..4b3c7d4f346b5 100644
@@ -5275,17 +5275,21 @@ bool mem_cgroup_swap_full(struct folio *folio)
 	if (do_memsw_account())
 		return false;
 
-	memcg = folio_memcg(folio);
-	if (!memcg)
+	if (!folio_memcg_charged(folio))
 		return false;
 
+	rcu_read_lock();
+	memcg = folio_memcg(folio);
 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
 		unsigned long usage = page_counter_read(&memcg->swap);
 
 		if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
-		    usage * 2 >= READ_ONCE(memcg->swap.max))
+		    usage * 2 >= READ_ONCE(memcg->swap.max)) {
+			rcu_read_unlock();
 			return true;
+		}
 	}
+	rcu_read_unlock();
 
 	return false;
 }
Signature · 1 line
2.20.1
author reviewer
#65 lore raw

PATCH 15/26 mm: workingset: prevent memory cgroup release in lru_gen_eviction()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in lru_gen_eviction().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/workingset.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
mm/workingset.c +7 -2
index 8cad8ee6dec6a..c4d21c15bad51 100644
@@ -241,11 +241,14 @@ static void *lru_gen_eviction(struct folio *folio)
 	int refs = folio_lru_refs(folio);
 	bool workingset = folio_test_workingset(folio);
 	int tier = lru_tier_from_refs(refs, workingset);
-	struct mem_cgroup *memcg = folio_memcg(folio);
+	struct mem_cgroup *memcg;
 	struct pglist_data *pgdat = folio_pgdat(folio);
+	unsigned short memcg_id;
 
 	BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_WIDTH > BITS_PER_LONG - EVICTION_SHIFT);
 
+	rcu_read_lock();
+	memcg = folio_memcg(folio);
 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
 	lrugen = &lruvec->lrugen;
 	min_seq = READ_ONCE(lrugen->min_seq[type]);
@@ -253,8 +256,10 @@ static void *lru_gen_eviction(struct folio *folio)
 
 	hist = lru_hist_from_seq(min_seq);
 	atomic_long_add(delta, &lrugen->evicted[hist][type][tier]);
+	memcg_id = mem_cgroup_id(memcg);
+	rcu_read_unlock();
 
-	return pack_shadow(mem_cgroup_id(memcg), pgdat, token, workingset);
+	return pack_shadow(memcg_id, pgdat, token, workingset);
 }
 
 /*
Signature · 1 line
2.20.1
author reviewer
#67 lore raw

PATCH 16/26 mm: thp: prevent memory cgroup release in folio_split_queue_lock{_irqsave}()

In reply to Qi Zheng

From: Qi Zheng <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in folio_split_queue_lock{_irqsave}().

---
 mm/huge_memory.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
mm/huge_memory.c +14 -2
index 9d3594df6eedf..067259a9e0809 100644
@@ -1153,13 +1153,25 @@ split_queue_lock_irqsave(int nid, struct mem_cgroup *memcg, unsigned long *flags
 
 static struct deferred_split *folio_split_queue_lock(struct folio *folio)
 {
-	return split_queue_lock(folio_nid(folio), folio_memcg(folio));
+	struct deferred_split *queue;
+
+	rcu_read_lock();
+	queue = split_queue_lock(folio_nid(folio), folio_memcg(folio));
+	rcu_read_unlock();
+
+	return queue;
 }
 
 static struct deferred_split *
 folio_split_queue_lock_irqsave(struct folio *folio, unsigned long *flags)
 {
-	return split_queue_lock_irqsave(folio_nid(folio), folio_memcg(folio), flags);
+	struct deferred_split *queue;
+
+	rcu_read_lock();
+	queue = split_queue_lock_irqsave(folio_nid(folio), folio_memcg(folio), flags);
+	rcu_read_unlock();
+
+	return queue;
 }
 
 static inline void split_queue_unlock(struct deferred_split *queue)
Signature · 1 line
2.20.1
author reviewer
#69 lore raw

PATCH 17/26 mm: workingset: prevent lruvec release in workingset_refault()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in workingset_refault().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/workingset.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
mm/workingset.c +4 -1
index c4d21c15bad51..a69cc7bf9246d 100644
@@ -560,11 +560,12 @@ void workingset_refault(struct folio *folio, void *shadow)
 	 * locked to guarantee folio_memcg() stability throughout.
 	 */
 	nr = folio_nr_pages(folio);
+	rcu_read_lock();
 	lruvec = folio_lruvec(folio);
 	mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + file, nr);
 
 	if (!workingset_test_recent(shadow, file, &workingset, true))
-		return;
+		goto out;
 
 	folio_set_active(folio);
 	workingset_age_nonresident(lruvec, nr);
@@ -580,6 +581,8 @@ void workingset_refault(struct folio *folio, void *shadow)
 		lru_note_cost_refault(folio);
 		mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + file, nr);
 	}
+out:
+	rcu_read_unlock();
 }
 
 /**
Signature · 1 line
2.20.1
author reviewer
#71 lore raw

PATCH 18/26 mm: zswap: prevent lruvec release in zswap_folio_swapin()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in zswap_folio_swapin().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/zswap.c | 2 ++
 1 file changed, 2 insertions(+)
mm/zswap.c +2 -0
index 5d0f8b13a958d..a341814468b95 100644
@@ -664,8 +664,10 @@ void zswap_folio_swapin(struct folio *folio)
 	struct lruvec *lruvec;
 
 	if (folio) {
+		rcu_read_lock();
 		lruvec = folio_lruvec(folio);
 		atomic_long_inc(&lruvec->zswap_lruvec_state.nr_disk_swapins);
+		rcu_read_unlock();
 	}
 }
 
Signature · 1 line
2.20.1
author reviewer
#73 lore raw

PATCH 19/26 mm: swap: prevent lruvec release in swap module

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in lru_note_cost_refault() and lru_activate().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/swap.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
mm/swap.c +5 -3
index ec0c654e128dc..0606795f3ccf3 100644
@@ -412,18 +412,20 @@ static void lru_gen_inc_refs(struct folio *folio)
 
 static bool lru_gen_clear_refs(struct folio *folio)
 {
-	struct lru_gen_folio *lrugen;
 	int gen = folio_lru_gen(folio);
 	int type = folio_is_file_lru(folio);
+	unsigned long seq;
 
 	if (gen < 0)
 		return true;
 
 	set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS | BIT(PG_workingset), 0);
 
-	lrugen = &folio_lruvec(folio)->lrugen;
+	rcu_read_lock();
+	seq = READ_ONCE(folio_lruvec(folio)->lrugen.min_seq[type]);
+	rcu_read_unlock();
 	/* whether can do without shuffling under the LRU lock */
-	return gen == lru_gen_from_seq(READ_ONCE(lrugen->min_seq[type]));
+	return gen == lru_gen_from_seq(seq);
 }
 
 #else /* !CONFIG_LRU_GEN */
Signature · 1 line
2.20.1
author reviewer
#76 lore raw

PATCH 20/26 mm: workingset: prevent lruvec release in workingset_activation()

In reply to Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in workingset_activation().

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/workingset.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
mm/workingset.c +4 -1
index a69cc7bf9246d..d0eb3636dcd1d 100644
@@ -595,8 +595,11 @@ void workingset_activation(struct folio *folio)
 	 * Filter non-memcg pages here, e.g. unmap can call
 	 * mark_page_accessed() on VDSO pages.
 	 */
-	if (mem_cgroup_disabled() || folio_memcg_charged(folio))
+	if (mem_cgroup_disabled() || folio_memcg_charged(folio)) {
+		rcu_read_lock();
 		workingset_age_nonresident(folio_lruvec(folio), folio_nr_pages(folio));
+		rcu_read_unlock();
+	}
 }
 
 /*
Signature · 1 line
2.20.1
author reviewer
#78 lore raw

PATCH 21/26 mm: memcontrol: prepare for reparenting LRU pages for lruvec lock

In reply to Qi Zheng

From: Muchun Song <[email protected]>

The following diagram illustrates how to ensure the safety of the folio lruvec lock when LRU folios undergo reparenting.

In the folio_lruvec_lock(folio) function:

```
    rcu_read_lock();
retry:
    lruvec = folio_lruvec(folio);
    /* There is a possibility of folio reparenting at this point. */
    spin_lock(&lruvec->lru_lock);
    if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
        /*
         * The wrong lruvec lock was acquired, and a retry is required.
         * This is because the folio resides on the parent memcg lruvec
         * list.
         */
        spin_unlock(&lruvec->lru_lock);
        goto retry;
    }

    /* Reaching here indicates that folio_memcg() is stable. */
```

In the memcg_reparent_objcgs(memcg) function:

```
    spin_lock(&lruvec->lru_lock);
    spin_lock(&lruvec_parent->lru_lock);
    /* Transfer folios from the lruvec list to the parent's. */
    spin_unlock(&lruvec_parent->lru_lock);
    spin_unlock(&lruvec->lru_lock);
```

After acquiring the lruvec lock, it is necessary to verify whether the folio has been reparented. If reparenting has occurred, the new lruvec lock must be reacquired. During the LRU folio reparenting process, the lruvec lock will also be acquired (this will be implemented in a subsequent patch). Therefore, folio_memcg() remains unchanged while the lruvec lock is held.

Given that lruvec_memcg(lruvec) is always equal to folio_memcg(folio) after the lruvec lock is acquired, the lruvec_memcg_debug() check is redundant. Hence, it is removed.

This patch serves as a preparation for the reparenting of LRU folios.

---
 include/linux/memcontrol.h | 23 ++++++-----------
 mm/compaction.c            | 29 ++++++++++++++++-----
 mm/memcontrol.c            | 53 +++++++++++++++++++-------------------
 3 files changed, 58 insertions(+), 47 deletions(-)
include/linux/memcontrol.h +8 -15
index ca8d4e09cbe7d..6f6b28f8f0f63 100644
@@ -740,7 +740,11 @@ static inline struct lruvec *mem_cgroup_lruvec(struct mem_cgroup *memcg,
  * folio_lruvec - return lruvec for isolating/putting an LRU folio
  * @folio: Pointer to the folio.
  *
- * This function relies on folio->mem_cgroup being stable.
+ * The user should hold an rcu read lock to protect lruvec associated with
+ * the folio from being released. But it does not prevent binding stability
+ * between the folio and the returned lruvec from being changed to its parent
+ * or ancestor (e.g. like folio_lruvec_lock() does that holds LRU lock to
+ * prevent the change).
  */
 static inline struct lruvec *folio_lruvec(struct folio *folio)
 {
@@ -763,15 +767,6 @@ struct lruvec *folio_lruvec_lock_irq(struct folio *folio);
 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
 						unsigned long *flags);
 
-#ifdef CONFIG_DEBUG_VM
-void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio);
-#else
-static inline
-void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
-{
-}
-#endif
-
 static inline
 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *css){
 	return css ? container_of(css, struct mem_cgroup, css) : NULL;
@@ -1204,11 +1199,6 @@ static inline struct lruvec *folio_lruvec(struct folio *folio)
 	return &pgdat->__lruvec;
 }
 
-static inline
-void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
-{
-}
-
 static inline struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
 {
 	return NULL;
@@ -1515,17 +1505,20 @@ static inline struct lruvec *parent_lruvec(struct lruvec *lruvec)
 static inline void lruvec_unlock(struct lruvec *lruvec)
 {
 	spin_unlock(&lruvec->lru_lock);
+	rcu_read_unlock();
 }
 
 static inline void lruvec_unlock_irq(struct lruvec *lruvec)
 {
 	spin_unlock_irq(&lruvec->lru_lock);
+	rcu_read_unlock();
 }
 
 static inline void lruvec_unlock_irqrestore(struct lruvec *lruvec,
 		unsigned long flags)
 {
 	spin_unlock_irqrestore(&lruvec->lru_lock, flags);
+	rcu_read_unlock();
 }
 
 /* Test requires a stable folio->memcg binding, see folio_memcg() */
mm/compaction.c +23 -6
index 4dce180f699b4..0d2a0e6239eb4 100644
@@ -518,6 +518,24 @@ static bool compact_lock_irqsave(spinlock_t *lock, unsigned long *flags,
 	return true;
 }
 
+static struct lruvec *
+compact_folio_lruvec_lock_irqsave(struct folio *folio, unsigned long *flags,
+				  struct compact_control *cc)
+{
+	struct lruvec *lruvec;
+
+	rcu_read_lock();
+retry:
+	lruvec = folio_lruvec(folio);
+	compact_lock_irqsave(&lruvec->lru_lock, flags, cc);
+	if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
+		spin_unlock_irqrestore(&lruvec->lru_lock, *flags);
+		goto retry;
+	}
+
+	return lruvec;
+}
+
 /*
  * Compaction requires the taking of some coarse locks that are potentially
  * very heavily contended. The lock should be periodically unlocked to avoid
@@ -839,7 +857,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 {
 	pg_data_t *pgdat = cc->zone->zone_pgdat;
 	unsigned long nr_scanned = 0, nr_isolated = 0;
-	struct lruvec *lruvec;
+	struct lruvec *lruvec = NULL;
 	unsigned long flags = 0;
 	struct lruvec *locked = NULL;
 	struct folio *folio = NULL;
@@ -1153,18 +1171,17 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
 		if (!folio_test_clear_lru(folio))
 			goto isolate_fail_put;
 
-		lruvec = folio_lruvec(folio);
+		if (locked)
+			lruvec = folio_lruvec(folio);
 
 		/* If we already hold the lock, we can skip some rechecking */
-		if (lruvec != locked) {
+		if (lruvec != locked || !locked) {
 			if (locked)
 				lruvec_unlock_irqrestore(locked, flags);
 
-			compact_lock_irqsave(&lruvec->lru_lock, &flags, cc);
+			lruvec = compact_folio_lruvec_lock_irqsave(folio, &flags, cc);
 			locked = lruvec;
 
-			lruvec_memcg_debug(lruvec, folio);
-
 			/*
 			 * Try get exclusive access under lock. If marked for
 			 * skip, the scan is aborted unless the current context
mm/memcontrol.c +27 -26

93 lines not on this page · raw message

Signature · 1 line
2.20.1
author reviewer
#83 lore raw

PATCH 22/26 mm: vmscan: prepare for reparenting traditional LRU folios

In reply to Qi Zheng

From: Qi Zheng <[email protected]>

To reslove the dying memcg issue, we need to reparent LRU folios of child memcg to its parent memcg. For traditional LRU list, each lruvec of every memcg comprises four LRU lists. Due to the symmetry of the LRU lists, it is feasible to transfer the LRU lists from a memcg to its parent memcg during the reparenting process.

This commit implements the specific function, which will be used during the reparenting process.

---
 include/linux/mmzone.h |  4 ++++
 mm/vmscan.c            | 39 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 43 insertions(+)
include/linux/mmzone.h +4 -0
index 4398e027f450e..0d8776e5b6747 100644
@@ -366,6 +366,10 @@ enum lruvec_flags {
 	LRUVEC_NODE_CONGESTED,
 };
 
+#ifdef CONFIG_MEMCG
+void lru_reparent_memcg(struct mem_cgroup *src, struct mem_cgroup *dst);
+#endif /* CONFIG_MEMCG */
+
 #endif /* !__GENERATING_BOUNDS_H */
 
 /*
mm/vmscan.c +39 -0
index 676e6270e5b45..7aa8e1472d10d 100644
@@ -2649,6 +2649,45 @@ static bool can_age_anon_pages(struct lruvec *lruvec,
 			  lruvec_memcg(lruvec));
 }
 
+
+#ifdef CONFIG_MEMCG
+static void lruvec_reparent_lru(struct lruvec *src, struct lruvec *dst,
+				enum lru_list lru)
+{
+	int zid;
+	struct mem_cgroup_per_node *mz_src, *mz_dst;
+
+	mz_src = container_of(src, struct mem_cgroup_per_node, lruvec);
+	mz_dst = container_of(dst, struct mem_cgroup_per_node, lruvec);
+
+	if (lru != LRU_UNEVICTABLE)
+		list_splice_tail_init(&src->lists[lru], &dst->lists[lru]);
+
+	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
+		mz_dst->lru_zone_size[zid][lru] += mz_src->lru_zone_size[zid][lru];
+		mz_src->lru_zone_size[zid][lru] = 0;
+	}
+}
+
+void lru_reparent_memcg(struct mem_cgroup *src, struct mem_cgroup *dst)
+{
+	int nid;
+
+	for_each_node(nid) {
+		enum lru_list lru;
+		struct lruvec *src_lruvec, *dst_lruvec;
+
+		src_lruvec = mem_cgroup_lruvec(src, NODE_DATA(nid));
+		dst_lruvec = mem_cgroup_lruvec(dst, NODE_DATA(nid));
+		dst_lruvec->anon_cost += src_lruvec->anon_cost;
+		dst_lruvec->file_cost += src_lruvec->file_cost;
+
+		for_each_lru(lru)
+			lruvec_reparent_lru(src_lruvec, dst_lruvec, lru);
+	}
+}
+#endif
+
 #ifdef CONFIG_LRU_GEN
 
 #ifdef CONFIG_LRU_GEN_ENABLED
Signature · 1 line
2.20.1
author reviewer
#85 lore raw

PATCH 23/26 mm: vmscan: prepare for reparenting MGLRU folios

In reply to Qi Zheng

From: Qi Zheng <[email protected]>

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

To prepare for the above work, this commit implements the specific functions, which will be used during reparenting.

---
 include/linux/mmzone.h | 16 ++++++++
 mm/vmscan.c            | 86 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 102 insertions(+)
include/linux/mmzone.h +16 -0
index 0d8776e5b6747..0a71bf015d12b 100644
@@ -628,6 +628,9 @@ void lru_gen_online_memcg(struct mem_cgroup *memcg);
 void lru_gen_offline_memcg(struct mem_cgroup *memcg);
 void lru_gen_release_memcg(struct mem_cgroup *memcg);
 void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid);
+void max_lru_gen_memcg(struct mem_cgroup *memcg);
+bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg);
+void lru_gen_reparent_memcg(struct mem_cgroup *src, struct mem_cgroup *dst);
 
 #else /* !CONFIG_LRU_GEN */
 
@@ -668,6 +671,19 @@ static inline void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
 {
 }
 
+static inline void max_lru_gen_memcg(struct mem_cgroup *memcg)
+{
+}
+
+static inline bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg)
+{
+	return true;
+}
+
+static inline void lru_gen_reparent_memcg(struct mem_cgroup *src, struct mem_cgroup *dst)
+{
+}
+
 #endif /* CONFIG_LRU_GEN */
 
 struct lruvec {
mm/vmscan.c +86 -0

92 lines not on this page · raw message

Signature · 1 line
2.20.1
author reviewer
#93 lore raw

PATCH 24/26 mm: memcontrol: refactor memcg_reparent_objcgs()

In reply to Qi Zheng

From: Qi Zheng <[email protected]>

Refactor the memcg_reparent_objcgs() to facilitate subsequent reparenting LRU folios here.

---
 mm/memcontrol.c | 37 +++++++++++++++++++++++++++----------
 mm/vmscan.c     |  1 -
 2 files changed, 27 insertions(+), 11 deletions(-)
mm/memcontrol.c +27 -10
index 7969dd93d858a..ee98c9e8fdcea 100644
@@ -206,24 +206,41 @@ static struct obj_cgroup *obj_cgroup_alloc(void)
 	return objcg;
 }
 
-static void memcg_reparent_objcgs(struct mem_cgroup *memcg)
+static void __memcg_reparent_objcgs(struct mem_cgroup *src,
+				    struct mem_cgroup *dst)
 {
 	struct obj_cgroup *objcg, *iter;
-	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
-
-	objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
-
-	spin_lock_irq(&objcg_lock);
 
+	objcg = rcu_replace_pointer(src->objcg, NULL, true);
 	/* 1) Ready to reparent active objcg. */
-	list_add(&objcg->list, &memcg->objcg_list);
+	list_add(&objcg->list, &src->objcg_list);
 	/* 2) Reparent active objcg and already reparented objcgs to parent. */
-	list_for_each_entry(iter, &memcg->objcg_list, list)
-		WRITE_ONCE(iter->memcg, parent);
+	list_for_each_entry(iter, &src->objcg_list, list)
+		WRITE_ONCE(iter->memcg, dst);
 	/* 3) Move already reparented objcgs to the parent's list */
-	list_splice(&memcg->objcg_list, &parent->objcg_list);
+	list_splice(&src->objcg_list, &dst->objcg_list);
+}
+
+static void reparent_locks(struct mem_cgroup *src, struct mem_cgroup *dst)
+{
+	spin_lock_irq(&objcg_lock);
+}
 
+static void reparent_unlocks(struct mem_cgroup *src, struct mem_cgroup *dst)
+{
 	spin_unlock_irq(&objcg_lock);
+}
+
+static void memcg_reparent_objcgs(struct mem_cgroup *src)
+{
+	struct obj_cgroup *objcg = rcu_dereference_protected(src->objcg, true);
+	struct mem_cgroup *dst = parent_mem_cgroup(src);
+
+	reparent_locks(src, dst);
+
+	__memcg_reparent_objcgs(src, dst);
+
+	reparent_unlocks(src, dst);
 
 	percpu_ref_kill(&objcg->refcnt);
 }
mm/vmscan.c +0 -1
index 3ee7fb96b8aeb..82c4cc6edbca5 100644
@@ -2649,7 +2649,6 @@ static bool can_age_anon_pages(struct lruvec *lruvec,
 			  lruvec_memcg(lruvec));
 }
 
-
 #ifdef CONFIG_MEMCG
 static void lruvec_reparent_lru(struct lruvec *src, struct lruvec *dst,
 				enum lru_list lru)
Signature · 1 line
2.20.1
author reviewer
#94 lore raw

PATCH 25/26 mm: memcontrol: eliminate the problem of dying memory cgroup for LRU folios

In reply to Qi Zheng

From: Muchun Song <[email protected]>

Pagecache pages are charged at allocation time and hold a reference to the original memory cgroup until reclaimed. Depending on memory pressure, page sharing patterns between different cgroups and cgroup creation/destruction rates, many dying memory cgroups can be pinned by pagecache pages, reducing page reclaim efficiency and wasting memory. Converting LRU folios and most other raw memory cgroup pins to the object cgroup direction can fix this long-living problem.

Finally, folio->memcg_data of LRU folios and kmem folios will always point to an object cgroup pointer. The folio->memcg_data of slab folios will point to an vector of object cgroups.

---
 include/linux/memcontrol.h |  77 +++++----------
 mm/memcontrol-v1.c         |  15 +--
 mm/memcontrol.c            | 189 +++++++++++++++++++++++--------------
 3 files changed, 150 insertions(+), 131 deletions(-)
include/linux/memcontrol.h +25 -52
index 6f6b28f8f0f63..f87aa43d8e54a 100644
@@ -369,9 +369,6 @@ enum objext_flags {
 #define OBJEXTS_FLAGS_MASK (__NR_OBJEXTS_FLAGS - 1)
 
 #ifdef CONFIG_MEMCG
-
-static inline bool folio_memcg_kmem(struct folio *folio);
-
 /*
  * After the initialization objcg->memcg is always pointing at
  * a valid memcg, but can be atomically swapped to the parent memcg.
@@ -385,43 +382,19 @@ static inline struct mem_cgroup *obj_cgroup_memcg(struct obj_cgroup *objcg)
 }
 
 /*
- * __folio_memcg - Get the memory cgroup associated with a non-kmem folio
- * @folio: Pointer to the folio.
- *
- * Returns a pointer to the memory cgroup associated with the folio,
- * or NULL. This function assumes that the folio is known to have a
- * proper memory cgroup pointer. It's not safe to call this function
- * against some type of folios, e.g. slab folios or ex-slab folios or
- * kmem folios.
- */
-static inline struct mem_cgroup *__folio_memcg(struct folio *folio)
-{
-	unsigned long memcg_data = folio->memcg_data;
-
-	VM_BUG_ON_FOLIO(folio_test_slab(folio), folio);
-	VM_BUG_ON_FOLIO(memcg_data & MEMCG_DATA_OBJEXTS, folio);
-	VM_BUG_ON_FOLIO(memcg_data & MEMCG_DATA_KMEM, folio);
-
-	return (struct mem_cgroup *)(memcg_data & ~OBJEXTS_FLAGS_MASK);
-}
-
-/*
- * __folio_objcg - get the object cgroup associated with a kmem folio.
+ * folio_objcg - get the object cgroup associated with a folio.
  * @folio: Pointer to the folio.
  *
  * Returns a pointer to the object cgroup associated with the folio,
  * or NULL. This function assumes that the folio is known to have a
- * proper object cgroup pointer. It's not safe to call this function
- * against some type of folios, e.g. slab folios or ex-slab folios or
- * LRU folios.
+ * proper object cgroup pointer.
  */
-static inline struct obj_cgroup *__folio_objcg(struct folio *folio)
+static inline struct obj_cgroup *folio_objcg(struct folio *folio)
 {
 	unsigned long memcg_data = folio->memcg_data;
 
 	VM_BUG_ON_FOLIO(folio_test_slab(folio), folio);
 	VM_BUG_ON_FOLIO(memcg_data & MEMCG_DATA_OBJEXTS, folio);
-	VM_BUG_ON_FOLIO(!(memcg_data & MEMCG_DATA_KMEM), folio);
 
 	return (struct obj_cgroup *)(memcg_data & ~OBJEXTS_FLAGS_MASK);
 }
@@ -435,21 +408,30 @@ static inline struct obj_cgroup *__folio_objcg(struct folio *folio)
  * proper memory cgroup pointer. It's not safe to call this function
  * against some type of folios, e.g. slab folios or ex-slab folios.
  *
- * For a non-kmem folio any of the following ensures folio and memcg binding
- * stability:
+ * For a folio any of the following ensures folio and objcg binding stability:
  *
  * - the folio lock
  * - LRU isolation
  * - exclusive reference
  *
- * For a kmem folio a caller should hold an rcu read lock to protect memcg
- * associated with a kmem folio from being released.
+ * Based on the stable binding of folio and objcg, for a folio any of the
+ * following ensures folio and memcg binding stability:
+ *
+ * - cgroup_mutex
+ * - the lruvec lock
+ *
+ * If the caller only want to ensure that the page counters of memcg are
+ * updated correctly, ensure that the binding stability of folio and objcg
+ * is sufficient.
+ *
+ * Note: The caller should hold an rcu read lock or cgroup_mutex to protect
+ * memcg associated with a folio from being released.
  */
 static inline struct mem_cgroup *folio_memcg(struct folio *folio)
 {
-	if (folio_memcg_kmem(folio))
-		return obj_cgroup_memcg(__folio_objcg(folio));
-	return __folio_memcg(folio);
+	struct obj_cgroup *objcg = folio_objcg(folio);
+
+	return objcg ? obj_cgroup_memcg(objcg) : NULL;
 }
 
 /*
@@ -473,15 +455,10 @@ static inline bool folio_memcg_charged(struct folio *folio)
  * has an associated memory cgroup pointer or an object cgroups vector or
  * an object cgroup.
  *
- * For a non-kmem folio any of the following ensures folio and memcg binding
- * stability:
+ * The page and objcg or memcg binding rules can refer to folio_memcg().
  *
- * - the folio lock
- * - LRU isolation
- * - exclusive reference
- *
- * For a kmem folio a caller should hold an rcu read lock to protect memcg
- * associated with a kmem folio from being released.
+ * A caller should hold an rcu read lock to protect memcg associated with a
+ * page from being released.
  */
 static inline struct mem_cgroup *folio_memcg_check(struct folio *folio)
 {
@@ -490,18 +467,14 @@ static inline struct mem_cgroup *folio_memcg_check(struct folio *folio)
 	 * for slabs, READ_ONCE() should be used here.
 	 */
 	unsigned long memcg_data = READ_ONCE(folio->memcg_data);
+	struct obj_cgroup *objcg;
 
 	if (memcg_data & MEMCG_DATA_OBJEXTS)
 		return NULL;
 
-	if (memcg_data & MEMCG_DATA_KMEM) {
-		struct obj_cgroup *objcg;
-
-		objcg = (void *)(memcg_data & ~OBJEXTS_FLAGS_MASK);
-		return obj_cgroup_memcg(objcg);
-	}
+	objcg = (void *)(memcg_data & ~OBJEXTS_FLAGS_MASK);
 
-	return (struct mem_cgroup *)(memcg_data & ~OBJEXTS_FLAGS_MASK);
+	return objcg ? obj_cgroup_memcg(objcg) : NULL;
 }
 
 static inline struct mem_cgroup *page_memcg_check(struct page *page)
mm/memcontrol-v1.c +9 -6
index 6eed14bff7426..23c07df2063c8 100644
@@ -591,6 +591,7 @@ void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
 void memcg1_swapout(struct folio *folio, swp_entry_t entry)
 {
 	struct mem_cgroup *memcg, *swap_memcg;
+	struct obj_cgroup *objcg;
 	unsigned int nr_entries;
 
 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
@@ -602,12 +603,13 @@ void memcg1_swapout(struct folio *folio, swp_entry_t entry)
 	if (!do_memsw_account())
 		return;
 
-	memcg = folio_memcg(folio);
-
-	VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
-	if (!memcg)
+	objcg = folio_objcg(folio);
+	VM_WARN_ON_ONCE_FOLIO(!objcg, folio);
+	if (!objcg)
 		return;
 
+	rcu_read_lock();
+	memcg = obj_cgroup_memcg(objcg);
 	/*
 	 * In case the memcg owning these pages has been offlined and doesn't
 	 * have an ID allocated to it anymore, charge the closest online
@@ -625,7 +627,7 @@ void memcg1_swapout(struct folio *folio, swp_entry_t entry)
 	folio_unqueue_deferred_split(folio);
 	folio->memcg_data = 0;
 
-	if (!mem_cgroup_is_root(memcg))
+	if (!obj_cgroup_is_root(objcg))
 		page_counter_uncharge(&memcg->memory, nr_entries);
 
 	if (memcg != swap_memcg) {
@@ -646,7 +648,8 @@ void memcg1_swapout(struct folio *folio, swp_entry_t entry)
 	preempt_enable_nested();
 	memcg1_check_events(memcg, folio_nid(folio));
 
-	css_put(&memcg->css);
+	rcu_read_unlock();
+	obj_cgroup_put(objcg);
 }
 
 /*
mm/memcontrol.c +116 -73

373 lines not on this page · raw message

Signature · 1 line
2.20.1
author reviewer
#98 lore raw

PATCH 26/26 mm: lru: add VM_WARN_ON_ONCE_FOLIO to lru maintenance helpers

In reply to Qi Zheng

From: Muchun Song <[email protected]>

We must ensure the folio is deleted from or added to the correct lruvec list. So, add VM_WARN_ON_ONCE_FOLIO() to catch invalid users. The VM_BUG_ON_PAGE() in move_pages_to_lru() can be removed as add_page_to_lru_list() will perform the necessary check.

---
 include/linux/mm_inline.h | 6 ++++++
 mm/vmscan.c               | 1 -
 2 files changed, 6 insertions(+), 1 deletion(-)
include/linux/mm_inline.h +6 -0
index f6a2b2d200162..dfed0523e0c43 100644
@@ -342,6 +342,8 @@ void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio)
 {
 	enum lru_list lru = folio_lru_list(folio);
 
+	VM_WARN_ON_ONCE_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
+
 	if (lru_gen_add_folio(lruvec, folio, false))
 		return;
 
@@ -356,6 +358,8 @@ void lruvec_add_folio_tail(struct lruvec *lruvec, struct folio *folio)
 {
 	enum lru_list lru = folio_lru_list(folio);
 
+	VM_WARN_ON_ONCE_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
+
 	if (lru_gen_add_folio(lruvec, folio, true))
 		return;
 
@@ -370,6 +374,8 @@ void lruvec_del_folio(struct lruvec *lruvec, struct folio *folio)
 {
 	enum lru_list lru = folio_lru_list(folio);
 
+	VM_WARN_ON_ONCE_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
+
 	if (lru_gen_del_folio(lruvec, folio, false))
 		return;
 
mm/vmscan.c +0 -1
index 82c4cc6edbca5..5f22ec438c018 100644
@@ -1934,7 +1934,6 @@ static unsigned int move_folios_to_lru(struct list_head *list)
 			continue;
 		}
 
-		VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
 		lruvec_add_folio(lruvec, folio);
 		nr_pages = folio_nr_pages(folio);
 		nr_moved += nr_pages;
Signature · 1 line
2.20.1
syzbot Tested-by [email protected] on the v1 series
#99 lore raw
In reply to Qi Zheng
syzbot ci has tested the following series

syzbot ci has tested the following series

[v1] Eliminate Dying Memory Cgroup
https://lore.kernel.org/all/[email protected]
* [PATCH v1 01/26] mm: memcontrol: remove dead code of checking parent memory cgroup
* [PATCH v1 02/26] mm: workingset: use folio_lruvec() in workingset_refault()
* [PATCH v1 03/26] mm: rename unlock_page_lruvec_irq and its variants
* [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()
* [PATCH v1 05/26] mm: memcontrol: allocate object cgroup for non-kmem case
* [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup
* [PATCH v1 07/26] mm: memcontrol: prevent memory cgroup release in get_mem_cgroup_from_folio()
* [PATCH v1 08/26] buffer: prevent memory cgroup release in folio_alloc_buffers()
* [PATCH v1 09/26] writeback: prevent memory cgroup release in writeback module
* [PATCH v1 10/26] mm: memcontrol: prevent memory cgroup release in count_memcg_folio_events()
* [PATCH v1 11/26] mm: page_io: prevent memory cgroup release in page_io module
* [PATCH v1 12/26] mm: migrate: prevent memory cgroup release in folio_migrate_mapping()
* [PATCH v1 13/26] mm: mglru: prevent memory cgroup release in mglru
* [PATCH v1 14/26] mm: memcontrol: prevent memory cgroup release in mem_cgroup_swap_full()
* [PATCH v1 15/26] mm: workingset: prevent memory cgroup release in lru_gen_eviction()
* [PATCH v1 16/26] mm: thp: prevent memory cgroup release in folio_split_queue_lock{_irqsave}()
* [PATCH v1 17/26] mm: workingset: prevent lruvec release in workingset_refault()
* [PATCH v1 18/26] mm: zswap: prevent lruvec release in zswap_folio_swapin()
* [PATCH v1 19/26] mm: swap: prevent lruvec release in swap module
* [PATCH v1 20/26] mm: workingset: prevent lruvec release in workingset_activation()
* [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock
* [PATCH v1 22/26] mm: vmscan: prepare for reparenting traditional LRU folios
* [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios
* [PATCH v1 24/26] mm: memcontrol: refactor memcg_reparent_objcgs()
* [PATCH v1 25/26] mm: memcontrol: eliminate the problem of dying memory cgroup for LRU folios
* [PATCH v1 26/26] mm: lru: add VM_WARN_ON_ONCE_FOLIO to lru maintenance helpers

and found the following issue:
WARNING in folio_memcg

Full report is available here:
https://ci.syzbot.org/series/0d48a77a-fb4f-485d-9fd6-086afd6fb650

***

WARNING in folio_memcg

tree:      mm-new
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/akpm/mm.git
base:      b227c04932039bccc21a0a89cd6df50fa57e4716
arch:      amd64
compiler:  Debian clang version 20.1.8 (++20250708063551+0c9f909b7976-1~exp1~20250708183702.136), Debian LLD 20.1.8
config:    https://ci.syzbot.org/builds/503d7034-ae99-44d1-8fb2-62e7ef5e1c7c/config
C repro:   https://ci.syzbot.org/findings/880c374a-1b49-436e-9be2-63d5e2c6b6ab/c_repro
syz repro: https://ci.syzbot.org/findings/880c374a-1b49-436e-9be2-63d5e2c6b6ab/syz_repro

exFAT-fs (loop0): failed to load upcase table (idx : 0x00010000, chksum : 0xe5674ec2, utbl_chksum : 0xe619d30d) exFAT-fs (loop0): failed to load alloc-bitmap
exFAT-fs (loop0): failed to recognize exfat type

------------[ cut here ]------------
WARNING: CPU: 1 PID: 5965 at ./include/linux/memcontrol.h:380 obj_cgroup_memcg include/linux/memcontrol.h:380 [inline]
WARNING: CPU: 1 PID: 5965 at ./include/linux/memcontrol.h:380 folio_memcg+0x148/0x1c0 include/linux/memcontrol.h:434
Modules linked in:
CPU: 1 UID: 0 PID: 5965 Comm: syz.0.17 Not tainted syzkaller #0 PREEMPT(full) 
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
RIP: 0010:obj_cgroup_memcg include/linux/memcontrol.h:380 [inline]
RIP: 0010:folio_memcg+0x148/0x1c0 include/linux/memcontrol.h:434
Code: 48 c1 e8 03 42 80 3c 20 00 74 08 48 89 df e8 5f c8 06 00 48 8b 03 5b 41 5c 41 5e 41 5f 5d e9 cf 89 2a 09 cc e8 a9 bb a0 ff 90 <0f> 0b 90 eb ca 44 89 f9 80 e1 07 80 c1 03 38 c1 0f 8c ef fe ff ff
RSP: 0018:ffffc90003ec66b0 EFLAGS: 00010293
RAX: ffffffff821f4b57 RBX: ffff888108b31480 RCX: ffff88816be91d00
RDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000000000000
RBP: 0000000000000000 R08: ffff88816be91d00 R09: 0000000000000002
R10: 00000000fffffff0 R11: 0000000000000000 R12: dffffc0000000000
R13: 00000000ffffffe4 R14: ffffea0006d5f840 R15: ffffea0006d5f870
FS:  000055555db87500(0000) GS:ffff8882a9f35000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000001b2ee63fff CR3: 000000010c308000 CR4: 00000000000006f0
Call Trace:
 <TASK>
 zswap_compress mm/zswap.c:900 [inline]
 zswap_store_page mm/zswap.c:1430 [inline]
 zswap_store+0xfa2/0x1f80 mm/zswap.c:1541
 swap_writeout+0x6e8/0xf20 mm/page_io.c:275
 writeout mm/vmscan.c:651 [inline]
 pageout mm/vmscan.c:699 [inline]
 shrink_folio_list+0x34ec/0x4c40 mm/vmscan.c:1418
 reclaim_folio_list+0xeb/0x500 mm/vmscan.c:2196
 reclaim_pages+0x454/0x520 mm/vmscan.c:2233
 madvise_cold_or_pageout_pte_range+0x1974/0x1d00 mm/madvise.c:565
 walk_pmd_range mm/pagewalk.c:130 [inline]
 walk_pud_range mm/pagewalk.c:224 [inline]
 walk_p4d_range mm/pagewalk.c:262 [inline]
 walk_pgd_range+0xfe9/0x1d40 mm/pagewalk.c:303
 __walk_page_range+0x14c/0x710 mm/pagewalk.c:410
 walk_page_range_vma+0x393/0x440 mm/pagewalk.c:717
 madvise_pageout_page_range mm/madvise.c:624 [inline]
 madvise_pageout mm/madvise.c:649 [inline]
 madvise_vma_behavior+0x311f/0x3a10 mm/madvise.c:1352
 madvise_walk_vmas+0x51c/0xa30 mm/madvise.c:1669
 madvise_do_behavior+0x38e/0x550 mm/madvise.c:1885
 do_madvise+0x1bc/0x270 mm/madvise.c:1978
 __do_sys_madvise mm/madvise.c:1987 [inline]
 __se_sys_madvise mm/madvise.c:1985 [inline]
 __x64_sys_madvise+0xa7/0xc0 mm/madvise.c:1985
 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
 do_syscall_64+0xfa/0xfa0 arch/x86/entry/syscall_64.c:94
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7fccac38efc9
Code: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 a8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007ffd9cc58708 EFLAGS: 00000246 ORIG_RAX: 000000000000001c
RAX: ffffffffffffffda RBX: 00007fccac5e5fa0 RCX: 00007fccac38efc9
RDX: 0000000000000015 RSI: 7fffffffffffffff RDI: 0000200000000000
RBP: 00007fccac411f91 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007fccac5e5fa0 R14: 00007fccac5e5fa0 R15: 0000000000000003
 </TASK>

***

If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:

---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].

#100 lore raw
Quoted 50 lines · syzbot ci

syzbot ci has tested the following series

[v1] Eliminate Dying Memory Cgroup
https://lore.kernel.org/all/[email protected]
* [PATCH v1 01/26] mm: memcontrol: remove dead code of checking parent memory cgroup
* [PATCH v1 02/26] mm: workingset: use folio_lruvec() in workingset_refault()
* [PATCH v1 03/26] mm: rename unlock_page_lruvec_irq and its variants
* [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()
* [PATCH v1 05/26] mm: memcontrol: allocate object cgroup for non-kmem case
* [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup
* [PATCH v1 07/26] mm: memcontrol: prevent memory cgroup release in get_mem_cgroup_from_folio()
* [PATCH v1 08/26] buffer: prevent memory cgroup release in folio_alloc_buffers()
* [PATCH v1 09/26] writeback: prevent memory cgroup release in writeback module
* [PATCH v1 10/26] mm: memcontrol: prevent memory cgroup release in count_memcg_folio_events()
* [PATCH v1 11/26] mm: page_io: prevent memory cgroup release in page_io module
* [PATCH v1 12/26] mm: migrate: prevent memory cgroup release in folio_migrate_mapping()
* [PATCH v1 13/26] mm: mglru: prevent memory cgroup release in mglru
* [PATCH v1 14/26] mm: memcontrol: prevent memory cgroup release in mem_cgroup_swap_full()
* [PATCH v1 15/26] mm: workingset: prevent memory cgroup release in lru_gen_eviction()
* [PATCH v1 16/26] mm: thp: prevent memory cgroup release in folio_split_queue_lock{_irqsave}()
* [PATCH v1 17/26] mm: workingset: prevent lruvec release in workingset_refault()
* [PATCH v1 18/26] mm: zswap: prevent lruvec release in zswap_folio_swapin()
* [PATCH v1 19/26] mm: swap: prevent lruvec release in swap module
* [PATCH v1 20/26] mm: workingset: prevent lruvec release in workingset_activation()
* [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock
* [PATCH v1 22/26] mm: vmscan: prepare for reparenting traditional LRU folios
* [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios
* [PATCH v1 24/26] mm: memcontrol: refactor memcg_reparent_objcgs()
* [PATCH v1 25/26] mm: memcontrol: eliminate the problem of dying memory cgroup for LRU folios
* [PATCH v1 26/26] mm: lru: add VM_WARN_ON_ONCE_FOLIO to lru maintenance helpers

and found the following issue:
WARNING in folio_memcg

Full report is available here:
https://ci.syzbot.org/series/0d48a77a-fb4f-485d-9fd6-086afd6fb650

***

WARNING in folio_memcg

tree:      mm-new
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/akpm/mm.git
base:      b227c04932039bccc21a0a89cd6df50fa57e4716
arch:      amd64
compiler:  Debian clang version 20.1.8 (++20250708063551+0c9f909b7976-1~exp1~20250708183702.136), Debian LLD 20.1.8
config:    https://ci.syzbot.org/builds/503d7034-ae99-44d1-8fb2-62e7ef5e1c7c/config
C repro:   https://ci.syzbot.org/findings/880c374a-1b49-436e-9be2-63d5e2c6b6ab/c_repro
syz repro: https://ci.syzbot.org/findings/880c374a-1b49-436e-9be2-63d5e2c6b6ab/syz_repro
Quoted 6 lines

exFAT-fs (loop0): failed to load upcase table (idx : 0x00010000, chksum : 0xe5674ec2, utbl_chksum : 0xe619d30d) exFAT-fs (loop0): failed to load alloc-bitmap
exFAT-fs (loop0): failed to recognize exfat type

------------[ cut here ]------------
WARNING: CPU: 1 PID: 5965 at ./include/linux/memcontrol.h:380 obj_cgroup_memcg include/linux/memcontrol.h:380 [inline]
WARNING: CPU: 1 PID: 5965 at ./include/linux/memcontrol.h:380 folio_memcg+0x148/0x1c0 include/linux/memcontrol.h:434

This is understandable as the code snippet was added fairly recently and is easy to miss during rebasing.

#syz test

mm/zswap.c +3 -0
index a341814468b9..738d914e5354 100644
@@ -896,11 +896,14 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry,
 	 * to the active LRU list in the case.
 	 */
 	if (comp_ret || !dlen || dlen >= PAGE_SIZE) {
+		rcu_read_lock();
 		if (!mem_cgroup_zswap_writeback_enabled(
 					folio_memcg(page_folio(page)))) {
+			rcu_read_unlock();
 			comp_ret = comp_ret ? comp_ret : -EINVAL;
 			goto unlock;
 		}
+		rcu_read_unlock();
 		comp_ret = 0;
 		dlen = PAGE_SIZE;
 		dst = kmap_local_page(page);
author reviewer
#102 lore raw
In reply to Harry Yoo

Hi Harry,

Quoted 58 lines · Harry Yoo
Quoted 50 lines · syzbot ci

syzbot ci has tested the following series

[v1] Eliminate Dying Memory Cgroup
https://lore.kernel.org/all/[email protected]
* [PATCH v1 01/26] mm: memcontrol: remove dead code of checking parent memory cgroup
* [PATCH v1 02/26] mm: workingset: use folio_lruvec() in workingset_refault()
* [PATCH v1 03/26] mm: rename unlock_page_lruvec_irq and its variants
* [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()
* [PATCH v1 05/26] mm: memcontrol: allocate object cgroup for non-kmem case
* [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup
* [PATCH v1 07/26] mm: memcontrol: prevent memory cgroup release in get_mem_cgroup_from_folio()
* [PATCH v1 08/26] buffer: prevent memory cgroup release in folio_alloc_buffers()
* [PATCH v1 09/26] writeback: prevent memory cgroup release in writeback module
* [PATCH v1 10/26] mm: memcontrol: prevent memory cgroup release in count_memcg_folio_events()
* [PATCH v1 11/26] mm: page_io: prevent memory cgroup release in page_io module
* [PATCH v1 12/26] mm: migrate: prevent memory cgroup release in folio_migrate_mapping()
* [PATCH v1 13/26] mm: mglru: prevent memory cgroup release in mglru
* [PATCH v1 14/26] mm: memcontrol: prevent memory cgroup release in mem_cgroup_swap_full()
* [PATCH v1 15/26] mm: workingset: prevent memory cgroup release in lru_gen_eviction()
* [PATCH v1 16/26] mm: thp: prevent memory cgroup release in folio_split_queue_lock{_irqsave}()
* [PATCH v1 17/26] mm: workingset: prevent lruvec release in workingset_refault()
* [PATCH v1 18/26] mm: zswap: prevent lruvec release in zswap_folio_swapin()
* [PATCH v1 19/26] mm: swap: prevent lruvec release in swap module
* [PATCH v1 20/26] mm: workingset: prevent lruvec release in workingset_activation()
* [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock
* [PATCH v1 22/26] mm: vmscan: prepare for reparenting traditional LRU folios
* [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios
* [PATCH v1 24/26] mm: memcontrol: refactor memcg_reparent_objcgs()
* [PATCH v1 25/26] mm: memcontrol: eliminate the problem of dying memory cgroup for LRU folios
* [PATCH v1 26/26] mm: lru: add VM_WARN_ON_ONCE_FOLIO to lru maintenance helpers

and found the following issue:
WARNING in folio_memcg

Full report is available here:
https://ci.syzbot.org/series/0d48a77a-fb4f-485d-9fd6-086afd6fb650

***

WARNING in folio_memcg

tree:      mm-new
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/akpm/mm.git
base:      b227c04932039bccc21a0a89cd6df50fa57e4716
arch:      amd64
compiler:  Debian clang version 20.1.8 (++20250708063551+0c9f909b7976-1~exp1~20250708183702.136), Debian LLD 20.1.8
config:    https://ci.syzbot.org/builds/503d7034-ae99-44d1-8fb2-62e7ef5e1c7c/config
C repro:   https://ci.syzbot.org/findings/880c374a-1b49-436e-9be2-63d5e2c6b6ab/c_repro
syz repro: https://ci.syzbot.org/findings/880c374a-1b49-436e-9be2-63d5e2c6b6ab/syz_repro
Quoted 6 lines

exFAT-fs (loop0): failed to load upcase table (idx : 0x00010000, chksum : 0xe5674ec2, utbl_chksum : 0xe619d30d) exFAT-fs (loop0): failed to load alloc-bitmap
exFAT-fs (loop0): failed to recognize exfat type

------------[ cut here ]------------
WARNING: CPU: 1 PID: 5965 at ./include/linux/memcontrol.h:380 obj_cgroup_memcg include/linux/memcontrol.h:380 [inline]
WARNING: CPU: 1 PID: 5965 at ./include/linux/memcontrol.h:380 folio_memcg+0x148/0x1c0 include/linux/memcontrol.h:434
Quoted 2 lines

This is understandable as the code snippet was added fairly recently and is easy to miss during rebasing.

My mistake, I should recheck it.

Quoted 12 lines

#syz test

mm/zswap.c +1 -0
index a341814468b9..738d914e5354 100644
@@ -896,11 +896,14 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry,
  	 * to the active LRU list in the case.
  	 */
  	if (comp_ret || !dlen || dlen >= PAGE_SIZE) {
+		rcu_read_lock();

mm/zswap.c static bool zswap_compress(struct page *page, struct zswap_entry *entry, · line 909

Quoted 10 lines
mm/zswap.c +2 -0
  		if (!mem_cgroup_zswap_writeback_enabled(
  					folio_memcg(page_folio(page)))) {
+			rcu_read_unlock();
  			comp_ret = comp_ret ? comp_ret : -EINVAL;
  			goto unlock;
  		}
+		rcu_read_unlock();
  		comp_ret = 0;
  		dlen = PAGE_SIZE;
  		dst = kmap_local_page(page);

LGTM, will do in the next version.

Thanks!

Quoted 1 line
reviewer
#103 lore raw
In reply to Qi Zheng
Quoted 6 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Hi all,

This series aims to eliminate the problem of dying memory cgroup. It completes the adaptation to the MGLRU scenarios based on the Muchun Song's patchset[1].

I high level summary and main design decisions should be describe in the cover letter.

Thanks!

Signature · 2 lines
Michal Hocko
SUSE Labs
author reviewer
#104 lore raw

Hi Michal,

Quoted 10 lines · Michal Hocko
Quoted 6 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Hi all,

This series aims to eliminate the problem of dying memory cgroup. It completes the adaptation to the MGLRU scenarios based on the Muchun Song's patchset[1].

I high level summary and main design decisions should be describe in the cover letter.

Got it. Will add it in the next version.

I've pasted the contents of Muchun Song's cover letter below:

```
## Introduction

This patchset is intended to transfer the LRU pages to the object cgroup
without holding a reference to the original memory cgroup in order to
address the issue of the dying memory cgroup. A consensus has already been
reached regarding this approach recently [1].

## Background

The issue of a dying memory cgroup refers to a situation where a memory
cgroup is no longer being used by users, but memory (the metadata
associated with memory cgroups) remains allocated to it. This situation
may potentially result in memory leaks or inefficiencies in memory
reclamation and has persisted as an issue for several years. Any memory
allocation that endures longer than the lifespan (from the users'
perspective) of a memory cgroup can lead to the issue of dying memory
cgroup. We have exerted greater efforts to tackle this problem by
introducing the infrastructure of object cgroup [2].

Presently, numerous types of objects (slab objects, non-slab kernel
allocations, per-CPU objects) are charged to the object cgroup without
holding a reference to the original memory cgroup. The final allocations
for LRU pages (anonymous pages and file pages) are charged at allocation
time and continues to hold a reference to the original memory cgroup
until reclaimed.

File pages are more complex than anonymous pages as they can be shared
among different memory cgroups and may persist beyond the lifespan of
the memory cgroup. The long-term pinning of file pages to memory cgroups
is a widespread issue that causes recurring problems in practical
scenarios [3]. File pages remain unreclaimed for extended periods.
Additionally, they are accessed by successive instances (second, third,
fourth, etc.) of the same job, which is restarted into a new cgroup each
time. As a result, unreclaimable dying memory cgroups accumulate,
leading to memory wastage and significantly reducing the efficiency
of page reclamation.

## Fundamentals

A folio will no longer pin its corresponding memory cgroup. It is necessary
to ensure that the memory cgroup or the lruvec associated with the memory
cgroup is not released when a user obtains a pointer to the memory cgroup
or lruvec returned by folio_memcg() or folio_lruvec(). Users are required
to hold the RCU read lock or acquire a reference to the memory cgroup
associated with the folio to prevent its release if they are not concerned
about the binding stability between the folio and its corresponding memory
cgroup. However, some users of folio_lruvec() (i.e., the lruvec lock)
desire a stable binding between the folio and its corresponding memory
cgroup. An approach is needed to ensure the stability of the binding while
the lruvec lock is held, and to detect the situation of holding the
incorrect lruvec lock when there is a race condition during memory cgroup
reparenting. The following four steps are taken to achieve these goals.

1. The first step  to be taken is to identify all users of both functions
   (folio_memcg() and folio_lruvec()) who are not concerned about binding
   stability and implement appropriate measures (such as holding a RCU read
   lock or temporarily obtaining a reference to the memory cgroup for a
   brief period) to prevent the release of the memory cgroup.

2. Secondly, the following refactoring of folio_lruvec_lock() demonstrates
   how to ensure the binding stability from the user's perspective of
   folio_lruvec().

   struct lruvec *folio_lruvec_lock(struct folio *folio)
   {
           struct lruvec *lruvec;

           rcu_read_lock();
   retry:
           lruvec = folio_lruvec(folio);
           spin_lock(&lruvec->lru_lock);
           if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
                   spin_unlock(&lruvec->lru_lock);
                   goto retry;
           }

           return lruvec;
   }

   From the perspective of memory cgroup removal, the entire reparenting
   process (altering the binding relationship between folio and its memory
   cgroup and moving the LRU lists to its parental memory cgroup) should be
   carried out under both the lruvec lock of the memory cgroup being 
removed
   and the lruvec lock of its parent.

3. Thirdly, another lock that requires the same approach is the split-queue
   lock of THP.

4. Finally, transfer the LRU pages to the object cgroup without holding a
   reference to the original memory cgroup.
```

And the details of the adaptation are below:

```
Similar to traditional LRU folios, in order to solve the dying memcg
problem, we also need to reparenting MGLRU folios to the parent memcg when
memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the
   number of generations of the parent and child memcg may be different,
   so we cannot simply transfer MGLRU folios in the child memcg to the
   parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot
   traverse these folios while holding the lru lock, otherwise it may
   cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size
   may be updated, but the folio is not immediately moved to the
   corresponding lru list. Therefore, there may be folios of different
   generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is
   found based on the generation information in folio->flags, and the
   corresponding LRU size will be updated. Therefore, we need to update
   the lru size correctly during reparenting, otherwise the lru size may
   be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru
list in the child memcg to the lru list of the same generation in the
parent memcg during reparenting. And in order to ensure that the parent
memcg has the same generation, we need to increase the generations in the
parent memcg to the MAX_NR_GENS before reparenting.

Of course, the same generation has different meanings in the parent and
child memcg, this will cause confusion in the hot and cold information of
folios. But other than that, this method is simple enough, the lru size
is correct, and there is no need to consider some concurrency issues (such
as lru_gen_del_folio()).
```

Thanks,
Qi

Quoted 2 lines

Thanks!

reviewer
#105 lore raw
Quoted 18 lines · Qi Zheng

Hi Michal,

Quoted 10 lines · Michal Hocko
Quoted 6 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Hi all,

This series aims to eliminate the problem of dying memory cgroup. It completes the adaptation to the MGLRU scenarios based on the Muchun Song's patchset[1].

I high level summary and main design decisions should be describe in the cover letter.

Got it. Will add it in the next version.

I've pasted the contents of Muchun Song's cover letter below:

Quoted 7 lines

```
## Introduction

This patchset is intended to transfer the LRU pages to the object cgroup without holding a reference to the original memory cgroup in order to address the issue of the dying memory cgroup. A consensus has already been reached regarding this approach recently [1].

Could you add those referenced links as well please?

Quoted 19 lines

## Background

The issue of a dying memory cgroup refers to a situation where a memory cgroup is no longer being used by users, but memory (the metadata associated with memory cgroups) remains allocated to it. This situation may potentially result in memory leaks or inefficiencies in memory reclamation and has persisted as an issue for several years. Any memory allocation that endures longer than the lifespan (from the users' perspective) of a memory cgroup can lead to the issue of dying memory cgroup. We have exerted greater efforts to tackle this problem by introducing the infrastructure of object cgroup [2].

Presently, numerous types of objects (slab objects, non-slab kernel allocations, per-CPU objects) are charged to the object cgroup without holding a reference to the original memory cgroup. The final allocations for LRU pages (anonymous pages and file pages) are charged at allocation time and continues to hold a reference to the original memory cgroup until reclaimed.

Quoted 10 lines

File pages are more complex than anonymous pages as they can be shared among different memory cgroups and may persist beyond the lifespan of the memory cgroup. The long-term pinning of file pages to memory cgroups is a widespread issue that causes recurring problems in practical scenarios [3]. File pages remain unreclaimed for extended periods. Additionally, they are accessed by successive instances (second, third, fourth, etc.) of the same job, which is restarted into a new cgroup each time. As a result, unreclaimable dying memory cgroups accumulate, leading to memory wastage and significantly reducing the efficiency of page reclamation.

Very useful introduction to the problem. Thanks!

Quoted 87 lines

## Fundamentals

A folio will no longer pin its corresponding memory cgroup. It is necessary to ensure that the memory cgroup or the lruvec associated with the memory cgroup is not released when a user obtains a pointer to the memory cgroup or lruvec returned by folio_memcg() or folio_lruvec(). Users are required to hold the RCU read lock or acquire a reference to the memory cgroup associated with the folio to prevent its release if they are not concerned about the binding stability between the folio and its corresponding memory cgroup. However, some users of folio_lruvec() (i.e., the lruvec lock) desire a stable binding between the folio and its corresponding memory cgroup. An approach is needed to ensure the stability of the binding while the lruvec lock is held, and to detect the situation of holding the incorrect lruvec lock when there is a race condition during memory cgroup reparenting. The following four steps are taken to achieve these goals.

1. The first step to be taken is to identify all users of both functions (folio_memcg() and folio_lruvec()) who are not concerned about binding stability and implement appropriate measures (such as holding a RCU read lock or temporarily obtaining a reference to the memory cgroup for a brief period) to prevent the release of the memory cgroup.

2. Secondly, the following refactoring of folio_lruvec_lock() demonstrates how to ensure the binding stability from the user's perspective of folio_lruvec().

   struct lruvec *folio_lruvec_lock(struct folio *folio)
   {
           struct lruvec *lruvec;
           rcu_read_lock();
   retry:
           lruvec = folio_lruvec(folio);
           spin_lock(&lruvec->lru_lock);
           if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
                   spin_unlock(&lruvec->lru_lock);
                   goto retry;
           }

           return lruvec;

}

From the perspective of memory cgroup removal, the entire reparenting process (altering the binding relationship between folio and its memory cgroup and moving the LRU lists to its parental memory cgroup) should be carried out under both the lruvec lock of the memory cgroup being removed and the lruvec lock of its parent.

3. Thirdly, another lock that requires the same approach is the split-queue lock of THP.

4. Finally, transfer the LRU pages to the object cgroup without holding a reference to the original memory cgroup.

```

And the details of the adaptation are below:

```

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Quoted 6 lines

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).
```

Thanks you this is very useful.

A high level overview on how the patch series (of this size) would be appreaciate as well.

Signature · 2 lines
Michal Hocko
SUSE Labs
author reviewer
#106 lore raw

Hi Michal,

Quoted 22 lines · Michal Hocko
Quoted 21 lines · Qi Zheng

Hi Michal,

Quoted 10 lines · Michal Hocko
Quoted 6 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Hi all,

This series aims to eliminate the problem of dying memory cgroup. It completes the adaptation to the MGLRU scenarios based on the Muchun Song's patchset[1].

I high level summary and main design decisions should be describe in the cover letter.

Got it. Will add it in the next version.

I've pasted the contents of Muchun Song's cover letter below:

```
## Introduction

Quoted 6 lines
Quoted 4 lines

This patchset is intended to transfer the LRU pages to the object cgroup without holding a reference to the original memory cgroup in order to address the issue of the dying memory cgroup. A consensus has already been reached regarding this approach recently [1].

Could you add those referenced links as well please?

Oh, I missed that.

[1]. https://lore.kernel.org/linux-mm/Z6OkXXYDorPrBvEQ@hm-sls2/

Quoted 12 lines
Quoted 12 lines

## Background

The issue of a dying memory cgroup refers to a situation where a memory cgroup is no longer being used by users, but memory (the metadata associated with memory cgroups) remains allocated to it. This situation may potentially result in memory leaks or inefficiencies in memory reclamation and has persisted as an issue for several years. Any memory allocation that endures longer than the lifespan (from the users' perspective) of a memory cgroup can lead to the issue of dying memory cgroup. We have exerted greater efforts to tackle this problem by introducing the infrastructure of object cgroup [2].

[2]. https://lwn.net/Articles/895431/

Quoted 8 lines
Quoted 8 lines

Presently, numerous types of objects (slab objects, non-slab kernel allocations, per-CPU objects) are charged to the object cgroup without holding a reference to the original memory cgroup. The final allocations for LRU pages (anonymous pages and file pages) are charged at allocation time and continues to hold a reference to the original memory cgroup until reclaimed.

Quoted 5 lines
Quoted 5 lines

File pages are more complex than anonymous pages as they can be shared among different memory cgroups and may persist beyond the lifespan of the memory cgroup. The long-term pinning of file pages to memory cgroups is a widespread issue that causes recurring problems in practical scenarios [3]. File pages remain unreclaimed for extended periods.

[3]. https://github.com/systemd/systemd/pull/36827

Quoted 102 lines
Quoted 5 lines

Additionally, they are accessed by successive instances (second, third, fourth, etc.) of the same job, which is restarted into a new cgroup each time. As a result, unreclaimable dying memory cgroups accumulate, leading to memory wastage and significantly reducing the efficiency of page reclamation.

Very useful introduction to the problem. Thanks!

Quoted 87 lines

## Fundamentals

A folio will no longer pin its corresponding memory cgroup. It is necessary to ensure that the memory cgroup or the lruvec associated with the memory cgroup is not released when a user obtains a pointer to the memory cgroup or lruvec returned by folio_memcg() or folio_lruvec(). Users are required to hold the RCU read lock or acquire a reference to the memory cgroup associated with the folio to prevent its release if they are not concerned about the binding stability between the folio and its corresponding memory cgroup. However, some users of folio_lruvec() (i.e., the lruvec lock) desire a stable binding between the folio and its corresponding memory cgroup. An approach is needed to ensure the stability of the binding while the lruvec lock is held, and to detect the situation of holding the incorrect lruvec lock when there is a race condition during memory cgroup reparenting. The following four steps are taken to achieve these goals.

1. The first step to be taken is to identify all users of both functions (folio_memcg() and folio_lruvec()) who are not concerned about binding stability and implement appropriate measures (such as holding a RCU read lock or temporarily obtaining a reference to the memory cgroup for a brief period) to prevent the release of the memory cgroup.

2. Secondly, the following refactoring of folio_lruvec_lock() demonstrates

    how to ensure the binding stability from the user's perspective of
    folio_lruvec().

    struct lruvec *folio_lruvec_lock(struct folio *folio)
    {
            struct lruvec *lruvec;

            rcu_read_lock();
    retry:
            lruvec = folio_lruvec(folio);
            spin_lock(&lruvec->lru_lock);
            if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
                    spin_unlock(&lruvec->lru_lock);
                    goto retry;
            }

            return lruvec;
    }

    From the perspective of memory cgroup removal, the entire reparenting
    process (altering the binding relationship between folio and its memory
    cgroup and moving the LRU lists to its parental memory cgroup) should be
    carried out under both the lruvec lock of the memory cgroup being removed
    and the lruvec lock of its parent.

3. Thirdly, another lock that requires the same approach is the split-queue lock of THP.

4. Finally, transfer the LRU pages to the object cgroup without holding a reference to the original memory cgroup.

```

And the details of the adaptation are below:

```

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Quoted 6 lines

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).
```

Quoted 4 lines

Thanks you this is very useful.

A high level overview on how the patch series (of this size) would be appreaciate as well.

OK. Will add this to the cover letter in the next version.

Thanks,
Qi

#79 lore raw

Re: [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock

In reply to Qi Zheng
kernel test robot noticed "WARNING:bad_unlock_balance_detected" on:

Hello,

kernel test robot noticed "WARNING:bad_unlock_balance_detected" on:

commit: dd9e066d9677ca28748a63b16b33c858af75164b ("[PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock")
url: https://github.com/intel-lab-lkp/linux/commits/Qi-Zheng/mm-memcontrol-remove-dead-code-of-checking-parent-memory-cgroup/20251028-221021
base: https://git.kernel.org/cgit/linux/kernel/git/akpm/mm.git mm-everything
patch link: https://lore.kernel.org/all/d5d72d101212e9fb82727c941d581c68728c7f53.1761658311.git.zhengqi.arch@bytedance.com/
patch subject: [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock

in testcase: boot

config: i386-randconfig-141-20251031
compiler: gcc-14
test machine: qemu-system-i386 -enable-kvm -cpu SandyBridge -smp 2 -m 4G

(please refer to attached dmesg/kmsg for entire log/backtrace)

+-----------------------------------------------------------------------------------+------------+------------+
|                                                                                   | c856dae1f8 | dd9e066d96 |
+-----------------------------------------------------------------------------------+------------+------------+
| WARNING:bad_unlock_balance_detected                                               | 0          | 87         |
| is_trying_to_release_lock(rcu_read_lock)at                                        | 0          | 87         |
| calltrace:rcu_read_unlock                                                         | 0          | 87         |
| WARNING:at_kernel/rcu/tree_plugin.h:#__rcu_read_unlock                            | 0          | 87         |
| EIP:__rcu_read_unlock                                                             | 0          | 87         |
| BUG:sleeping_function_called_from_invalid_context_at_mm/filemap.c                 | 0          | 87         |
| WARNING:at_kernel/rcu/tree_plugin.h:#rcu_sched_clock_irq                          | 0          | 87         |
| EIP:rcu_sched_clock_irq                                                           | 0          | 87         |
| EIP:evm_inode_alloc_security                                                      | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_include/linux/percpu-rwsem.h | 0          | 84         |
| BUG:sleeping_function_called_from_invalid_context_at_include/linux/sched/mm.h     | 0          | 86         |
| BUG:workqueue_leaked_atomic,lock_or_RCU:kworker##[#]                              | 0          | 84         |
| BUG:sleeping_function_called_from_invalid_context_at_mm/slab_common.c             | 0          | 23         |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/workqueue.c           | 0          | 60         |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/locking/rwsem.c       | 0          | 73         |
| BUG:sleeping_function_called_from_invalid_context_at_lib/strncpy_from_user.c      | 0          | 41         |
| BUG:sleeping_function_called_from_invalid_context_at_mm/mmap.c                    | 0          | 16         |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/locking/mutex.c       | 0          | 70         |
| BUG:sleeping_function_called_from_invalid_context_at_include/linux/uaccess.h      | 0          | 40         |
| BUG:sleeping_function_called_from_invalid_context_at_mm/memory.c                  | 0          | 55         |
| EIP:kmem_cache_alloc_noprof                                                       | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_fs/dcache.c                  | 0          | 69         |
| BUG:sleeping_function_called_from_invalid_context_at_fs/file_table.c              | 0          | 32         |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/task_work.c           | 0          | 25         |
| BUG:sleeping_function_called_from_invalid_context_at_arch/x86/entry/syscall_32.c  | 0          | 46         |
| WARNING:at_kernel/rcu/tree_exp.h:#rcu_exp_handler                                 | 0          | 58         |
| EIP:rcu_exp_handler                                                               | 0          | 58         |
| EIP:find_bug                                                                      | 0          | 13         |
| BUG:sleeping_function_called_from_invalid_context_at_fs/pidfs.c                   | 0          | 9          |
| EIP:_parse_integer_limit                                                          | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_lib/iov_iter.c               | 0          | 64         |
| EIP:ep_poll                                                                       | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_mm/mmu_gather.c              | 0          | 18         |
| BUG:sleeping_function_called_from_invalid_context_at_fs/select.c                  | 0          | 12         |
| BUG:sleeping_function_called_from_invalid_context_at_net/core/sock.c              | 0          | 15         |
| EIP:handle_bug                                                                    | 0          | 25         |
| BUG:sleeping_function_called_from_invalid_context_at_include/linux/pagemap.h      | 0          | 14         |
| EIP:inflate_fast                                                                  | 0          | 20         |
| EIP:zlib_inflate_table                                                            | 0          | 2          |
| BUG:sleeping_function_called_from_invalid_context_at_mm/shmem.c                   | 0          | 2          |
| EIP:unwind_get_return_address                                                     | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_mm/vma.c                     | 0          | 11         |
| EIP:kmem_cache_alloc_lru_noprof                                                   | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_mm/mprotect.c                | 0          | 2          |
| EIP:console_emit_next_record                                                      | 0          | 10         |
| EIP:dump_stack_lvl                                                                | 0          | 31         |
| BUG:sleeping_function_called_from_invalid_context_at_include/linux/mmu_notifier.h | 0          | 13         |
| BUG:sleeping_function_called_from_invalid_context_at_mm/vmalloc.c                 | 0          | 2          |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/nsproxy.c             | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_fs/exec.c                    | 0          | 1          |
| EIP:preempt_count_sub                                                             | 0          | 1          |
| EIP:kunmap_local_indexed                                                          | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_mm/gup.c                     | 0          | 2          |
| EIP:seqcount_lockdep_reader_access                                                | 0          | 1          |
| EIP:_raw_spin_unlock_irqrestore                                                   | 0          | 5          |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/exit.c                | 0          | 2          |
| BUG:sleeping_function_called_from_invalid_context_at_mm/rmap.c                    | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_mm/truncate.c                | 0          | 1          |
| EIP:finish_task_switch                                                            | 0          | 2          |
| EIP:inode_init_once                                                               | 0          | 1          |
| EIP:check_lifetime                                                                | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_fs/namei.c                   | 0          | 3          |
| BUG:sleeping_function_called_from_invalid_context_at_fs/readdir.c                 | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/rcu/srcutree.c        | 0          | 1          |
| EIP:memset_no_sanitize_memory                                                     | 0          | 1          |
| EIP:lookup_one_qstr_excl                                                          | 0          | 1          |
| EIP:__up_read                                                                     | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_fs/file.c                    | 0          | 3          |
| EIP:ramfs_symlink                                                                 | 0          | 1          |
| EIP:do_dentry_open                                                                | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/printk/printk.c       | 0          | 1          |
| EIP:unwind_next_frame                                                             | 0          | 1          |
| EIP:handle_softirqs                                                               | 0          | 1          |
| EIP:bad_range                                                                     | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_include/linux/freezer.h      | 0          | 2          |
| EIP:security_file_open                                                            | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/fork.c                | 0          | 2          |
| EIP:kernel_init_pages                                                             | 0          | 1          |
| EIP:filemap_add_folio                                                             | 0          | 1          |
| EIP:update_stack_state                                                            | 0          | 1          |
| EIP:folio_nr_pages                                                                | 0          | 1          |
| EIP:mntput                                                                        | 0          | 1          |
| BUG:sleeping_function_called_from_invalid_context_at_kernel/sched/completion.c    | 0          | 1          |
| EIP:__alloc_frozen_pages_noprof                                                   | 0          | 1          |
| EIP:unwind_get_return_address_ptr                                                 | 0          | 1          |
| EIP:copy_folio_from_iter_atomic                                                   | 0          | 1          |
| EIP:filp_flush                                                                    | 0          | 1          |
| EIP:__put_user_4                                                                  | 0          | 2          |
| EIP:balance_dirty_pages_ratelimited_flags                                         | 0          | 1          |
| EIP:zlib_updatewindow                                                             | 0          | 1          |
+-----------------------------------------------------------------------------------+------------+------------+

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-lkp/[email protected]

[    1.392214][   T45] WARNING: bad unlock balance detected!
[    1.393285][   T45] 6.18.0-rc3-00251-gdd9e066d9677 #1 Not tainted
[    1.394579][   T45] -------------------------------------
[    1.395442][   T45] kworker/u9:1/45 is trying to release lock (rcu_read_lock) at:
[    1.396977][   T45] rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.398160][   T45] but there are no more locks to release!
[    1.399337][   T45]
[    1.399337][   T45] other info that might help us debug this:
[    1.399707][   T45] 5 locks held by kworker/u9:1/45:
[    1.399707][   T45]  #0: c01ad6c4 ((wq_completion)async){+.+.}-{0:0}, at: process_one_work (kernel/workqueue.c:3238)
[    1.399707][   T45]  #1: c08e9f18 ((work_completion)(&entry->work)){+.+.}-{0:0}, at: process_one_work (kernel/workqueue.c:3239)
[    1.399707][   T45]  #2: c02ed27c (sb_writers#2){.+.+}-{0:0}, at: file_start_write+0x1e/0x30
[    1.399707][   T45]  #3: c042e0ec (&sb->s_type->i_mutex_key){++++}-{4:4}, at: generic_file_write_iter (mm/filemap.c:4404)
[    1.399707][   T45]  #4: eaa771a0 (lock#3){+.+.}-{3:3}, at: local_lock_acquire (include/linux/local_lock_internal.h:40)
[    1.399707][   T45]
[    1.399707][   T45] stack backtrace:
[    1.399707][   T45] CPU: 0 UID: 0 PID: 45 Comm: kworker/u9:1 Not tainted 6.18.0-rc3-00251-gdd9e066d9677 #1 PREEMPT(none)
[    1.399707][   T45] Workqueue: async async_run_entry_fn
[    1.399707][   T45] Call Trace:
[    1.399707][   T45]  dump_stack_lvl (lib/dump_stack.c:122)
[    1.399707][   T45]  ? rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.399707][   T45]  dump_stack (lib/dump_stack.c:130)
[    1.399707][   T45]  print_unlock_imbalance_bug (kernel/locking/lockdep.c:5300 kernel/locking/lockdep.c:5272)
[    1.399707][   T45]  ? rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.399707][   T45]  __lock_release+0x5e/0x150
[    1.399707][   T45]  ? rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.399707][   T45]  lock_release (kernel/locking/lockdep.c:470 kernel/locking/lockdep.c:5891 kernel/locking/lockdep.c:5875)
[    1.399707][   T45]  ? lru_deactivate_file (mm/swap.c:119)
[    1.399707][   T45]  rcu_read_unlock (include/linux/rcupdate.h:899)
[    1.399707][   T45]  lruvec_unlock_irqrestore (include/linux/memcontrol.h:1522)
[    1.399707][   T45]  folio_batch_move_lru (include/linux/mm.h:1501 mm/swap.c:179)
[    1.399707][   T45]  __folio_batch_add_and_move (mm/swap.c:196 (discriminator 2))
[    1.399707][   T45]  ? lru_deactivate_file (mm/swap.c:119)
[    1.399707][   T45]  folio_add_lru (mm/swap.c:514)
[    1.399707][   T45]  filemap_add_folio (mm/filemap.c:996)
[    1.399707][   T45]  __filemap_get_folio (mm/filemap.c:2023)
[    1.399707][   T45]  simple_write_begin (fs/libfs.c:932 (discriminator 1))
[    1.399707][   T45]  generic_perform_write (mm/filemap.c:4263)
[    1.399707][   T45]  __generic_file_write_iter (mm/filemap.c:4380)
[    1.399707][   T45]  generic_file_write_iter (mm/filemap.c:4406)
[    1.399707][   T45]  __kernel_write_iter (fs/read_write.c:619)
[    1.399707][   T45]  __kernel_write (fs/read_write.c:640)
[    1.399707][   T45]  kernel_write (fs/read_write.c:660 fs/read_write.c:650)
[    1.399707][   T45]  xwrite+0x27/0x80
[    1.399707][   T45]  do_copy (init/initramfs.c:417 (discriminator 1))
[    1.399707][   T45]  write_buffer (init/initramfs.c:470 (discriminator 1))
[    1.399707][   T45]  flush_buffer (init/initramfs.c:482 (discriminator 1))
[    1.399707][   T45]  __gunzip+0x21d/0x2c0
[    1.399707][   T45]  ? bunzip2 (lib/decompress_inflate.c:39)
[    1.399707][   T45]  ? __gunzip+0x2c0/0x2c0
[    1.399707][   T45]  gunzip (lib/decompress_inflate.c:208)
[    1.399707][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.399707][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.399707][   T45]  unpack_to_rootfs (init/initramfs.c:553)
[    1.399707][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.399707][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.399707][   T45]  ? reserve_initrd_mem (init/initramfs.c:719)
[    1.399707][   T45]  do_populate_rootfs (init/initramfs.c:734)
[    1.399707][   T45]  async_run_entry_fn (kernel/async.c:136 (discriminator 1))
[    1.399707][   T45]  ? async_schedule_node (kernel/async.c:118)
[    1.399707][   T45]  process_one_work (arch/x86/include/asm/atomic.h:23 include/linux/atomic/atomic-arch-fallback.h:457 include/linux/jump_label.h:262 include/trace/events/workqueue.h:110 kernel/workqueue.c:3268)
[    1.399707][   T45]  process_scheduled_works (kernel/workqueue.c:3346)
[    1.399707][   T45]  worker_thread (include/linux/list.h:381 (discriminator 2) kernel/workqueue.c:952 (discriminator 2) kernel/workqueue.c:3428 (discriminator 2))
[    1.399707][   T45]  kthread (kernel/kthread.c:465)
[    1.399707][   T45]  ? process_scheduled_works (kernel/workqueue.c:3373)
[    1.399707][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.399707][   T45]  ret_from_fork (arch/x86/kernel/process.c:164)
[    1.399707][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.399707][   T45]  ret_from_fork_asm (arch/x86/entry/entry_32.S:737)
[    1.399707][   T45]  entry_INT80_32 (arch/x86/entry/entry_32.S:945)
[    1.467118][   T32] Callback from call_rcu_tasks() invoked.
[    1.468370][   T45] ------------[ cut here ]------------
[    1.469508][   T45] WARNING: CPU: 0 PID: 45 at kernel/rcu/tree_plugin.h:443 __rcu_read_unlock (kernel/rcu/tree_plugin.h:443)
[    1.471711][   T45] Modules linked in:
[    1.472490][   T45] CPU: 0 UID: 0 PID: 45 Comm: kworker/u9:1 Not tainted 6.18.0-rc3-00251-gdd9e066d9677 #1 PREEMPT(none)
[    1.474777][   T45] Workqueue: async async_run_entry_fn
[    1.475823][   T45] EIP: __rcu_read_unlock (kernel/rcu/tree_plugin.h:443)
[    1.476872][   T45] Code: 0c d0 56 c2 ff 8b a4 02 00 00 75 11 8b 83 a8 02 00 00 85 c0 74 07 89 d8 e8 7c fe ff ff 8b 83 a4 02 00 00 3d ff ff ff 3f 76 02 <0f> 0b 5b 5d 31 c0 c3 2e 8d b4 26 00 00 00 00 55 89 e5 57 56 89 c6
All code
========
   0:	0c d0                	or     $0xd0,%al
   2:	56                   	push   %rsi
   3:	c2 ff 8b             	ret    $0x8bff
   6:	a4                   	movsb  %ds:(%rsi),%es:(%rdi)
   7:	02 00                	add    (%rax),%al
   9:	00 75 11             	add    %dh,0x11(%rbp)
   c:	8b 83 a8 02 00 00    	mov    0x2a8(%rbx),%eax
  12:	85 c0                	test   %eax,%eax
  14:	74 07                	je     0x1d
  16:	89 d8                	mov    %ebx,%eax
  18:	e8 7c fe ff ff       	call   0xfffffffffffffe99
  1d:	8b 83 a4 02 00 00    	mov    0x2a4(%rbx),%eax
  23:	3d ff ff ff 3f       	cmp    $0x3fffffff,%eax
  28:	76 02                	jbe    0x2c
  2a:*	0f 0b                	ud2		<-- trapping instruction
  2c:	5b                   	pop    %rbx
  2d:	5d                   	pop    %rbp
  2e:	31 c0                	xor    %eax,%eax
  30:	c3                   	ret
  31:	2e 8d b4 26 00 00 00 	cs lea 0x0(%rsi,%riz,1),%esi
  38:	00 
  39:	55                   	push   %rbp
  3a:	89 e5                	mov    %esp,%ebp
  3c:	57                   	push   %rdi
  3d:	56                   	push   %rsi
  3e:	89 c6                	mov    %eax,%esi

Code starting with the faulting instruction
===========================================

   0:	0f 0b                	ud2
   2:	5b                   	pop    %rbx
   3:	5d                   	pop    %rbp
   4:	31 c0                	xor    %eax,%eax
   6:	c3                   	ret
   7:	2e 8d b4 26 00 00 00 	cs lea 0x0(%rsi,%riz,1),%esi
   e:	00 
   f:	55                   	push   %rbp
  10:	89 e5                	mov    %esp,%ebp
  12:	57                   	push   %rdi
  13:	56                   	push   %rsi
  14:	89 c6                	mov    %eax,%esi
[    1.480862][   T45] EAX: ffffffff EBX: c0bfd640 ECX: 00000000 EDX: 00000000
[    1.482292][   T45] ESI: eaa771c0 EDI: c119e160 EBP: c08e9c0c ESP: c08e9c08
[    1.483721][   T45] DS: 007b ES: 007b FS: 00d8 GS: 0000 SS: 0068 EFLAGS: 00010286
[    1.485350][   T45] CR0: 80050033 CR2: ffbff000 CR3: 026c6000 CR4: 000006f0
[    1.486725][   T45] Call Trace:
[    1.487465][   T45]  rcu_read_unlock (include/linux/rcupdate.h:900)
[    1.488404][   T45]  lruvec_unlock_irqrestore (include/linux/memcontrol.h:1522)
[    1.489570][   T45]  folio_batch_move_lru (include/linux/mm.h:1501 mm/swap.c:179)
[    1.491100][   T45]  __folio_batch_add_and_move (mm/swap.c:196 (discriminator 2))
[    1.492318][   T45]  ? lru_deactivate_file (mm/swap.c:119)
[    1.493827][   T45]  folio_add_lru (mm/swap.c:514)
[    1.494817][   T45]  filemap_add_folio (mm/filemap.c:996)
[    1.495891][   T45]  __filemap_get_folio (mm/filemap.c:2023)
[    1.497735][   T45]  simple_write_begin (fs/libfs.c:932 (discriminator 1))
[    1.498813][   T45]  generic_perform_write (mm/filemap.c:4263)
[    1.500292][   T45]  __generic_file_write_iter (mm/filemap.c:4380)
[    1.501552][   T45]  generic_file_write_iter (mm/filemap.c:4406)
[    1.502790][   T45]  __kernel_write_iter (fs/read_write.c:619)
[    1.504090][   T45]  __kernel_write (fs/read_write.c:640)
[    1.505377][   T45]  kernel_write (fs/read_write.c:660 fs/read_write.c:650)
[    1.506306][   T45]  xwrite+0x27/0x80
[    1.507429][   T45]  do_copy (init/initramfs.c:417 (discriminator 1))
[    1.508361][   T45]  write_buffer (init/initramfs.c:470 (discriminator 1))
[    1.509300][   T45]  flush_buffer (init/initramfs.c:482 (discriminator 1))
[    1.510307][   T45]  __gunzip+0x21d/0x2c0
[    1.511424][   T45]  ? bunzip2 (lib/decompress_inflate.c:39)
[    1.512312][   T45]  ? __gunzip+0x2c0/0x2c0
[    1.513515][   T45]  gunzip (lib/decompress_inflate.c:208)
[    1.514359][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.515304][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.516217][   T45]  unpack_to_rootfs (init/initramfs.c:553)
[    1.517220][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.518175][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.519172][   T45]  ? reserve_initrd_mem (init/initramfs.c:719)
[    1.520375][   T45]  do_populate_rootfs (init/initramfs.c:734)
[    1.521401][   T45]  async_run_entry_fn (kernel/async.c:136 (discriminator 1))
[    1.522378][   T45]  ? async_schedule_node (kernel/async.c:118)
[    1.523492][   T45]  process_one_work (arch/x86/include/asm/atomic.h:23 include/linux/atomic/atomic-arch-fallback.h:457 include/linux/jump_label.h:262 include/trace/events/workqueue.h:110 kernel/workqueue.c:3268)
[    1.526446][   T45]  process_scheduled_works (kernel/workqueue.c:3346)
[    1.527578][   T45]  worker_thread (include/linux/list.h:381 (discriminator 2) kernel/workqueue.c:952 (discriminator 2) kernel/workqueue.c:3428 (discriminator 2))
[    1.528573][   T45]  kthread (kernel/kthread.c:465)
[    1.529483][   T45]  ? process_scheduled_works (kernel/workqueue.c:3373)
[    1.530780][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.531779][   T45]  ret_from_fork (arch/x86/kernel/process.c:164)
[    1.532664][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.533736][   T45]  ret_from_fork_asm (arch/x86/entry/entry_32.S:737)
[    1.534846][   T45]  entry_INT80_32 (arch/x86/entry/entry_32.S:945)
[    1.536182][   T45] irq event stamp: 2161
[    1.536994][   T45] hardirqs last  enabled at (2161): _raw_spin_unlock_irqrestore (arch/x86/include/asm/irqflags.h:26 arch/x86/include/asm/irqflags.h:109 arch/x86/include/asm/irqflags.h:151 include/linux/spinlock_api_smp.h:151 kernel/locking/spinlock.c:194)
[    1.538763][   T45] hardirqs last disabled at (2160): _raw_spin_lock_irqsave (include/linux/spinlock_api_smp.h:109 kernel/locking/spinlock.c:162)
[    1.540674][   T45] softirqs last  enabled at (1956): handle_softirqs (kernel/softirq.c:469 (discriminator 2) kernel/softirq.c:650 (discriminator 2))
[    1.542454][   T45] softirqs last disabled at (1949): __do_softirq (kernel/softirq.c:657)
[    1.544105][   T45] ---[ end trace 0000000000000000 ]---

The kernel config and materials to reproduce are available at:
https://download.01.org/0day-ci/archive/20251104/[email protected]

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author reviewer
#80 lore raw

Re: [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock

Quoted 1 line · kernel test robot

[...]

Quoted 183 lines

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-lkp/[email protected]

[    1.392214][   T45] WARNING: bad unlock balance detected!
[    1.393285][   T45] 6.18.0-rc3-00251-gdd9e066d9677 #1 Not tainted
[    1.394579][   T45] -------------------------------------
[    1.395442][   T45] kworker/u9:1/45 is trying to release lock (rcu_read_lock) at:
[    1.396977][   T45] rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.398160][   T45] but there are no more locks to release!
[    1.399337][   T45]
[    1.399337][   T45] other info that might help us debug this:
[    1.399707][   T45] 5 locks held by kworker/u9:1/45:
[    1.399707][   T45]  #0: c01ad6c4 ((wq_completion)async){+.+.}-{0:0}, at: process_one_work (kernel/workqueue.c:3238)
[    1.399707][   T45]  #1: c08e9f18 ((work_completion)(&entry->work)){+.+.}-{0:0}, at: process_one_work (kernel/workqueue.c:3239)
[    1.399707][   T45]  #2: c02ed27c (sb_writers#2){.+.+}-{0:0}, at: file_start_write+0x1e/0x30
[    1.399707][   T45]  #3: c042e0ec (&sb->s_type->i_mutex_key){++++}-{4:4}, at: generic_file_write_iter (mm/filemap.c:4404)
[    1.399707][   T45]  #4: eaa771a0 (lock#3){+.+.}-{3:3}, at: local_lock_acquire (include/linux/local_lock_internal.h:40)
[    1.399707][   T45]
[    1.399707][   T45] stack backtrace:
[    1.399707][   T45] CPU: 0 UID: 0 PID: 45 Comm: kworker/u9:1 Not tainted 6.18.0-rc3-00251-gdd9e066d9677 #1 PREEMPT(none)
[    1.399707][   T45] Workqueue: async async_run_entry_fn
[    1.399707][   T45] Call Trace:
[    1.399707][   T45]  dump_stack_lvl (lib/dump_stack.c:122)
[    1.399707][   T45]  ? rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.399707][   T45]  dump_stack (lib/dump_stack.c:130)
[    1.399707][   T45]  print_unlock_imbalance_bug (kernel/locking/lockdep.c:5300 kernel/locking/lockdep.c:5272)
[    1.399707][   T45]  ? rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.399707][   T45]  __lock_release+0x5e/0x150
[    1.399707][   T45]  ? rcu_read_unlock (include/linux/rcupdate.h:341 include/linux/rcupdate.h:897)
[    1.399707][   T45]  lock_release (kernel/locking/lockdep.c:470 kernel/locking/lockdep.c:5891 kernel/locking/lockdep.c:5875)
[    1.399707][   T45]  ? lru_deactivate_file (mm/swap.c:119)
[    1.399707][   T45]  rcu_read_unlock (include/linux/rcupdate.h:899)
[    1.399707][   T45]  lruvec_unlock_irqrestore (include/linux/memcontrol.h:1522)
[    1.399707][   T45]  folio_batch_move_lru (include/linux/mm.h:1501 mm/swap.c:179)
[    1.399707][   T45]  __folio_batch_add_and_move (mm/swap.c:196 (discriminator 2))
[    1.399707][   T45]  ? lru_deactivate_file (mm/swap.c:119)
[    1.399707][   T45]  folio_add_lru (mm/swap.c:514)
[    1.399707][   T45]  filemap_add_folio (mm/filemap.c:996)
[    1.399707][   T45]  __filemap_get_folio (mm/filemap.c:2023)
[    1.399707][   T45]  simple_write_begin (fs/libfs.c:932 (discriminator 1))
[    1.399707][   T45]  generic_perform_write (mm/filemap.c:4263)
[    1.399707][   T45]  __generic_file_write_iter (mm/filemap.c:4380)
[    1.399707][   T45]  generic_file_write_iter (mm/filemap.c:4406)
[    1.399707][   T45]  __kernel_write_iter (fs/read_write.c:619)
[    1.399707][   T45]  __kernel_write (fs/read_write.c:640)
[    1.399707][   T45]  kernel_write (fs/read_write.c:660 fs/read_write.c:650)
[    1.399707][   T45]  xwrite+0x27/0x80
[    1.399707][   T45]  do_copy (init/initramfs.c:417 (discriminator 1))
[    1.399707][   T45]  write_buffer (init/initramfs.c:470 (discriminator 1))
[    1.399707][   T45]  flush_buffer (init/initramfs.c:482 (discriminator 1))
[    1.399707][   T45]  __gunzip+0x21d/0x2c0
[    1.399707][   T45]  ? bunzip2 (lib/decompress_inflate.c:39)
[    1.399707][   T45]  ? __gunzip+0x2c0/0x2c0
[    1.399707][   T45]  gunzip (lib/decompress_inflate.c:208)
[    1.399707][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.399707][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.399707][   T45]  unpack_to_rootfs (init/initramfs.c:553)
[    1.399707][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.399707][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.399707][   T45]  ? reserve_initrd_mem (init/initramfs.c:719)
[    1.399707][   T45]  do_populate_rootfs (init/initramfs.c:734)
[    1.399707][   T45]  async_run_entry_fn (kernel/async.c:136 (discriminator 1))
[    1.399707][   T45]  ? async_schedule_node (kernel/async.c:118)
[    1.399707][   T45]  process_one_work (arch/x86/include/asm/atomic.h:23 include/linux/atomic/atomic-arch-fallback.h:457 include/linux/jump_label.h:262 include/trace/events/workqueue.h:110 kernel/workqueue.c:3268)
[    1.399707][   T45]  process_scheduled_works (kernel/workqueue.c:3346)
[    1.399707][   T45]  worker_thread (include/linux/list.h:381 (discriminator 2) kernel/workqueue.c:952 (discriminator 2) kernel/workqueue.c:3428 (discriminator 2))
[    1.399707][   T45]  kthread (kernel/kthread.c:465)
[    1.399707][   T45]  ? process_scheduled_works (kernel/workqueue.c:3373)
[    1.399707][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.399707][   T45]  ret_from_fork (arch/x86/kernel/process.c:164)
[    1.399707][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.399707][   T45]  ret_from_fork_asm (arch/x86/entry/entry_32.S:737)
[    1.399707][   T45]  entry_INT80_32 (arch/x86/entry/entry_32.S:945)
[    1.467118][   T32] Callback from call_rcu_tasks() invoked.
[    1.468370][   T45] ------------[ cut here ]------------
[    1.469508][   T45] WARNING: CPU: 0 PID: 45 at kernel/rcu/tree_plugin.h:443 __rcu_read_unlock (kernel/rcu/tree_plugin.h:443)
[    1.471711][   T45] Modules linked in:
[    1.472490][   T45] CPU: 0 UID: 0 PID: 45 Comm: kworker/u9:1 Not tainted 6.18.0-rc3-00251-gdd9e066d9677 #1 PREEMPT(none)
[    1.474777][   T45] Workqueue: async async_run_entry_fn
[    1.475823][   T45] EIP: __rcu_read_unlock (kernel/rcu/tree_plugin.h:443)
[    1.476872][   T45] Code: 0c d0 56 c2 ff 8b a4 02 00 00 75 11 8b 83 a8 02 00 00 85 c0 74 07 89 d8 e8 7c fe ff ff 8b 83 a4 02 00 00 3d ff ff ff 3f 76 02 <0f> 0b 5b 5d 31 c0 c3 2e 8d b4 26 00 00 00 00 55 89 e5 57 56 89 c6
All code
========
    0:	0c d0                	or     $0xd0,%al
    2:	56                   	push   %rsi
    3:	c2 ff 8b             	ret    $0x8bff
    6:	a4                   	movsb  %ds:(%rsi),%es:(%rdi)
    7:	02 00                	add    (%rax),%al
    9:	00 75 11             	add    %dh,0x11(%rbp)
    c:	8b 83 a8 02 00 00    	mov    0x2a8(%rbx),%eax
   12:	85 c0                	test   %eax,%eax
   14:	74 07                	je     0x1d
   16:	89 d8                	mov    %ebx,%eax
   18:	e8 7c fe ff ff       	call   0xfffffffffffffe99
   1d:	8b 83 a4 02 00 00    	mov    0x2a4(%rbx),%eax
   23:	3d ff ff ff 3f       	cmp    $0x3fffffff,%eax
   28:	76 02                	jbe    0x2c
   2a:*	0f 0b                	ud2		<-- trapping instruction
   2c:	5b                   	pop    %rbx
   2d:	5d                   	pop    %rbp
   2e:	31 c0                	xor    %eax,%eax
   30:	c3                   	ret
   31:	2e 8d b4 26 00 00 00 	cs lea 0x0(%rsi,%riz,1),%esi
   38:	00
   39:	55                   	push   %rbp
   3a:	89 e5                	mov    %esp,%ebp
   3c:	57                   	push   %rdi
   3d:	56                   	push   %rsi
   3e:	89 c6                	mov    %eax,%esi

Code starting with the faulting instruction
===========================================

    0:	0f 0b                	ud2
    2:	5b                   	pop    %rbx
    3:	5d                   	pop    %rbp
    4:	31 c0                	xor    %eax,%eax
    6:	c3                   	ret
    7:	2e 8d b4 26 00 00 00 	cs lea 0x0(%rsi,%riz,1),%esi
    e:	00
    f:	55                   	push   %rbp
   10:	89 e5                	mov    %esp,%ebp
   12:	57                   	push   %rdi
   13:	56                   	push   %rsi
   14:	89 c6                	mov    %eax,%esi
[    1.480862][   T45] EAX: ffffffff EBX: c0bfd640 ECX: 00000000 EDX: 00000000
[    1.482292][   T45] ESI: eaa771c0 EDI: c119e160 EBP: c08e9c0c ESP: c08e9c08
[    1.483721][   T45] DS: 007b ES: 007b FS: 00d8 GS: 0000 SS: 0068 EFLAGS: 00010286
[    1.485350][   T45] CR0: 80050033 CR2: ffbff000 CR3: 026c6000 CR4: 000006f0
[    1.486725][   T45] Call Trace:
[    1.487465][   T45]  rcu_read_unlock (include/linux/rcupdate.h:900)
[    1.488404][   T45]  lruvec_unlock_irqrestore (include/linux/memcontrol.h:1522)
[    1.489570][   T45]  folio_batch_move_lru (include/linux/mm.h:1501 mm/swap.c:179)
[    1.491100][   T45]  __folio_batch_add_and_move (mm/swap.c:196 (discriminator 2))
[    1.492318][   T45]  ? lru_deactivate_file (mm/swap.c:119)
[    1.493827][   T45]  folio_add_lru (mm/swap.c:514)
[    1.494817][   T45]  filemap_add_folio (mm/filemap.c:996)
[    1.495891][   T45]  __filemap_get_folio (mm/filemap.c:2023)
[    1.497735][   T45]  simple_write_begin (fs/libfs.c:932 (discriminator 1))
[    1.498813][   T45]  generic_perform_write (mm/filemap.c:4263)
[    1.500292][   T45]  __generic_file_write_iter (mm/filemap.c:4380)
[    1.501552][   T45]  generic_file_write_iter (mm/filemap.c:4406)
[    1.502790][   T45]  __kernel_write_iter (fs/read_write.c:619)
[    1.504090][   T45]  __kernel_write (fs/read_write.c:640)
[    1.505377][   T45]  kernel_write (fs/read_write.c:660 fs/read_write.c:650)
[    1.506306][   T45]  xwrite+0x27/0x80
[    1.507429][   T45]  do_copy (init/initramfs.c:417 (discriminator 1))
[    1.508361][   T45]  write_buffer (init/initramfs.c:470 (discriminator 1))
[    1.509300][   T45]  flush_buffer (init/initramfs.c:482 (discriminator 1))
[    1.510307][   T45]  __gunzip+0x21d/0x2c0
[    1.511424][   T45]  ? bunzip2 (lib/decompress_inflate.c:39)
[    1.512312][   T45]  ? __gunzip+0x2c0/0x2c0
[    1.513515][   T45]  gunzip (lib/decompress_inflate.c:208)
[    1.514359][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.515304][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.516217][   T45]  unpack_to_rootfs (init/initramfs.c:553)
[    1.517220][   T45]  ? write_buffer (init/initramfs.c:476)
[    1.518175][   T45]  ? initrd_load (init/initramfs.c:64)
[    1.519172][   T45]  ? reserve_initrd_mem (init/initramfs.c:719)
[    1.520375][   T45]  do_populate_rootfs (init/initramfs.c:734)
[    1.521401][   T45]  async_run_entry_fn (kernel/async.c:136 (discriminator 1))
[    1.522378][   T45]  ? async_schedule_node (kernel/async.c:118)
[    1.523492][   T45]  process_one_work (arch/x86/include/asm/atomic.h:23 include/linux/atomic/atomic-arch-fallback.h:457 include/linux/jump_label.h:262 include/trace/events/workqueue.h:110 kernel/workqueue.c:3268)
[    1.526446][   T45]  process_scheduled_works (kernel/workqueue.c:3346)
[    1.527578][   T45]  worker_thread (include/linux/list.h:381 (discriminator 2) kernel/workqueue.c:952 (discriminator 2) kernel/workqueue.c:3428 (discriminator 2))
[    1.528573][   T45]  kthread (kernel/kthread.c:465)
[    1.529483][   T45]  ? process_scheduled_works (kernel/workqueue.c:3373)
[    1.530780][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.531779][   T45]  ret_from_fork (arch/x86/kernel/process.c:164)
[    1.532664][   T45]  ? kthread_is_per_cpu (kernel/kthread.c:412)
[    1.533736][   T45]  ret_from_fork_asm (arch/x86/entry/entry_32.S:737)
[    1.534846][   T45]  entry_INT80_32 (arch/x86/entry/entry_32.S:945)
[    1.536182][   T45] irq event stamp: 2161
[    1.536994][   T45] hardirqs last  enabled at (2161): _raw_spin_unlock_irqrestore (arch/x86/include/asm/irqflags.h:26 arch/x86/include/asm/irqflags.h:109 arch/x86/include/asm/irqflags.h:151 include/linux/spinlock_api_smp.h:151 kernel/locking/spinlock.c:194)
[    1.538763][   T45] hardirqs last disabled at (2160): _raw_spin_lock_irqsave (include/linux/spinlock_api_smp.h:109 kernel/locking/spinlock.c:162)
[    1.540674][   T45] softirqs last  enabled at (1956): handle_softirqs (kernel/softirq.c:469 (discriminator 2) kernel/softirq.c:650 (discriminator 2))
[    1.542454][   T45] softirqs last disabled at (1949): __do_softirq (kernel/softirq.c:657)
[    1.544105][   T45] ---[ end trace 0000000000000000 ]---
Quoted 2 lines

The kernel config and materials to reproduce are available at:
https://download.01.org/0day-ci/archive/20251104/[email protected]

In this config file, CONFIG_MEMCG is not set:

# CONFIG_MEMCG is not set

In this case, folio_lruvec_lock*() was not modified (add rcu_read_lock()), will fix it in the next version.

Thanks,
Qi

Quoted 3 lines
Reviewed-by on v1 1/26
#2 lore raw

Re: [PATCH v1 01/26] mm: memcontrol: remove dead code of checking parent memory cgroup

In reply to Qi Zheng
Quoted 11 lines · Qi Zheng

From: Muchun Song <[email protected]>

Since the no-hierarchy mode has been deprecated after the commit:

commit bef8620cd8e0 ("mm: memcg: deprecate the non-hierarchical mode").

As a result, parent_mem_cgroup() will not return NULL except when passing the root memcg, and the root memcg cannot be offline. Hence, it's safe to remove the check on the returned value of parent_mem_cgroup(). Remove the corresponding dead code.

Quoted 5 lines

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 2/26
#5 lore raw

Re: [PATCH v1 02/26] mm: workingset: use folio_lruvec() in workingset_refault()

In reply to Qi Zheng
Quoted 8 lines · Qi Zheng

From: Muchun Song <[email protected]>

Use folio_lruvec() to simplify the code.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 3/26
#7 lore raw

Re: [PATCH v1 03/26] mm: rename unlock_page_lruvec_irq and its variants

In reply to Qi Zheng
Quoted 8 lines · Qi Zheng

From: Muchun Song <[email protected]>

It is inappropriate to use folio_lruvec_lock() variants in conjunction with unlock_page_lruvec() variants, as this involves the inconsistent operation of locking a folio while unlocking a page. To rectify this, the functions unlock_page_lruvec{_irq, _irqrestore} are renamed to lruvec_unlock{_irq,_irqrestore}.

Quoted 5 lines

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
#10 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Qi Zheng
Quoted 23 lines · Qi Zheng

From: Muchun Song <[email protected]>

In a subsequent patch, we'll reparent the LRU folios. The folios that are moved to the appropriate LRU list can undergo reparenting during the move_folios_to_lru() process. Hence, it's incorrect for the caller to hold a lruvec lock. Instead, we should utilize the more general interface of folio_lruvec_relock_irq() to obtain the correct lruvec lock.

This patch involves only code refactoring and doesn't introduce any functional changes.

---
 mm/vmscan.c | 46 +++++++++++++++++++++++-----------------------
 1 file changed, 23 insertions(+), 23 deletions(-)
mm/vmscan.c +0 -0
index 3a1044ce30f1e..660cd40cfddd4 100644

mm/vmscan.c static unsigned long shrink_inactive_list(unsigned long nr_to_scan, · line 2023

Quoted 10 lines
mm/vmscan.c +2 -2
@@ -2016,9 +2016,9 @@ static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
 	nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false,
 					 lruvec_memcg(lruvec));
 
-	spin_lock_irq(&lruvec->lru_lock);
-	move_folios_to_lru(lruvec, &folio_list);
+	move_folios_to_lru(&folio_list);
 
+	spin_lock_irq(&lruvec->lru_lock);
 	__mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc),
 					stat.nr_demoted);

Maybe I'm missing something or just confused for now, but let me ask...

How do we make sure the lruvec (and the mem_cgroup containing the lruvec) did not disappear (due to offlining) after move_folios_to_lru()?

Quoted 23 lines
mm/vmscan.c +3 -7
 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
@@ -2166,11 +2166,10 @@ static void shrink_active_list(unsigned long nr_to_scan,
 	/*
 	 * Move folios back to the lru list.
 	 */
-	spin_lock_irq(&lruvec->lru_lock);
-
-	nr_activate = move_folios_to_lru(lruvec, &l_active);
-	nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
+	nr_activate = move_folios_to_lru(&l_active);
+	nr_deactivate = move_folios_to_lru(&l_inactive);
 
+	spin_lock_irq(&lruvec->lru_lock);
 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
 	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
 
@@ -4735,14 +4734,15 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
 			set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active));
 	}
 
-	spin_lock_irq(&lruvec->lru_lock);
-
-	move_folios_to_lru(lruvec, &list);

mm/vmscan.c static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, · line 4746

Quoted 10 lines
mm/vmscan.c +4 -0
+	move_folios_to_lru(&list);
 
+	local_irq_disable();
 	walk = current->reclaim_state->mm_walk;
 	if (walk && walk->batched) {
 		walk->lruvec = lruvec;
+		spin_lock(&lruvec->lru_lock);
 		reset_batch_size(walk);
+		spin_unlock(&lruvec->lru_lock);
 	}

Cc'ing RT folks as they may not want to disable IRQ on PREEMPT_RT.

IIRC there has been some effort in MM to reduce the scope of IRQ-disabled section in MM when PREEMPT_RT config was added to the mainline. spin_lock_irq() doesn't disable IRQ on PREEMPT_RT.

Also, this will break RT according to Documentation/locking/locktypes.rst:

Quoted 21 lines

The changes in spinlock_t and rwlock_t semantics on PREEMPT_RT kernels have a few implications. For example, on a non-PREEMPT_RT kernel the following code sequence works as expected:

local_irq_disable();
spin_lock(&lock);

and is fully equivalent to:

spin_lock_irq(&lock);
Same applies to rwlock_t and the _irqsave() suffix variants.

On PREEMPT_RT kernel this code sequence breaks because RT-mutex requires a fully preemptible context. Instead, use spin_lock_irq() or spin_lock_irqsave() and their unlock counterparts.

In cases where the interrupt disabling and locking must remain separate, PREEMPT_RT offers a local_lock mechanism. Acquiring the local_lock pins the task to a CPU, allowing things like per-CPU interrupt disabled locks to be acquired. However, this approach should be used only where absolutely necessary.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author reviewer
#11 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Hi Harry,

Quoted 31 lines · Harry Yoo
Quoted 30 lines · Qi Zheng

From: Muchun Song <[email protected]>

In a subsequent patch, we'll reparent the LRU folios. The folios that are moved to the appropriate LRU list can undergo reparenting during the move_folios_to_lru() process. Hence, it's incorrect for the caller to hold a lruvec lock. Instead, we should utilize the more general interface of folio_lruvec_relock_irq() to obtain the correct lruvec lock.

This patch involves only code refactoring and doesn't introduce any functional changes.

---
  mm/vmscan.c | 46 +++++++++++++++++++++++-----------------------
  1 file changed, 23 insertions(+), 23 deletions(-)
mm/vmscan.c +1 -2
index 3a1044ce30f1e..660cd40cfddd4 100644
@@ -2016,9 +2016,9 @@ static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
  	nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false,
  					 lruvec_memcg(lruvec));
 
-	spin_lock_irq(&lruvec->lru_lock);
-	move_folios_to_lru(lruvec, &folio_list);
+	move_folios_to_lru(&folio_list);
 
Quoted 8 lines

mm/vmscan.c static unsigned long shrink_inactive_list(unsigned long nr_to_scan, · line 2023

Quoted 3 lines
mm/vmscan.c +1 -0
+	spin_lock_irq(&lruvec->lru_lock);
  	__mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc),
  					stat.nr_demoted);

Maybe I'm missing something or just confused for now, but let me ask...

How do we make sure the lruvec (and the mem_cgroup containing the lruvec) did not disappear (due to offlining) after move_folios_to_lru()?

We obtained lruvec through the following method:

memcg = mem_cgroup_iter(target_memcg, NULL, partial);

do {
    struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);

    shrink_lruvec(lruvec, sc);
    --> shrink_inactive_list
} while ((memcg = mem_cgroup_iter(target_memcg, memcg, partial)));

The mem_cgroup_iter() will hold the refcount of this memcg, so IIUC, the memcg will not disappear at this time.

Quoted 37 lines
Quoted 24 lines
mm/vmscan.c +3 -7
  	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
@@ -2166,11 +2166,10 @@ static void shrink_active_list(unsigned long nr_to_scan,
  	/*
  	 * Move folios back to the lru list.
  	 */
-	spin_lock_irq(&lruvec->lru_lock);
-
-	nr_activate = move_folios_to_lru(lruvec, &l_active);
-	nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
+	nr_activate = move_folios_to_lru(&l_active);
+	nr_deactivate = move_folios_to_lru(&l_inactive);
 
+	spin_lock_irq(&lruvec->lru_lock);
  	__count_vm_events(PGDEACTIVATE, nr_deactivate);
  	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
 
@@ -4735,14 +4734,15 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
  			set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active));
  	}
 
-	spin_lock_irq(&lruvec->lru_lock);
-
-	move_folios_to_lru(lruvec, &list);

mm/vmscan.c static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, · line 4746

Quoted 10 lines
mm/vmscan.c +4 -0
+	move_folios_to_lru(&list);
 
+	local_irq_disable();
  	walk = current->reclaim_state->mm_walk;
  	if (walk && walk->batched) {
  		walk->lruvec = lruvec;
+		spin_lock(&lruvec->lru_lock);
  		reset_batch_size(walk);
+		spin_unlock(&lruvec->lru_lock);
  	}

Cc'ing RT folks as they may not want to disable IRQ on PREEMPT_RT.

Quoted 3 lines

IIRC there has been some effort in MM to reduce the scope of IRQ-disabled section in MM when PREEMPT_RT config was added to the mainline. spin_lock_irq() doesn't disable IRQ on PREEMPT_RT.

Thanks for this information.

Quoted 23 lines

Also, this will break RT according to Documentation/locking/locktypes.rst:

Quoted 21 lines

The changes in spinlock_t and rwlock_t semantics on PREEMPT_RT kernels have a few implications. For example, on a non-PREEMPT_RT kernel the following code sequence works as expected:

local_irq_disable();
spin_lock(&lock);

and is fully equivalent to:

spin_lock_irq(&lock);
Same applies to rwlock_t and the _irqsave() suffix variants.

On PREEMPT_RT kernel this code sequence breaks because RT-mutex requires a fully preemptible context. Instead, use spin_lock_irq() or spin_lock_irqsave() and their unlock counterparts.

In cases where the interrupt disabling and locking must remain separate, PREEMPT_RT offers a local_lock mechanism. Acquiring the local_lock pins the task to a CPU, allowing things like per-CPU interrupt disabled locks to be acquired. However, this approach should be used only where absolutely necessary.

But how do we determine if it's necessary?

Thanks,
Qi

Quoted 1 line
#31 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Harry Yoo
Quoted 9 lines · Harry Yoo
Quoted 9 lines
mm/vmscan.c +1 -3
@@ -4735,14 +4734,15 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
 			set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active));
 	}
 
-	spin_lock_irq(&lruvec->lru_lock);
-
-	move_folios_to_lru(lruvec, &list);
+	move_folios_to_lru(&list);
 
Quoted 10 lines

mm/vmscan.c static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, · line 4746

Quoted 8 lines
mm/vmscan.c +3 -0
+	local_irq_disable();
 	walk = current->reclaim_state->mm_walk;
 	if (walk && walk->batched) {
 		walk->lruvec = lruvec;
+		spin_lock(&lruvec->lru_lock);
 		reset_batch_size(walk);
+		spin_unlock(&lruvec->lru_lock);
 	}

Cc'ing RT folks as they may not want to disable IRQ on PREEMPT_RT.

Thank you, this is not going to work. The local_irq_disable() shouldn't be used.

Quoted 3 lines

IIRC there has been some effort in MM to reduce the scope of IRQ-disabled section in MM when PREEMPT_RT config was added to the mainline. spin_lock_irq() doesn't disable IRQ on PREEMPT_RT.

Exactly.

Sebastian

#12 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Qi Zheng
Quoted 51 lines · Qi Zheng

Hi Harry,

Quoted 35 lines · Harry Yoo
Quoted 23 lines · Qi Zheng

From: Muchun Song <[email protected]>

In a subsequent patch, we'll reparent the LRU folios. The folios that are moved to the appropriate LRU list can undergo reparenting during the move_folios_to_lru() process. Hence, it's incorrect for the caller to hold a lruvec lock. Instead, we should utilize the more general interface of folio_lruvec_relock_irq() to obtain the correct lruvec lock.

This patch involves only code refactoring and doesn't introduce any functional changes.

---
  mm/vmscan.c | 46 +++++++++++++++++++++++-----------------------
  1 file changed, 23 insertions(+), 23 deletions(-)
mm/vmscan.c +0 -0
index 3a1044ce30f1e..660cd40cfddd4 100644

mm/vmscan.c static unsigned long shrink_inactive_list(unsigned long nr_to_scan, · line 2021

Quoted 8 lines
mm/vmscan.c +2 -2
@@ -2016,9 +2016,9 @@ static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
  	nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false,
  					 lruvec_memcg(lruvec));
-	spin_lock_irq(&lruvec->lru_lock);
-	move_folios_to_lru(lruvec, &folio_list);
+	move_folios_to_lru(&folio_list);
+	spin_lock_irq(&lruvec->lru_lock);
  	__mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc),
  					stat.nr_demoted);

Maybe I'm missing something or just confused for now, but let me ask...

Quoted 2 lines

How do we make sure the lruvec (and the mem_cgroup containing the lruvec) did not disappear (due to offlining) after move_folios_to_lru()?

We obtained lruvec through the following method:

memcg = mem_cgroup_iter(target_memcg, NULL, partial);

do {
    struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);

    shrink_lruvec(lruvec, sc);
    --> shrink_inactive_list
} while ((memcg = mem_cgroup_iter(target_memcg, memcg, partial)));
Quoted 2 lines

The mem_cgroup_iter() will hold the refcount of this memcg, so IIUC, the memcg will not disappear at this time.

Ah, right!

It can be offlined, but won't be released due to the refcount.

Thanks for the explanation.

Quoted 56 lines
Quoted 32 lines
Quoted 19 lines
mm/vmscan.c +3 -6
  	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
@@ -2166,11 +2166,10 @@ static void shrink_active_list(unsigned long nr_to_scan,
  	/*
  	 * Move folios back to the lru list.
  	 */
-	spin_lock_irq(&lruvec->lru_lock);
-
-	nr_activate = move_folios_to_lru(lruvec, &l_active);
-	nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
+	nr_activate = move_folios_to_lru(&l_active);
+	nr_deactivate = move_folios_to_lru(&l_inactive);
+	spin_lock_irq(&lruvec->lru_lock);
  	__count_vm_events(PGDEACTIVATE, nr_deactivate);
  	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
@@ -4735,14 +4734,15 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
  			set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active));
  	}
-	spin_lock_irq(&lruvec->lru_lock);
-

mm/vmscan.c static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, · line 4744

Quoted 10 lines
mm/vmscan.c +4 -1
-	move_folios_to_lru(lruvec, &list);
+	move_folios_to_lru(&list);
+	local_irq_disable();
  	walk = current->reclaim_state->mm_walk;
  	if (walk && walk->batched) {
  		walk->lruvec = lruvec;
+		spin_lock(&lruvec->lru_lock);
  		reset_batch_size(walk);
+		spin_unlock(&lruvec->lru_lock);
  	}

Cc'ing RT folks as they may not want to disable IRQ on PREEMPT_RT.

Quoted 3 lines

IIRC there has been some effort in MM to reduce the scope of IRQ-disabled section in MM when PREEMPT_RT config was added to the mainline. spin_lock_irq() doesn't disable IRQ on PREEMPT_RT.

Thanks for this information.

Quoted 18 lines

Also, this will break RT according to Documentation/locking/locktypes.rst:

Quoted 16 lines

The changes in spinlock_t and rwlock_t semantics on PREEMPT_RT kernels have a few implications. For example, on a non-PREEMPT_RT kernel the following code sequence works as expected:

local_irq_disable();
spin_lock(&lock);

and is fully equivalent to:

spin_lock_irq(&lock);
Same applies to rwlock_t and the _irqsave() suffix variants.

On PREEMPT_RT kernel this code sequence breaks because RT-mutex requires a fully preemptible context. Instead, use spin_lock_irq() or spin_lock_irqsave() and their unlock counterparts.

Quoted 7 lines
Quoted 5 lines
Quoted 5 lines

In cases where the interrupt disabling and locking must remain separate, PREEMPT_RT offers a local_lock mechanism. Acquiring the local_lock pins the task to a CPU, allowing things like per-CPU interrupt disabled locks to be acquired. However, this approach should be used only where absolutely necessary.

But how do we determine if it's necessary?

Although it's mentioned in the locking documentation, I'm afraid that local_lock is not the right interface to use here. Preemption will be disabled anyway (on both PREEMPT_RT and !PREEMPT_RT) when the stats are updated (in __mod_node_page_state()).

Here we just want to disable IRQ only on !PREEMPT_RT (to update the stats safely).

Maybe we'll need some ifdeffery? I don't see a better way around...

Signature · 2 lines
Cheers,
Harry / Hyeonggon
maintainer
#13 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 8 lines · Harry Yoo

Although it's mentioned in the locking documentation, I'm afraid that local_lock is not the right interface to use here. Preemption will be disabled anyway (on both PREEMPT_RT and !PREEMPT_RT) when the stats are updated (in __mod_node_page_state()).

Here we just want to disable IRQ only on !PREEMPT_RT (to update the stats safely).

I don't think there is a need to disable IRQs. There are three stats update functions called in that hunk.

1) __mod_lruvec_state
2) __count_vm_events
3) count_memcg_events

count_memcg_events() can be called with IRQs. __count_vm_events can be replaced with count_vm_events. For __mod_lruvec_state, the __mod_node_page_state() inside needs preemption disabled.

Easy way would be to just disable/enable preemption instead of IRQs. Otherwise go a bit more fine-grained approach i.e. replace __count_vm_events with count_vm_events and just disable preemption across __mod_node_page_state().

#14 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 13 lines · Shakeel Butt
Quoted 8 lines · Harry Yoo

Although it's mentioned in the locking documentation, I'm afraid that local_lock is not the right interface to use here. Preemption will be disabled anyway (on both PREEMPT_RT and !PREEMPT_RT) when the stats are updated (in __mod_node_page_state()).

Here we just want to disable IRQ only on !PREEMPT_RT (to update the stats safely).

I don't think there is a need to disable IRQs. There are three stats update functions called in that hunk.

Quoted 6 lines

1) __mod_lruvec_state
2) __count_vm_events
3) count_memcg_events

count_memcg_events() can be called with IRQs. __count_vm_events can be replaced with count_vm_events.

Right.

Quoted 2 lines

For __mod_lruvec_state, the __mod_node_page_state() inside needs preemption disabled.

The function __mod_node_page_state() disables preemption. And there's a comment in __mod_zone_page_state():

Quoted 8 lines

/*
* Accurate vmstat updates require a RMW. On !PREEMPT_RT kernels,
* atomicity is provided by IRQs being disabled -- either explicitly
* or via local_lock_irq. On PREEMPT_RT, local_lock_irq only disables
* CPU migrations and preemption potentially corrupts a counter so
* disable preemption.
*/
preempt_disable_nested();

We're relying on IRQs being disabled on !PREEMPT_RT.

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Quoted 4 lines

Easy way would be to just disable/enable preemption instead of IRQs. Otherwise go a bit more fine-grained approach i.e. replace __count_vm_events with count_vm_events and just disable preemption across __mod_node_page_state().

author reviewer
#15 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 38 lines · Harry Yoo
Quoted 13 lines · Shakeel Butt
Quoted 8 lines · Harry Yoo

Although it's mentioned in the locking documentation, I'm afraid that local_lock is not the right interface to use here. Preemption will be disabled anyway (on both PREEMPT_RT and !PREEMPT_RT) when the stats are updated (in __mod_node_page_state()).

Here we just want to disable IRQ only on !PREEMPT_RT (to update the stats safely).

I don't think there is a need to disable IRQs. There are three stats update functions called in that hunk.

Quoted 6 lines

1) __mod_lruvec_state
2) __count_vm_events
3) count_memcg_events

count_memcg_events() can be called with IRQs. __count_vm_events can be replaced with count_vm_events.

Right.

Quoted 2 lines

For __mod_lruvec_state, the __mod_node_page_state() inside needs preemption disabled.

The function __mod_node_page_state() disables preemption. And there's a comment in __mod_zone_page_state():

Quoted 8 lines

/*
* Accurate vmstat updates require a RMW. On !PREEMPT_RT kernels,
* atomicity is provided by IRQs being disabled -- either explicitly
* or via local_lock_irq. On PREEMPT_RT, local_lock_irq only disables
* CPU migrations and preemption potentially corrupts a counter so
* disable preemption.
*/
preempt_disable_nested();

Quoted 1 line

We're relying on IRQs being disabled on !PREEMPT_RT.

So it's possible for us to update vmstat within an interrupt context, right?

There is also a comment above __mod_zone_page_state():

/*
* For use when we know that interrupts are disabled,
* or when we know that preemption is disabled and that
* particular counter cannot be updated from interrupt context. */

BTW, the comment inside __mod_node_page_state() should be:

/* See __mod_zone_page_state */

instead of

/* See __mod_node_page_state */

Will fix it.

Quoted 3 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

Quoted 1 line
#16 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 41 lines · Qi Zheng
Quoted 38 lines · Harry Yoo
Quoted 13 lines · Shakeel Butt
Quoted 8 lines · Harry Yoo

Although it's mentioned in the locking documentation, I'm afraid that local_lock is not the right interface to use here. Preemption will be disabled anyway (on both PREEMPT_RT and !PREEMPT_RT) when the stats are updated (in __mod_node_page_state()).

Here we just want to disable IRQ only on !PREEMPT_RT (to update the stats safely).

I don't think there is a need to disable IRQs. There are three stats update functions called in that hunk.

Quoted 6 lines

1) __mod_lruvec_state
2) __count_vm_events
3) count_memcg_events

count_memcg_events() can be called with IRQs. __count_vm_events can be replaced with count_vm_events.

Right.

Quoted 2 lines

For __mod_lruvec_state, the __mod_node_page_state() inside needs preemption disabled.

The function __mod_node_page_state() disables preemption. And there's a comment in __mod_zone_page_state():

Quoted 8 lines

/*
* Accurate vmstat updates require a RMW. On !PREEMPT_RT kernels,
* atomicity is provided by IRQs being disabled -- either explicitly
* or via local_lock_irq. On PREEMPT_RT, local_lock_irq only disables
* CPU migrations and preemption potentially corrupts a counter so
* disable preemption.
*/
preempt_disable_nested();

Quoted 4 lines
Quoted 1 line

We're relying on IRQs being disabled on !PREEMPT_RT.

So it's possible for us to update vmstat within an interrupt context, right?

Yes, for instance when freeing memory in an interrupt context we can update vmstat and that's why we disable interrupts now.

Quoted 7 lines

There is also a comment above __mod_zone_page_state():

/*
* For use when we know that interrupts are disabled,
* or when we know that preemption is disabled and that
* particular counter cannot be updated from interrupt context. */

Yeah we don't have to disable IRQs when we already know it's disabled.

Quoted 9 lines

BTW, the comment inside __mod_node_page_state() should be:

/* See __mod_zone_page_state */

instead of

/* See __mod_node_page_state */

Will fix it.

Right :) Thanks!

Quoted 5 lines
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author reviewer
#17 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 42 lines · Harry Yoo
Quoted 41 lines · Qi Zheng
Quoted 38 lines · Harry Yoo
Quoted 13 lines · Shakeel Butt
Quoted 8 lines · Harry Yoo

Although it's mentioned in the locking documentation, I'm afraid that local_lock is not the right interface to use here. Preemption will be disabled anyway (on both PREEMPT_RT and !PREEMPT_RT) when the stats are updated (in __mod_node_page_state()).

Here we just want to disable IRQ only on !PREEMPT_RT (to update the stats safely).

I don't think there is a need to disable IRQs. There are three stats update functions called in that hunk.

Quoted 6 lines

1) __mod_lruvec_state
2) __count_vm_events
3) count_memcg_events

count_memcg_events() can be called with IRQs. __count_vm_events can be replaced with count_vm_events.

Right.

Quoted 2 lines

For __mod_lruvec_state, the __mod_node_page_state() inside needs preemption disabled.

The function __mod_node_page_state() disables preemption. And there's a comment in __mod_zone_page_state():

Quoted 8 lines

/*
* Accurate vmstat updates require a RMW. On !PREEMPT_RT kernels,
* atomicity is provided by IRQs being disabled -- either explicitly
* or via local_lock_irq. On PREEMPT_RT, local_lock_irq only disables
* CPU migrations and preemption potentially corrupts a counter so
* disable preemption.
*/
preempt_disable_nested();

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

We're relying on IRQs being disabled on !PREEMPT_RT.

So it's possible for us to update vmstat within an interrupt context, right?

Yes, for instance when freeing memory in an interrupt context we can update vmstat and that's why we disable interrupts now.

Got it.

Quoted 23 lines
Quoted 8 lines

There is also a comment above __mod_zone_page_state():

/*
* For use when we know that interrupts are disabled,
* or when we know that preemption is disabled and that
* particular counter cannot be updated from interrupt context. */

Yeah we don't have to disable IRQs when we already know it's disabled.

Quoted 9 lines

BTW, the comment inside __mod_node_page_state() should be:

/* See __mod_zone_page_state */

instead of

/* See __mod_node_page_state */

Will fix it.

Right :) Thanks!

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

Got it. I will give it a try.

Thanks,
Qi

Quoted 1 line
maintainer
#18 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Harry Yoo
Quoted 9 lines · Harry Yoo
Quoted 5 lines · Qi Zheng
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

We already have mod_node_page_state() which is safe from IRQs and is optimized to not disable IRQs for archs with HAVE_CMPXCHG_LOCAL which includes x86 and arm64.

Let me send the patch to cleanup the memcg code which uses __mod_node_page_state.

#19 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 8 lines · Shakeel Butt
Quoted 7 lines · Harry Yoo
Quoted 5 lines · Qi Zheng
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

Quoted 6 lines
Quoted 2 lines

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

We already have mod_node_page_state() which is safe from IRQs and is optimized to not disable IRQs for archs with HAVE_CMPXCHG_LOCAL which includes x86 and arm64.

Nice observation, thanks!

Quoted 2 lines

Let me send the patch to cleanup the memcg code which uses __mod_node_page_state.

I'll take a look.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author reviewer
#20 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Shakeel Butt
Quoted 8 lines · Shakeel Butt
Quoted 7 lines · Harry Yoo
Quoted 5 lines · Qi Zheng
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

Quoted 6 lines
Quoted 2 lines

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

We already have mod_node_page_state() which is safe from IRQs and is optimized to not disable IRQs for archs with HAVE_CMPXCHG_LOCAL which includes x86 and arm64.

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Quoted 3 lines

Let me send the patch to cleanup the memcg code which uses __mod_node_page_state.

#21 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 13 lines · Qi Zheng
Quoted 11 lines · Shakeel Butt
Quoted 9 lines · Harry Yoo
Quoted 5 lines · Qi Zheng
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

Quoted 6 lines
Quoted 3 lines

We already have mod_node_page_state() which is safe from IRQs and is optimized to not disable IRQs for archs with HAVE_CMPXCHG_LOCAL which includes x86 and arm64.

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Hmm I was going to say it's necessary, but AFAICT we don't allocate or free memory in hardirq context on PREEMPT_RT (that's the policy) and so I'd say it's not necessary to disable IRQs.

Sounds like we still want to disable IRQs only on !PREEMPT_RT on such architectures?

Not sure how seriously do PREEMPT_RT folks care about architectures without HAVE_CMPXCHG_LOCAL. (riscv and loongarch have ARCH_SUPPORTS_RT but doesn't have HAVE_CMPXCHG_LOCAL).

If they do care, this can be done as a separate patch series because we already call local_irq_{save,restore}() in many places in mm/vmstat.c if the architecture doesn't not have HAVE_CMPXCHG_LOCAL.

Quoted 2 lines
Quoted 2 lines

Let me send the patch to cleanup the memcg code which uses __mod_node_page_state.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
maintainer
#29 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Qi Zheng
Quoted 13 lines · Qi Zheng
Quoted 11 lines · Shakeel Butt
Quoted 9 lines · Harry Yoo
Quoted 5 lines · Qi Zheng
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

Quoted 7 lines
Quoted 3 lines

We already have mod_node_page_state() which is safe from IRQs and is optimized to not disable IRQs for archs with HAVE_CMPXCHG_LOCAL which includes x86 and arm64.

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Yes we can disable irqs on PREEMPT_RT but it is usually frown upon and it is usually requested to do so only for short window. However if someone running PREEMPT_RT on an arch without HAVE_CMPXCHG_LOCAL and has issues with mod_node_page_state() then they can solve it then. I don't think we need to fix that now.

author reviewer
#22 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Harry Yoo
Quoted 28 lines · Harry Yoo
Quoted 13 lines · Qi Zheng
Quoted 11 lines · Shakeel Butt
Quoted 9 lines · Harry Yoo
Quoted 5 lines · Qi Zheng
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

Quoted 6 lines
Quoted 3 lines

We already have mod_node_page_state() which is safe from IRQs and is optimized to not disable IRQs for archs with HAVE_CMPXCHG_LOCAL which includes x86 and arm64.

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Hmm I was going to say it's necessary, but AFAICT we don't allocate or free memory in hardirq context on PREEMPT_RT (that's the policy) and so I'd say it's not necessary to disable IRQs.

Sounds like we still want to disable IRQs only on !PREEMPT_RT on such architectures?

Quoted 7 lines

Not sure how seriously do PREEMPT_RT folks care about architectures without HAVE_CMPXCHG_LOCAL. (riscv and loongarch have ARCH_SUPPORTS_RT but doesn't have HAVE_CMPXCHG_LOCAL).

If they do care, this can be done as a separate patch series because we already call local_irq_{save,restore}() in many places in mm/vmstat.c if the architecture doesn't not have HAVE_CMPXCHG_LOCAL.

Got it. I will ignore it for now.

Quoted 4 lines
Quoted 3 lines
Quoted 3 lines

Let me send the patch to cleanup the memcg code which uses __mod_node_page_state.

author reviewer
#30 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Shakeel Butt
Quoted 18 lines · Shakeel Butt
Quoted 17 lines · Qi Zheng
Quoted 14 lines · Shakeel Butt
Quoted 9 lines · Harry Yoo
Quoted 5 lines · Qi Zheng
Quoted 2 lines

Maybe we could make it safe against re-entrant IRQ handlers by using read-modify-write operations?

Isn't it because of the RMW operation that we need to use IRQ to guarantee atomicity? Or have I misunderstood something?

I meant using atomic operations instead of disabling IRQs, like, by using this_cpu_add() or cmpxchg() instead.

We already have mod_node_page_state() which is safe from IRQs and is optimized to not disable IRQs for archs with HAVE_CMPXCHG_LOCAL which includes x86 and arm64.

Quoted 6 lines
Quoted 3 lines

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Yes we can disable irqs on PREEMPT_RT but it is usually frown upon and it is usually requested to do so only for short window. However if

Got it.

Quoted 3 lines

someone running PREEMPT_RT on an arch without HAVE_CMPXCHG_LOCAL and has issues with mod_node_page_state() then they can solve it then. I don't think we need to fix that now.

OK.

Quoted 1 line
#23 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Harry Yoo
Quoted 7 lines · Harry Yoo
Quoted 2 lines

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Hmm I was going to say it's necessary, but AFAICT we don't allocate or free memory in hardirq context on PREEMPT_RT (that's the policy) and so I'd say it's not necessary to disable IRQs.

Quoted 6 lines

Sounds like we still want to disable IRQs only on !PREEMPT_RT on such architectures?

Not sure how seriously do PREEMPT_RT folks care about architectures without HAVE_CMPXCHG_LOCAL. (riscv and loongarch have ARCH_SUPPORTS_RT but doesn't have HAVE_CMPXCHG_LOCAL).

We take things seriously and you shouldn't make assumption based on implementation. Either the API can be used as such or not. In case of mod_node_page_state(), the non-IRQ off version (__mod_node_page_state()) has a preempt_disable_nested() to ensure atomic update on PREEMPT_RT without disabling interrupts.

Sebastian

maintainer
#24 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 15 lines · Sebastian Andrzej Siewior
Quoted 7 lines · Harry Yoo
Quoted 2 lines

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Hmm I was going to say it's necessary, but AFAICT we don't allocate or free memory in hardirq context on PREEMPT_RT (that's the policy) and so I'd say it's not necessary to disable IRQs.

Quoted 6 lines

Sounds like we still want to disable IRQs only on !PREEMPT_RT on such architectures?

Not sure how seriously do PREEMPT_RT folks care about architectures without HAVE_CMPXCHG_LOCAL. (riscv and loongarch have ARCH_SUPPORTS_RT but doesn't have HAVE_CMPXCHG_LOCAL).

Quoted 6 lines

We take things seriously and you shouldn't make assumption based on implementation. Either the API can be used as such or not. In case of mod_node_page_state(), the non-IRQ off version (__mod_node_page_state()) has a preempt_disable_nested() to ensure atomic update on PREEMPT_RT without disabling interrupts.

Harry is talking about mod_node_page_state() on !CONFIG_HAVE_CMPXCHG_LOCAL which is disabling irqs.

void mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
long delta)

{
	unsigned long flags;

	local_irq_save(flags);
	__mod_node_page_state(pgdat, item, delta);
	local_irq_restore(flags);
}

Is PREEMPT_RT fine with this?

#25 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 36 lines · Shakeel Butt
Quoted 15 lines · Sebastian Andrzej Siewior
Quoted 7 lines · Harry Yoo
Quoted 2 lines

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Hmm I was going to say it's necessary, but AFAICT we don't allocate or free memory in hardirq context on PREEMPT_RT (that's the policy) and so I'd say it's not necessary to disable IRQs.

Quoted 6 lines

Sounds like we still want to disable IRQs only on !PREEMPT_RT on such architectures?

Not sure how seriously do PREEMPT_RT folks care about architectures without HAVE_CMPXCHG_LOCAL. (riscv and loongarch have ARCH_SUPPORTS_RT but doesn't have HAVE_CMPXCHG_LOCAL).

Quoted 6 lines

We take things seriously and you shouldn't make assumption based on implementation. Either the API can be used as such or not. In case of mod_node_page_state(), the non-IRQ off version (__mod_node_page_state()) has a preempt_disable_nested() to ensure atomic update on PREEMPT_RT without disabling interrupts.

Harry is talking about mod_node_page_state() on !CONFIG_HAVE_CMPXCHG_LOCAL which is disabling irqs.

void mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
long delta)

{
	unsigned long flags;

	local_irq_save(flags);
	__mod_node_page_state(pgdat, item, delta);
	local_irq_restore(flags);
}
Quoted 1 line

Is PREEMPT_RT fine with this?

Yes.
The local_irq_save() is not strictly needed but I am fine with it to keep it simple. The inner part is just counting.

Sebastian

#26 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 36 lines · Sebastian Andrzej Siewior
Quoted 35 lines · Shakeel Butt
Quoted 15 lines · Sebastian Andrzej Siewior
Quoted 7 lines · Harry Yoo
Quoted 2 lines

However, in the !CONFIG_HAVE_CMPXCHG_LOCAL case, mod_node_page_state() still calls local_irq_save(). Is this feasible in the PREEMPT_RT kernel?

Hmm I was going to say it's necessary, but AFAICT we don't allocate or free memory in hardirq context on PREEMPT_RT (that's the policy) and so I'd say it's not necessary to disable IRQs.

Quoted 6 lines

Sounds like we still want to disable IRQs only on !PREEMPT_RT on such architectures?

Not sure how seriously do PREEMPT_RT folks care about architectures without HAVE_CMPXCHG_LOCAL. (riscv and loongarch have ARCH_SUPPORTS_RT but doesn't have HAVE_CMPXCHG_LOCAL).

Quoted 5 lines

We take things seriously and you shouldn't make assumption based on implementation. Either the API can be used as such or not. In case of mod_node_page_state(), the non-IRQ off version (__mod_node_page_state()) has a preempt_disable_nested() to ensure atomic update on PREEMPT_RT without disabling interrupts.

Harry is talking about mod_node_page_state() on !CONFIG_HAVE_CMPXCHG_LOCAL which is disabling irqs.

void mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
long delta)

{
	unsigned long flags;

	local_irq_save(flags);
	__mod_node_page_state(pgdat, item, delta);
	local_irq_restore(flags);
}
Quoted 5 lines
Quoted 1 line

Is PREEMPT_RT fine with this?

Yes.
The local_irq_save() is not strictly needed but I am fine with it to keep it simple. The inner part is just counting.

Yeah I was wondering about this... and thanks for confirming!

Signature · 2 lines
Cheers,
Harry / Hyeonggon
#27 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

Quoted 7 lines · Harry Yoo
Quoted 5 lines
Quoted 1 line

Is PREEMPT_RT fine with this?

Yes.
The local_irq_save() is not strictly needed but I am fine with it to keep it simple. The inner part is just counting.

Yeah I was wondering about this... and thanks for confirming!

The preempt_disable_nested() and no in-IRQ user makes it okay. Not the counting, that was meant as "it is a small section". That might have been too short of an explanation.

Sebastian

maintainer
#28 lore raw

Re: [PATCH v1 04/26] mm: vmscan: refactor move_folios_to_lru()

In reply to Shakeel Butt
Quoted 13 lines · On Tue, 11 Nov 2025 08:44:14 -0800 Shakeel Butt <[email protected]> wrote:

Harry is talking about mod_node_page_state() on !CONFIG_HAVE_CMPXCHG_LOCAL which is disabling irqs.

void mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
long delta)

{
	unsigned long flags;

	local_irq_save(flags);
	__mod_node_page_state(pgdat, item, delta);
	local_irq_restore(flags);
}
Quoted 1 line

Is PREEMPT_RT fine with this?

But should be:

void mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
long delta)

{
	guard(irqsave)();
	__mod_node_page_state(pgdat, item, delta);
}

-- Steve

maintainer
#95 lore raw

Re: [PATCH v1 25/26] mm: memcontrol: eliminate the problem of dying memory cgroup for LRU folios

In reply to Qi Zheng
Quoted 14 lines · Qi Zheng

From: Muchun Song <[email protected]>

Pagecache pages are charged at allocation time and hold a reference to the original memory cgroup until reclaimed. Depending on memory pressure, page sharing patterns between different cgroups and cgroup creation/destruction rates, many dying memory cgroups can be pinned by pagecache pages, reducing page reclaim efficiency and wasting memory. Converting LRU folios and most other raw memory cgroup pins to the object cgroup direction can fix this long-living problem.

Finally, folio->memcg_data of LRU folios and kmem folios will always point to an object cgroup pointer. The folio->memcg_data of slab folios will point to an vector of object cgroups.

Quoted 7 lines
---
 include/linux/memcontrol.h |  77 +++++----------
 mm/memcontrol-v1.c         |  15 +--
 mm/memcontrol.c            | 189 +++++++++++++++++++++++--------------
 3 files changed, 150 insertions(+), 131 deletions(-)

(I know it's not only this patch but all the preceding ones, still) thanks!

Michal

Reviewed-by on v1 5/26
#33 lore raw

Re: [PATCH v1 05/26] mm: memcontrol: allocate object cgroup for non-kmem case

In reply to Qi Zheng
Quoted 21 lines · Qi Zheng

From: Muchun Song <[email protected]>

Pagecache pages are charged at allocation time and hold a reference to the original memory cgroup until reclaimed. Depending on memory pressure, page sharing patterns between different cgroups and cgroup creation/destruction rates, many dying memory cgroups can be pinned by pagecache pages, reducing page reclaim efficiency and wasting memory. Converting LRU folios and most other raw memory cgroup pins to the object cgroup direction can fix this long-living problem.

As a result, the objcg infrastructure is no longer solely applicable to the kmem case. In this patch, we extend the scope of the objcg infrastructure beyond the kmem case, enabling LRU folios to reuse it for folio charging purposes.

It should be noted that LRU folios are not accounted for at the root level, yet the folio->memcg_data points to the root_mem_cgroup. Hence, the folio->memcg_data of LRU folios always points to a valid pointer. However, the root_mem_cgroup does not possess an object cgroup. Therefore, we also allocate an object cgroup for the root_mem_cgroup.

Quoted 3 lines

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
#37 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

In reply to Qi Zheng
Quoted 33 lines · Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
 include/linux/memcontrol.h | 29 +++++++++++++++++-------
 mm/memcontrol.c            | 45 ++++++++++++++++++++------------------
 mm/percpu.c                |  2 +-
 3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +1 -0
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
 #define MEMCG_CHARGE_BATCH 64U
 
 extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
 
 enum page_memcg_data_flags {
 	/* page->memcg_data is a pointer to an slabobj_ext vector */

include/linux/memcontrol.h static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) · line 556

Quoted 7 lines
include/linux/memcontrol.h +4 -0
@@ -549,6 +550,11 @@ static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
 	return (memcg == root_mem_cgroup);
 }
 
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+	return objcg == root_obj_cgroup;
+}

After reparenting, an objcg may satisfy objcg->memcg == root_mem_cgroup while objcg != root_obj_cgroup. Should they be considered as root objcgs?

mm/memcontrol.c int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) · line 2868

Quoted 13 lines
include/linux/memcontrol.h +0 -0
 static inline bool mem_cgroup_disabled(void)
 {
 	return !cgroup_subsys_enabled(memory_cgrp_subsys);
mm/memcontrol.c +1 -1
index 2afd7f99ca101..d484b632c790f 100644
@@ -2871,7 +2865,7 @@ int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
 	int ret = 0;
 
 	objcg = current_obj_cgroup();
-	if (objcg) {
+	if (!obj_cgroup_is_root(objcg)) {

Now that we support the page and slab allocators support allocating memory in NMI contexts (on some archs), current_obj_cgroup() can return NULL if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) returns true (then it leads to a NULL-pointer-deref bug).

But IIUC this is applied to kmem charging only (as they use this_cpu ops for stats update), and we don't have to apply the same restriction to charging LRU pages with objcg.

Maybe Shakeel has more insight on this.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
#38 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

Quoted 8 lines · Harry Yoo
Quoted 7 lines · Qi Zheng
mm/memcontrol.c +0 -0
index 2afd7f99ca101..d484b632c790f 100644
@@ -2871,7 +2865,7 @@ int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
 	int ret = 0;
 
Quoted 8 lines

mm/memcontrol.c int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) · line 2868

Quoted 3 lines
mm/memcontrol.c +1 -1
 	objcg = current_obj_cgroup();
-	if (objcg) {
+	if (!obj_cgroup_is_root(objcg)) {

Now that we support the page and slab allocators support allocating memory in NMI contexts (on some archs), current_obj_cgroup() can return NULL if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) returns true (then it leads to a NULL-pointer-deref bug).

This is a real issue, but

Quoted 3 lines

But IIUC this is applied to kmem charging only (as they use this_cpu ops for stats update), and we don't have to apply the same restriction to charging LRU pages with objcg.

actually this should be fine for now since we use get_mem_cgroup_from_mm() and obj_cgroup_from_memcg() instead of current_obj_cgroup() when charging LRU pages.

But it is not immediately obvious that there are multiple ways to get an objcg, each with different restrictions depending on what you are going to charge :/

Quoted 3 lines

Maybe Shakeel has more insight on this.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author reviewer
#40 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

In reply to Harry Yoo

Hi Harry,

Quoted 37 lines · Harry Yoo
Quoted 36 lines · Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
  include/linux/memcontrol.h | 29 +++++++++++++++++-------
  mm/memcontrol.c            | 45 ++++++++++++++++++++------------------
  mm/percpu.c                |  2 +-
  3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +1 -0
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
  #define MEMCG_CHARGE_BATCH 64U
 
  extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
 
  enum page_memcg_data_flags {
  	/* page->memcg_data is a pointer to an slabobj_ext vector */
@@ -549,6 +550,11 @@ static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
  	return (memcg == root_mem_cgroup);
  }
 
Quoted 8 lines

include/linux/memcontrol.h static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) · line 556

Quoted 4 lines
include/linux/memcontrol.h +4 -0
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+	return objcg == root_obj_cgroup;
+}

After reparenting, an objcg may satisfy objcg->memcg == root_mem_cgroup while objcg != root_obj_cgroup. Should they be considered as root objcgs?

Indeed, it's pointless to charge to root_mem_cgroup (objcg->memcg).

So it should be:

static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)

{
	return (objcg == root_obj_cgroup) || (objcg->memcg == root_mem_cgroup);
}
Quoted 20 lines
Quoted 9 lines
include/linux/memcontrol.h +0 -0
  static inline bool mem_cgroup_disabled(void)
  {
  	return !cgroup_subsys_enabled(memory_cgrp_subsys);
mm/memcontrol.c +0 -0
index 2afd7f99ca101..d484b632c790f 100644

mm/memcontrol.c int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) · line 2868

Quoted 5 lines
mm/memcontrol.c +1 -1
@@ -2871,7 +2865,7 @@ int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
  	int ret = 0;
 
  	objcg = current_obj_cgroup();
-	if (objcg) {
+	if (!obj_cgroup_is_root(objcg)) {

Now that we support the page and slab allocators support allocating memory in NMI contexts (on some archs), current_obj_cgroup() can return NULL if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) returns true (then it leads to a NULL-pointer-deref bug).

Quoted 7 lines

But IIUC this is applied to kmem charging only (as they use this_cpu ops for stats update), and we don't have to apply the same restriction to charging LRU pages with objcg.

Maybe Shakeel has more insight on this.

Thanks for this information, and it seems there's nothing wrong here.

Thanks,
Qi

Quoted 1 line
author reviewer
#39 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

In reply to Harry Yoo
Quoted 24 lines · Harry Yoo
Quoted 8 lines · Harry Yoo
Quoted 7 lines · Qi Zheng
mm/memcontrol.c +0 -0
index 2afd7f99ca101..d484b632c790f 100644
@@ -2871,7 +2865,7 @@ int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
  	int ret = 0;
 
Quoted 8 lines

mm/memcontrol.c int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) · line 2868

Quoted 3 lines
mm/memcontrol.c +1 -1
  	objcg = current_obj_cgroup();
-	if (objcg) {
+	if (!obj_cgroup_is_root(objcg)) {

Now that we support the page and slab allocators support allocating memory in NMI contexts (on some archs), current_obj_cgroup() can return NULL if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) returns true (then it leads to a NULL-pointer-deref bug).

This is a real issue, but

Quoted 3 lines

But IIUC this is applied to kmem charging only (as they use this_cpu ops for stats update), and we don't have to apply the same restriction to charging LRU pages with objcg.

Quoted 7 lines

actually this should be fine for now since we use get_mem_cgroup_from_mm() and obj_cgroup_from_memcg() instead of current_obj_cgroup() when charging LRU pages.

But it is not immediately obvious that there are multiple ways to get an objcg, each with different restrictions depending on what you are going to charge :/

Perhaps some comments need to be added. :)

Quoted 5 lines
Quoted 4 lines

Maybe Shakeel has more insight on this.

author reviewer
#41 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

In reply to Qi Zheng
Quoted 49 lines · Qi Zheng

Hi Harry,

Quoted 35 lines · Harry Yoo
Quoted 34 lines · Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
  include/linux/memcontrol.h | 29 +++++++++++++++++------- mm/memcontrol.c            | 45 ++++++++++++++++++++------------------ mm/percpu.c                |  2 +-

  3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +1 -0
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
   #define MEMCG_CHARGE_BATCH 64U
   extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
   enum page_memcg_data_flags {
       /* page->memcg_data is a pointer to an slabobj_ext vector */
@@ -549,6 +550,11 @@ static inline bool mem_cgroup_is_root(struct 
 mem_cgroup *memcg)
       return (memcg == root_mem_cgroup);
   }
Quoted 8 lines

include/linux/memcontrol.h static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) · line 556

Quoted 4 lines
include/linux/memcontrol.h +4 -0
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+    return objcg == root_obj_cgroup;
+}

After reparenting, an objcg may satisfy objcg->memcg == root_mem_cgroup while objcg != root_obj_cgroup. Should they be considered as root objcgs?

Indeed, it's pointless to charge to root_mem_cgroup (objcg->memcg).

Quoted 7 lines

So it should be:

static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg) {
    return (objcg == root_obj_cgroup) || (objcg->memcg ==
root_mem_cgroup);
}

Oh, we can't do that because we still need to consider this objcg when uncharging. Some pages may be charged before reparenting.

Quoted 36 lines
Quoted 21 lines
Quoted 10 lines
include/linux/memcontrol.h +0 -0
   static inline bool mem_cgroup_disabled(void)
   {
       return !cgroup_subsys_enabled(memory_cgrp_subsys);
mm/memcontrol.c +0 -0
index 2afd7f99ca101..d484b632c790f 100644

mm/memcontrol.c int __memcg_kmem_charge_page(struct page *page, · line 2868

Quoted 5 lines
mm/memcontrol.c +1 -1
@@ -2871,7 +2865,7 @@ int __memcg_kmem_charge_page(struct page *page, 
 gfp_t gfp, int order)
       int ret = 0;
       objcg = current_obj_cgroup();
-    if (objcg) {
+    if (!obj_cgroup_is_root(objcg)) {

Now that we support the page and slab allocators support allocating memory in NMI contexts (on some archs), current_obj_cgroup() can return NULL if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) returns true (then it leads to a NULL-pointer-deref bug).

Quoted 7 lines

But IIUC this is applied to kmem charging only (as they use this_cpu ops for stats update), and we don't have to apply the same restriction to charging LRU pages with objcg.

Maybe Shakeel has more insight on this.

Thanks for this information, and it seems there's nothing wrong here.

Thanks,
Qi

Quoted 1 line
#44 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

In reply to Qi Zheng
Quoted 46 lines · Qi Zheng

Hi Harry,

Quoted 34 lines · Harry Yoo
Quoted 33 lines · Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
  include/linux/memcontrol.h | 29 +++++++++++++++++-------
  mm/memcontrol.c            | 45 ++++++++++++++++++++------------------
  mm/percpu.c                |  2 +-
  3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +1 -0
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
  #define MEMCG_CHARGE_BATCH 64U
  extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
  enum page_memcg_data_flags {
  	/* page->memcg_data is a pointer to an slabobj_ext vector */
@@ -549,6 +550,11 @@ static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
  	return (memcg == root_mem_cgroup);
  }
Quoted 8 lines

include/linux/memcontrol.h static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) · line 556

Quoted 4 lines
include/linux/memcontrol.h +4 -0
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+	return objcg == root_obj_cgroup;
+}

After reparenting, an objcg may satisfy objcg->memcg == root_mem_cgroup while objcg != root_obj_cgroup. Should they be considered as root objcgs?

Quoted 9 lines

Indeed, it's pointless to charge to root_mem_cgroup (objcg->memcg).

So it should be:

static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)

{
	return (objcg == root_obj_cgroup) || (objcg->memcg == root_mem_cgroup);
}

Thanks and tomorrow I'll try to review if will be correct ;)

Quoted 22 lines
Quoted 22 lines

mm/memcontrol.c int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) · line 2867

Quoted 12 lines
include/linux/memcontrol.h +0 -0
  static inline bool mem_cgroup_disabled(void)
  {
  	return !cgroup_subsys_enabled(memory_cgrp_subsys);
mm/memcontrol.c +1 -1
index 2afd7f99ca101..d484b632c790f 100644
@@ -2871,7 +2865,7 @@ int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
  	int ret = 0;
  	objcg = current_obj_cgroup();
-	if (objcg) {
+	if (!obj_cgroup_is_root(objcg)) {

Now that we support the page and slab allocators support allocating memory in NMI contexts (on some archs), current_obj_cgroup() can return NULL if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) returns true (then it leads to a NULL-pointer-deref bug).

But IIUC this is applied to kmem charging only (as they use this_cpu ops for stats update), and we don't have to apply the same restriction to charging LRU pages with objcg.

Quoted 5 lines
Quoted 3 lines

Maybe Shakeel has more insight on this.

Thanks for this information, and it seems there's nothing wrong here.

I mean at least we should not introduce a NULL-pointer-deref bug in __memcg_kmem_charge_page(), by assuming objcg returned by current_obj_cgroup() is non-NULL?

1. Someone allocates non-slab kmem in an NMI context (in_nmi() == true), calling __memcg_kmem_charge_page().
2. current_obj_cgruop() returns NULL because the architectures has CONFIG_MEMCG_NMI_UNSAFE and it's in an NMI context.
3. obj_cgroup_is_root() returns false since
objcg (NULL) != root_obj_cgroup
4. we pass NULL to obj_cgroup_charge_pages().
5. obj_cgroup_charge_pages() calls get_mem_cgroup_from_objcg(), dereference objcg->memcg (! a NULL-pointer-deref).

Quoted 4 lines

Thanks,
Qi

Quoted 1 line
Signature · 2 lines
Cheers,
Harry / Hyeonggon
author reviewer
#45 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

Quoted 96 lines · Harry Yoo
Quoted 46 lines · Qi Zheng

Hi Harry,

Quoted 34 lines · Harry Yoo
Quoted 33 lines · Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
   include/linux/memcontrol.h | 29 +++++++++++++++++-------
   mm/memcontrol.c            | 45 ++++++++++++++++++++------------------
   mm/percpu.c                |  2 +-
   3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +1 -0
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
   #define MEMCG_CHARGE_BATCH 64U
   extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
   enum page_memcg_data_flags {
   	/* page->memcg_data is a pointer to an slabobj_ext vector */
@@ -549,6 +550,11 @@ static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
   	return (memcg == root_mem_cgroup);
   }
Quoted 8 lines

include/linux/memcontrol.h static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) · line 556

Quoted 4 lines
include/linux/memcontrol.h +4 -0
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+	return objcg == root_obj_cgroup;
+}

After reparenting, an objcg may satisfy objcg->memcg == root_mem_cgroup while objcg != root_obj_cgroup. Should they be considered as root objcgs?

Quoted 9 lines

Indeed, it's pointless to charge to root_mem_cgroup (objcg->memcg).

So it should be:

static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)

{
	return (objcg == root_obj_cgroup) || (objcg->memcg == root_mem_cgroup);
}

Thanks and tomorrow I'll try to review if will be correct ;)

Quoted 22 lines
Quoted 22 lines

mm/memcontrol.c int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) · line 2867

Quoted 12 lines
include/linux/memcontrol.h +0 -0
   static inline bool mem_cgroup_disabled(void)
   {
   	return !cgroup_subsys_enabled(memory_cgrp_subsys);
mm/memcontrol.c +1 -1
index 2afd7f99ca101..d484b632c790f 100644
@@ -2871,7 +2865,7 @@ int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
   	int ret = 0;
   	objcg = current_obj_cgroup();
-	if (objcg) {
+	if (!obj_cgroup_is_root(objcg)) {

Now that we support the page and slab allocators support allocating memory in NMI contexts (on some archs), current_obj_cgroup() can return NULL if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) returns true (then it leads to a NULL-pointer-deref bug).

But IIUC this is applied to kmem charging only (as they use this_cpu ops for stats update), and we don't have to apply the same restriction to charging LRU pages with objcg.

Quoted 5 lines
Quoted 3 lines

Maybe Shakeel has more insight on this.

Thanks for this information, and it seems there's nothing wrong here.

I mean at least we should not introduce a NULL-pointer-deref bug in __memcg_kmem_charge_page(), by assuming objcg returned by current_obj_cgroup() is non-NULL?

1. Someone allocates non-slab kmem in an NMI context (in_nmi() == true), calling __memcg_kmem_charge_page().
2. current_obj_cgruop() returns NULL because the architectures has CONFIG_MEMCG_NMI_UNSAFE and it's in an NMI context.
3. obj_cgroup_is_root() returns false since

Quoted 4 lines
    objcg (NULL) != root_obj_cgroup
4. we pass NULL to obj_cgroup_charge_pages().
5. obj_cgroup_charge_pages() calls get_mem_cgroup_from_objcg(),
    dereference objcg->memcg (! a NULL-pointer-deref).

Oh, indeed. After adding MEMCG_NMI_UNSAFE, we should first check if objcg is NULL.

Thanks!

Quoted 6 lines
Quoted 5 lines

Thanks,
Qi

Quoted 1 line
#42 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

In reply to Qi Zheng
Quoted 54 lines · Qi Zheng
Quoted 51 lines · Qi Zheng

Hi Harry,

Quoted 35 lines · Harry Yoo
Quoted 34 lines · Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
  include/linux/memcontrol.h | 29 +++++++++++++++++------- mm/memcontrol.c            | 45 ++++++++++++++++++++------------------ mm/percpu.c                |  2 +-

  3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +1 -0
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
   #define MEMCG_CHARGE_BATCH 64U
   extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
   enum page_memcg_data_flags {
       /* page->memcg_data is a pointer to an slabobj_ext vector */
@@ -549,6 +550,11 @@ static inline bool
 mem_cgroup_is_root(struct mem_cgroup *memcg)
       return (memcg == root_mem_cgroup);
   }
Quoted 8 lines

include/linux/memcontrol.h static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) · line 556

Quoted 4 lines
include/linux/memcontrol.h +4 -0
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+    return objcg == root_obj_cgroup;
+}

After reparenting, an objcg may satisfy objcg->memcg == root_mem_cgroup while objcg != root_obj_cgroup. Should they be considered as root objcgs?

Indeed, it's pointless to charge to root_mem_cgroup (objcg->memcg).

So it should be:

Quoted 8 lines
Quoted 5 lines

static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg) {
    return (objcg == root_obj_cgroup) || (objcg->memcg ==
root_mem_cgroup);
}

Oh, we can't do that because we still need to consider this objcg when uncharging. Some pages may be charged before reparenting.

Ouch, right. We don't know if it's charged before reparenting and so it can break statistics in a few places if we skip uncharging it after repareting.

And I think we don't charge new pages to objcgs that satisfy (objcg->memcg == root_mem_cgroup) && (objcg != root_obj_cgroup) after they're reparented anyway...

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author reviewer
#43 lore raw

Re: [PATCH v1 06/26] mm: memcontrol: return root object cgroup for root memory cgroup

Quoted 61 lines · Harry Yoo
Quoted 60 lines · Qi Zheng
Quoted 56 lines · Qi Zheng

Hi Harry,

Quoted 35 lines · Harry Yoo
Quoted 34 lines · Qi Zheng

From: Muchun Song <[email protected]>

Memory cgroup functions such as get_mem_cgroup_from_folio() and get_mem_cgroup_from_mm() return a valid memory cgroup pointer, even for the root memory cgroup. In contrast, the situation for object cgroups has been different.

Previously, the root object cgroup couldn't be returned because it didn't exist. Now that a valid root object cgroup exists, for the sake of consistency, it's necessary to align the behavior of object-cgroup-related operations with that of memory cgroup APIs.

---
   include/linux/memcontrol.h | 29 +++++++++++++++++-------
   mm/memcontrol.c            | 45 ++++++++++++++++++++------------------
   mm/percpu.c                |  2 +-
   3 files changed, 46 insertions(+), 30 deletions(-)
include/linux/memcontrol.h +1 -0
index 6185d8399a54e..9fdbd4970021d 100644
@@ -332,6 +332,7 @@ struct mem_cgroup {
   #define MEMCG_CHARGE_BATCH 64U
   extern struct mem_cgroup *root_mem_cgroup;
+extern struct obj_cgroup *root_obj_cgroup;
   enum page_memcg_data_flags {
       /* page->memcg_data is a pointer to an slabobj_ext vector */
@@ -549,6 +550,11 @@ static inline bool
 mem_cgroup_is_root(struct mem_cgroup *memcg)
       return (memcg == root_mem_cgroup);
   }
Quoted 8 lines

include/linux/memcontrol.h static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) · line 556

Quoted 4 lines
include/linux/memcontrol.h +4 -0
+static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg)
+{
+    return objcg == root_obj_cgroup;
+}

After reparenting, an objcg may satisfy objcg->memcg == root_mem_cgroup while objcg != root_obj_cgroup. Should they be considered as root objcgs?

Indeed, it's pointless to charge to root_mem_cgroup (objcg->memcg).

So it should be:

static inline bool obj_cgroup_is_root(const struct obj_cgroup *objcg) {
    return (objcg == root_obj_cgroup) || (objcg->memcg ==
root_mem_cgroup);
}

Quoted 6 lines
Quoted 2 lines

Oh, we can't do that because we still need to consider this objcg when uncharging. Some pages may be charged before reparenting.

Ouch, right. We don't know if it's charged before reparenting and so it can break statistics in a few places if we skip uncharging it after repareting.

Right.

Quoted 4 lines

And I think we don't charge new pages to objcgs that satisfy (objcg->memcg == root_mem_cgroup) && (objcg != root_obj_cgroup) after they're reparented anyway...

The charge and uncharge operations must be symmetrical, so we cannot control the charge operation independently.

Otherwise:

charge
======

if ((objcg->memcg == root_mem_cgroup))
skip charge this page

uncharge
========

we can't decide whether to skip this page.

Thanks,
Qi

Quoted 1 line
Reviewed-by on v1 7/26
#47 lore raw

Re: [PATCH v1 07/26] mm: memcontrol: prevent memory cgroup release in get_mem_cgroup_from_folio()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in get_mem_cgroup_from_folio().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

This patch looks correct to me, so:

with a few side question on current implementation rather than this change...

Quoted 12 lines
 mm/memcontrol.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
mm/memcontrol.c +0 -1
index d484b632c790f..1da3ad77054d3 100644
@@ -973,14 +973,19 @@ struct mem_cgroup *get_mem_cgroup_from_current(void)
  */
 struct mem_cgroup *get_mem_cgroup_from_folio(struct folio *folio)
 {
-	struct mem_cgroup *memcg = folio_memcg(folio);

mm/memcontrol.c struct mem_cgroup *get_mem_cgroup_from_current(void) · line 982

Quoted 10 lines
mm/memcontrol.c +4 -1
+	struct mem_cgroup *memcg;
 
 	if (mem_cgroup_disabled())
 		return NULL;
 
+	if (!folio_memcg_charged(folio))
+		return root_mem_cgroup;
+
 	rcu_read_lock();
-	if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))

I have no idea why we're already calling rcu_read_lock() when a folio pins the memcg :)

Quoted 10 lines
mm/memcontrol.c +4 -1
-		memcg = root_mem_cgroup;
+retry:
+	memcg = folio_memcg(folio);
+	if (unlikely(!css_tryget(&memcg->css)))
+		goto retry;
 	rcu_read_unlock();
 	return memcg;
 }
Signature · 1 line
2.20.1
Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 8/26
#50 lore raw

Re: [PATCH v1 08/26] buffer: prevent memory cgroup release in folio_alloc_buffers()

In reply to Qi Zheng
Quoted 7 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

Quoted 8 lines

In the current patch, the function get_mem_cgroup_from_folio() is employed to safeguard against the release of the memory cgroup. This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 9/26
#52 lore raw

Re: [PATCH v1 09/26] writeback: prevent memory cgroup release in writeback module

In reply to Qi Zheng
Quoted 11 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the function get_mem_cgroup_css_from_folio() and the rcu read lock are employed to safeguard against the release of the memory cgroup.

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Quoted 22 lines
 fs/fs-writeback.c                | 22 +++++++++++-----------
 include/linux/memcontrol.h       |  9 +++++++--
 include/trace/events/writeback.h |  3 +++
 mm/memcontrol.c                  | 14 ++++++++------
 4 files changed, 29 insertions(+), 19 deletions(-)
include/linux/memcontrol.h +1 -1
index 9fdbd4970021d..174e52d8e7039 100644
@@ -895,7 +895,7 @@ static inline bool mm_match_cgroup(struct mm_struct *mm,
 	return match;
 }
 
-struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio);
+struct cgroup_subsys_state *get_mem_cgroup_css_from_folio(struct folio *folio);
 ino_t page_cgroup_ino(struct page *page);
 
 static inline bool mem_cgroup_online(struct mem_cgroup *memcg)
@@ -1577,9 +1577,14 @@ static inline void mem_cgroup_track_foreign_dirty(struct folio *folio,
 	if (mem_cgroup_disabled())
 		return;

include/linux/memcontrol.h static inline void mem_cgroup_track_foreign_dirty(struct folio *folio, · line 1587

Quoted 10 lines
include/linux/memcontrol.h +6 -1
 
+	if (!folio_memcg_charged(folio))
+		return;
+
+	rcu_read_lock();
 	memcg = folio_memcg(folio);
-	if (unlikely(memcg && &memcg->css != wb->memcg_css))
+	if (unlikely(&memcg->css != wb->memcg_css))
 		mem_cgroup_track_foreign_dirty_slowpath(folio, wb);
+	rcu_read_unlock();

I was wondering if it's fine to record foreign dirty info to a dying cgroup and lose this info, but mem_cgroup_track_foreign_dirty_slowpath() says:

"The mechanism only remembers IDs and doesn't hold any object references.
As being wrong occasionally doesn't matter, updates and accesses to the records are lockless and racy"

so this looks fine.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 10/26
#54 lore raw

Re: [PATCH v1 10/26] mm: memcontrol: prevent memory cgroup release in count_memcg_folio_events()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in count_memcg_folio_events().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 11/26
#56 lore raw

Re: [PATCH v1 11/26] mm: page_io: prevent memory cgroup release in page_io module

In reply to Qi Zheng
Quoted 9 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in swap_writepage() and

nit: ^ swap_writeout()

Quoted 8 lines

bio_associate_blkg_from_page().

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 12/26
#59 lore raw

Re: [PATCH v1 12/26] mm: migrate: prevent memory cgroup release in folio_migrate_mapping()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in folio_migrate_mapping().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
#61 lore raw

Re: [PATCH v1 13/26] mm: mglru: prevent memory cgroup release in mglru

In reply to Qi Zheng
Quoted 24 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in mglru.

This serves as a preparatory measure for the reparenting of the LRU pages.

---
 mm/vmscan.c | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
mm/vmscan.c +0 -0
index 660cd40cfddd4..676e6270e5b45 100644

mm/vmscan.c bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw) · line 4295

Quoted 8 lines
mm/vmscan.c +2 -0
@@ -4279,6 +4288,8 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
 
 	arch_leave_lazy_mmu_mode();
 
+	rcu_read_unlock();
+
 	/* feedback from rmap walkers to page table walkers */
 	if (mm_state && suitable_to_scan(i, young))
 		update_bloom_filter(mm_state, max_seq, pvmw->pmd);

mm_state has the same life cycle as mem_cgroup. So it should be protected by rcu read lock?

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 14/26
#64 lore raw

Re: [PATCH v1 14/26] mm: memcontrol: prevent memory cgroup release in mem_cgroup_swap_full()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in mem_cgroup_swap_full().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 15/26
#66 lore raw

Re: [PATCH v1 15/26] mm: workingset: prevent memory cgroup release in lru_gen_eviction()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in lru_gen_eviction().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

As this touches workingset detection logic, I was wondering what would happen if a memcg id is recorded to a shadow entry and the memcg is destroyed. But both the traditional LRU and MGLRU seem to handle that.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 16/26
#68 lore raw

Re: [PATCH v1 16/26] mm: thp: prevent memory cgroup release in folio_split_queue_lock{_irqsave}()

In reply to Qi Zheng
Quoted 7 lines · Qi Zheng

From: Qi Zheng <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

Quoted 5 lines

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in folio_split_queue_lock{_irqsave}().

---

Looks good to me,

Yeah, once we acquire the split-queue lock, the split queue won't disappear under us because the reparenting logic also takes the same lock before reparenting.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 1/26
#3 lore raw

Re: [PATCH v1 01/26] mm: memcontrol: remove dead code of checking parent memory cgroup

In reply to Qi Zheng
Quoted 53 lines · Qi Zheng

From: Muchun Song <[email protected]>

Since the no-hierarchy mode has been deprecated after the commit:

commit bef8620cd8e0 ("mm: memcg: deprecate the non-hierarchical mode").

As a result, parent_mem_cgroup() will not return NULL except when passing the root memcg, and the root memcg cannot be offline. Hence, it's safe to remove the check on the returned value of parent_mem_cgroup(). Remove the corresponding dead code.

---
 mm/memcontrol.c | 5 -----
 mm/shrinker.c   | 6 +-----
 2 files changed, 1 insertion(+), 10 deletions(-)
mm/memcontrol.c +0 -5
index 93f7c76f0ce96..d5257465c9d75 100644
@@ -3339,9 +3339,6 @@ static void memcg_offline_kmem(struct mem_cgroup *memcg)
 		return;
 
 	parent = parent_mem_cgroup(memcg);
-	if (!parent)
-		parent = root_mem_cgroup;
-
 	memcg_reparent_list_lrus(memcg, parent);
 
 	/*
@@ -3632,8 +3629,6 @@ struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
 			break;
 		}
 		memcg = parent_mem_cgroup(memcg);
-		if (!memcg)
-			memcg = root_mem_cgroup;
 	}
 	return memcg;
 }
mm/shrinker.c +1 -1
index 4a93fd433689a..e8e092a2f7f41 100644
@@ -286,14 +286,10 @@ void reparent_shrinker_deferred(struct mem_cgroup *memcg)
 {
 	int nid, index, offset;
 	long nr;
-	struct mem_cgroup *parent;
+	struct mem_cgroup *parent = parent_mem_cgroup(memcg);

mm/shrinker.c void reparent_shrinker_deferred(struct mem_cgroup *memcg) · line 295

Quoted 10 lines
mm/shrinker.c +0 -4
 	struct shrinker_info *child_info, *parent_info;
 	struct shrinker_info_unit *child_unit, *parent_unit;
 
-	parent = parent_mem_cgroup(memcg);
-	if (!parent)
-		parent = root_mem_cgroup;
-
 	/* Prevent from concurrent shrinker_info expand */
 	mutex_lock(&shrinker_mutex);
 	for_each_node(nid) {

LGTM.

Signature · 2 lines
Best regards,
Ridong
Reviewed-by on v1 17/26
#70 lore raw

Re: [PATCH v1 17/26] mm: workingset: prevent lruvec release in workingset_refault()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in workingset_refault().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 18/26
#72 lore raw

Re: [PATCH v1 18/26] mm: zswap: prevent lruvec release in zswap_folio_swapin()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in zswap_folio_swapin().

Quoted 8 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 19/26
#74 lore raw

Re: [PATCH v1 19/26] mm: swap: prevent lruvec release in swap module

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in lru_note_cost_refault() and lru_activate().

nit: the above paragraph looks incorrect.

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Reviewed-by on v1 20/26
#77 lore raw

Re: [PATCH v1 20/26] mm: workingset: prevent lruvec release in workingset_activation()

In reply to Qi Zheng
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in workingset_activation().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Signature · 2 lines
Cheers,
Harry / Hyeonggon
#96 lore raw

Re: [PATCH v1 25/26] mm: memcontrol: eliminate the problem of dying memory cgroup for LRU folios

In reply to Qi Zheng
Quoted 14 lines · Qi Zheng

static void reparent_locks(struct mem_cgroup *src, struct mem_cgroup *dst) {

mm/memcontrol.c +8 -0
+	int nid, nest = 0;
+
 	spin_lock_irq(&objcg_lock);
+	for_each_node(nid) {
+		spin_lock_nested(&mem_cgroup_lruvec(src,
+				 NODE_DATA(nid))->lru_lock, nest++);
+		spin_lock_nested(&mem_cgroup_lruvec(dst,
+				 NODE_DATA(nid))->lru_lock, nest++);
+	}
 }
 

mm/memcontrol.c static void __memcg_reparent_objcgs(struct mem_cgroup *src, · line 246

Quoted 10 lines
mm/memcontrol.c +6 -0
 static void reparent_unlocks(struct mem_cgroup *src, struct mem_cgroup *dst)
 {
+	int nid;
+
+	for_each_node(nid) {
+		spin_unlock(&mem_cgroup_lruvec(dst, NODE_DATA(nid))->lru_lock);
+		spin_unlock(&mem_cgroup_lruvec(src, NODE_DATA(nid))->lru_lock);
+	}
 	spin_unlock_irq(&objcg_lock);
 }

The lock order follows S0→D0→S1→D1→…, and the correct unlock sequence should be Dn→Sn→…→D1→S0

However, the current unlock implementation uses D0→S0→D1→S1→…

I’m not certain whether this unlock order will cause any issues—could this lead to potential problems like deadlocks or lock state inconsistencies?

Signature · 2 lines
Best regards,
Ridong
Reviewed-by on v1 3/26
#8 lore raw

Re: [PATCH v1 03/26] mm: rename unlock_page_lruvec_irq and its variants

In reply to Qi Zheng
Quoted 8 lines · Qi Zheng

From: Muchun Song <[email protected]>

It is inappropriate to use folio_lruvec_lock() variants in conjunction with unlock_page_lruvec() variants, as this involves the inconsistent operation of locking a folio while unlocking a page. To rectify this, the functions unlock_page_lruvec{_irq, _irqrestore} are renamed to lruvec_unlock{_irq,_irqrestore}.

Quoted 4 lines

LGTM.

Signature · 2 lines
Best regards,
Ridong
author reviewer
#48 lore raw

Re: [PATCH v1 07/26] mm: memcontrol: prevent memory cgroup release in get_mem_cgroup_from_folio()

In reply to Harry Yoo
Quoted 41 lines · Harry Yoo
Quoted 10 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in get_mem_cgroup_from_folio().

Quoted 6 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

This patch looks correct to me, so:

with a few side question on current implementation rather than this change...

Quoted 17 lines
  mm/memcontrol.c | 11 ++++++++---
  1 file changed, 8 insertions(+), 3 deletions(-)
mm/memcontrol.c +1 -1
index d484b632c790f..1da3ad77054d3 100644
@@ -973,14 +973,19 @@ struct mem_cgroup *get_mem_cgroup_from_current(void)
   */
  struct mem_cgroup *get_mem_cgroup_from_folio(struct folio *folio)
  {
-	struct mem_cgroup *memcg = folio_memcg(folio);
+	struct mem_cgroup *memcg;
 
  	if (mem_cgroup_disabled())
  		return NULL;
 
Quoted 8 lines

mm/memcontrol.c struct mem_cgroup *get_mem_cgroup_from_current(void) · line 982

Quoted 5 lines
mm/memcontrol.c +3 -1
+	if (!folio_memcg_charged(folio))
+		return root_mem_cgroup;
+
  	rcu_read_lock();
-	if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))

I have no idea why we're already calling rcu_read_lock() when a folio pins the memcg :)

+1, this was introduced by https://github.com/torvalds/linux/commit/f77f0c7514789577125c1b2df145703161736359,
may be some defensive programming.

Quoted 12 lines
Quoted 11 lines
mm/memcontrol.c +4 -1
-		memcg = root_mem_cgroup;
+retry:
+	memcg = folio_memcg(folio);
+	if (unlikely(!css_tryget(&memcg->css)))
+		goto retry;
  	rcu_read_unlock();
  	return memcg;
  }
Signature · 1 line
2.20.1
author reviewer
#57 lore raw

Re: [PATCH v1 11/26] mm: page_io: prevent memory cgroup release in page_io module

In reply to Harry Yoo
Quoted 8 lines · Harry Yoo
Quoted 7 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

Quoted 4 lines
Quoted 2 lines

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in swap_writepage() and

nit: ^ swap_writeout()

will fix it.

Quoted 6 lines
Quoted 6 lines

bio_associate_blkg_from_page().

This serves as a preparatory measure for the reparenting of the LRU pages.

Quoted 6 lines
Quoted 3 lines

---

Looks good to me,

Thanks!

Quoted 1 line
author reviewer
#62 lore raw

Re: [PATCH v1 13/26] mm: mglru: prevent memory cgroup release in mglru

In reply to Harry Yoo
Quoted 28 lines · Harry Yoo
Quoted 27 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. To ensure safety, it will only be appropriate to hold the rcu read lock or acquire a reference to the memory cgroup returned by folio_memcg(), thereby preventing it from being released.

In the current patch, the rcu read lock is employed to safeguard against the release of the memory cgroup in mglru.

This serves as a preparatory measure for the reparenting of the LRU pages.

---
  mm/vmscan.c | 23 +++++++++++++++++------
  1 file changed, 17 insertions(+), 6 deletions(-)
mm/vmscan.c +0 -0
index 660cd40cfddd4..676e6270e5b45 100644
@@ -4279,6 +4288,8 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
 
  	arch_leave_lazy_mmu_mode();
 
Quoted 8 lines

mm/vmscan.c bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw) · line 4295

Quoted 5 lines
mm/vmscan.c +2 -0
+	rcu_read_unlock();
+
  	/* feedback from rmap walkers to page table walkers */
  	if (mm_state && suitable_to_scan(i, young))
  		update_bloom_filter(mm_state, max_seq, pvmw->pmd);

mm_state has the same life cycle as mem_cgroup. So it should be protected by rcu read lock?

You are right. The mm_state is defined as follows:

struct lruvec {
        struct lru_gen_mm_state		mm_state;
};

will fix it in the next version.

Thanks,
Qi

Quoted 1 line
author reviewer
#75 lore raw

Re: [PATCH v1 19/26] mm: swap: prevent lruvec release in swap module

In reply to Harry Yoo
Quoted 8 lines · Harry Yoo
Quoted 7 lines · Qi Zheng

From: Muchun Song <[email protected]>

In the near future, a folio will no longer pin its corresponding memory cgroup. So an lruvec returned by folio_lruvec() could be released without the rcu read lock or a reference to its memory cgroup.

Quoted 5 lines
Quoted 3 lines

In the current patch, the rcu read lock is employed to safeguard against the release of the lruvec in lru_note_cost_refault() and lru_activate().

nit: the above paragraph looks incorrect.

Right, will fix it in the version.

Quoted 10 lines
Quoted 7 lines

This serves as a preparatory measure for the reparenting of the LRU pages.

---

Looks good to me,

Thanks!

Quoted 1 line
author reviewer
#97 lore raw

Re: [PATCH v1 25/26] mm: memcontrol: eliminate the problem of dying memory cgroup for LRU folios

In reply to Chen Ridong
Quoted 30 lines · Chen Ridong
Quoted 14 lines · Qi Zheng
  static void reparent_locks(struct mem_cgroup *src, struct mem_cgroup *dst)
  {
mm/memcontrol.c +8 -0
+	int nid, nest = 0;
+
  	spin_lock_irq(&objcg_lock);
+	for_each_node(nid) {
+		spin_lock_nested(&mem_cgroup_lruvec(src,
+				 NODE_DATA(nid))->lru_lock, nest++);
+		spin_lock_nested(&mem_cgroup_lruvec(dst,
+				 NODE_DATA(nid))->lru_lock, nest++);
+	}
  }
 

mm/memcontrol.c static void __memcg_reparent_objcgs(struct mem_cgroup *src, · line 246

Quoted 10 lines
mm/memcontrol.c +6 -0
  static void reparent_unlocks(struct mem_cgroup *src, struct mem_cgroup *dst)
  {
+	int nid;
+
+	for_each_node(nid) {
+		spin_unlock(&mem_cgroup_lruvec(dst, NODE_DATA(nid))->lru_lock);
+		spin_unlock(&mem_cgroup_lruvec(src, NODE_DATA(nid))->lru_lock);
+	}
  	spin_unlock_irq(&objcg_lock);
  }

The lock order follows S0→D0→S1→D1→…, and the correct unlock sequence should be Dn→Sn→…→D1→S0

Quoted 4 lines

However, the current unlock implementation uses D0→S0→D1→S1→…

I’m not certain whether this unlock order will cause any issues—could this lead to potential problems like deadlocks or lock state inconsistencies?

As long as the order in which the locks are held is consistent, there should be no deadlock problem?

Quoted 1 line
#81 lore raw

Re: [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock

In reply to Qi Zheng
Quoted 7 lines · Qi Zheng

From: Muchun Song <[email protected]>

The following diagram illustrates how to ensure the safety of the folio lruvec lock when LRU folios undergo reparenting.

In the folio_lruvec_lock(folio) function:
```

Quoted 16 lines
    rcu_read_lock();
retry:
    lruvec = folio_lruvec(folio);
    /* There is a possibility of folio reparenting at this point. */
    spin_lock(&lruvec->lru_lock);
    if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
        /*
         * The wrong lruvec lock was acquired, and a retry is required.
         * This is because the folio resides on the parent memcg lruvec
         * list.
         */
        spin_unlock(&lruvec->lru_lock);
        goto retry;
    }

    /* Reaching here indicates that folio_memcg() is stable. */

Does that mean we call rcu_read_unlock() in lruvec_unlock() instead of in folio_lruvec_lock() only to avoid false warnings inside the critical section, and technically calling rcu_read_unlock() right after acquiring the spinlock is fine?

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Quoted 27 lines
```

In the memcg_reparent_objcgs(memcg) function:
```
    spin_lock(&lruvec->lru_lock);
    spin_lock(&lruvec_parent->lru_lock);
    /* Transfer folios from the lruvec list to the parent's. */
    spin_unlock(&lruvec_parent->lru_lock);
    spin_unlock(&lruvec->lru_lock);

```

After acquiring the lruvec lock, it is necessary to verify whether the folio has been reparented. If reparenting has occurred, the new lruvec lock must be reacquired. During the LRU folio reparenting process, the lruvec lock will also be acquired (this will be implemented in a subsequent patch). Therefore, folio_memcg() remains unchanged while the lruvec lock is held.

Given that lruvec_memcg(lruvec) is always equal to folio_memcg(folio) after the lruvec lock is acquired, the lruvec_memcg_debug() check is redundant. Hence, it is removed.

This patch serves as a preparation for the reparenting of LRU folios.

---

#34 lore raw

Re: [PATCH v1 05/26] mm: memcontrol: allocate object cgroup for non-kmem case

In reply to Qi Zheng
Quoted 106 lines · Qi Zheng

From: Muchun Song <[email protected]>

Pagecache pages are charged at allocation time and hold a reference to the original memory cgroup until reclaimed. Depending on memory pressure, page sharing patterns between different cgroups and cgroup creation/destruction rates, many dying memory cgroups can be pinned by pagecache pages, reducing page reclaim efficiency and wasting memory. Converting LRU folios and most other raw memory cgroup pins to the object cgroup direction can fix this long-living problem.

As a result, the objcg infrastructure is no longer solely applicable to the kmem case. In this patch, we extend the scope of the objcg infrastructure beyond the kmem case, enabling LRU folios to reuse it for folio charging purposes.

It should be noted that LRU folios are not accounted for at the root level, yet the folio->memcg_data points to the root_mem_cgroup. Hence, the folio->memcg_data of LRU folios always points to a valid pointer. However, the root_mem_cgroup does not possess an object cgroup. Therefore, we also allocate an object cgroup for the root_mem_cgroup.

---
 mm/memcontrol.c | 51 +++++++++++++++++++++++--------------------------
 1 file changed, 24 insertions(+), 27 deletions(-)
mm/memcontrol.c +7 -26
index d5257465c9d75..2afd7f99ca101 100644
@@ -204,10 +204,10 @@ static struct obj_cgroup *obj_cgroup_alloc(void)
 	return objcg;
 }
 
-static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
-				  struct mem_cgroup *parent)
+static void memcg_reparent_objcgs(struct mem_cgroup *memcg)
 {
 	struct obj_cgroup *objcg, *iter;
+	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
 
 	objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
 
@@ -3302,30 +3302,17 @@ unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
 	return val;
 }
 
-static int memcg_online_kmem(struct mem_cgroup *memcg)
+static void memcg_online_kmem(struct mem_cgroup *memcg)
 {
-	struct obj_cgroup *objcg;
-
 	if (mem_cgroup_kmem_disabled())
-		return 0;
+		return;
 
 	if (unlikely(mem_cgroup_is_root(memcg)))
-		return 0;
-
-	objcg = obj_cgroup_alloc();
-	if (!objcg)
-		return -ENOMEM;
-
-	objcg->memcg = memcg;
-	rcu_assign_pointer(memcg->objcg, objcg);
-	obj_cgroup_get(objcg);
-	memcg->orig_objcg = objcg;
+		return;
 
 	static_branch_enable(&memcg_kmem_online_key);
 
 	memcg->kmemcg_id = memcg->id.id;
-
-	return 0;
 }
 
 static void memcg_offline_kmem(struct mem_cgroup *memcg)
@@ -3340,12 +3327,6 @@ static void memcg_offline_kmem(struct mem_cgroup *memcg)
 
 	parent = parent_mem_cgroup(memcg);
 	memcg_reparent_list_lrus(memcg, parent);
-
-	/*
-	 * Objcg's reparenting must be after list_lru's, make sure list_lru
-	 * helpers won't use parent's list_lru until child is drained.
-	 */
-	memcg_reparent_objcgs(memcg, parent);
 }
 
 #ifdef CONFIG_CGROUP_WRITEBACK
@@ -3862,9 +3843,9 @@ mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
 {
 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
+	struct obj_cgroup *objcg;
 
-	if (memcg_online_kmem(memcg))
-		goto remove_id;
+	memcg_online_kmem(memcg);
 
 	/*
 	 * A memcg must be visible for expand_shrinker_info()
@@ -3874,6 +3855,15 @@ static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
 	if (alloc_shrinker_info(memcg))
 		goto offline_kmem;

mm/memcontrol.c static int mem_cgroup_css_online(struct cgroup_subsys_state *css) · line 3866

Quoted 10 lines
mm/memcontrol.c +9 -0
 
+	objcg = obj_cgroup_alloc();
+	if (!objcg)
+		goto free_shrinker;
+
+	objcg->memcg = memcg;
+	rcu_assign_pointer(memcg->objcg, objcg);
+	obj_cgroup_get(objcg);
+	memcg->orig_objcg = objcg;
+

Will it be better to add a helper function like obj_cgroup_init()?

Quoted 28 lines
mm/memcontrol.c +8 -1
 	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
 		queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
 				   FLUSH_TIME);
@@ -3896,9 +3886,10 @@ static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
 	xa_store(&mem_cgroup_ids, memcg->id.id, memcg, GFP_KERNEL);
 
 	return 0;
+free_shrinker:
+	free_shrinker_info(memcg);
 offline_kmem:
 	memcg_offline_kmem(memcg);
-remove_id:
 	mem_cgroup_id_remove(memcg);
 	return -ENOMEM;
 }
@@ -3916,6 +3907,12 @@ static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
 
 	memcg_offline_kmem(memcg);
 	reparent_deferred_split_queue(memcg);
+	/*
+	 * The reparenting of objcg must be after the reparenting of the
+	 * list_lru and deferred_split_queue above, which ensures that they will
+	 * not mistakenly get the parent list_lru and deferred_split_queue.
+	 */
+	memcg_reparent_objcgs(memcg);
 	reparent_shrinker_deferred(memcg);
 	wb_memcg_offline(memcg);
 	lru_gen_offline_memcg(memcg);
Signature · 2 lines
Best regards,
Ridong
author reviewer
#82 lore raw

Re: [PATCH v1 21/26] mm: memcontrol: prepare for reparenting LRU pages for lruvec lock

In reply to Harry Yoo
Quoted 23 lines · Harry Yoo
Quoted 22 lines · Qi Zheng

From: Muchun Song <[email protected]>

The following diagram illustrates how to ensure the safety of the folio lruvec lock when LRU folios undergo reparenting.

In the folio_lruvec_lock(folio) function:
```

     rcu_read_lock();
retry:
     lruvec = folio_lruvec(folio);
     /* There is a possibility of folio reparenting at this point. */
     spin_lock(&lruvec->lru_lock);
     if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
         /*
          * The wrong lruvec lock was acquired, and a retry is required.
          * This is because the folio resides on the parent memcg lruvec
          * list.
          */
         spin_unlock(&lruvec->lru_lock);
         goto retry;
     }
Quoted 4 lines
Quoted 1 line
     /* Reaching here indicates that folio_memcg() is stable. */

Does that mean we call rcu_read_unlock() in lruvec_unlock() instead of in folio_lruvec_lock() only to avoid false warnings inside the critical

Right.

Quoted 2 lines

section, and technically calling rcu_read_unlock() right after acquiring the spinlock is fine?

Right.

Quoted 1 line
author reviewer
#35 lore raw

Re: [PATCH v1 05/26] mm: memcontrol: allocate object cgroup for non-kmem case

In reply to Chen Ridong
Quoted 110 lines · Chen Ridong
Quoted 107 lines · Qi Zheng

From: Muchun Song <[email protected]>

Pagecache pages are charged at allocation time and hold a reference to the original memory cgroup until reclaimed. Depending on memory pressure, page sharing patterns between different cgroups and cgroup creation/destruction rates, many dying memory cgroups can be pinned by pagecache pages, reducing page reclaim efficiency and wasting memory. Converting LRU folios and most other raw memory cgroup pins to the object cgroup direction can fix this long-living problem.

As a result, the objcg infrastructure is no longer solely applicable to the kmem case. In this patch, we extend the scope of the objcg infrastructure beyond the kmem case, enabling LRU folios to reuse it for folio charging purposes.

It should be noted that LRU folios are not accounted for at the root level, yet the folio->memcg_data points to the root_mem_cgroup. Hence, the folio->memcg_data of LRU folios always points to a valid pointer. However, the root_mem_cgroup does not possess an object cgroup. Therefore, we also allocate an object cgroup for the root_mem_cgroup.

---
  mm/memcontrol.c | 51 +++++++++++++++++++++++--------------------------
  1 file changed, 24 insertions(+), 27 deletions(-)
mm/memcontrol.c +7 -26
index d5257465c9d75..2afd7f99ca101 100644
@@ -204,10 +204,10 @@ static struct obj_cgroup *obj_cgroup_alloc(void)
  	return objcg;
  }
 
-static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
-				  struct mem_cgroup *parent)
+static void memcg_reparent_objcgs(struct mem_cgroup *memcg)
  {
  	struct obj_cgroup *objcg, *iter;
+	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
 
  	objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
 
@@ -3302,30 +3302,17 @@ unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  	return val;
  }
 
-static int memcg_online_kmem(struct mem_cgroup *memcg)
+static void memcg_online_kmem(struct mem_cgroup *memcg)
  {
-	struct obj_cgroup *objcg;
-
  	if (mem_cgroup_kmem_disabled())
-		return 0;
+		return;
 
  	if (unlikely(mem_cgroup_is_root(memcg)))
-		return 0;
-
-	objcg = obj_cgroup_alloc();
-	if (!objcg)
-		return -ENOMEM;
-
-	objcg->memcg = memcg;
-	rcu_assign_pointer(memcg->objcg, objcg);
-	obj_cgroup_get(objcg);
-	memcg->orig_objcg = objcg;
+		return;
 
  	static_branch_enable(&memcg_kmem_online_key);
 
  	memcg->kmemcg_id = memcg->id.id;
-
-	return 0;
  }
 
  static void memcg_offline_kmem(struct mem_cgroup *memcg)
@@ -3340,12 +3327,6 @@ static void memcg_offline_kmem(struct mem_cgroup *memcg)
 
  	parent = parent_mem_cgroup(memcg);
  	memcg_reparent_list_lrus(memcg, parent);
-
-	/*
-	 * Objcg's reparenting must be after list_lru's, make sure list_lru
-	 * helpers won't use parent's list_lru until child is drained.
-	 */
-	memcg_reparent_objcgs(memcg, parent);
  }
 
  #ifdef CONFIG_CGROUP_WRITEBACK
@@ -3862,9 +3843,9 @@ mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
  {
  	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
+	struct obj_cgroup *objcg;
 
-	if (memcg_online_kmem(memcg))
-		goto remove_id;
+	memcg_online_kmem(memcg);
 
  	/*
  	 * A memcg must be visible for expand_shrinker_info()
@@ -3874,6 +3855,15 @@ static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
  	if (alloc_shrinker_info(memcg))
  		goto offline_kmem;
 
Quoted 11 lines

mm/memcontrol.c static int mem_cgroup_css_online(struct cgroup_subsys_state *css) · line 3866

Quoted 9 lines
mm/memcontrol.c +9 -0
+	objcg = obj_cgroup_alloc();
+	if (!objcg)
+		goto free_shrinker;
+
+	objcg->memcg = memcg;
+	rcu_assign_pointer(memcg->objcg, objcg);
+	obj_cgroup_get(objcg);
+	memcg->orig_objcg = objcg;
+

Will it be better to add a helper function like obj_cgroup_init()?

This part is not complicated, and it is only called in this one place, so perhaps there is no need to add a helper function?

Of course, it doesn't matter, I'm fine with either method.

Quoted 30 lines
Quoted 29 lines
mm/memcontrol.c +8 -1
  	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
  		queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
  				   FLUSH_TIME);
@@ -3896,9 +3886,10 @@ static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
  	xa_store(&mem_cgroup_ids, memcg->id.id, memcg, GFP_KERNEL);
 
  	return 0;
+free_shrinker:
+	free_shrinker_info(memcg);
  offline_kmem:
  	memcg_offline_kmem(memcg);
-remove_id:
  	mem_cgroup_id_remove(memcg);
  	return -ENOMEM;
  }
@@ -3916,6 +3907,12 @@ static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
 
  	memcg_offline_kmem(memcg);
  	reparent_deferred_split_queue(memcg);
+	/*
+	 * The reparenting of objcg must be after the reparenting of the
+	 * list_lru and deferred_split_queue above, which ensures that they will
+	 * not mistakenly get the parent list_lru and deferred_split_queue.
+	 */
+	memcg_reparent_objcgs(memcg);
  	reparent_shrinker_deferred(memcg);
  	wb_memcg_offline(memcg);
  	lru_gen_offline_memcg(memcg);
Reviewed-by on v1 22/26
#84 lore raw

Re: [PATCH v1 22/26] mm: vmscan: prepare for reparenting traditional LRU folios

In reply to Qi Zheng
Quoted 8 lines · Qi Zheng

From: Qi Zheng <[email protected]>

To reslove the dying memcg issue, we need to reparent LRU folios of child memcg to its parent memcg. For traditional LRU list, each lruvec of every memcg comprises four LRU lists. Due to the symmetry of the LRU lists, it is feasible to transfer the LRU lists from a memcg to its parent memcg during the reparenting process.

Quoted 5 lines

This commit implements the specific function, which will be used during the reparenting process.

---

I tried my best to find flaws or pathological cases affecting the memory manager, but I couldn't spot anything, so:

#86 lore raw

Re: [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios

In reply to Qi Zheng
Quoted 83 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

To prepare for the above work, this commit implements the specific functions, which will be used during reparenting.

---
 include/linux/mmzone.h | 16 ++++++++
 mm/vmscan.c            | 86 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 102 insertions(+)
mm/vmscan.c +27 -0
index 7aa8e1472d10d..3ee7fb96b8aeb 100644
@@ -4468,6 +4468,92 @@ void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
 		lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
 }
 
+bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
+				return false;
+		}
+	}
+
+	return true;
+}
+
+/*
+ * We need to ensure that the folios of child memcg can be reparented to the
+ * same gen of the parent memcg, so the gens of the parent memcg needed be
+ * incremented to the MAX_NR_GENS before reparenting.
+ */
+void max_lru_gen_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4507

Quoted 10 lines
mm/vmscan.c +10 -0
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			while (get_nr_gens(lruvec, type) < MAX_NR_GENS) {
+				DEFINE_MAX_SEQ(lruvec);
+
+				inc_max_seq(lruvec, max_seq, mem_cgroup_swappiness(memcg));
+				cond_resched();
+			}

To best of my knowledge this looks functionally correct.

Quoted 7 lines
mm/vmscan.c +7 -0
+		}
+	}
+}
+
+static void __lru_gen_reparent_memcg(struct lruvec *src_lruvec, struct lruvec *dst_lruvec,
+				     int zone, int type)
+{

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4524

Quoted 10 lines
mm/vmscan.c +10 -0
+	struct lru_gen_folio *src_lrugen, *dst_lrugen;
+	enum lru_list lru = type * LRU_INACTIVE_FILE;
+	int i;
+
+	src_lrugen = &src_lruvec->lrugen;
+	dst_lrugen = &dst_lruvec->lrugen;
+
+	for (i = 0; i < get_nr_gens(src_lruvec, type); i++) {
+		int gen = lru_gen_from_seq(src_lrugen->max_seq - i);
+		int nr_pages = src_lrugen->nr_pages[gen][type][zone];

nr_pages should be long type since nothing prevents us from reparenting more than 2 billions of pages :)

Otherwise looks correct to me.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
Quoted 38 lines
mm/vmscan.c +32 -0
+		int src_lru_active = lru_gen_is_active(src_lruvec, gen) ? LRU_ACTIVE : 0;
+		int dst_lru_active = lru_gen_is_active(dst_lruvec, gen) ? LRU_ACTIVE : 0;
+
+		list_splice_tail_init(&src_lrugen->folios[gen][type][zone],
+				      &dst_lrugen->folios[gen][type][zone]);
+
+		WRITE_ONCE(src_lrugen->nr_pages[gen][type][zone], 0);
+		WRITE_ONCE(dst_lrugen->nr_pages[gen][type][zone],
+			   dst_lrugen->nr_pages[gen][type][zone] + nr_pages);
+
+		__update_lru_size(src_lruvec, lru + src_lru_active, zone, -nr_pages);
+		__update_lru_size(dst_lruvec, lru + dst_lru_active, zone, nr_pages);
+	}
+}
+
+void lru_gen_reparent_memcg(struct mem_cgroup *src, struct mem_cgroup *dst)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *src_lruvec, *dst_lruvec;
+		int type, zone;
+
+		src_lruvec = get_lruvec(src, nid);
+		dst_lruvec = get_lruvec(dst, nid);
+
+		for (zone = 0; zone < MAX_NR_ZONES; zone++)
+			for (type = 0; type < ANON_AND_FILE; type++)
+				__lru_gen_reparent_memcg(src_lruvec, dst_lruvec, zone, type);
+	}
+}
+
 #endif /* CONFIG_MEMCG */
 
 /******************************************************************************
Signature · 1 line
2.20.1
author reviewer
#87 lore raw

Re: [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios

Quoted 109 lines · Harry Yoo
Quoted 83 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

To prepare for the above work, this commit implements the specific functions, which will be used during reparenting.

---
  include/linux/mmzone.h | 16 ++++++++
  mm/vmscan.c            | 86 ++++++++++++++++++++++++++++++++++++++++++
  2 files changed, 102 insertions(+)
mm/vmscan.c +27 -0
index 7aa8e1472d10d..3ee7fb96b8aeb 100644
@@ -4468,6 +4468,92 @@ void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
  		lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
  }
 
+bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
+				return false;
+		}
+	}
+
+	return true;
+}
+
+/*
+ * We need to ensure that the folios of child memcg can be reparented to the
+ * same gen of the parent memcg, so the gens of the parent memcg needed be
+ * incremented to the MAX_NR_GENS before reparenting.
+ */
+void max_lru_gen_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4507

Quoted 10 lines
mm/vmscan.c +10 -0
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			while (get_nr_gens(lruvec, type) < MAX_NR_GENS) {
+				DEFINE_MAX_SEQ(lruvec);
+
+				inc_max_seq(lruvec, max_seq, mem_cgroup_swappiness(memcg));
+				cond_resched();
+			}

To best of my knowledge this looks functionally correct.

Quoted 12 lines
mm/vmscan.c +12 -0
+		}
+	}
+}
+
+static void __lru_gen_reparent_memcg(struct lruvec *src_lruvec, struct lruvec *dst_lruvec,
+				     int zone, int type)
+{
+	struct lru_gen_folio *src_lrugen, *dst_lrugen;
+	enum lru_list lru = type * LRU_INACTIVE_FILE;
+	int i;
+
+	src_lrugen = &src_lruvec->lrugen;
Quoted 8 lines

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4524

Quoted 5 lines
mm/vmscan.c +5 -0
+	dst_lrugen = &dst_lruvec->lrugen;
+
+	for (i = 0; i < get_nr_gens(src_lruvec, type); i++) {
+		int gen = lru_gen_from_seq(src_lrugen->max_seq - i);
+		int nr_pages = src_lrugen->nr_pages[gen][type][zone];

nr_pages should be long type since nothing prevents us from reparenting more than 2 billions of pages :)

Right. The lru_gen_folio.nr_pages is long type, I don't know how I ended up writing it as an int type.

Will fix it in the next version.

Quoted 2 lines

Otherwise looks correct to me.

Thanks!

Quoted 1 line
#88 lore raw

Re: [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios

In reply to Qi Zheng
Quoted 76 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

To prepare for the above work, this commit implements the specific functions, which will be used during reparenting.

---
 include/linux/mmzone.h | 16 ++++++++
 mm/vmscan.c            | 86 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 102 insertions(+)
mm/vmscan.c +20 -0
index 7aa8e1472d10d..3ee7fb96b8aeb 100644
@@ -4468,6 +4468,92 @@ void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
 		lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
 }
 
+bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
+				return false;
+		}
+	}
+
+	return true;
+}
+
+/*
+ * We need to ensure that the folios of child memcg can be reparented to the
+ * same gen of the parent memcg, so the gens of the parent memcg needed be

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4500

Quoted 10 lines
mm/vmscan.c +10 -0
+ * incremented to the MAX_NR_GENS before reparenting.
+ */
+void max_lru_gen_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+

I was testing this series and observed two warnings...

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4506

Quoted 6 lines
mm/vmscan.c +6 -0
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			while (get_nr_gens(lruvec, type) < MAX_NR_GENS) {
+				DEFINE_MAX_SEQ(lruvec);
+
+				inc_max_seq(lruvec, max_seq, mem_cgroup_swappiness(memcg));
+				cond_resched();

Warning 1) Here we increment max_seq but we skip updating mm_state->seq. (try_to_inc_max_seq() iterates the mm list and update mm_state->seq after an iteration, but since we directly call inc_max_seq(), we don't update it)

When mm_state->seq is more than one generation behind walk->seq, a warning is triggered in iterate_mm_list():

        VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);

Warning 2) In try_to_inc_max_seq(), the last walker of mm list is supposed to succeed to increment max_seq by calling inc_max_seq():

        if (success) {                                                          
                 success = inc_max_seq(lruvec, seq, swappiness);                 
                 WARN_ON_ONCE(!success);                                         
         }   

But with this patch it may observe the max_seq is already advanced due to reparenting and thus inc_max_seq() returns false, triggering the warning.

I'm learning MGLRU internals to see whether we can simply remove the warnings or if we need to do something to advance max_seq without actually iterating over the mm list.

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author reviewer
#89 lore raw

Re: [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios

Quoted 109 lines · Harry Yoo
Quoted 76 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

To prepare for the above work, this commit implements the specific functions, which will be used during reparenting.

---
  include/linux/mmzone.h | 16 ++++++++
  mm/vmscan.c            | 86 ++++++++++++++++++++++++++++++++++++++++++
  2 files changed, 102 insertions(+)
mm/vmscan.c +20 -0
index 7aa8e1472d10d..3ee7fb96b8aeb 100644
@@ -4468,6 +4468,92 @@ void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
  		lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
  }
 
+bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
+				return false;
+		}
+	}
+
+	return true;
+}
+
+/*
+ * We need to ensure that the folios of child memcg can be reparented to the
+ * same gen of the parent memcg, so the gens of the parent memcg needed be

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4500

Quoted 10 lines
mm/vmscan.c +10 -0
+ * incremented to the MAX_NR_GENS before reparenting.
+ */
+void max_lru_gen_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+

I was testing this series and observed two warnings...

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4506

Quoted 6 lines
mm/vmscan.c +6 -0
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			while (get_nr_gens(lruvec, type) < MAX_NR_GENS) {
+				DEFINE_MAX_SEQ(lruvec);
+
+				inc_max_seq(lruvec, max_seq, mem_cgroup_swappiness(memcg));
+				cond_resched();

Warning 1) Here we increment max_seq but we skip updating mm_state->seq. (try_to_inc_max_seq() iterates the mm list and update mm_state->seq after an iteration, but since we directly call inc_max_seq(), we don't update it)

When mm_state->seq is more than one generation behind walk->seq, a warning is triggered in iterate_mm_list():

         VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);

Warning 2) In try_to_inc_max_seq(), the last walker of mm list is supposed to succeed to increment max_seq by calling inc_max_seq():

Quoted 7 lines
         if (success) {
                  success = inc_max_seq(lruvec, seq, swappiness);
                  WARN_ON_ONCE(!success);
          }

But with this patch it may observe the max_seq is already advanced due to reparenting and thus inc_max_seq() returns false, triggering the warning.

Got it. Thanks for testing and reporting!

Quoted 4 lines

I'm learning MGLRU internals to see whether we can simply remove the warnings or if we need to do something to advance max_seq without actually iterating over the mm list.

Thanks! I will also check on this.

Quoted 1 line
author reviewer
#90 lore raw

Re: [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios

In reply to Harry Yoo
Quoted 101 lines · Harry Yoo
Quoted 76 lines · Qi Zheng

From: Qi Zheng <[email protected]>

Similar to traditional LRU folios, in order to solve the dying memcg problem, we also need to reparenting MGLRU folios to the parent memcg when memcg offline.

However, there are the following challenges:

1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the number of generations of the parent and child memcg may be different, so we cannot simply transfer MGLRU folios in the child memcg to the parent memcg as we did for traditional LRU folios.
2. The generation information is stored in folio->flags, but we cannot traverse these folios while holding the lru lock, otherwise it may cause softlockup.
3. In walk_update_folio(), the gen of folio and corresponding lru size may be updated, but the folio is not immediately moved to the corresponding lru list. Therefore, there may be folios of different generations on an LRU list.
4. In lru_gen_del_folio(), the generation to which the folio belongs is found based on the generation information in folio->flags, and the corresponding LRU size will be updated. Therefore, we need to update the lru size correctly during reparenting, otherwise the lru size may be updated incorrectly in lru_gen_del_folio().

Finally, this patch chose a compromise method, which is to splice the lru list in the child memcg to the lru list of the same generation in the parent memcg during reparenting. And in order to ensure that the parent memcg has the same generation, we need to increase the generations in the parent memcg to the MAX_NR_GENS before reparenting.

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

To prepare for the above work, this commit implements the specific functions, which will be used during reparenting.

---
  include/linux/mmzone.h | 16 ++++++++
  mm/vmscan.c            | 86 ++++++++++++++++++++++++++++++++++++++++++
  2 files changed, 102 insertions(+)
mm/vmscan.c +20 -0
index 7aa8e1472d10d..3ee7fb96b8aeb 100644
@@ -4468,6 +4468,92 @@ void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
  		lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
  }
 
+bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
+				return false;
+		}
+	}
+
+	return true;
+}
+
+/*
+ * We need to ensure that the folios of child memcg can be reparented to the
+ * same gen of the parent memcg, so the gens of the parent memcg needed be

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4500

Quoted 10 lines
mm/vmscan.c +10 -0
+ * incremented to the MAX_NR_GENS before reparenting.
+ */
+void max_lru_gen_memcg(struct mem_cgroup *memcg)
+{
+	int nid;
+
+	for_each_node(nid) {
+		struct lruvec *lruvec = get_lruvec(memcg, nid);
+		int type;
+

I was testing this series and observed two warnings...

mm/vmscan.c void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) · line 4506

Quoted 6 lines
mm/vmscan.c +6 -0
+		for (type = 0; type < ANON_AND_FILE; type++) {
+			while (get_nr_gens(lruvec, type) < MAX_NR_GENS) {
+				DEFINE_MAX_SEQ(lruvec);
+
+				inc_max_seq(lruvec, max_seq, mem_cgroup_swappiness(memcg));
+				cond_resched();

Warning 1) Here we increment max_seq but we skip updating mm_state->seq. (try_to_inc_max_seq() iterates the mm list and update mm_state->seq after an iteration, but since we directly call inc_max_seq(), we don't update it)

Quoted 4 lines

When mm_state->seq is more than one generation behind walk->seq, a warning is triggered in iterate_mm_list():

         VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);

The mm_state->seq is just to record the completion of a full traversal of mm_list. If we simply delete this warning, it may cause this judgment in iterate_mm_list to become invalid:

        if (walk->seq <= mm_state->seq)
		goto done;

So it seems we can manually increase mm_state->seq during reparenting to avoid this warning.

However, we cannot directly call iterate_mm_list_nowalk() because we do not want to reset mm_state->head and mm_state->tail to NULL. Otherwise, we wouldn't be able to continue iterating over the mm_list.

Quoted 11 lines

Warning 2) In try_to_inc_max_seq(), the last walker of mm list is supposed to succeed to increment max_seq by calling inc_max_seq():

         if (success) {
                  success = inc_max_seq(lruvec, seq, swappiness);
                  WARN_ON_ONCE(!success);
          }

But with this patch it may observe the max_seq is already advanced due to reparenting and thus inc_max_seq() returns false, triggering the warning.

After we correct the warning above, we will satisfy this condition in iterate_mm_list():

        if (walk->seq <= mm_state->seq)
		goto done;

thus returning false, and avoiding triggering this warning.

Quoted 4 lines

I'm learning MGLRU internals to see whether we can simply remove the warnings or if we need to do something to advance max_seq without actually iterating over the mm list.

So IIUC, we can simple increase mm_state->seq during reparenting to fix these warnings.

Quoted 1 line
reviewer
#91 lore raw

Re: [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios

Quoted 13 lines · Qi Zheng
Quoted 8 lines

Warning 1) Here we increment max_seq but we skip updating mm_state->seq. (try_to_inc_max_seq() iterates the mm list and update mm_state->seq after an iteration, but since we directly call inc_max_seq(), we don't update it)

When mm_state->seq is more than one generation behind walk->seq, a warning is triggered in iterate_mm_list():

         VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);

The mm_state->seq is just to record the completion of a full traversal of mm_list. If we simply delete this warning, it may cause this judgment in iterate_mm_list to become invalid:

Quoted 5 lines
         if (walk->seq <= mm_state->seq)
                goto done;

So it seems we can manually increase mm_state->seq during reparenting to avoid this warning.

Agreed, don't get rid of the warning as this check is supposed to make stale walkers exit early.

Quoted 5 lines

However, we cannot directly call iterate_mm_list_nowalk() because we do not want to reset mm_state->head and mm_state->tail to NULL. Otherwise, we wouldn't be able to continue iterating over the mm_list.

From the original posting:

Quoted 5 lines

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

One way to solve this is to map generations based on lrugen->timestamp, but of course this runs into the reading folio->flags issue you described. I think the current method is a good compromise, but the splicing of generations doesn't much make semantic sense. It would be good to leave a comment somewhere in __lru_gen_reparent_memcg to note this weirdness.

author reviewer
#92 lore raw

Re: [PATCH v1 23/26] mm: vmscan: prepare for reparenting MGLRU folios

Quoted 14 lines · Yuanchu Xie
Quoted 13 lines · Qi Zheng
Quoted 8 lines

Warning 1) Here we increment max_seq but we skip updating mm_state->seq. (try_to_inc_max_seq() iterates the mm list and update mm_state->seq after an iteration, but since we directly call inc_max_seq(), we don't update it)

When mm_state->seq is more than one generation behind walk->seq, a warning is triggered in iterate_mm_list():

          VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);

The mm_state->seq is just to record the completion of a full traversal of mm_list. If we simply delete this warning, it may cause this judgment in iterate_mm_list to become invalid:

Quoted 7 lines
Quoted 5 lines
          if (walk->seq <= mm_state->seq)
                 goto done;

So it seems we can manually increase mm_state->seq during reparenting to avoid this warning.

Agreed, don't get rid of the warning as this check is supposed to make stale walkers exit early.

OK, will incease mm_state->seq during reparenting in the next version.

Quoted 13 lines
Quoted 6 lines

However, we cannot directly call iterate_mm_list_nowalk() because we do not want to reset mm_state->head and mm_state->tail to NULL. Otherwise, we wouldn't be able to continue iterating over the mm_list.

From the original posting:

Quoted 5 lines

Of course, the same generation has different meanings in the parent and child memcg, this will cause confusion in the hot and cold information of folios. But other than that, this method is simple enough, the lru size is correct, and there is no need to consider some concurrency issues (such as lru_gen_del_folio()).

Quoted 6 lines

One way to solve this is to map generations based on lrugen->timestamp, but of course this runs into the reading folio->flags issue you described. I think the current method is a good compromise, but the splicing of generations doesn't much make semantic sense. It would be good to leave a comment somewhere in __lru_gen_reparent_memcg to note this weirdness.

OK, will do.

Thanks!