[PATCH 1/2] memcg: add NMI stat deltas before marking the css updated
From: Shakeel Butt
Date: Fri Dec 04 2026 - 16:57:34 EST
On CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC architectures,
account_kmem_nmi_safe() and account_slab_nmi_safe() keep stat updates
made in NMI in atomics, which flush_nmi_stats() folds in when the css
is flushed. Since commit 8dcb0ed834a3 ("memcg: cgroup: call
css_rstat_updated irrespective of in_nmi()"), they mark the css updated
first and add the delta second. Regular stat updates do it the other
way around.
With this order, a flush on another CPU can take the css off the update
list and run flush_nmi_stats() between the two steps. The delta then
lands after the flush, while the css is no longer on the update list.
It waits there until the next update marks the css again. If the memcg
is freed first, the delta never reaches the ancestors, because
css_rstat_exit() only flushes csses that are on the update list.
Add the delta first. If the css is not on the update list yet,
__css_rstat_updated() puts it there with fully ordered cmpxchg
operations, so a flush that takes the css off the list also sees the
delta. If the css is already on the list, a concurrent flush can still
miss the update. That is the race described in
css_process_update_tree(), which regular updates have too.
Fixes: 8dcb0ed834a3 ("memcg: cgroup: call css_rstat_updated irrespective of in_nmi()")
Signed-off-by: Shakeel Butt <shakeel.butt@xxxxxxxxx>
---
mm/memcontrol.c | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index b75a61ddeded..53e688083350 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -3016,12 +3016,15 @@ static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
} else {
struct mem_cgroup_per_node *pn = memcg->nodeinfo[pgdat->node_id];
- /* preemption is disabled in_nmi(). */
- __css_rstat_updated(&memcg->css, smp_processor_id());
if (idx == NR_SLAB_RECLAIMABLE_B)
atomic_add(nr, &pn->slab_reclaimable);
else
atomic_add(nr, &pn->slab_unreclaimable);
+ /*
+ * Mark the css after the update, like regular stat updates
+ * do. Preemption is disabled in_nmi().
+ */
+ __css_rstat_updated(&memcg->css, smp_processor_id());
}
}
#else
@@ -3240,9 +3243,12 @@ static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
if (likely(!in_nmi())) {
mod_memcg_state(memcg, MEMCG_KMEM, val);
} else {
- /* preemption is disabled in_nmi(). */
- __css_rstat_updated(&memcg->css, smp_processor_id());
atomic_add(val, &memcg->kmem_stat);
+ /*
+ * Mark the css after the update, like regular stat updates
+ * do. Preemption is disabled in_nmi().
+ */
+ __css_rstat_updated(&memcg->css, smp_processor_id());
}
}
#else
--
2.53.1-Meta