Skip to contentSkip to conversation

memcg: switch lruvec stats to rstat

PATCH Superseded Shakeel Butt 4 participants 8 messages Jun 15, 2021 – Jul 5, 2021

Subsystems (5)

v2 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/2 memcg: switch lruvec stats to rstat

The commit 2d146aa3aa84 ("mm: memcontrol: switch to rstat") but skipped the conversion of the lruvec stats as such stats are read in the performance critical code paths and flushing stats may have impacted the performances of the applications. This patch converts the lruvec stats to rstat and later patch adds the periodic flushing of the stats and thus remove the need to synchronously flushing the stats in the performance critical code paths.

The rstat conversion comes with the price i.e. memory cost. Effectively this patch reverts the savings done by the commit f3344adf38bd ("mm:
memcontrol: optimize per-lruvec stats counter memory usage"). However this cost is justified due to negative impact of the inaccurate lruvec stats on many heuristics. One such case is reported in [1].

The memory reclaim code is filled with plethora of heuristics and many of those heuristics reads the lruvec stats. So, inaccurate stats can make such heuristics ineffective. [1] reports the impact of inaccurate lruvec stats on the "cache trim mode" heuristic. Inaccurate lruvec stats can impact the deactivation and aging anon heuristics as well.

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

---
Changes since v1:
- no changes

 include/linux/memcontrol.h |  42 +++++++------
 mm/memcontrol.c            | 118 +++++++++++++------------------------
 2 files changed, 60 insertions(+), 100 deletions(-)
include/linux/memcontrol.h +20 -22
index bfe5c486f4ad..0bfa0409af22 100644
@@ -105,14 +105,6 @@ struct mem_cgroup_reclaim_iter {
 	unsigned int generation;
 };
 
-struct lruvec_stat {
-	long count[NR_VM_NODE_STAT_ITEMS];
-};
-
-struct batched_lruvec_stat {
-	s32 count[NR_VM_NODE_STAT_ITEMS];
-};
-
 /*
  * Bitmap and deferred work of shrinker::id corresponding to memcg-aware
  * shrinkers, which have elements charged to this memcg.
@@ -123,24 +115,30 @@ struct shrinker_info {
 	unsigned long *map;
 };
 
+struct lruvec_stats_percpu {
+	/* Local (CPU and cgroup) state */
+	long state[NR_VM_NODE_STAT_ITEMS];
+
+	/* Delta calculation for lockless upward propagation */
+	long state_prev[NR_VM_NODE_STAT_ITEMS];
+};
+
+struct lruvec_stats {
+	/* Aggregated (CPU and subtree) state */
+	long state[NR_VM_NODE_STAT_ITEMS];
+
+	/* Pending child counts during tree propagation */
+	long state_pending[NR_VM_NODE_STAT_ITEMS];
+};
+
 /*
  * per-node information in memory controller.
  */
 struct mem_cgroup_per_node {
 	struct lruvec		lruvec;
 
-	/*
-	 * Legacy local VM stats. This should be struct lruvec_stat and
-	 * cannot be optimized to struct batched_lruvec_stat. Because
-	 * the threshold of the lruvec_stat_cpu can be as big as
-	 * MEMCG_CHARGE_BATCH * PAGE_SIZE. It can fit into s32. But this
-	 * filed has no upper limit.
-	 */
-	struct lruvec_stat __percpu *lruvec_stat_local;
-
-	/* Subtree VM stats (batched updates) */
-	struct batched_lruvec_stat __percpu *lruvec_stat_cpu;
-	atomic_long_t		lruvec_stat[NR_VM_NODE_STAT_ITEMS];
+	struct lruvec_stats_percpu __percpu	*lruvec_stats_percpu;
+	struct lruvec_stats			lruvec_stats;
 
 	unsigned long		lru_zone_size[MAX_NR_ZONES][NR_LRU_LISTS];
 
@@ -965,7 +963,7 @@ static inline unsigned long lruvec_page_state(struct lruvec *lruvec,
 		return node_page_state(lruvec_pgdat(lruvec), idx);
 
 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
-	x = atomic_long_read(&pn->lruvec_stat[idx]);
+	x = READ_ONCE(pn->lruvec_stats.state[idx]);
 #ifdef CONFIG_SMP
 	if (x < 0)
 		x = 0;
@@ -985,7 +983,7 @@ static inline unsigned long lruvec_page_state_local(struct lruvec *lruvec,
 
 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
 	for_each_possible_cpu(cpu)
-		x += per_cpu(pn->lruvec_stat_local->count[idx], cpu);
+		x += per_cpu(pn->lruvec_stats_percpu->state[idx], cpu);
 #ifdef CONFIG_SMP
 	if (x < 0)
 		x = 0;
mm/memcontrol.c +40 -78

185 lines not on this page · raw message

Signature · 1 line
2.32.0.272.g935e593368-goog
#1 lore raw

PATCH v2 2/2 memcg: periodically flush the memcg stats

At the moment memcg stats are read in four contexts:

1. memcg stat user interfaces
2. dirty throttling
3. page fault
4. memory reclaim

Currently the kernel flushes the stats for first two cases. Flushing the stats for remaining two casese may have performance impact. Always flushing the memcg stats on the page fault code path may negatively impacts the performance of the applications. In addition flushing in the memory reclaim code path, though treated as slowpath, can become the source of contention for the global lock taken for stat flushing because when system or memcg is under memory pressure, many tasks may enter the reclaim path.

Instead of synchronously flushing the stats, this patch adds support of asynchronous periodic flushing of the memcg stats. For now the flushing period is hardcoded to 2*HZ but that can be changed later through maybe sysctl if need arise.

This patch does add the explicit flushing in the kswapd thread as the number of kswapd threads which corresponds to the number of nodes on realistic machines are usually low.

---
Changes since v1:
- use system_unbound_wq for flushing the memcg stats

 include/linux/memcontrol.h | 10 ++++++++++
 mm/memcontrol.c            | 14 ++++++++++++++
 mm/vmscan.c                |  6 ++++++
 3 files changed, 30 insertions(+)
include/linux/memcontrol.h +10 -0
index 0bfa0409af22..f34214382a1c 100644
@@ -991,6 +991,12 @@ static inline unsigned long lruvec_page_state_local(struct lruvec *lruvec,
 	return x;
 }
 
+static inline void mem_cgroup_flush_stats(void)
+{
+	if (!mem_cgroup_disabled())
+		cgroup_rstat_flush(root_mem_cgroup->css.cgroup);
+}
+
 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
 			      int val);
 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val);
@@ -1400,6 +1406,10 @@ static inline unsigned long lruvec_page_state_local(struct lruvec *lruvec,
 	return node_page_state(lruvec_pgdat(lruvec), idx);
 }
 
+static inline void mem_cgroup_flush_stats(void)
+{
+}
+
 static inline void __mod_memcg_lruvec_state(struct lruvec *lruvec,
 					    enum node_stat_item idx, int val)
 {
mm/memcontrol.c +14 -0
index 6e24fd8c5301..5910658bac84 100644
@@ -97,6 +97,10 @@ bool cgroup_memory_noswap __ro_after_init;
 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
 #endif
 
+/* Periodically flush memcg and lruvec stats. */
+static void flush_memcg_stats(struct work_struct *w);
+static DECLARE_DEFERRABLE_WORK(stats_flush, flush_memcg_stats);
+
 /* Whether legacy memory+swap accounting is active */
 static bool do_memsw_account(void)
 {
@@ -5248,6 +5252,10 @@ static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
 	/* Online state pins memcg ID, memcg ID pins CSS */
 	refcount_set(&memcg->id.ref, 1);
 	css_get(css);
+
+	if (unlikely(mem_cgroup_is_root(memcg)))
+		queue_delayed_work(system_unbound_wq, &stats_flush, 2UL*HZ);
+
 	return 0;
 }
 
@@ -5339,6 +5347,12 @@ static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
 	memcg_wb_domain_size_changed(memcg);
 }
 
+static void flush_memcg_stats(struct work_struct *w)
+{
+	cgroup_rstat_flush(root_mem_cgroup->css.cgroup);
+	queue_delayed_work(system_unbound_wq, &stats_flush, 2UL*HZ);
+}
+
 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
 {
 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
mm/vmscan.c +6 -0
index a7602f71ec04..7bf9a4241dd9 100644
@@ -3893,6 +3893,12 @@ static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
 		sc.may_swap = !nr_boost_reclaim;
 
+		/*
+		 * Flush the memory cgroup stats, so that we read accurate
+		 * per-memcg lruvec stats for heuristics later.
+		 */
+		mem_cgroup_flush_stats();
+
 		/*
 		 * Do some background aging of the anon list, to give
 		 * pages a chance to be referenced before reclaiming. All
Signature · 1 line
2.32.0.272.g935e593368-goog
maintainer
#2 lore raw

Re: [PATCH v2 2/2] memcg: periodically flush the memcg stats

Hey Shakeel,

Quoted 16 lines · Shakeel Butt

At the moment memcg stats are read in four contexts:

1. memcg stat user interfaces
2. dirty throttling
3. page fault
4. memory reclaim

Currently the kernel flushes the stats for first two cases. Flushing the stats for remaining two casese may have performance impact. Always flushing the memcg stats on the page fault code path may negatively impacts the performance of the applications. In addition flushing in the memory reclaim code path, though treated as slowpath, can become the source of contention for the global lock taken for stat flushing because when system or memcg is under memory pressure, many tasks may enter the reclaim path.

Quoted 4 lines

Instead of synchronously flushing the stats, this patch adds support of asynchronous periodic flushing of the memcg stats. For now the flushing period is hardcoded to 2*HZ but that can be changed later through maybe sysctl if need arise.

I'm concerned that quite a lot can happen in terms of reclaim and page faults in 2 seconds. It's conceivable that the error of a fixed 2s flush can actually exceed the error of a fixed percpu batch size.

The way the global vmstat implementation manages error is doing both:
ratelimiting and timelimiting. It uses percpu batching to limit the error when it gets busy, and periodic flushing to limit the length of time consumers of those stats could be stuck trying to reach a state that the batching would otherwise prevent from being reflected.

Maybe we can use a combination of ratelimiting and timelimiting too?

We shouldn't flush on every fault, but what about a percpu ratelimit that would at least bound the error to NR_CPU instead of nr_cgroups?

For thundering herds during reclaim: as long as they all tried to flush from the root, only one of them would actually need to do the work, and we could use trylock. If the lock is already taken, you can move on knowing that somebody is already doing the shared flush work.

#3 lore raw

Re: [PATCH v2 2/2] memcg: periodically flush the memcg stats

Quoted 20 lines · Johannes Weiner

Hey Shakeel,

Quoted 16 lines · Shakeel Butt

At the moment memcg stats are read in four contexts:

1. memcg stat user interfaces
2. dirty throttling
3. page fault
4. memory reclaim

Currently the kernel flushes the stats for first two cases. Flushing the stats for remaining two casese may have performance impact. Always flushing the memcg stats on the page fault code path may negatively impacts the performance of the applications. In addition flushing in the memory reclaim code path, though treated as slowpath, can become the source of contention for the global lock taken for stat flushing because when system or memcg is under memory pressure, many tasks may enter the reclaim path.

Quoted 9 lines
Quoted 4 lines

Instead of synchronously flushing the stats, this patch adds support of asynchronous periodic flushing of the memcg stats. For now the flushing period is hardcoded to 2*HZ but that can be changed later through maybe sysctl if need arise.

I'm concerned that quite a lot can happen in terms of reclaim and page faults in 2 seconds. It's conceivable that the error of a fixed 2s flush can actually exceed the error of a fixed percpu batch size.

Yes, that is possible.

Quoted 11 lines

The way the global vmstat implementation manages error is doing both:
ratelimiting and timelimiting. It uses percpu batching to limit the error when it gets busy, and periodic flushing to limit the length of time consumers of those stats could be stuck trying to reach a state that the batching would otherwise prevent from being reflected.

Maybe we can use a combination of ratelimiting and timelimiting too?

We shouldn't flush on every fault, but what about a percpu ratelimit that would at least bound the error to NR_CPU instead of nr_cgroups?

Couple questions here:

First, to convert the error bound to NR_CPU from nr_cgroups, I think we have to move from (delta > threshold) comparison to (num_update_events > threshold). Previously an increment event followed by decrement would keep the delta to 0 (or same) but after this change num_update_events would be 2. Is that ok?

Second, do we want to synchronously flush the stats when we cross the threshold on update or asynchronously by queuing the flush with zero delay?

Quoted 4 lines

For thundering herds during reclaim: as long as they all tried to flush from the root, only one of them would actually need to do the work, and we could use trylock. If the lock is already taken, you can move on knowing that somebody is already doing the shared flush work.

Yes, this makes sense.

maintainer
#4 lore raw

Re: [PATCH v2 2/2] memcg: periodically flush the memcg stats

Hey Shakeel,

Sorry about the delay.

Quoted 13 lines · Shakeel Butt
Quoted 11 lines · Johannes Weiner

The way the global vmstat implementation manages error is doing both:
ratelimiting and timelimiting. It uses percpu batching to limit the error when it gets busy, and periodic flushing to limit the length of time consumers of those stats could be stuck trying to reach a state that the batching would otherwise prevent from being reflected.

Maybe we can use a combination of ratelimiting and timelimiting too?

We shouldn't flush on every fault, but what about a percpu ratelimit that would at least bound the error to NR_CPU instead of nr_cgroups?

Quoted 7 lines

Couple questions here:

First, to convert the error bound to NR_CPU from nr_cgroups, I think we have to move from (delta > threshold) comparison to (num_update_events > threshold). Previously an increment event followed by decrement would keep the delta to 0 (or same) but after this change num_update_events would be 2. Is that ok?

Yeah, I think that's fine. Or at least I can't think of a real-world application that would inc and dec the same counter over and over and so would do much better with delta spilling over event ratelimiting.

And the ratelimiting should already ensure by itself that the cost is at least acceptable when continuously updating and reading counters.

Quoted 3 lines

Second, do we want to synchronously flush the stats when we cross the threshold on update or asynchronously by queuing the flush with zero delay?

I think flushing by worker is better because we can see updates from all sorts of contexts with all sorts of locks held. That could make for some difficult dependencies and latency sources when serializing those on cgroup_rstat_lock.

maintainer
#5 lore raw

Re: [PATCH v2 2/2] memcg: periodically flush the memcg stats

In reply to Shakeel Butt

Hello Shakeel.

Quoted 6 lines · Shakeel Butt

At the moment memcg stats are read in four contexts:

1. memcg stat user interfaces
2. dirty throttling
3. page fault
4. memory reclaim

Sorry for being dense or ignorant -- what do you refer to with the point no. 3 (memcg stats reader during page fault)?

Thanks,
Michal

#6 lore raw

Re: [PATCH v2 2/2] memcg: periodically flush the memcg stats

Quoted 6 lines · Michal Koutný

Hello Shakeel.

Quoted 2 lines · Shakeel Butt

At the moment memcg stats are read in four contexts:

Quoted 8 lines
Quoted 4 lines

1. memcg stat user interfaces
2. dirty throttling
3. page fault
4. memory reclaim

Sorry for being dense or ignorant -- what do you refer to with the point no. 3 (memcg stats reader during page fault)?

Yes, specifically workingset_refault() which reads lruvec stats directly through lruvec_page_state and indirectly through lru_note_cost_page.

#7 lore raw
In reply to Shakeel Butt

Hi, Shakeel,

Quoted 14 lines · Shakeel Butt

The commit 2d146aa3aa84 ("mm: memcontrol: switch to rstat") but skipped the conversion of the lruvec stats as such stats are read in the performance critical code paths and flushing stats may have impacted the performances of the applications. This patch converts the lruvec stats to rstat and later patch adds the periodic flushing of the stats and thus remove the need to synchronously flushing the stats in the performance critical code paths.

The rstat conversion comes with the price i.e. memory cost. Effectively this patch reverts the savings done by the commit f3344adf38bd ("mm:
memcontrol: optimize per-lruvec stats counter memory usage"). However this cost is justified due to negative impact of the inaccurate lruvec stats on many heuristics. One such case is reported in [1].

Quoted 7 lines

The memory reclaim code is filled with plethora of heuristics and many of those heuristics reads the lruvec stats. So, inaccurate stats can make such heuristics ineffective. [1] reports the impact of inaccurate lruvec stats on the "cache trim mode" heuristic. Inaccurate lruvec stats can impact the deactivation and aging anon heuristics as well.

[1] https://lore.kernel.org/linux-mm/20210311004449.1170308-1-ying.huang-ral2JQCrhuEAvxtiuMwx3w@public.gmane.org/

Sorry for late reply. I have just verified that this patchset can resolve the problem as in the above link for me. Thanks!

Best Regards,
Huang, Ying

Quoted 5 lines

---
Changes since v1:
- no changes