[PATCH 2/2] memcg: make memcg_uncharge_kmem() NMI safe

From: Shakeel Butt

Date: Fri Dec 04 2026 - 16:57:38 EST


On architectures where this_cpu operations are not NMI safe but atomics
are (CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC), MEMCG_KMEM updates that
can run in NMI must go through account_kmem_nmi_safe(). The objcg charge
and uncharge paths do, but memcg_uncharge_kmem() still calls
mod_memcg_state() directly.

memcg_uncharge_kmem() runs in NMI when kmalloc_nolock() or
kfree_nolock() has to evict an object stock slot that holds at least a
page of charged bytes:

__refill_obj_stock()
drain_obj_stock_slot()
memcg_uncharge_kmem()
mod_memcg_state()

If the NMI interrupted mod_memcg_state() on the same CPU, the nested
read-modify-write of the per-CPU MEMCG_KMEM counter, or of the rstat
update counter, loses one of the two updates.

Use account_kmem_nmi_safe() in memcg_uncharge_kmem(). Outside NMI it
still calls mod_memcg_state(), so nothing changes there.

Hitting this needs slub_debug, because on these architectures
kmalloc_nolock() only works on slab debug caches. It also needs a base
page size below 64K, because an object stock slot holds at most
U16_MAX bytes, and a kernel without PREEMPT_RT, where local_trylock()
always fails in NMI.

Kernels without commit afe9ae3fda96 ("mm: memcontrol: factor out memcg
kmem uncharge sequence") have the same mod_memcg_state() call
open-coded in drain_obj_stock_slot(), or in drain_obj_stock() in older
ones. Backports to them need the change there.

Fixes: af92793e52c3 ("slab: Introduce kmalloc_nolock() and kfree_nolock().")
Signed-off-by: Shakeel Butt <shakeel.butt@xxxxxxxxx>
---
mm/memcontrol.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 53e688083350..4289eb5a6d06 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -136,10 +136,11 @@ bool mem_cgroup_kmem_disabled(void)
}

static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages);
+static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val);

static void memcg_uncharge_kmem(struct mem_cgroup *memcg, unsigned int nr_pages)
{
- mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
+ account_kmem_nmi_safe(memcg, -nr_pages);
memcg1_account_kmem(memcg, -nr_pages);
if (!mem_cgroup_is_root(memcg))
memcg_uncharge(memcg, nr_pages);
--
2.53.1-Meta