* [PATCH bpf-next v4 01/17] bpf: mark struct oom_control's memcg field as TRUSTED_OR_NULL
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 02/17] mm, bpf: introduce BPF OOM struct ops Ben Gardon
` (16 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, John Fastabend
From: Roman Gushchin <roman.gushchin@linux.dev>
Struct oom_control is used to describe the OOM context.
Its memcg field defines the scope of OOM: it's NULL for global
OOMs and a valid memcg pointer for memcg-scoped OOMs.
Teach bpf verifier to recognize it as trusted or NULL pointer.
It will provide the bpf OOM handler a trusted memcg pointer,
which for example is required for iterating the memcg's subtree.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Acked-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
Acked-by: Yafang Shao <laoar.shao@gmail.com>
Acked-by: Matt Bobrowski <mattbobrowski@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Fix commit message typo ("It's" -> "Its").
v3: https://lore.kernel.org/all/20260127024421.494929-6-roman.gushchin@linux.dev/
kernel/bpf/verifier.c | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 8021afe783b6..6e7c5a7b2018 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -6978,6 +6978,10 @@ BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
struct file *vm_file;
};
+BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct oom_control) {
+ struct mem_cgroup *memcg;
+};
+
static bool type_is_rcu(struct bpf_verifier_env *env,
struct bpf_reg_state *reg,
const char *field_name, u32 btf_id)
@@ -7025,6 +7029,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm));
BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
+ BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct oom_control));
return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
"__safe_trusted_or_null");
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 02/17] mm, bpf: introduce BPF OOM struct ops
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 01/17] bpf: mark struct oom_control's memcg field as TRUSTED_OR_NULL Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 03/17] mm, bpf: introduce bpf_oom_kill_process() BPF kfunc Ben Gardon
` (15 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, John Fastabend, Michal Hocko
From: Roman Gushchin <roman.gushchin@linux.dev>
Introduce cgroup BPF struct_ops (bpf_oom_ops, attach type CGROUP_OOM_OPS) for
implementing custom OOM policies.
Policies can be attached to a cgroup via bpf_map__attach_cgroup_opts(). Root
cgroup attachments cover system-wide OOMs as well as fallback from descendant
cgroups. By default, effective handlers run from the OOMing memory cgroup
upward toward the root unless an ancestor attaches with BPF_F_PREORDER.
The handle_out_of_memory callback receives the oom_control describing the OOM
scope and the cgroup where the policy is attached. Returning a positive value
signals that the OOM condition has been handled. This could be by terminating a
task, expanding a memcg limit, or backing off while a previously selected task
exits. Returning <= 0 delegates to the next handler in the effective chain and
ultimately to the in-kernel OOM handler.
SysRq-triggered OOMs bypass BPF handlers so SysRq-f remains a failsafe.
Existing heuristics and sysctls such as panic_on_oom and
sysctl_oom_kill_allocating_task continue to run prior to bpf_handle_oom().
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Co-developed-by: Ben Gardon <bgardon@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Adopted mainline cgroup struct_ops attachment (CGROUP_OOM_OPS) and
changed handle_out_of_memory() to receive (struct oom_control *,
struct cgroup *).
- Dropped oc->bpf_memory_freed dual-reporting check so handlers can
return > 0 to back off while an existing selected task exits; treat
only positive returns (> 0) as handled so negative errnos delegate.
- Bypassed bpf_handle_oom() on SysRq-triggered OOMs (is_sysrq_oom(oc)).
- Added .validate callback requiring handle_out_of_memory, validated
ops->name via bpf_obj_name_cpy(), switched bpf_oom_func_proto() to
curated bpf_base_func_proto() (blocking user-copy/stack helpers),
walked up offline cgroups to the nearest online ancestor, and
encapsulated sleepable RCU Tasks Trace locking in bpf-cgroup.h.
v3: https://lore.kernel.org/all/20260127024421.494929-8-roman.gushchin@linux.dev/
MAINTAINERS | 2 +
include/linux/bpf-cgroup-defs.h | 1 +
include/linux/bpf-cgroup.h | 16 ++-
include/linux/bpf.h | 1 +
include/linux/bpf_oom.h | 44 ++++++++
include/linux/oom.h | 17 +++
kernel/bpf/cgroup.c | 1 +
mm/Makefile | 3 +
mm/bpf_oom.c | 187 ++++++++++++++++++++++++++++++++
mm/oom_kill.c | 10 ++
10 files changed, 280 insertions(+), 2 deletions(-)
create mode 100644 include/linux/bpf_oom.h
create mode 100644 mm/bpf_oom.c
diff --git a/MAINTAINERS b/MAINTAINERS
index b430b29e3878..d4ef52c5594b 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -5177,7 +5177,9 @@ M: Shakeel Butt <shakeel.butt@linux.dev>
L: bpf@vger.kernel.org
L: linux-mm@kvack.org
S: Maintained
+F: include/linux/bpf_oom.h
F: mm/bpf_memcontrol.c
+F: mm/bpf_oom.c
BPF [MISC]
L: bpf@vger.kernel.org
diff --git a/include/linux/bpf-cgroup-defs.h b/include/linux/bpf-cgroup-defs.h
index 671f27ba6a62..ff650a422e36 100644
--- a/include/linux/bpf-cgroup-defs.h
+++ b/include/linux/bpf-cgroup-defs.h
@@ -48,6 +48,7 @@ enum cgroup_bpf_attach_type {
CGROUP_UNIX_GETSOCKNAME,
CGROUP_INET_SOCK_RELEASE,
CGROUP_TCP_SOCK_OPS,
+ CGROUP_OOM_OPS,
CGROUP_LSM_START,
CGROUP_LSM_END = CGROUP_LSM_START + CGROUP_LSM_NUM - 1,
MAX_CGROUP_BPF_ATTACH_TYPE
diff --git a/include/linux/bpf-cgroup.h b/include/linux/bpf-cgroup.h
index 0b63c2cc1399..13a74791be46 100644
--- a/include/linux/bpf-cgroup.h
+++ b/include/linux/bpf-cgroup.h
@@ -8,6 +8,7 @@
#include <linux/jump_label.h>
#include <linux/percpu.h>
#include <linux/rbtree.h>
+#include <linux/rcupdate_trace.h>
#include <net/sock.h>
#include <uapi/linux/bpf.h>
@@ -112,14 +113,25 @@ struct bpf_prog_list {
u32 flags;
};
+static inline void bpf_cgroup_struct_ops_lock_sleepable(void)
+{
+ rcu_read_lock_trace();
+}
+
+static inline void bpf_cgroup_struct_ops_unlock_sleepable(void)
+{
+ rcu_read_unlock_trace();
+}
+
#define bpf_cgroup_struct_ops_foreach(var, item, cgrp, atype) \
- for (item = rcu_dereference((cgrp)->bpf.effective[atype])->items;\
+ for (item = rcu_dereference_check((cgrp)->bpf.effective[atype], \
+ rcu_read_lock_trace_held())->items;\
((var) = READ_ONCE(item->kdata)); \
item++)
static inline bool cgroup_bpf_is_struct_ops_atype(enum cgroup_bpf_attach_type atype)
{
- return atype == CGROUP_TCP_SOCK_OPS;
+ return atype == CGROUP_TCP_SOCK_OPS || atype == CGROUP_OOM_OPS;
}
void cgroup_bpf_struct_ops_register(int atype, u32 type_id, void *cfi_stubs, bool mult_trace);
int cgroup_bpf_struct_ops_attach(struct bpf_map *map, const union bpf_attr *attr);
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 96e249bd00fb..82f99b92c481 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -2761,6 +2761,7 @@ struct bpf_prog_array_item {
};
union {
struct bpf_cgroup_storage *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE];
+ struct cgroup *cgroup;
u64 bpf_cookie;
};
};
diff --git a/include/linux/bpf_oom.h b/include/linux/bpf_oom.h
new file mode 100644
index 000000000000..23e3131a12be
--- /dev/null
+++ b/include/linux/bpf_oom.h
@@ -0,0 +1,44 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#ifndef __BPF_OOM_H
+#define __BPF_OOM_H
+
+struct cgroup;
+struct oom_control;
+
+#define BPF_OOM_NAME_MAX_LEN 64
+
+/**
+ * struct bpf_oom_ops - BPF operations for customizing OOM handling
+ */
+struct bpf_oom_ops {
+ /**
+ * @handle_out_of_memory: Out of memory BPF handler, invoked before the
+ * in-kernel OOM selector.
+ *
+ * Receives @oc describing the OOM scope/constraint and @cgrp where this
+ * policy instance is attached. Return a positive value (> 0) if the
+ * OOM event was handled (either by freeing/expanding memory or
+ * backing off for an already-exiting task), or <= 0 to defer to the
+ * next handler in the hierarchy and ultimately the in-kernel OOM
+ * handler.
+ */
+ int (*handle_out_of_memory)(struct oom_control *oc,
+ struct cgroup *cgrp);
+
+ /**
+ * @name: BPF OOM policy name logged in OOM reports.
+ */
+ char name[BPF_OOM_NAME_MAX_LEN];
+};
+
+#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG)
+bool bpf_handle_oom(struct oom_control *oc);
+#else
+static inline bool bpf_handle_oom(struct oom_control *oc)
+{
+ return false;
+}
+#endif
+
+#endif /* __BPF_OOM_H */
diff --git a/include/linux/oom.h b/include/linux/oom.h
index 00da05d227e6..ca3192c42533 100644
--- a/include/linux/oom.h
+++ b/include/linux/oom.h
@@ -51,8 +51,25 @@ struct oom_control {
/* Used to print the constraint info. */
enum oom_constraint constraint;
+
+#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG)
+ /* Active BPF OOM handler name */
+ const char *bpf_handler_name;
+#endif
};
+#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG)
+static inline const char *oom_handler_name(const struct oom_control *oc)
+{
+ return oc->bpf_handler_name;
+}
+#else
+static inline const char *oom_handler_name(const struct oom_control *oc)
+{
+ return NULL;
+}
+#endif
+
extern struct mutex oom_lock;
extern struct mutex oom_adj_mutex;
diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c
index e4e680dfb63d..dba22e99197d 100644
--- a/kernel/bpf/cgroup.c
+++ b/kernel/bpf/cgroup.c
@@ -572,6 +572,7 @@ static void prog_list_init_item(struct bpf_prog_list *pl, struct bpf_prog_array_
{
if (prog_list_is_struct_ops(pl)) {
item->kdata = bpf_struct_ops_map_kdata(pl->link->map);
+ item->cgroup = pl->link->cgroup;
return;
}
diff --git a/mm/Makefile b/mm/Makefile
index 2a3ec53d62ee..66b53e569eed 100644
--- a/mm/Makefile
+++ b/mm/Makefile
@@ -107,6 +107,9 @@ obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o
ifdef CONFIG_BPF_SYSCALL
obj-$(CONFIG_MEMCG) += bpf_memcontrol.o
endif
+ifdef CONFIG_CGROUP_BPF
+obj-$(CONFIG_MEMCG) += bpf_oom.o
+endif
obj-$(CONFIG_CGROUP_HUGETLB) += hugetlb_cgroup.o
obj-$(CONFIG_GUP_TEST) += gup_test.o
obj-$(CONFIG_DMAPOOL_TEST) += dmapool_test.o
diff --git a/mm/bpf_oom.c b/mm/bpf_oom.c
new file mode 100644
index 000000000000..bc0838d55335
--- /dev/null
+++ b/mm/bpf_oom.c
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * BPF-driven OOM killer customization
+ *
+ * Author: Roman Gushchin <roman.gushchin@linux.dev>
+ */
+
+#include <linux/bpf-cgroup.h>
+#include <linux/bpf.h>
+#include <linux/bpf_oom.h>
+#include <linux/cgroup.h>
+#include <linux/lockdep.h>
+#include <linux/memcontrol.h>
+#include <linux/oom.h>
+#include <linux/uaccess.h>
+
+static int bpf_ops_handle_oom(struct bpf_oom_ops *bpf_oom_ops,
+ struct cgroup *cgrp,
+ struct oom_control *oc)
+{
+ int ret;
+
+ oc->bpf_handler_name = &bpf_oom_ops->name[0];
+ pagefault_disable();
+ ret = bpf_oom_ops->handle_out_of_memory(oc, cgrp);
+ pagefault_enable();
+ oc->bpf_handler_name = NULL;
+
+ return ret;
+}
+
+static struct cgroup *bpf_oom_cgroup(struct mem_cgroup *memcg)
+{
+ if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !mem_cgroup_disabled()) {
+ struct cgroup *cgrp;
+
+ memcg = memcg ?: root_mem_cgroup;
+ cgrp = READ_ONCE(memcg->css.cgroup);
+ if (cgrp->root == &cgrp_dfl_root)
+ return cgrp;
+ }
+
+ /*
+ * Fall back to the cgroup v2 root when memory cgroups are disabled or
+ * mounted on cgroup v1 (cgroup BPF only attaches to the v2 hierarchy).
+ */
+ return &cgrp_dfl_root.cgrp;
+}
+
+/**
+ * bpf_handle_oom() - Invoke attached cgroup BPF OOM policies
+ * @oc: OOM control structure describing the OOM event
+ *
+ * Return: true if a BPF policy handled the OOM, false to fall back to the
+ * in-kernel OOM handler.
+ */
+bool bpf_handle_oom(struct oom_control *oc)
+{
+ const struct bpf_prog_array_item *item;
+ struct bpf_oom_ops *bpf_oom_ops;
+ struct cgroup *cgrp;
+ int ret = 0;
+
+ lockdep_assert_held(&oom_lock);
+
+ if (!cgroup_bpf_enabled(CGROUP_OOM_OPS))
+ return false;
+
+ cgrp = bpf_oom_cgroup(oc->memcg);
+
+ bpf_cgroup_struct_ops_lock_sleepable();
+ while (cgrp && !(READ_ONCE(cgrp->self.flags) & CSS_ONLINE))
+ cgrp = cgroup_parent(cgrp);
+ if (!cgrp)
+ goto out_unlock;
+
+ bpf_cgroup_struct_ops_foreach(bpf_oom_ops, item, cgrp, CGROUP_OOM_OPS) {
+ ret = bpf_ops_handle_oom(bpf_oom_ops, item->cgroup, oc);
+ if (ret > 0)
+ break;
+ }
+
+out_unlock:
+ bpf_cgroup_struct_ops_unlock_sleepable();
+
+ return ret > 0;
+}
+
+static int __handle_out_of_memory(struct oom_control *oc,
+ struct cgroup *cgrp)
+{
+ return 0;
+}
+
+static struct bpf_oom_ops __bpf_oom_ops = {
+ .handle_out_of_memory = __handle_out_of_memory,
+};
+
+static const struct bpf_func_proto *
+bpf_oom_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
+{
+ switch (func_id) {
+ case BPF_FUNC_copy_from_user:
+ case BPF_FUNC_copy_from_user_task:
+ case BPF_FUNC_get_task_stack:
+ return NULL;
+ default:
+ return bpf_base_func_proto(func_id, prog);
+ }
+}
+
+static bool bpf_oom_ops_is_valid_access(int off, int size,
+ enum bpf_access_type type,
+ const struct bpf_prog *prog,
+ struct bpf_insn_access_aux *info)
+{
+ return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
+}
+
+static const struct bpf_verifier_ops bpf_oom_verifier_ops = {
+ .get_func_proto = bpf_oom_func_proto,
+ .is_valid_access = bpf_oom_ops_is_valid_access,
+};
+
+static int bpf_oom_ops_check_member(const struct btf_type *t,
+ const struct btf_member *member,
+ const struct bpf_prog *prog)
+{
+ return 0;
+}
+
+static int bpf_oom_ops_init_member(const struct btf_type *t,
+ const struct btf_member *member,
+ void *kdata, const void *udata)
+{
+ const struct bpf_oom_ops *uops = udata;
+ struct bpf_oom_ops *ops = kdata;
+ u32 moff = __btf_member_bit_offset(t, member) / 8;
+
+ switch (moff) {
+ case offsetof(struct bpf_oom_ops, name):
+ if (uops->name[0]) {
+ if (bpf_obj_name_cpy(ops->name, uops->name,
+ sizeof(ops->name)) <= 0)
+ return -EINVAL;
+ } else {
+ strscpy_pad(ops->name, "bpf_defined_policy",
+ sizeof(ops->name));
+ }
+ return 1;
+ }
+ return 0;
+}
+
+static int bpf_oom_ops_validate(void *kdata)
+{
+ struct bpf_oom_ops *ops = kdata;
+
+ if (!ops->handle_out_of_memory)
+ return -EINVAL;
+
+ return 0;
+}
+
+static int bpf_oom_ops_init(struct btf *btf)
+{
+ return 0;
+}
+
+static struct bpf_struct_ops bpf_oom_bpf_ops = {
+ .verifier_ops = &bpf_oom_verifier_ops,
+ .check_member = bpf_oom_ops_check_member,
+ .init_member = bpf_oom_ops_init_member,
+ .validate = bpf_oom_ops_validate,
+ .init = bpf_oom_ops_init,
+ .name = "bpf_oom_ops",
+ .cgroup_atype = CGROUP_OOM_OPS,
+ .owner = THIS_MODULE,
+ .cfi_stubs = &__bpf_oom_ops,
+ .free_after_mult_rcu_gp = true,
+};
+
+static int __init bpf_oom_struct_ops_init(void)
+{
+ return register_bpf_struct_ops(&bpf_oom_bpf_ops, bpf_oom_ops);
+}
+late_initcall(bpf_oom_struct_ops_init);
diff --git a/mm/oom_kill.c b/mm/oom_kill.c
index 5d48bd862c27..fa9088c965b6 100644
--- a/mm/oom_kill.c
+++ b/mm/oom_kill.c
@@ -45,6 +45,7 @@
#include <linux/mmu_notifier.h>
#include <linux/cred.h>
#include <linux/nmi.h>
+#include <linux/bpf_oom.h>
#include <asm/tlb.h>
#include "internal.h"
@@ -451,6 +452,8 @@ static void dump_header(struct oom_control *oc)
pr_warn("%s invoked oom-killer: gfp_mask=%#x(%pGg), order=%d, oom_score_adj=%d\n",
current->comm, oc->gfp_mask, &oc->gfp_mask, oc->order,
current->signal->oom_score_adj);
+ if (oom_handler_name(oc))
+ pr_warn("oom bpf handler: %s\n", oom_handler_name(oc));
if (!IS_ENABLED(CONFIG_COMPACTION) && oc->order)
pr_warn("COMPACTION is disabled!!!\n");
@@ -1145,6 +1148,13 @@ bool out_of_memory(struct oom_control *oc)
return true;
}
+ /*
+ * Let BPF handle the OOM first unless triggered via SysRq, which
+ * skips to the kernel OOM handler.
+ */
+ if (!is_sysrq_oom(oc) && bpf_handle_oom(oc))
+ return true;
+
select_bad_process(oc);
/* Found nothing?!?! */
if (!oc->chosen) {
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 03/17] mm, bpf: introduce bpf_oom_kill_process() BPF kfunc
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 01/17] bpf: mark struct oom_control's memcg field as TRUSTED_OR_NULL Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 02/17] mm, bpf: introduce BPF OOM struct ops Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 04/17] mm, bpf: introduce bpf_out_of_memory() " Ben Gardon
` (14 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Muchun Song
From: Roman Gushchin <roman.gushchin@linux.dev>
Introduce bpf_oom_kill_process() for bpf_oom_ops programs to terminate a chosen
process through oom_kill_process(), preserving the existing path used by the
kernel OOM implementation.
Init/kernel threads (unkillable), tasks protected with OOM_SCORE_ADJ_MIN, tasks
with no live mm or MMF_OOM_SKIP set, and tasks outside oc->memcg's hierarchy
during a memcg-scoped OOM are rejected in the kernel.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Co-developed-by: Ben Gardon <bgardon@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Guard BPF OOM kfunc block with CONFIG_CGROUP_BPF && CONFIG_MEMCG so
!CONFIG_MEMCG builds do not fail resolve_btfids.
- Use find_lock_task_mm() and reject tasks with no live mm or
MMF_OOM_SKIP set (-ESRCH) in addition to oom_unkillable_task() and
OOM_SCORE_ADJ_MIN checks.
- Add mem_cgroup_task_in_hierarchy() and reject tasks outside oc->memcg
with -EINVAL during memcg-scoped OOMs.
- Fix bpf_oom_kfunc_filter() to check btf_id_set8_contains() and use
default-deny so BPF_PROG_TYPE_EXT (freplace) on non-OOM struct_ops
cannot bypass the filter.
v3: https://lore.kernel.org/all/20260127024421.494929-9-roman.gushchin@linux.dev/
include/linux/memcontrol.h | 20 ++++++++
mm/oom_kill.c | 102 +++++++++++++++++++++++++++++++++++++
2 files changed, 122 insertions(+)
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index 69e1bcc67c58..bc30d7baecd7 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -892,6 +892,20 @@ static inline bool mem_cgroup_is_descendant(const struct mem_cgroup *memcg,
return cgroup_is_descendant(memcg->css.cgroup, root->css.cgroup);
}
+static inline bool mem_cgroup_task_in_hierarchy(struct task_struct *task,
+ const struct mem_cgroup *origin)
+{
+ struct mem_cgroup *memcg;
+ bool ret = false;
+
+ rcu_read_lock();
+ memcg = mem_cgroup_from_task(task);
+ if (memcg)
+ ret = mem_cgroup_is_descendant(memcg, origin);
+ rcu_read_unlock();
+ return ret;
+}
+
static inline bool mm_match_cgroup(struct mm_struct *mm,
const struct mem_cgroup *memcg)
{
@@ -1513,6 +1527,12 @@ static inline u64 cgroup_id_from_mm(struct mm_struct *mm)
static inline void mem_cgroup_flush_workqueue(void) { }
+static inline bool mem_cgroup_task_in_hierarchy(struct task_struct *task,
+ const struct mem_cgroup *origin)
+{
+ return true;
+}
+
static inline int mem_cgroup_init(void) { return 0; }
#endif /* CONFIG_MEMCG */
diff --git a/mm/oom_kill.c b/mm/oom_kill.c
index fa9088c965b6..85da2a39e18a 100644
--- a/mm/oom_kill.c
+++ b/mm/oom_kill.c
@@ -1258,3 +1258,105 @@ SYSCALL_DEFINE2(process_mrelease, int, pidfd, unsigned int, flags)
return -ENOSYS;
#endif /* CONFIG_MMU */
}
+
+#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG)
+
+__bpf_kfunc_start_defs();
+/**
+ * bpf_oom_kill_process() - Terminate a process via the kernel OOM handler
+ * @oc: pointer to oom_control structure describing the OOM context
+ * @task: task to be terminated
+ * @message__str: reason string logged in the OOM report
+ *
+ * Terminate @task using the kernel OOM machinery: emit the OOM report,
+ * update memcg OOM events, trigger asynchronous OOM memory reclamation,
+ * and honor memory.oom.group recursive behavior.
+ *
+ * Kernel-enforced safety constraints:
+ * - Tasks exempt via oom_unkillable_task() (init and kernel threads) are
+ * rejected with -EPERM.
+ * - Tasks with oom_score_adj == OOM_SCORE_ADJ_MIN (-1000), or tasks
+ * outside @oc->memcg's subtree during a memcg-scoped OOM, are rejected
+ * with -EINVAL.
+ * - Tasks with no live mm or with MMF_OOM_SKIP set return -ESRCH.
+ *
+ * Return: 0 on success, or a negative errno on failure.
+ */
+__bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc,
+ struct task_struct *task,
+ const char *message__str)
+{
+ struct task_struct *p;
+
+ if (oom_unkillable_task(task))
+ return -EPERM;
+
+ if (oc->memcg && !mem_cgroup_task_in_hierarchy(task, oc->memcg))
+ return -EINVAL;
+
+ p = find_lock_task_mm(task);
+ if (!p)
+ return -ESRCH;
+
+ if (p->signal->oom_score_adj == OOM_SCORE_ADJ_MIN) {
+ task_unlock(p);
+ return -EINVAL;
+ }
+
+ if (mm_flags_test(MMF_OOM_SKIP, p->mm)) {
+ task_unlock(p);
+ return -ESRCH;
+ }
+
+ /* paired with put_task_struct() in oom_kill_process() */
+ get_task_struct(p);
+ task_unlock(p);
+
+ oc->chosen = p;
+ oom_kill_process(oc, message__str);
+ oc->chosen = NULL;
+
+ return 0;
+}
+
+__bpf_kfunc_end_defs();
+
+BTF_KFUNCS_START(bpf_oom_kfuncs)
+BTF_ID_FLAGS(func, bpf_oom_kill_process, KF_SLEEPABLE)
+BTF_KFUNCS_END(bpf_oom_kfuncs)
+
+BTF_ID_LIST_SINGLE(bpf_oom_ops_ids, struct, bpf_oom_ops)
+
+static int bpf_oom_kfunc_filter(const struct bpf_prog *prog, u32 kfunc_id)
+{
+ if (!btf_id_set8_contains(&bpf_oom_kfuncs, kfunc_id))
+ return 0;
+
+ if (prog->type == BPF_PROG_TYPE_STRUCT_OPS &&
+ bpf_oom_ops_ids[0] &&
+ prog->aux->attach_btf_id == bpf_oom_ops_ids[0])
+ return 0;
+
+ return -EACCES;
+}
+
+static const struct btf_kfunc_id_set bpf_oom_kfunc_set = {
+ .owner = THIS_MODULE,
+ .set = &bpf_oom_kfuncs,
+ .filter = bpf_oom_kfunc_filter,
+};
+
+static int __init bpf_oom_init(void)
+{
+ int err;
+
+ err = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
+ &bpf_oom_kfunc_set);
+ if (err)
+ pr_warn("error while registering bpf oom kfuncs: %d\n", err);
+
+ return err;
+}
+late_initcall(bpf_oom_init);
+
+#endif /* CONFIG_CGROUP_BPF && CONFIG_MEMCG */
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 04/17] mm, bpf: introduce bpf_out_of_memory() BPF kfunc
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (2 preceding siblings ...)
2026-12-02 21:03 ` [PATCH bpf-next v4 03/17] mm, bpf: introduce bpf_oom_kill_process() BPF kfunc Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:18 ` sashiko-bot
2026-12-02 21:03 ` [PATCH bpf-next v4 05/17] selftests/bpf: Add BPF OOM struct ops test Ben Gardon
` (13 subsequent siblings)
17 siblings, 1 reply; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Michal Hocko
From: Roman Gushchin <roman.gushchin@linux.dev>
Introduce bpf_out_of_memory() to allow BPF programs to declare an
OOM proactively.
BPF-declared OOMs are marked via oc->bpf_declared so they do not panic the
kernel when no killable tasks remain or panic_on_oom is set. They do not
terminate the calling task via sysctl_oom_kill_allocating_task either.
Registered directly on BPF_PROG_TYPE_SYSCALL (extended to PSI tracepoints
later in the series) so bpf_oom_ops and arbitrary tracing/LSM hooks cannot
deadlock on oom_lock.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Co-developed-by: Ben Gardon <bgardon@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Registered directly on BPF_PROG_TYPE_SYSCALL instead of
BPF_PROG_TYPE_UNSPEC.
- Moved BPF_OOM_FLAGS_ALL outside BTF-exported enum bpf_oom_flags.
- Added oc->bpf_declared guard against panic() and
sysctl_oom_kill_allocating_task, clamped oc->totalpages in
constrained_alloc(), normalized root_mem_cgroup to NULL, rejected
dying memcgs, and accounted MEMCG_OOM.
v3: https://lore.kernel.org/all/20260127024421.494929-10-roman.gushchin@linux.dev/
include/linux/oom.h | 19 +++++++++
mm/oom_kill.c | 101 ++++++++++++++++++++++++++++++++++++++++----
2 files changed, 111 insertions(+), 9 deletions(-)
diff --git a/include/linux/oom.h b/include/linux/oom.h
index ca3192c42533..168b64dfb6ad 100644
--- a/include/linux/oom.h
+++ b/include/linux/oom.h
@@ -14,6 +14,12 @@ struct notifier_block;
struct mem_cgroup;
struct task_struct;
+enum bpf_oom_flags {
+ BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK = BIT(0),
+};
+
+#define BPF_OOM_FLAGS_ALL BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK
+
enum oom_constraint {
CONSTRAINT_NONE,
CONSTRAINT_CPUSET,
@@ -55,6 +61,9 @@ struct oom_control {
#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG)
/* Active BPF OOM handler name */
const char *bpf_handler_name;
+
+ /* Declared via BPF outside an allocation failure */
+ bool bpf_declared;
#endif
};
@@ -63,11 +72,21 @@ static inline const char *oom_handler_name(const struct oom_control *oc)
{
return oc->bpf_handler_name;
}
+
+static inline bool is_bpf_declared_oom(const struct oom_control *oc)
+{
+ return oc->bpf_declared;
+}
#else
static inline const char *oom_handler_name(const struct oom_control *oc)
{
return NULL;
}
+
+static inline bool is_bpf_declared_oom(const struct oom_control *oc)
+{
+ return false;
+}
#endif
extern struct mutex oom_lock;
diff --git a/mm/oom_kill.c b/mm/oom_kill.c
index 85da2a39e18a..9b5df00f98ab 100644
--- a/mm/oom_kill.c
+++ b/mm/oom_kill.c
@@ -256,7 +256,9 @@ static enum oom_constraint constrained_alloc(struct oom_control *oc)
int nid;
if (is_memcg_oom(oc)) {
- oc->totalpages = mem_cgroup_get_max(oc->memcg) ?: 1;
+ unsigned long max = mem_cgroup_get_max(oc->memcg);
+
+ oc->totalpages = min(max, totalram_pages() + total_swap_pages) ?: 1;
return CONSTRAINT_MEMCG;
}
@@ -1024,7 +1026,8 @@ static void oom_kill_process(struct oom_control *oc, const char *message)
task_unlock(victim);
if (__ratelimit(&oom_rs)) {
- dump_header(oc);
+ if (!is_bpf_declared_oom(oc))
+ dump_header(oc);
dump_oom_victim(oc, victim);
}
@@ -1065,8 +1068,8 @@ static void check_panic_on_oom(struct oom_control *oc)
if (oc->constraint != CONSTRAINT_NONE)
return;
}
- /* Do not panic for oom kills triggered by sysrq */
- if (is_sysrq_oom(oc))
+ /* Do not panic for oom kills triggered by sysrq or BPF */
+ if (is_sysrq_oom(oc) || is_bpf_declared_oom(oc))
return;
dump_header(oc);
panic("Out of memory: %s panic_on_oom is enabled\n",
@@ -1138,7 +1141,8 @@ bool out_of_memory(struct oom_control *oc)
oc->nodemask = NULL;
check_panic_on_oom(oc);
- if (!is_memcg_oom(oc) && sysctl_oom_kill_allocating_task &&
+ if (!is_memcg_oom(oc) && !is_bpf_declared_oom(oc) &&
+ sysctl_oom_kill_allocating_task &&
current->mm && !oom_unkillable_task(current) &&
oom_cpuset_eligible(current, oc) &&
current->signal->oom_score_adj != OOM_SCORE_ADJ_MIN) {
@@ -1165,7 +1169,8 @@ bool out_of_memory(struct oom_control *oc)
* system level, we cannot survive this and will enter
* an endless loop in the allocator. Bail out now.
*/
- if (!is_sysrq_oom(oc) && !is_memcg_oom(oc))
+ if (!is_sysrq_oom(oc) && !is_memcg_oom(oc) &&
+ !is_bpf_declared_oom(oc))
panic("System is deadlocked on memory\n");
}
if (oc->chosen && oc->chosen != (void *)-1UL)
@@ -1319,6 +1324,66 @@ __bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc,
return 0;
}
+/**
+ * bpf_out_of_memory() - Declare an OOM condition and invoke OOM handling
+ * @memcg__nullable: target memory cgroup, or NULL for system-wide OOM
+ * @order: allocation page order (0..MAX_PAGE_ORDER), passed through to
+ * bpf_oom_ops handlers as a memory-reclaim size hint
+ * @flags: bitmask of &enum bpf_oom_flags
+ *
+ * Synchronizes on oom_lock: waits (interruptible by fatal signals) when
+ * BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK is set, or returns -EBUSY immediately if
+ * oom_lock is contended. Root @memcg__nullable is normalized to NULL
+ * (system-wide OOM); dying memory cgroups are rejected with -EINVAL.
+ *
+ * Return: 1 if forward progress was made, 0 if no process was terminated, or a
+ * negative errno on failure.
+ */
+__bpf_kfunc int bpf_out_of_memory(struct mem_cgroup *memcg__nullable,
+ int order, u64 flags)
+{
+ struct oom_control oc = {
+ .gfp_mask = GFP_KERNEL,
+ .order = order,
+ .bpf_declared = true,
+ };
+ int ret;
+
+ if (flags & ~BPF_OOM_FLAGS_ALL)
+ return -EINVAL;
+
+ /*
+ * Keep order so callers can signal a higher-order memory need to
+ * reactive bpf_oom_ops handlers (or exercise high-order OOM policies).
+ */
+ if (oc.order < 0 || oc.order > MAX_PAGE_ORDER)
+ return -EINVAL;
+
+ if (memcg__nullable && mem_cgroup_is_root(memcg__nullable))
+ memcg__nullable = NULL;
+
+ if (memcg__nullable && memcg_is_dying(memcg__nullable))
+ return -EINVAL;
+
+ oc.memcg = memcg__nullable;
+
+ if (flags & BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK) {
+ ret = mutex_lock_killable(&oom_lock);
+ if (ret)
+ return ret;
+ } else if (!mutex_trylock(&oom_lock)) {
+ return -EBUSY;
+ }
+
+ if (oc.memcg)
+ memcg_memory_event(oc.memcg, MEMCG_OOM);
+
+ ret = out_of_memory(&oc);
+
+ mutex_unlock(&oom_lock);
+ return ret;
+}
+
__bpf_kfunc_end_defs();
BTF_KFUNCS_START(bpf_oom_kfuncs)
@@ -1346,16 +1411,34 @@ static const struct btf_kfunc_id_set bpf_oom_kfunc_set = {
.filter = bpf_oom_kfunc_filter,
};
+BTF_KFUNCS_START(bpf_declare_oom_kfuncs)
+BTF_ID_FLAGS(func, bpf_out_of_memory, KF_SLEEPABLE)
+BTF_KFUNCS_END(bpf_declare_oom_kfuncs)
+
+static const struct btf_kfunc_id_set bpf_declare_oom_syscall_kfunc_set = {
+ .owner = THIS_MODULE,
+ .set = &bpf_declare_oom_kfuncs,
+};
+
static int __init bpf_oom_init(void)
{
int err;
err = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
&bpf_oom_kfunc_set);
- if (err)
- pr_warn("error while registering bpf oom kfuncs: %d\n", err);
+ if (err) {
+ pr_warn("error while registering struct_ops bpf oom kfuncs: %d\n", err);
+ return err;
+ }
+
+ err = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
+ &bpf_declare_oom_syscall_kfunc_set);
+ if (err) {
+ pr_warn("error while registering syscall bpf oom kfuncs: %d\n", err);
+ return err;
+ }
- return err;
+ return 0;
}
late_initcall(bpf_oom_init);
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 04/17] mm, bpf: introduce bpf_out_of_memory() BPF kfunc
2026-12-02 21:03 ` [PATCH bpf-next v4 04/17] mm, bpf: introduce bpf_out_of_memory() " Ben Gardon
@ 2026-12-02 21:18 ` sashiko-bot
0 siblings, 0 replies; 27+ messages in thread
From: sashiko-bot @ 2026-12-02 21:18 UTC (permalink / raw)
To: Ben Gardon, Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, Michal Hocko, mkoutny
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] mm: unguarded task_will_free_mem() in out_of_memory() for
BPF-declared OOMs
- [Medium] mm: oom_cpuset_eligible() filters global BPF OOM victims by
current cpuset
- [Low] mm, bpf: inconsistent dump_header() handling for BPF-declared
OOMs
--
commit 9e727626010671020de30395390afd2758b2e296
Author: Roman Gushchin <roman.gushchin@linux.dev>
mm, bpf: introduce bpf_out_of_memory() BPF kfunc
This commit introduces the bpf_out_of_memory() kfunc to allow BPF programs
to proactively declare an OOM condition and invoke OOM handling.
> diff --git a/mm/oom_kill.c b/mm/oom_kill.c
> index 85da2a39e18a1..9b5df00f98abd 100644
> --- a/mm/oom_kill.c
> +++ b/mm/oom_kill.c
[ ... ]
> @@ -1024,7 +1026,8 @@ static void oom_kill_process(struct oom_control *oc, const char *message)
> task_unlock(victim);
>
> if (__ratelimit(&oom_rs)) {
> - dump_header(oc);
> + if (!is_bpf_declared_oom(oc))
> + dump_header(oc);
> dump_oom_victim(oc, victim);
> }
>
[ ... ]
> @@ -1138,7 +1141,8 @@ bool out_of_memory(struct oom_control *oc)
> oc->nodemask = NULL;
> check_panic_on_oom(oc);
>
> - if (!is_memcg_oom(oc) && sysctl_oom_kill_allocating_task &&
> + if (!is_memcg_oom(oc) && !is_bpf_declared_oom(oc) &&
> + sysctl_oom_kill_allocating_task &&
> current->mm && !oom_unkillable_task(current) &&
> oom_cpuset_eligible(current, oc) &&
> current->signal->oom_score_adj != OOM_SCORE_ADJ_MIN) {
[Severity: Medium]
Should the task_will_free_mem(current) shortcut earlier in out_of_memory()
also check !is_bpf_declared_oom(oc)?
mm/oom_kill.c:out_of_memory() {
...
if (task_will_free_mem(current)) {
mark_oom_victim(current);
queue_oom_reaper(current);
return true;
}
...
}
If the task calling bpf_out_of_memory() has a pending fatal signal or is in
a concurrent group exit (when BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK is unset, when
oom_lock is acquired on the uncontended fastpath, or when SIGKILL arrives
after taking oom_lock), out_of_memory() treats current as an allocating
task, marks and reaps it as the OOM victim, and returns true without
running OOM handling on the target domain.
> @@ -1165,7 +1169,8 @@ bool out_of_memory(struct oom_control *oc)
> * system level, we cannot survive this and will enter
> * an endless loop in the allocator. Bail out now.
> */
> - if (!is_sysrq_oom(oc) && !is_memcg_oom(oc))
> + if (!is_sysrq_oom(oc) && !is_memcg_oom(oc) &&
> + !is_bpf_declared_oom(oc))
> panic("System is deadlocked on memory\n");
> }
> if (oc->chosen && oc->chosen != (void *)-1UL)
[Severity: Low]
Should dump_header(oc) in the !oc->chosen path right above this check also
be skipped (or ratelimited) when is_bpf_declared_oom(oc) is true? Repeated
bpf_out_of_memory() calls on a domain with no killable tasks will otherwise
emit unratelimited stack traces, meminfo, and task dumps for current.
Conversely, because oom_handler_name(oc) is only logged inside
dump_header(), skipping dump_header() in oom_kill_process() for
BPF-declared OOMs suppresses logging the active bpf_oom_ops handler name
when a victim is killed.
> @@ -1319,6 +1324,66 @@ __bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc,
> return 0;
> }
>
> +/**
> + * bpf_out_of_memory() - Declare an OOM condition and invoke OOM handling
> + * @memcg__nullable: target memory cgroup, or NULL for system-wide OOM
> + * @order: allocation page order (0..MAX_PAGE_ORDER), passed through to
> + * bpf_oom_ops handlers as a memory-reclaim size hint
> + * @flags: bitmask of &enum bpf_oom_flags
> + *
> + * Synchronizes on oom_lock: waits (interruptible by fatal signals) when
> + * BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK is set, or returns -EBUSY immediately if
> + * oom_lock is contended. Root @memcg__nullable is normalized to NULL
> + * (system-wide OOM); dying memory cgroups are rejected with -EINVAL.
> + *
> + * Return: 1 if forward progress was made, 0 if no process was terminated, or a
> + * negative errno on failure.
> + */
> +__bpf_kfunc int bpf_out_of_memory(struct mem_cgroup *memcg__nullable,
> + int order, u64 flags)
> +{
> + struct oom_control oc = {
> + .gfp_mask = GFP_KERNEL,
> + .order = order,
> + .bpf_declared = true,
> + };
> + int ret;
> +
> + if (flags & ~BPF_OOM_FLAGS_ALL)
> + return -EINVAL;
> +
> + /*
> + * Keep order so callers can signal a higher-order memory need to
> + * reactive bpf_oom_ops handlers (or exercise high-order OOM policies).
> + */
> + if (oc.order < 0 || oc.order > MAX_PAGE_ORDER)
> + return -EINVAL;
> +
> + if (memcg__nullable && mem_cgroup_is_root(memcg__nullable))
> + memcg__nullable = NULL;
> +
> + if (memcg__nullable && memcg_is_dying(memcg__nullable))
> + return -EINVAL;
> +
> + oc.memcg = memcg__nullable;
> +
> + if (flags & BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK) {
> + ret = mutex_lock_killable(&oom_lock);
> + if (ret)
> + return ret;
> + } else if (!mutex_trylock(&oom_lock)) {
> + return -EBUSY;
> + }
> +
> + if (oc.memcg)
> + memcg_memory_event(oc.memcg, MEMCG_OOM);
> +
> + ret = out_of_memory(&oc);
> +
> + mutex_unlock(&oom_lock);
> + return ret;
> +}
[Severity: Medium]
On a system-wide BPF-declared OOM (oc.memcg == NULL and oc.nodemask ==
NULL), if execution falls back to select_bad_process(), does
oom_evaluate_task() -> oom_cpuset_eligible() unintentionally filter
candidate victims against current's cpuset?
mm/oom_kill.c:oom_cpuset_eligible() {
...
if (mask) {
ret = mempolicy_in_oom_domain(tsk, mask);
} else {
ret = cpuset_mems_allowed_intersects(current, tsk);
}
...
}
Under CONFIG_NUMA, if the task calling bpf_out_of_memory() is confined to a
cpuset covering a subset of NUMA nodes, tasks on disjoint NUMA nodes will
be skipped as ineligible even though the declared OOM is unconstrained across
the whole system.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261202210415.517651-1-bgardon@google.com?part=4
^ permalink raw reply [flat|nested] 27+ messages in thread
* [PATCH bpf-next v4 05/17] selftests/bpf: Add BPF OOM struct ops test
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (3 preceding siblings ...)
2026-12-02 21:03 ` [PATCH bpf-next v4 04/17] mm, bpf: introduce bpf_out_of_memory() " Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 06/17] sched/psi: add a tracepoint to psi_avgs_work() Ben Gardon
` (12 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Shuah Khan, linux-kselftest
From: Roman Gushchin <roman.gushchin@linux.dev>
Implement a kselftest for the OOM handling functionality.
This BPF OOM policy terminates all tasks belonging to the largest leaf
cgroup (excluding page cache) that contains no exempt tasks
(oom_score_adj set to -1000).
The test:
1. builds a hierarchy of memory cgroups
2. pre-allocates baseline memory, below memory.max
3. triggers an OOM from the largest eligible leaf
4. verifies that the expected process is selected and terminated with SIGKILL
5. checks the chosen memcg's memory.events oom_kill counter to validate
Attaching the same policy to both the subtree root (where it returns 0)
and the root cgroup verifies hierarchical delegation.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Co-developed-by: Ben Gardon <bgardon@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Adopted bpf_map__attach_cgroup_opts() and CO-RE task->signal->oom_mm.
- Replaced cgroup freezing with pipes to synchronize with workers so
multi-CPU runs cannot flake.
- Renamed to serial_test_oom() to avoid root-cgroup collisions under
test_progs -j.
- Scanned the full subtree for in-flight oom_mm, passed acquired task
reference to bpf_oom_kill_process(), and checked its return value.
v3: https://lore.kernel.org/all/20260127024421.494929-13-roman.gushchin@linux.dev/
.../selftests/bpf/prog_tests/memory_holder.h | 158 +++++++++++++
.../selftests/bpf/prog_tests/test_oom.c | 218 ++++++++++++++++++
tools/testing/selftests/bpf/progs/test_oom.c | 132 +++++++++++
3 files changed, 508 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/memory_holder.h
create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom.c
diff --git a/tools/testing/selftests/bpf/prog_tests/memory_holder.h b/tools/testing/selftests/bpf/prog_tests/memory_holder.h
new file mode 100644
index 000000000000..34b408da3958
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/memory_holder.h
@@ -0,0 +1,158 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef __MEMORY_HOLDER_H
+#define __MEMORY_HOLDER_H
+
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+
+struct memory_holder {
+ pid_t pid;
+ int start_fd;
+ int done_fd;
+};
+
+static inline void memory_holder_init(struct memory_holder *w)
+{
+ w->pid = -1;
+ w->start_fd = -1;
+ w->done_fd = -1;
+}
+
+static inline void memory_holder_cleanup(struct memory_holder *w)
+{
+ if (w->start_fd >= 0) {
+ close(w->start_fd);
+ w->start_fd = -1;
+ }
+ if (w->done_fd >= 0) {
+ close(w->done_fd);
+ w->done_fd = -1;
+ }
+ if (w->pid > 0) {
+ kill(w->pid, SIGKILL);
+ waitpid(w->pid, NULL, 0);
+ w->pid = -1;
+ }
+}
+
+/*
+ * Fork a child that sets /proc/self/oom_score_adj, waits for a byte on
+ * start_fd (after the parent places it into a cgroup), faults in @target
+ * bytes of anonymous memory (in @chunk-byte chunks if @chunk > 0), writes a
+ * byte to done_fd, and either exits (if @exit_after_alloc is true) or sleeps
+ * until killed.
+ */
+static inline int memory_holder_spawn(struct memory_holder *w, size_t target,
+ size_t chunk, int oom_score_adj,
+ bool exit_after_alloc)
+{
+ int start_pipe[2] = { -1, -1 };
+ int done_pipe[2] = { -1, -1 };
+ int ret = 0;
+ pid_t pid;
+ char c;
+
+ memory_holder_init(w);
+
+ if (pipe(start_pipe) < 0)
+ return -errno;
+ if (pipe(done_pipe) < 0) {
+ ret = -errno;
+ goto err_pipes;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ ret = -errno;
+ goto err_pipes;
+ }
+
+ if (pid > 0) {
+ w->pid = pid;
+ w->start_fd = start_pipe[1];
+ w->done_fd = done_pipe[0];
+ close(start_pipe[0]);
+ close(done_pipe[1]);
+ return 0;
+ }
+
+ close(start_pipe[1]);
+ close(done_pipe[0]);
+
+ {
+ char buf[8];
+ int fd = open("/proc/self/oom_score_adj", O_WRONLY);
+
+ if (fd < 0)
+ _exit(1);
+ snprintf(buf, sizeof(buf), "%d", oom_score_adj);
+ if (write(fd, buf, strlen(buf)) < 0)
+ _exit(1);
+ close(fd);
+ }
+
+ /* Wait for parent to place us in the target cgroup and release us */
+ if (read(start_pipe[0], &c, 1) != 1)
+ _exit(1);
+ close(start_pipe[0]);
+
+ if (target) {
+ size_t step = chunk ?: target;
+ size_t done = 0;
+
+ while (done < target) {
+ size_t sz = target - done < step ? target - done : step;
+ char *ptr = malloc(sz);
+
+ if (!ptr)
+ _exit(ENOMEM);
+ memset(ptr, 'a', sz);
+ /* Prevent -O2 dead-store elimination before _exit() */
+ asm volatile("" : : "r"(ptr) : "memory");
+ done += sz;
+ }
+ }
+
+ if (write(done_pipe[1], "d", 1) != 1)
+ _exit(1);
+ close(done_pipe[1]);
+
+ if (exit_after_alloc)
+ _exit(0);
+
+ for (;;)
+ sleep(1000);
+
+err_pipes:
+ if (start_pipe[0] >= 0)
+ close(start_pipe[0]);
+ if (start_pipe[1] >= 0)
+ close(start_pipe[1]);
+ if (done_pipe[0] >= 0)
+ close(done_pipe[0]);
+ if (done_pipe[1] >= 0)
+ close(done_pipe[1]);
+ return ret;
+}
+
+static inline int memory_holder_start(struct memory_holder *w)
+{
+ return write(w->start_fd, "g", 1) == 1 ? 0 : -EIO;
+}
+
+static inline int memory_holder_wait_ready(struct memory_holder *w)
+{
+ char c;
+
+ return read(w->done_fd, &c, 1) == 1 ? 0 : -EIO;
+}
+
+#endif /* __MEMORY_HOLDER_H */
diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom.c b/tools/testing/selftests/bpf/prog_tests/test_oom.c
new file mode 100644
index 000000000000..f17742ace1ce
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/test_oom.c
@@ -0,0 +1,218 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <sys/wait.h>
+#include <test_progs.h>
+#include <bpf/bpf.h>
+#include <bpf/btf.h>
+
+#include "cgroup_helpers.h"
+#include "memory_holder.h"
+
+#define MB (1024UL * 1024UL)
+#include "test_oom.skel.h"
+
+#define OOM_SCORE_ADJ_MIN (-1000)
+#define OOM_SCORE_ADJ_MAX 1000
+
+struct cgroup_desc {
+ const char *path;
+ int fd;
+ struct memory_holder worker;
+ size_t target;
+ size_t max;
+ int oom_score_adj;
+ bool expect_terminated;
+};
+
+/*
+ * Baseline workers (cg1 10 MB + cg2 35 MB + cg5 10 MB = 55 MB) allocate first
+ * and wait under the 80 MB limit. Then cg4 (35 MB) allocates and crosses 80 MB
+ * at ~25 MB, triggering a single deterministic OOM where cg2 (35 MB) is exempt
+ * via OOM_SCORE_ADJ_MIN and cg4 (~25 MB) is the largest eligible leaf.
+ */
+static struct cgroup_desc cgroups[] = {
+ { .path = "/oom_test", .max = 80 * MB },
+ { .path = "/oom_test/cg1", .target = 10 * MB,
+ .oom_score_adj = OOM_SCORE_ADJ_MAX },
+ { .path = "/oom_test/cg2", .target = 35 * MB,
+ .oom_score_adj = OOM_SCORE_ADJ_MIN },
+ { .path = "/oom_test/cg3" },
+ { .path = "/oom_test/cg3/cg4", .target = 35 * MB,
+ .expect_terminated = true },
+ { .path = "/oom_test/cg3/cg5", .target = 10 * MB },
+};
+
+static void reset_cgroups(void)
+{
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ cgroups[i].fd = -1;
+ memory_holder_init(&cgroups[i].worker);
+ }
+}
+
+static void cleanup_workers(void)
+{
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ memory_holder_cleanup(&cgroups[i].worker);
+ if (cgroups[i].fd >= 0) {
+ close(cgroups[i].fd);
+ cgroups[i].fd = -1;
+ }
+ }
+}
+
+static int setup_environment(void)
+{
+ int i, err;
+
+ reset_cgroups();
+
+ err = setup_cgroup_environment();
+ if (!ASSERT_OK(err, "setup_cgroup_environment"))
+ return -1;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ char buf[64];
+
+ cgroups[i].fd = create_and_get_cgroup(cgroups[i].path);
+ if (!ASSERT_GE(cgroups[i].fd, 0, "create_and_get_cgroup"))
+ return -1;
+
+ if (cgroups[i].target == 0) {
+ err = write_cgroup_file(cgroups[i].path,
+ "cgroup.subtree_control",
+ "+memory");
+ if (!ASSERT_OK(err, "enable memory controller"))
+ return -1;
+ }
+
+ if (cgroups[i].max) {
+ snprintf(buf, sizeof(buf), "%zu", cgroups[i].max);
+ err = write_cgroup_file(cgroups[i].path, "memory.max",
+ buf);
+ if (!ASSERT_OK(err, "set memory.max"))
+ return -1;
+ write_cgroup_file(cgroups[i].path, "memory.swap.max",
+ "0");
+ }
+
+ if (cgroups[i].target) {
+ err = memory_holder_spawn(&cgroups[i].worker,
+ cgroups[i].target, 0,
+ cgroups[i].oom_score_adj,
+ cgroups[i].expect_terminated);
+ if (!ASSERT_OK(err, "spawn worker"))
+ return -1;
+
+ snprintf(buf, sizeof(buf), "%d", cgroups[i].worker.pid);
+ err = write_cgroup_file(cgroups[i].path, "cgroup.procs",
+ buf);
+ if (!ASSERT_OK(err, "put child into cgroup"))
+ return -1;
+ }
+ }
+
+ /* Pre-allocate all non-trigger baseline workers under memory.max */
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ if (!cgroups[i].target || cgroups[i].expect_terminated)
+ continue;
+
+ if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker),
+ "start baseline worker"))
+ return -1;
+ if (!ASSERT_OK(memory_holder_wait_ready(&cgroups[i].worker),
+ "wait baseline worker"))
+ return -1;
+ }
+
+ return 0;
+}
+
+/*
+ * Serialized because this test attaches a BPF OOM policy to the root cgroup
+ * and triggers real memcg OOMs, which would collide with other OOM tests
+ * running in parallel under test_progs -j.
+ */
+void serial_test_oom(void)
+{
+ LIBBPF_OPTS(bpf_cgroup_opts, opts);
+ struct bpf_link *cgroup_link = NULL, *root_link = NULL;
+ struct test_oom *skel = NULL;
+ int root_cg_fd = -1, status = 0, i;
+ char buf[4096] = {};
+
+ if (setup_environment())
+ goto cleanup;
+
+ skel = test_oom__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "open_and_load"))
+ goto cleanup;
+
+ /*
+ * Attach to both /oom_test (which returns 0) and root (which handles
+ * the OOM) to exercise hierarchical delegation.
+ */
+ cgroup_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom,
+ cgroups[0].fd, &opts);
+ if (!ASSERT_OK_PTR(cgroup_link, "attach_oom_cgroup"))
+ goto cleanup;
+
+ root_cg_fd = get_root_cgroup();
+ if (!ASSERT_GE(root_cg_fd, 0, "get_root_cgroup"))
+ goto cleanup;
+
+ root_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom,
+ root_cg_fd, &opts);
+ if (!ASSERT_OK_PTR(root_link, "attach_oom_root"))
+ goto cleanup;
+
+ /* Release the trigger worker (cg4) to cross memory.max */
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ if (!cgroups[i].expect_terminated)
+ continue;
+
+ if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker),
+ "start trigger worker"))
+ goto cleanup;
+
+ if (!ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status, 0),
+ cgroups[i].worker.pid, "waitpid trigger"))
+ goto cleanup;
+ cgroups[i].worker.pid = -1;
+
+ if (!ASSERT_TRUE(WIFSIGNALED(status) &&
+ WTERMSIG(status) == SIGKILL,
+ "expected process was terminated"))
+ goto cleanup;
+
+ if (!ASSERT_OK(read_cgroup_file(cgroups[i].path,
+ "memory.events",
+ buf, sizeof(buf)),
+ "read memory.events"))
+ goto cleanup;
+
+ if (!ASSERT_OK_PTR(strstr(buf, "oom_kill 1"),
+ "oom_kill count check"))
+ goto cleanup;
+ }
+
+ /* Verify all other baseline workers survived */
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ if (cgroups[i].worker.pid > 0)
+ ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status,
+ WNOHANG), 0,
+ "non-target worker survived");
+ }
+
+cleanup:
+ bpf_link__destroy(root_link);
+ bpf_link__destroy(cgroup_link);
+ if (root_cg_fd >= 0)
+ close(root_cg_fd);
+ cleanup_workers();
+ cleanup_cgroup_environment();
+ test_oom__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/test_oom.c b/tools/testing/selftests/bpf/progs/test_oom.c
new file mode 100644
index 000000000000..a752d332f8b7
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom.c
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Example BPF OOM policy for selftests (not intended for production use).
+ *
+ * Exercises bpf_oom_ops attachment, hierarchical delegation (returning 0 on
+ * the subtree root and handling on root), and bpf_oom_kill_process() by
+ * terminating all tasks in the largest eligible leaf cgroup (similar to
+ * memory.oom.group semantics).
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_core_read.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+char _license[] SEC("license") = "GPL";
+
+#define OOM_SCORE_ADJ_MIN (-1000)
+
+static bool mem_cgroup_has_oom_victim(struct mem_cgroup *memcg)
+{
+ struct task_struct *task;
+
+ bpf_for_each(css_task, task, &memcg->css, CSS_TASK_ITER_PROCS)
+ if (BPF_CORE_READ(task, signal, oom_mm))
+ return true;
+
+ return false;
+}
+
+static bool mem_cgroup_killable(struct mem_cgroup *memcg)
+{
+ struct task_struct *task;
+
+ bpf_for_each(css_task, task, &memcg->css, CSS_TASK_ITER_PROCS)
+ if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN)
+ return false;
+
+ return true;
+}
+
+/*
+ * Find the largest leaf cgroup (ignoring page cache) without exempt tasks
+ * and terminate all belonging tasks.
+ */
+SEC("struct_ops.s/handle_out_of_memory")
+int BPF_PROG(test_out_of_memory, struct oom_control *oc, struct cgroup *cgrp)
+{
+ struct task_struct *task;
+ struct mem_cgroup *root_memcg = oc->memcg;
+ struct mem_cgroup *memcg, *chosen = NULL;
+ struct cgroup_subsys_state *css_pos, *css;
+ unsigned long usage, max_usage = 0;
+ unsigned long pagecache = 0;
+ int ret = 0;
+
+ if (root_memcg)
+ root_memcg = bpf_get_mem_cgroup(&root_memcg->css);
+ else
+ root_memcg = bpf_get_root_mem_cgroup();
+
+ if (!root_memcg)
+ return 0;
+
+ css = &root_memcg->css;
+ if (css && css->cgroup == cgrp)
+ goto exit;
+
+ bpf_rcu_read_lock();
+ bpf_for_each(css, css_pos, &root_memcg->css, BPF_CGROUP_ITER_DESCENDANTS_POST) {
+ if (css_pos->cgroup->nr_descendants + css_pos->cgroup->nr_dying_descendants)
+ continue;
+
+ memcg = bpf_get_mem_cgroup(css_pos);
+ if (!memcg)
+ continue;
+
+ /*
+ * If any task in the subtree is already exiting due to OOM,
+ * back off and let it release memory.
+ */
+ if (mem_cgroup_has_oom_victim(memcg)) {
+ bpf_put_mem_cgroup(memcg);
+ ret = 1;
+ break;
+ }
+
+ usage = bpf_mem_cgroup_usage(memcg);
+ pagecache = bpf_mem_cgroup_page_state(memcg, NR_FILE_PAGES);
+
+ if (usage > pagecache)
+ usage -= pagecache;
+ else
+ usage = 0;
+
+ if (usage > max_usage && mem_cgroup_killable(memcg)) {
+ max_usage = usage;
+ if (chosen)
+ bpf_put_mem_cgroup(chosen);
+ chosen = bpf_get_mem_cgroup(&memcg->css);
+ }
+
+ bpf_put_mem_cgroup(memcg);
+ }
+ bpf_rcu_read_unlock();
+
+ if (ret || !chosen)
+ goto put_chosen;
+
+ bpf_for_each(css_task, task, &chosen->css, CSS_TASK_ITER_PROCS) {
+ struct task_struct *t = bpf_task_acquire(task);
+
+ if (t) {
+ if (!bpf_oom_kill_process(oc, t, "bpf oom test"))
+ ret = 1;
+ bpf_task_release(t);
+ }
+ }
+
+put_chosen:
+ if (chosen)
+ bpf_put_mem_cgroup(chosen);
+exit:
+ bpf_put_mem_cgroup(root_memcg);
+
+ return ret;
+}
+
+SEC(".struct_ops.link")
+struct bpf_oom_ops test_bpf_oom = {
+ .name = "bpf_test_policy",
+ .handle_out_of_memory = (void *)test_out_of_memory,
+};
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 06/17] sched/psi: add a tracepoint to psi_avgs_work()
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (4 preceding siblings ...)
2026-12-02 21:03 ` [PATCH bpf-next v4 05/17] selftests/bpf: Add BPF OOM struct ops test Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:15 ` sashiko-bot
2026-12-02 21:03 ` [PATCH bpf-next v4 07/17] sched/psi: add cgroup_id field to psi_group structure Ben Gardon
` (11 subsequent siblings)
17 siblings, 1 reply; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Peter Zijlstra, Steven Rostedt, Masami Hiramatsu,
Mathieu Desnoyers, Ingo Molnar, Juri Lelli, Vincent Guittot,
Dietmar Eggemann, Ben Segall, Mel Gorman, Valentin Schneider,
K Prateek Nayak, linux-trace-kernel
From: Roman Gushchin <roman.gushchin@linux.dev>
Add a bare tracepoint to psi_avgs_work() to allow BPF programs to
monitor memory pressure.
Add include/trace/events/psi.h to the PSI entry in MAINTAINERS.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Co-developed-by: Ben Gardon <bgardon@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Switched from TRACE_EVENT() to bare DECLARE_TRACE() (psi_avgs_work_tp)
so no pointer-only tracefs event ABI is exported.
- Added include/trace/events/psi.h to the PSI entry in MAINTAINERS.
v3: https://lore.kernel.org/all/20260127024421.494929-14-roman.gushchin@linux.dev/
MAINTAINERS | 1 +
include/trace/events/psi.h | 19 +++++++++++++++++++
kernel/sched/psi.c | 6 ++++++
3 files changed, 26 insertions(+)
create mode 100644 include/trace/events/psi.h
diff --git a/MAINTAINERS b/MAINTAINERS
index d4ef52c5594b..8bb61211b7f0 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -22397,6 +22397,7 @@ M: Suren Baghdasaryan <surenb@google.com>
R: Peter Zijlstra <peterz@infradead.org>
S: Maintained
F: include/linux/psi*
+F: include/trace/events/psi.h
F: kernel/sched/psi.c
PROPELLER BUILD
diff --git a/include/trace/events/psi.h b/include/trace/events/psi.h
new file mode 100644
index 000000000000..838dc95c3401
--- /dev/null
+++ b/include/trace/events/psi.h
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#undef TRACE_SYSTEM
+#define TRACE_SYSTEM psi
+
+#if !defined(_TRACE_PSI_H) || defined(TRACE_HEADER_MULTI_READ)
+#define _TRACE_PSI_H
+
+#include <linux/tracepoint.h>
+
+struct psi_group;
+
+DECLARE_TRACE(psi_avgs_work,
+ TP_PROTO(struct psi_group *group),
+ TP_ARGS(group));
+
+#endif /* _TRACE_PSI_H */
+
+/* This part must be outside protection */
+#include <trace/define_trace.h>
diff --git a/kernel/sched/psi.c b/kernel/sched/psi.c
index 7c5381423334..d89c40902492 100644
--- a/kernel/sched/psi.c
+++ b/kernel/sched/psi.c
@@ -141,6 +141,10 @@
#include <linux/psi.h>
#include "sched.h"
+#define CREATE_TRACE_POINTS
+#include <trace/events/psi.h>
+#undef CREATE_TRACE_POINTS
+
static int psi_bug __read_mostly;
DEFINE_STATIC_KEY_FALSE(psi_disabled);
@@ -607,6 +611,8 @@ static void psi_avgs_work(struct work_struct *work)
group->avg_next_update - now) + 1);
}
+ trace_psi_avgs_work_tp(group);
+
mutex_unlock(&group->avgs_lock);
}
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 06/17] sched/psi: add a tracepoint to psi_avgs_work()
2026-12-02 21:03 ` [PATCH bpf-next v4 06/17] sched/psi: add a tracepoint to psi_avgs_work() Ben Gardon
@ 2026-12-02 21:15 ` sashiko-bot
0 siblings, 0 replies; 27+ messages in thread
From: sashiko-bot @ 2026-12-02 21:15 UTC (permalink / raw)
To: Ben Gardon, Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, Peter Zijlstra,
Steven Rostedt, Masami Hiramatsu, Mathieu Desnoyers, Ingo Molnar,
Juri Lelli, Vincent Guittot, Dietmar Eggemann, Ben Segall,
Mel Gorman, Valentin Schneider, K Prateek Nayak,
linux-trace-kernel, mkoutny
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] sched/psi: unused str__psi__trace_system_name under W=1 in psi.h
--
commit ccf7af309445d6294253ead38a2646c48459fef4
Author: Roman Gushchin <roman.gushchin@linux.dev>
sched/psi: add a tracepoint to psi_avgs_work()
This commit adds a bare tracepoint to psi_avgs_work() so BPF programs can
monitor pressure stall information updates.
> diff --git a/include/trace/events/psi.h b/include/trace/events/psi.h
> new file mode 100644
> index 0000000000000..838dc95c34012
> --- /dev/null
> +++ b/include/trace/events/psi.h
> @@ -0,0 +1,19 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +#undef TRACE_SYSTEM
> +#define TRACE_SYSTEM psi
> +
> +#if !defined(_TRACE_PSI_H) || defined(TRACE_HEADER_MULTI_READ)
> +#define _TRACE_PSI_H
> +
> +#include <linux/tracepoint.h>
> +
> +struct psi_group;
> +
> +DECLARE_TRACE(psi_avgs_work,
> + TP_PROTO(struct psi_group *group),
> + TP_ARGS(group));
> +
> +#endif /* _TRACE_PSI_H */
> +
> +/* This part must be outside protection */
> +#include <trace/define_trace.h>
[Severity: Low]
Does building with W=1 emit a -Wunused-const-variable warning (and fail under
CONFIG_WERROR=y) for str__psi__trace_system_name[] when kernel/sched/psi.c
defines CREATE_TRACE_POINTS?
When CONFIG_TRACEPOINTS=y, include/trace/define_trace.h pulls in
include/trace/trace_events.h and include/trace/stages/init.h, which defines
static const char str__psi__trace_system_name[] via TRACE_MAKE_SYSTEM_STR()
without __maybe_unused. That string is only referenced by
DECLARE_EVENT_CLASS(), TRACE_DEFINE_ENUM() and TRACE_DEFINE_SIZEOF(), so a
header with only DECLARE_TRACE() leaves it unused.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261202210415.517651-1-bgardon@google.com?part=6
^ permalink raw reply [flat|nested] 27+ messages in thread
* [PATCH bpf-next v4 07/17] sched/psi: add cgroup_id field to psi_group structure
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (5 preceding siblings ...)
2026-12-02 21:03 ` [PATCH bpf-next v4 06/17] sched/psi: add a tracepoint to psi_avgs_work() Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 08/17] mm, bpf: allow calling bpf_out_of_memory() from a PSI tracepoint Ben Gardon
` (10 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Peter Zijlstra, Ingo Molnar, Juri Lelli,
Vincent Guittot, Dietmar Eggemann, Steven Rostedt, Ben Segall,
Mel Gorman, Valentin Schneider, K Prateek Nayak
From: Roman Gushchin <roman.gushchin@linux.dev>
Allow a BPF program attached to a PSI tracepoint to identify the associated
memory cgroup, store cgroup_id inside struct psi_group.
Note that the root cgroup aliases psi_system and keeps cgroup_id == 0.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Guard cgroup_id with #ifdef CONFIG_CGROUPS and note root/psi_system
aliasing (cgroup_id == 0).
v3: https://lore.kernel.org/all/20260127024421.494929-15-roman.gushchin@linux.dev/
include/linux/psi_types.h | 6 ++++++
kernel/sched/psi.c | 1 +
2 files changed, 7 insertions(+)
diff --git a/include/linux/psi_types.h b/include/linux/psi_types.h
index dd10c22299ab..597f6fabf688 100644
--- a/include/linux/psi_types.h
+++ b/include/linux/psi_types.h
@@ -159,6 +159,12 @@ struct psi_trigger {
struct psi_group {
struct psi_group *parent;
+
+#ifdef CONFIG_CGROUPS
+ /* Cgroup id for non-root cgroups; 0 for root (aliases psi_system) */
+ u64 cgroup_id;
+#endif
+
bool enabled;
/* Protects data used by the aggregator */
diff --git a/kernel/sched/psi.c b/kernel/sched/psi.c
index d89c40902492..571266028a50 100644
--- a/kernel/sched/psi.c
+++ b/kernel/sched/psi.c
@@ -1119,6 +1119,7 @@ int psi_cgroup_alloc(struct cgroup *cgroup)
if (!cgroup->psi)
return -ENOMEM;
+ cgroup->psi->cgroup_id = cgroup_id(cgroup);
cgroup->psi->pcpu = alloc_percpu(struct psi_group_cpu);
if (!cgroup->psi->pcpu) {
kfree(cgroup->psi);
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 08/17] mm, bpf: allow calling bpf_out_of_memory() from a PSI tracepoint
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (6 preceding siblings ...)
2026-12-02 21:03 ` [PATCH bpf-next v4 07/17] sched/psi: add cgroup_id field to psi_group structure Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:03 ` [PATCH bpf-next v4 09/17] selftests/bpf: Enable CONFIG_PSI Ben Gardon
` (9 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Michal Hocko
From: Roman Gushchin <roman.gushchin@linux.dev>
Register bpf_declare_oom_kfuncs on BPF_PROG_TYPE_TRACING with a
filter restricted to the btf_trace_psi_avgs_work_tp tracepoint.
psi_avgs_work() runs in workqueue context outside oom_lock, and because
bpf_out_of_memory() is KF_SLEEPABLE, tracepoint programs invoke it
asynchronously via a sleepable callback (such as bpf_task_work
or bpf_wq), avoiding any deadlock on oom_lock or avgs_lock.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Co-developed-by: Ben Gardon <bgardon@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Registered directly on BPF_PROG_TYPE_TRACING with a tracing-only
filter checking BPF_TRACE_RAW_TP and !prog->aux->dst_prog.
- Guarded with CONFIG_PSI && CONFIG_BPF_EVENTS and updated to
btf_trace_psi_avgs_work_tp.
v3: https://lore.kernel.org/all/20260127024421.494929-16-roman.gushchin@linux.dev/
mm/oom_kill.c | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/mm/oom_kill.c b/mm/oom_kill.c
index 9b5df00f98ab..21b88332a46a 100644
--- a/mm/oom_kill.c
+++ b/mm/oom_kill.c
@@ -1420,6 +1420,32 @@ static const struct btf_kfunc_id_set bpf_declare_oom_syscall_kfunc_set = {
.set = &bpf_declare_oom_kfuncs,
};
+#if defined(CONFIG_PSI) && defined(CONFIG_BPF_EVENTS)
+BTF_ID_LIST_SINGLE(bpf_oom_trace_ids, typedef, btf_trace_psi_avgs_work_tp)
+
+static int bpf_declare_oom_tracing_filter(const struct bpf_prog *prog,
+ u32 kfunc_id)
+{
+ if (!btf_id_set8_contains(&bpf_declare_oom_kfuncs, kfunc_id))
+ return 0;
+
+ if (prog->type == BPF_PROG_TYPE_TRACING &&
+ prog->expected_attach_type == BPF_TRACE_RAW_TP &&
+ !prog->aux->dst_prog &&
+ bpf_oom_trace_ids[0] &&
+ prog->aux->attach_btf_id == bpf_oom_trace_ids[0])
+ return 0;
+
+ return -EACCES;
+}
+
+static const struct btf_kfunc_id_set bpf_declare_oom_tracing_kfunc_set = {
+ .owner = THIS_MODULE,
+ .set = &bpf_declare_oom_kfuncs,
+ .filter = bpf_declare_oom_tracing_filter,
+};
+#endif /* CONFIG_PSI && CONFIG_BPF_EVENTS */
+
static int __init bpf_oom_init(void)
{
int err;
@@ -1438,6 +1464,15 @@ static int __init bpf_oom_init(void)
return err;
}
+#if defined(CONFIG_PSI) && defined(CONFIG_BPF_EVENTS)
+ err = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
+ &bpf_declare_oom_tracing_kfunc_set);
+ if (err) {
+ pr_warn("error while registering tracing bpf oom kfuncs: %d\n", err);
+ return err;
+ }
+#endif
+
return 0;
}
late_initcall(bpf_oom_init);
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 09/17] selftests/bpf: Enable CONFIG_PSI
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (7 preceding siblings ...)
2026-12-02 21:03 ` [PATCH bpf-next v4 08/17] mm, bpf: allow calling bpf_out_of_memory() from a PSI tracepoint Ben Gardon
@ 2026-12-02 21:03 ` Ben Gardon
2026-12-02 21:04 ` [PATCH bpf-next v4 10/17] selftests/bpf: Add PSI tracepoint OOM test Ben Gardon
` (8 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:03 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
JP Kobryn, Ben Gardon, Shuah Khan, linux-kselftest
From: JP Kobryn <inwardvessel@gmail.com>
Include CONFIG_PSI to allow dependent tests to build.
Suggested-by: Song Liu <song@kernel.org>
Signed-off-by: JP Kobryn <inwardvessel@gmail.com>
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Standardized subject prefix.
v3: https://lore.kernel.org/all/20260127024421.494929-17-roman.gushchin@linux.dev/
tools/testing/selftests/bpf/config | 1 +
1 file changed, 1 insertion(+)
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index ce0db4be4d26..36651bf5533c 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -121,6 +121,7 @@ CONFIG_IP6_NF_IPTABLES=y
CONFIG_IP6_NF_FILTER=y
CONFIG_NF_NAT=y
CONFIG_PACKET=y
+CONFIG_PSI=y
CONFIG_RC_CORE=y
CONFIG_SAMPLES=y
CONFIG_SAMPLE_LIVEPATCH=m
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 10/17] selftests/bpf: Add PSI tracepoint OOM test
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (8 preceding siblings ...)
2026-12-02 21:03 ` [PATCH bpf-next v4 09/17] selftests/bpf: Enable CONFIG_PSI Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:04 ` [PATCH bpf-next v4 11/17] selftests/bpf: Add systemd-oomd style OOM policy test Ben Gardon
` (7 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Shuah Khan, linux-kselftest
From: Roman Gushchin <roman.gushchin@linux.dev>
Add a BPF selftest attaching to the psi_avgs_work_tp tracepoint to
monitor memory pressure in a cgroup throttled by memory.high.
When full memory stall growth exceeds 50 ms within an update interval,
the tracepoint schedules a sleepable bpf_task_work callback that invokes
bpf_out_of_memory() for the pressured cgroup, verifying that the
allocating task is terminated with SIGKILL and memory.events records
oom_kill 1.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Co-developed-by: Ben Gardon <bgardon@google.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
v3 -> v4:
- Updated subject/body from stale "PSI struct ops test" to reflect the
psi_avgs_work_tp tracepoint design.
- Indexed the BTF-flattened group->total array explicitly as
total[PSI_AVGS * (NR_PSI_STATES - 1) + PSI_MEM_FULL], added missing
SPDX header, removed redundant extern __ksym declarations, and
dropped the first-interval skip.
- Replaced cgroup freezing and racy fork/migration with a sync pipe,
removed dead struct_ops remnants and FD/child leaks, added runtime PSI
skip check, verified SIGKILL, and renamed to serial_test_psi().
v3: https://lore.kernel.org/all/20260127024421.494929-18-roman.gushchin@linux.dev/
.../selftests/bpf/prog_tests/test_psi.c | 107 ++++++++++++++++++
tools/testing/selftests/bpf/progs/test_psi.c | 88 ++++++++++++++
2 files changed, 195 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/test_psi.c
create mode 100644 tools/testing/selftests/bpf/progs/test_psi.c
diff --git a/tools/testing/selftests/bpf/prog_tests/test_psi.c b/tools/testing/selftests/bpf/prog_tests/test_psi.c
new file mode 100644
index 000000000000..9f3fdf2d6c5b
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/test_psi.c
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <sys/wait.h>
+#include <test_progs.h>
+#include <bpf/bpf.h>
+#include <bpf/btf.h>
+
+#include "cgroup_helpers.h"
+#include "memory_holder.h"
+
+#define MB (1024UL * 1024UL)
+#include "test_psi.skel.h"
+
+/*
+ * Serialized because this test attaches to the global psi_avgs_work_tp
+ * tracepoint and drives real memory pressure / OOM under memory.high, which
+ * can interfere with other OOM tests running concurrently under test_progs -j.
+ */
+void serial_test_psi(void)
+{
+ const char *parent_cg = "/psi_test";
+ const char *target_cg = "/psi_test/cg";
+ struct test_psi *skel = NULL;
+ struct memory_holder worker;
+ int parent_fd = -1, target_fd = -1;
+ int status = 0, err;
+ unsigned long long cg_id;
+ char buf[4096] = {};
+
+ memory_holder_init(&worker);
+
+ if (access("/proc/pressure/memory", R_OK) != 0) {
+ test__skip();
+ return;
+ }
+
+ err = setup_cgroup_environment();
+ if (!ASSERT_OK(err, "setup_cgroup_environment"))
+ return;
+
+ parent_fd = create_and_get_cgroup(parent_cg);
+ if (!ASSERT_GE(parent_fd, 0, "create parent cgroup"))
+ goto cleanup;
+
+ err = write_cgroup_file(parent_cg, "cgroup.subtree_control", "+memory");
+ if (!ASSERT_OK(err, "enable memory controller"))
+ goto cleanup;
+
+ target_fd = create_and_get_cgroup(target_cg);
+ if (!ASSERT_GE(target_fd, 0, "create target cgroup"))
+ goto cleanup;
+
+ cg_id = get_cgroup_id(target_cg);
+ if (!ASSERT_GT(cg_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%lu", 40 * MB);
+ err = write_cgroup_file(target_cg, "memory.high", buf);
+ if (!ASSERT_OK(err, "set memory.high"))
+ goto cleanup;
+ write_cgroup_file(target_cg, "memory.swap.max", "0");
+
+ err = memory_holder_spawn(&worker, 500 * MB, MB, 0, true);
+ if (!ASSERT_OK(err, "spawn worker"))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%d", worker.pid);
+ err = write_cgroup_file(target_cg, "cgroup.procs", buf);
+ if (!ASSERT_OK(err, "put child into cgroup"))
+ goto cleanup;
+
+ skel = test_psi__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "open_and_load"))
+ goto cleanup;
+
+ skel->bss->high_pressure_cgroup_id = cg_id;
+ skel->bss->my_pid = getpid();
+
+ err = test_psi__attach(skel);
+ if (!ASSERT_OK(err, "attach"))
+ goto cleanup;
+
+ /* Release worker now that it is inside target_cg and PSI BPF is attached */
+ if (!ASSERT_OK(memory_holder_start(&worker), "release worker"))
+ goto cleanup;
+
+ if (!ASSERT_EQ(waitpid(worker.pid, &status, 0), worker.pid,
+ "waitpid worker"))
+ goto cleanup;
+ worker.pid = -1;
+
+ ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL,
+ "worker terminated by SIGKILL");
+
+ if (ASSERT_OK(read_cgroup_file(target_cg, "memory.events",
+ buf, sizeof(buf)),
+ "read memory.events"))
+ ASSERT_OK_PTR(strstr(buf, "oom_kill 1"), "oom_kill count check");
+
+cleanup:
+ memory_holder_cleanup(&worker);
+ if (target_fd >= 0)
+ close(target_fd);
+ if (parent_fd >= 0)
+ close(parent_fd);
+ test_psi__destroy(skel);
+ cleanup_cgroup_environment();
+}
diff --git a/tools/testing/selftests/bpf/progs/test_psi.c b/tools/testing/selftests/bpf/progs/test_psi.c
new file mode 100644
index 000000000000..927c1b8323d0
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_psi.c
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include "bpf_experimental.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include <bpf/bpf_core_read.h>
+
+char _license[] SEC("license") = "GPL";
+
+/* cgroup which will experience the high memory pressure */
+u64 high_pressure_cgroup_id;
+u32 my_pid = 0;
+
+/* last total full memory pressure value */
+u64 last_mem_full_total = 0;
+
+struct elem {
+ struct bpf_task_work tw;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, int);
+ __type(value, struct elem);
+} tw_map SEC(".maps");
+
+static int psi_oom_work(struct bpf_map *map, void *key, void *value)
+{
+ struct cgroup *cgrp;
+ struct mem_cgroup *memcg;
+
+ cgrp = bpf_cgroup_from_id(high_pressure_cgroup_id);
+ if (!cgrp)
+ return 0;
+
+ memcg = bpf_get_mem_cgroup(&cgrp->self);
+ if (memcg) {
+ bpf_out_of_memory(memcg, 0, BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK);
+ bpf_put_mem_cgroup(memcg);
+ }
+
+ bpf_cgroup_release(cgrp);
+ return 0;
+}
+
+static void schedule_oom_work(void)
+{
+ struct task_struct *task;
+ struct elem *val;
+ int key = 0;
+
+ task = bpf_task_from_pid(my_pid);
+ if (task) {
+ val = bpf_map_lookup_elem(&tw_map, &key);
+ if (val)
+ bpf_task_work_schedule_signal(task, &val->tw,
+ &tw_map, psi_oom_work);
+ bpf_task_release(task);
+ }
+}
+
+SEC("tp_btf/psi_avgs_work_tp")
+int BPF_PROG(psi_avgs, struct psi_group *group)
+{
+ u64 current_total;
+ u64 growth;
+
+ /* Monitor only a single target cgroup */
+ if (group->cgroup_id != high_pressure_cgroup_id)
+ return 0;
+
+ /*
+ * Check for memory pressure. BTF flattens the 2D array
+ * total[NR_PSI_AGGREGATORS][NR_PSI_STATES - 1] in vmlinux.h.
+ */
+ current_total = BPF_CORE_READ(group,
+ total[PSI_AVGS * (NR_PSI_STATES - 1) +
+ PSI_MEM_FULL]);
+ growth = current_total - last_mem_full_total;
+ last_mem_full_total = current_total;
+
+ /* Declare an OOM if growth > 50ms within the update period */
+ if (growth > 50000000)
+ schedule_oom_work();
+
+ return 0;
+}
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 11/17] selftests/bpf: Add systemd-oomd style OOM policy test
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (9 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 10/17] selftests/bpf: Add PSI tracepoint OOM test Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:58 ` bot+bpf-ci
2026-12-02 21:04 ` [PATCH bpf-next v4 12/17] mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention Ben Gardon
` (6 subsequent siblings)
17 siblings, 1 reply; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Shuah Khan, linux-kselftest
From: Roman Gushchin <roman.gushchin@linux.dev>
Add a BPF OOM policy example that mirrors the core candidate selection
rules used by systemd-oomd.
The policy treats leaf cgroups and memory.oom.group cgroups as candidates.
User-space ManagedOOMPreference-style inputs, are supplied through a cgroup-id
keyed map. The policy excludes "omit" candidates, demotes "avoid" candidates,
and ranks the rest by memory.stat pgscan delta with memory.current as the tie
breaker.
The selftest:
1. builds a small systemd-like hierarchy with various types of memory holders:
a. omitted
b. avoided
c. normal
d. oom_score_adj=-1000
2. attaches the policy through cgroup struct_ops
3. forces a memcg OOM
4. verifies that the selected cgroup, selected task, skipped-candidate
accounting, and BPF OOM status match expectations.
Signed-off-by: Roman Gushchin <roman.gushchin@linux.dev>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
.../selftests/bpf/prog_tests/test_oomd.c | 274 ++++++++++++++
tools/testing/selftests/bpf/progs/test_oomd.c | 346 ++++++++++++++++++
tools/testing/selftests/bpf/progs/test_oomd.h | 33 ++
3 files changed, 653 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oomd.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oomd.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oomd.h
diff --git a/tools/testing/selftests/bpf/prog_tests/test_oomd.c b/tools/testing/selftests/bpf/prog_tests/test_oomd.c
new file mode 100644
index 000000000000..001b2262a2ae
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/test_oomd.c
@@ -0,0 +1,274 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <sys/wait.h>
+#include <test_progs.h>
+#include <bpf/bpf.h>
+#include <bpf/btf.h>
+
+#include "cgroup_helpers.h"
+#include "memory_holder.h"
+
+#define MB (1024UL * 1024UL)
+#include "progs/test_oomd.h"
+#include "test_oomd.skel.h"
+
+struct oomd_cgroup_desc {
+ const char *path;
+ int fd;
+ unsigned long long id;
+ struct memory_holder worker;
+ size_t target;
+ size_t max;
+ int oom_score_adj;
+ enum oomd_preference preference;
+ bool expect_terminated;
+};
+
+/*
+ * Baseline workers total 110 MB (critical 30 + batch-a 35 + batch-c 15 +
+ * exempt 30), under the 135 MB memory.max. Once they are idle, batch-b
+ * allocates 35 MB and crosses 135 MB at ~25 MB, triggering a single
+ * deterministic OOM where critical (OMIT), batch-a (AVOID), and exempt
+ * (OOM_SCORE_ADJ_MIN) are all larger than batch-b, and batch-b (~25 MB) is
+ * larger than batch-c (15 MB).
+ */
+static struct oomd_cgroup_desc cgroups[] = {
+ { .path = "/oomd_test", .max = 135 * MB },
+ { .path = "/oomd_test/system.slice" },
+ { .path = "/oomd_test/system.slice/critical.service",
+ .target = 30 * MB, .preference = OOMD_PREFERENCE_OMIT },
+ { .path = "/oomd_test/workload.slice" },
+ { .path = "/oomd_test/workload.slice/batch-a.service",
+ .target = 35 * MB, .preference = OOMD_PREFERENCE_AVOID },
+ { .path = "/oomd_test/workload.slice/batch-b.service",
+ .target = 35 * MB, .expect_terminated = true },
+ { .path = "/oomd_test/workload.slice/batch-c.service",
+ .target = 15 * MB },
+ { .path = "/oomd_test/workload.slice/exempt.service",
+ .target = 30 * MB, .oom_score_adj = OOM_SCORE_ADJ_MIN },
+};
+
+static void reset_cgroups(void)
+{
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ cgroups[i].fd = -1;
+ cgroups[i].id = 0;
+ memory_holder_init(&cgroups[i].worker);
+ }
+}
+
+static void cleanup_cgroups(void)
+{
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ memory_holder_cleanup(&cgroups[i].worker);
+ if (cgroups[i].fd >= 0) {
+ close(cgroups[i].fd);
+ cgroups[i].fd = -1;
+ }
+ }
+}
+
+static int setup_environment(void)
+{
+ int i, err;
+
+ reset_cgroups();
+
+ err = setup_cgroup_environment();
+ if (!ASSERT_OK(err, "setup_cgroup_environment"))
+ return -1;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ char buf[64];
+
+ cgroups[i].fd = create_and_get_cgroup(cgroups[i].path);
+ if (!ASSERT_GE(cgroups[i].fd, 0, "create_and_get_cgroup"))
+ return -1;
+
+ cgroups[i].id = get_cgroup_id(cgroups[i].path);
+ if (!ASSERT_GT(cgroups[i].id, 0, "get_cgroup_id"))
+ return -1;
+
+ if (cgroups[i].target == 0) {
+ err = write_cgroup_file(cgroups[i].path,
+ "cgroup.subtree_control",
+ "+memory");
+ if (!ASSERT_OK(err, "enable memory controller"))
+ return -1;
+ }
+
+ if (cgroups[i].max) {
+ snprintf(buf, sizeof(buf), "%zu", cgroups[i].max);
+ err = write_cgroup_file(cgroups[i].path, "memory.max",
+ buf);
+ if (!ASSERT_OK(err, "set memory.max"))
+ return -1;
+ write_cgroup_file(cgroups[i].path, "memory.swap.max",
+ "0");
+ }
+
+ if (cgroups[i].target) {
+ err = memory_holder_spawn(&cgroups[i].worker,
+ cgroups[i].target, 0,
+ cgroups[i].oom_score_adj,
+ cgroups[i].expect_terminated);
+ if (!ASSERT_OK(err, "spawn task"))
+ return -1;
+
+ snprintf(buf, sizeof(buf), "%d", cgroups[i].worker.pid);
+ err = write_cgroup_file(cgroups[i].path, "cgroup.procs",
+ buf);
+ if (!ASSERT_OK(err, "put child into cgroup"))
+ return -1;
+ }
+ }
+
+ /* Pre-allocate all baseline workers under memory.max */
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ if (!cgroups[i].target || cgroups[i].expect_terminated)
+ continue;
+
+ if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker),
+ "start baseline task"))
+ return -1;
+ if (!ASSERT_OK(memory_holder_wait_ready(&cgroups[i].worker),
+ "wait baseline task"))
+ return -1;
+ }
+
+ return 0;
+}
+
+static int configure_policies(struct test_oomd *skel)
+{
+ int map_fd = bpf_map__fd(skel->maps.oomd_policies);
+ int i, err;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ struct oomd_policy policy = {
+ .preference = cgroups[i].preference,
+ };
+ __u64 cgid = cgroups[i].id;
+
+ err = bpf_map_update_elem(map_fd, &cgid, &policy, BPF_ANY);
+ if (!ASSERT_OK(err, "configure oomd policy"))
+ return -1;
+ }
+
+ return 0;
+}
+
+static int run_and_wait_for_oom(struct test_oomd *skel)
+{
+ int map_fd = bpf_map__fd(skel->maps.oomd_decisions);
+ struct oomd_decision decision = {};
+ struct oomd_cgroup_desc *target = NULL;
+ __u32 key = 0;
+ pid_t target_pid;
+ int status = 0;
+ int i, err;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ if (cgroups[i].expect_terminated) {
+ target = &cgroups[i];
+ break;
+ }
+ }
+ if (!ASSERT_OK_PTR(target, "find target cgroup"))
+ return -1;
+
+ target_pid = target->worker.pid;
+
+ /* Release the trigger worker to cross memory.max */
+ if (!ASSERT_OK(memory_holder_start(&target->worker),
+ "start trigger task"))
+ return -1;
+
+ if (!ASSERT_EQ(waitpid(target_pid, &status, 0), target_pid,
+ "waitpid trigger"))
+ return -1;
+ target->worker.pid = -1;
+
+ if (!ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL,
+ "expected process was terminated"))
+ return -1;
+
+ for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
+ if (cgroups[i].worker.pid > 0) {
+ if (!ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status,
+ WNOHANG),
+ 0, "non-target task survived"))
+ return -1;
+ }
+ }
+
+ err = bpf_map_lookup_elem(map_fd, &key, &decision);
+ if (!ASSERT_OK(err, "lookup oomd decision"))
+ return -1;
+
+ if (!ASSERT_EQ(decision.victim_cgid, target->id, "selected cgroup"))
+ return -1;
+ if (!ASSERT_EQ(decision.killed_pid, target_pid, "selected task"))
+ return -1;
+ if (!ASSERT_GE(decision.scanned_candidates, 3, "scanned candidates"))
+ return -1;
+ if (!ASSERT_GE(decision.skipped_omit, 1, "skipped omitted cgroup"))
+ return -1;
+ if (!ASSERT_GE(decision.skipped_unkillable, 1, "skipped exempt cgroup"))
+ return -1;
+ if (!ASSERT_OK(decision.kill_ret, "bpf oom kill"))
+ return -1;
+
+ return 0;
+}
+
+/*
+ * Serialized because this test attaches a BPF OOM policy to the root cgroup
+ * and triggers real memcg OOMs, which would collide with other OOM tests
+ * running in parallel under test_progs -j.
+ */
+void serial_test_oomd(void)
+{
+ LIBBPF_OPTS(bpf_cgroup_opts, opts);
+ struct bpf_link *cgroup_link = NULL, *root_link = NULL;
+ struct test_oomd *skel = NULL;
+ int root_cg_fd = -1;
+
+ if (setup_environment())
+ goto cleanup;
+
+ skel = test_oomd__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "open_and_load"))
+ goto cleanup;
+
+ if (configure_policies(skel))
+ goto cleanup;
+
+ cgroup_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oomd,
+ cgroups[0].fd, &opts);
+ if (!ASSERT_OK_PTR(cgroup_link, "attach_oomd_cgroup"))
+ goto cleanup;
+
+ root_cg_fd = get_root_cgroup();
+ if (!ASSERT_GE(root_cg_fd, 0, "get_root_cgroup"))
+ goto cleanup;
+
+ root_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oomd,
+ root_cg_fd, &opts);
+ if (!ASSERT_OK_PTR(root_link, "attach_oomd_root"))
+ goto cleanup;
+
+ ASSERT_OK(run_and_wait_for_oom(skel), "run_and_wait_for_oom");
+
+cleanup:
+ bpf_link__destroy(root_link);
+ bpf_link__destroy(cgroup_link);
+ if (root_cg_fd >= 0)
+ close(root_cg_fd);
+ cleanup_cgroups();
+ cleanup_cgroup_environment();
+ test_oomd__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/test_oomd.c b/tools/testing/selftests/bpf/progs/test_oomd.c
new file mode 100644
index 000000000000..c307fa276c43
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oomd.c
@@ -0,0 +1,346 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include <bpf/bpf_core_read.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "test_oomd.h"
+
+char _license[] SEC("license") = "GPL";
+
+struct {
+ __uint(type, BPF_MAP_TYPE_HASH);
+ __uint(max_entries, 128);
+ __type(key, __u64);
+ __type(value, struct oomd_policy);
+} oomd_policies SEC(".maps");
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, struct oomd_decision);
+} oomd_decisions SEC(".maps");
+
+static __u64 cgroup_id(struct cgroup *cgrp)
+{
+ return BPF_CORE_READ(cgrp, kn, id);
+}
+
+/* Caller must hold bpf_rcu_read_lock() */
+static bool mem_cgroup_has_oom_victim(struct mem_cgroup *root_memcg)
+{
+ struct cgroup_subsys_state *pos;
+ struct task_struct *task;
+ bool found = false;
+
+ bpf_for_each(css, pos, &root_memcg->css,
+ BPF_CGROUP_ITER_DESCENDANTS_PRE) {
+ struct mem_cgroup *m = bpf_get_mem_cgroup(pos);
+
+ if (!m)
+ continue;
+ bpf_for_each(css_task, task, &m->css, CSS_TASK_ITER_PROCS) {
+ if (BPF_CORE_READ(task, signal, oom_mm)) {
+ found = true;
+ break;
+ }
+ }
+ bpf_put_mem_cgroup(m);
+ if (found)
+ return true;
+ }
+
+ return false;
+}
+
+/* Caller must hold bpf_rcu_read_lock() */
+static bool mem_cgroup_killable(struct mem_cgroup *memcg)
+{
+ struct cgroup_subsys_state *pos;
+ struct task_struct *task;
+ bool killable = true;
+
+ bpf_for_each(css, pos, &memcg->css, BPF_CGROUP_ITER_DESCENDANTS_PRE) {
+ struct mem_cgroup *m = bpf_get_mem_cgroup(pos);
+
+ if (!m)
+ continue;
+ bpf_for_each(css_task, task, &m->css, CSS_TASK_ITER_PROCS) {
+ if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN) {
+ killable = false;
+ break;
+ }
+ }
+ bpf_put_mem_cgroup(m);
+ if (!killable)
+ return false;
+ }
+
+ return true;
+}
+
+static __u64 memcg_pgscan(struct mem_cgroup *memcg)
+{
+ int kswapd = bpf_core_enum_value(enum node_stat_item, PGSCAN_KSWAPD);
+ int direct = bpf_core_enum_value(enum node_stat_item, PGSCAN_DIRECT);
+ int khugepaged = bpf_core_enum_value(enum node_stat_item,
+ PGSCAN_KHUGEPAGED);
+ int proactive = bpf_core_enum_value(enum node_stat_item,
+ PGSCAN_PROACTIVE);
+
+ return bpf_mem_cgroup_page_state(memcg, kswapd) +
+ bpf_mem_cgroup_page_state(memcg, direct) +
+ bpf_mem_cgroup_page_state(memcg, khugepaged) +
+ bpf_mem_cgroup_page_state(memcg, proactive);
+}
+
+static __u64 oomd_pgscan_delta(struct oomd_policy *policy, __u64 pgscan)
+{
+ __u64 last_pgscan = 0;
+
+ if (policy) {
+ last_pgscan = policy->last_pgscan;
+ policy->last_pgscan = pgscan;
+ }
+
+ if (last_pgscan > pgscan)
+ return 0;
+
+ return pgscan - last_pgscan;
+}
+
+static bool oomd_better_candidate(__u8 pref, __u64 delta, __u64 usage,
+ __u8 best_pref, __u64 best_delta,
+ __u64 best_usage, bool have_best)
+{
+ if (!have_best)
+ return true;
+
+ /* Prefer normal candidates over "avoid" candidates */
+ if (pref != best_pref)
+ return pref < best_pref;
+
+ /* Primary score: pgscan delta; tie breaker: memory.current */
+ if (delta != best_delta)
+ return delta > best_delta;
+
+ return usage > best_usage;
+}
+
+static int oomd_kill_task(struct oom_control *oc, struct task_struct *task,
+ struct oomd_decision *decision)
+{
+ struct task_struct *t;
+ int ret;
+
+ t = bpf_task_acquire(task);
+ if (!t)
+ return 0;
+
+ if (BPF_CORE_READ(t, signal, oom_mm)) {
+ if (decision)
+ decision->killed_pid = t->pid;
+ bpf_task_release(t);
+ return 1;
+ }
+
+ ret = bpf_oom_kill_process(oc, t, "bpf systemd-oomd policy");
+ if (decision) {
+ decision->kill_ret = ret;
+ if (!ret)
+ decision->killed_pid = t->pid;
+ }
+
+ bpf_task_release(t);
+ return ret ? 0 : 1;
+}
+
+static int oomd_kill_memcg(struct oom_control *oc, struct mem_cgroup *chosen,
+ struct oomd_decision *decision)
+{
+ struct cgroup_subsys_state *pos;
+ struct task_struct *task, *victim = NULL;
+
+ /*
+ * Walk descendants as well as chosen itself so non-leaf
+ * memory.oom.group candidates (which hold no direct tasks in cgroup v2)
+ * still yield a task for bpf_oom_kill_process() to group-kill.
+ */
+ bpf_rcu_read_lock();
+ bpf_for_each(css, pos, &chosen->css, BPF_CGROUP_ITER_DESCENDANTS_PRE) {
+ struct mem_cgroup *m = bpf_get_mem_cgroup(pos);
+
+ if (!m)
+ continue;
+ bpf_for_each(css_task, task, &m->css, CSS_TASK_ITER_PROCS) {
+ victim = bpf_task_acquire(task);
+ if (victim)
+ break;
+ }
+ bpf_put_mem_cgroup(m);
+ if (victim)
+ break;
+ }
+ bpf_rcu_read_unlock();
+
+ if (!victim)
+ return 0;
+
+ {
+ int ret = oomd_kill_task(oc, victim, decision);
+
+ bpf_task_release(victim);
+ return ret;
+ }
+}
+
+/*
+ * A systemd-oomd-style OOM policy:
+ *
+ * - candidates are leaf cgroups, or cgroups marked with memory.oom.group;
+ * - user-space-only systemd inputs such as ManagedOOMPreference/xattrs are
+ * supplied through oomd_policies, keyed by cgroup id;
+ * - "omit" cgroups are ignored and "avoid" cgroups are ranked last;
+ * - the primary score is memory.stat pgscan delta, with memory.current as the
+ * tie breaker;
+ * - when memory.oom.group is set, bpf_oom_kill_process() delegates recursive
+ * group behavior to the kernel OOM handler for the selected task;
+ * - at hard OOM we still allow the memory.current tie breaker to select a
+ * cgroup when all pgscan deltas are zero, so the kernel can make progress.
+ */
+SEC("struct_ops.s/handle_out_of_memory")
+int BPF_PROG(test_oomd_out_of_memory, struct oom_control *oc,
+ struct cgroup *attached_cgrp)
+{
+ struct mem_cgroup *root_memcg = oc->memcg;
+ struct mem_cgroup *memcg, *chosen = NULL;
+ struct cgroup_subsys_state *css_pos, *css;
+ struct oomd_decision *decision;
+ __u8 preference, best_preference = OOMD_PREFERENCE_NONE;
+ __u64 usage, pgscan, delta, swap_usage, cgid;
+ __u64 best_usage = 0, best_delta = 0;
+ struct oomd_policy *policy;
+ bool have_best = false;
+ __u32 zero = 0;
+ int swap_item;
+ int ret = 0;
+
+ if (root_memcg)
+ root_memcg = bpf_get_mem_cgroup(&root_memcg->css);
+ else
+ root_memcg = bpf_get_root_mem_cgroup();
+
+ if (!root_memcg)
+ return 0;
+
+ css = &root_memcg->css;
+ if (css && css->cgroup == attached_cgrp)
+ goto out_put_root;
+
+ /* Back off without overwriting decision while a prior victim exits */
+ bpf_rcu_read_lock();
+ if (mem_cgroup_has_oom_victim(root_memcg)) {
+ bpf_rcu_read_unlock();
+ ret = 1;
+ goto out_put_root;
+ }
+ bpf_rcu_read_unlock();
+
+ decision = bpf_map_lookup_elem(&oomd_decisions, &zero);
+ if (decision) {
+ __builtin_memset(decision, 0, sizeof(*decision));
+ decision->root_cgid = cgroup_id(css->cgroup);
+ }
+
+ bpf_mem_cgroup_flush_stats(root_memcg);
+ swap_item = bpf_core_enum_value(enum memcg_stat_item, MEMCG_SWAP);
+
+ bpf_rcu_read_lock();
+ bpf_for_each(css, css_pos, &root_memcg->css,
+ BPF_CGROUP_ITER_DESCENDANTS_POST) {
+ struct cgroup *cgrp = css_pos->cgroup;
+ bool is_leaf, is_oom_group;
+
+ is_leaf = !(cgrp->nr_descendants + cgrp->nr_dying_descendants);
+
+ memcg = bpf_get_mem_cgroup(css_pos);
+ if (!memcg)
+ continue;
+
+ is_oom_group = BPF_CORE_READ(memcg, oom_group);
+ if (!is_leaf && !is_oom_group) {
+ bpf_put_mem_cgroup(memcg);
+ continue;
+ }
+
+ cgid = cgroup_id(cgrp);
+ policy = bpf_map_lookup_elem(&oomd_policies, &cgid);
+ preference = policy ? policy->preference : OOMD_PREFERENCE_NONE;
+
+ if (preference == OOMD_PREFERENCE_OMIT) {
+ if (decision)
+ decision->skipped_omit++;
+ bpf_put_mem_cgroup(memcg);
+ continue;
+ }
+
+ if (!mem_cgroup_killable(memcg)) {
+ if (decision)
+ decision->skipped_unkillable++;
+ bpf_put_mem_cgroup(memcg);
+ continue;
+ }
+
+ usage = bpf_mem_cgroup_usage(memcg);
+ pgscan = memcg_pgscan(memcg);
+ delta = oomd_pgscan_delta(policy, pgscan);
+ swap_usage = bpf_mem_cgroup_page_state(memcg, swap_item);
+
+ if (decision)
+ decision->scanned_candidates++;
+
+ if (pgscan == 0 && usage == 0) {
+ bpf_put_mem_cgroup(memcg);
+ continue;
+ }
+
+ if (oomd_better_candidate(preference, delta, usage,
+ best_preference, best_delta,
+ best_usage, have_best)) {
+ best_preference = preference;
+ best_delta = delta;
+ best_usage = usage;
+ have_best = true;
+
+ if (chosen)
+ bpf_put_mem_cgroup(chosen);
+ chosen = bpf_get_mem_cgroup(&memcg->css);
+
+ if (decision) {
+ decision->victim_cgid = cgid;
+ decision->victim_usage = usage;
+ decision->victim_pgscan = pgscan;
+ decision->victim_pgscan_delta = delta;
+ decision->victim_swap_usage = swap_usage;
+ }
+ }
+
+ bpf_put_mem_cgroup(memcg);
+ }
+ bpf_rcu_read_unlock();
+
+ if (chosen) {
+ ret = oomd_kill_memcg(oc, chosen, decision);
+ bpf_put_mem_cgroup(chosen);
+ }
+
+out_put_root:
+ bpf_put_mem_cgroup(root_memcg);
+ return ret;
+}
+
+SEC(".struct_ops.link")
+struct bpf_oom_ops test_bpf_oomd = {
+ .name = "bpf_systemd_oomd_policy",
+ .handle_out_of_memory = (void *)test_oomd_out_of_memory,
+};
diff --git a/tools/testing/selftests/bpf/progs/test_oomd.h b/tools/testing/selftests/bpf/progs/test_oomd.h
new file mode 100644
index 000000000000..cbd0d9a9e928
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oomd.h
@@ -0,0 +1,33 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef __TEST_OOMD_H
+#define __TEST_OOMD_H
+
+#define OOM_SCORE_ADJ_MIN (-1000)
+
+enum oomd_preference {
+ OOMD_PREFERENCE_NONE,
+ OOMD_PREFERENCE_AVOID,
+ OOMD_PREFERENCE_OMIT,
+};
+
+struct oomd_policy {
+ __u8 preference;
+ __u8 _pad[7];
+ __u64 last_pgscan;
+};
+
+struct oomd_decision {
+ __u64 root_cgid;
+ __u64 victim_cgid;
+ __u64 victim_usage;
+ __u64 victim_pgscan;
+ __u64 victim_pgscan_delta;
+ __u64 victim_swap_usage;
+ __u64 killed_pid;
+ __u64 scanned_candidates;
+ __u64 skipped_omit;
+ __u64 skipped_unkillable;
+ __s32 kill_ret;
+};
+
+#endif /* __TEST_OOMD_H */
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 11/17] selftests/bpf: Add systemd-oomd style OOM policy test
2026-12-02 21:04 ` [PATCH bpf-next v4 11/17] selftests/bpf: Add systemd-oomd style OOM policy test Ben Gardon
@ 2026-12-02 21:58 ` bot+bpf-ci
0 siblings, 0 replies; 27+ messages in thread
From: bot+bpf-ci @ 2026-12-02 21:58 UTC (permalink / raw)
To: bgardon, ast, daniel, andrii, akpm, hannes, mhocko, shakeel.butt,
roman.gushchin, tj
Cc: jp.kobryn, eddyz87, memxor, martin.lau, song, yonghong.song,
jolsa, emil, ihor.solodrai, rientjes, surenb, joshdon,
sweettea-kernel, zhouchuyi, laoar.shao, benbwgardon, bpf,
linux-mm, cgroups, linux-kernel, bgardon, shuah, linux-kselftest,
ast, andrii, daniel, martin.lau, eddyz87, yonghong.song, mason,
ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 4146 bytes --]
> selftests/bpf: Add systemd-oomd style OOM policy test
TL;DR: Nits only in the selftest: setup code duplicated from test_oom.c, a
redundant task acquire/release, a misnamed cleanup function, and unused
decision fields such as swap usage.
> diff --git a/tools/testing/selftests/bpf/prog_tests/test_oomd.c b/tools/testing/selftests/bpf/prog_tests/test_oomd.c
> new file mode 100644
> --- /dev/null
> +++ b/tools/testing/selftests/bpf/prog_tests/test_oomd.c
[ ... ]
> +static void reset_cgroups(void)
> +{
> + int i;
> +
> + for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
> + cgroups[i].fd = -1;
> + cgroups[i].id = 0;
> + memory_holder_init(&cgroups[i].worker);
> + }
> +}
> +
> +static void cleanup_cgroups(void)
> +{
> + int i;
> +
> + for (i = 0; i < ARRAY_SIZE(cgroups); i++) {
> + memory_holder_cleanup(&cgroups[i].worker);
> + if (cgroups[i].fd >= 0) {
> + close(cgroups[i].fd);
> + cgroups[i].fd = -1;
> + }
> + }
> +}
> +
> +static int setup_environment(void)
> +{
[ ... ]
This isn't a bug, but reset_cgroups(), cleanup_cgroups() and
setup_environment() look almost identical to reset_cgroups(),
cleanup_workers() and setup_environment() in prog_tests/test_oom.c.
The differences appear to be the new cgroups[i].id field with its
get_cgroup_id() call, the rename of cleanup_workers(), and "worker" changed
to "task" in a few assertion strings. The trigger/waitpid/WIFSIGNALED
sequence in run_and_wait_for_oom() and the attach sequence in
serial_test_oomd() also repeat serial_test_oom().
Could the table-driven cgroup and worker setup go into memory_holder.h, or
a sibling helper, so both OOM tests share one copy?
Also, cleanup_cgroups() kills the workers and closes the fds but removes
no cgroups, which is left to cleanup_cgroup_environment(). Is the name
accurate?
> diff --git a/tools/testing/selftests/bpf/progs/test_oomd.c b/tools/testing/selftests/bpf/progs/test_oomd.c
> new file mode 100644
> --- /dev/null
> +++ b/tools/testing/selftests/bpf/progs/test_oomd.c
[ ... ]
> +static int oomd_kill_task(struct oom_control *oc, struct task_struct *task,
> + struct oomd_decision *decision)
> +{
> + struct task_struct *t;
> + int ret;
> +
> + t = bpf_task_acquire(task);
> + if (!t)
> + return 0;
[ ... ]
> + if (!victim)
> + return 0;
> +
> + {
> + int ret = oomd_kill_task(oc, victim, decision);
> +
> + bpf_task_release(victim);
> + return ret;
> + }
> +}
This isn't a bug, but oomd_kill_memcg() already holds a reference on victim
from bpf_task_acquire(), and oomd_kill_task() is its only caller. Is the
extra bpf_task_acquire()/bpf_task_release() pair in oomd_kill_task()
needed?
Could the bare block around "int ret" in oomd_kill_memcg() become a plain
local declared at the top of the function, like the neighbouring functions
do?
[ ... ]
> + usage = bpf_mem_cgroup_usage(memcg);
> + pgscan = memcg_pgscan(memcg);
> + delta = oomd_pgscan_delta(policy, pgscan);
> + swap_usage = bpf_mem_cgroup_page_state(memcg, swap_item);
> +
> + if (decision)
> + decision->scanned_candidates++;
[ ... ]
> + if (decision) {
> + decision->victim_cgid = cgid;
> + decision->victim_usage = usage;
> + decision->victim_pgscan = pgscan;
> + decision->victim_pgscan_delta = delta;
> + decision->victim_swap_usage = swap_usage;
> + }
This isn't a bug, but is the swap usage read (and the victim_swap_usage
field) needed for this test?
swap_usage plays no part in ranking and is only copied into
decision->victim_swap_usage. The test also sets memory.swap.max to 0 on
/oomd_test, so the value is always zero, and prog_tests/test_oomd.c never
reads it.
The same seems to apply to root_cgid, victim_usage, victim_pgscan and
victim_pgscan_delta in struct oomd_decision, since run_and_wait_for_oom()
checks only victim_cgid, killed_pid, scanned_candidates, skipped_omit,
skipped_unkillable and kill_ret. Could these be dropped, or asserted on?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46974333971
^ permalink raw reply [flat|nested] 27+ messages in thread
* [PATCH bpf-next v4 12/17] mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (10 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 11/17] selftests/bpf: Add systemd-oomd style OOM policy test Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:58 ` bot+bpf-ci
2026-12-02 21:04 ` [PATCH bpf-next v4 13/17] selftests/bpf: Add bpf_oom_proactive_kill() proactive OOM test Ben Gardon
` (5 subsequent siblings)
17 siblings, 1 reply; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Michal Hocko, Christian Brauner
bpf_out_of_memory() invokes out_of_memory(), which falls back to
select_bad_process() if no attached bpf_oom_ops policy handles the event.
It cannot directly terminate a specific task chosen by a proactive
userspace/BPF policy.
Existing userspace options (pidfd_send_signal(SIGKILL) + process_mrelease()
or cgroup.kill) cannot atomically honor memory.oom.group expansion from
a chosen task, do not record memory.events oom_kill / oom_group_kill
counters or unified kernel OOM logging, and cannot be invoked directly
from a PSI tracepoint callback.
Add bpf_oom_proactive_kill to bpf_declare_oom_kfuncs. The function
synchronizes on oom_lock, validates that @task resides under a memcg
(if specified), and terminates @task through bpf_oom_kill_process(). Thus
asynchronous OOM memory reclamation, memcg OOM event counters,
and memory.oom.group semantics apply as usual.
Set oc->bpf_declared so dump_header() is skipped for proactive
terminations since there is no failed allocation stack,
meminfo snapshot, or task table to diagnose. dump_oom_victim() and
"Killed process" still record the target, origin memcg, and reason
string.
Signed-off-by: Ben Gardon <bgardon@google.com>
---
include/linux/oom.h | 3 ++
mm/oom_kill.c | 71 +++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 74 insertions(+)
diff --git a/include/linux/oom.h b/include/linux/oom.h
index 168b64dfb6ad..2725f17c7b40 100644
--- a/include/linux/oom.h
+++ b/include/linux/oom.h
@@ -64,6 +64,7 @@ struct oom_control {
/* Declared via BPF outside an allocation failure */
bool bpf_declared;
+
#endif
};
@@ -77,6 +78,7 @@ static inline bool is_bpf_declared_oom(const struct oom_control *oc)
{
return oc->bpf_declared;
}
+
#else
static inline const char *oom_handler_name(const struct oom_control *oc)
{
@@ -87,6 +89,7 @@ static inline bool is_bpf_declared_oom(const struct oom_control *oc)
{
return false;
}
+
#endif
extern struct mutex oom_lock;
diff --git a/mm/oom_kill.c b/mm/oom_kill.c
index 21b88332a46a..42c986ec1520 100644
--- a/mm/oom_kill.c
+++ b/mm/oom_kill.c
@@ -1384,6 +1384,76 @@ __bpf_kfunc int bpf_out_of_memory(struct mem_cgroup *memcg__nullable,
return ret;
}
+/**
+ * bpf_oom_proactive_kill() - Terminate a task proactively outside of OOM
+ * @origin__nullable: memcg bounding OOM group and log attribution, or NULL
+ * @task: task to be terminated
+ * @message__str: reason string logged in dmesg
+ * @flags: bitmask of &enum bpf_oom_flags
+ *
+ * Terminate @task through the OOM machinery (asynchronous OOM memory
+ * reclamation, memcg OOM events, memory.oom.group recursive behavior, and
+ * single-line summary) without an allocation failure having occurred and
+ * without falling back to select_bad_process(). The full allocation-failure
+ * dump_header() report is suppressed because no page allocation failed.
+ *
+ * Synchronizes on oom_lock: waits (interruptible by fatal signals) when
+ * BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK is set, or returns -EBUSY immediately if
+ * oom_lock is contended.
+ *
+ * When @origin__nullable is non-NULL (and not the root memcg), @task must
+ * belong to @origin__nullable or one of its descendants, and
+ * mem_cgroup_get_oom_group() bounds any memory.oom.group expansion at
+ * @origin__nullable.
+ *
+ * Return: 0 on success, or a negative errno on failure.
+ */
+__bpf_kfunc int bpf_oom_proactive_kill(struct mem_cgroup *origin__nullable,
+ struct task_struct *task,
+ const char *message__str,
+ u64 flags)
+{
+ struct oom_control oc = {
+ .gfp_mask = GFP_USER,
+ .order = 0,
+ .bpf_declared = true,
+ };
+ int ret;
+
+ if (flags & ~BPF_OOM_FLAGS_ALL)
+ return -EINVAL;
+
+ if (origin__nullable && mem_cgroup_is_root(origin__nullable))
+ origin__nullable = NULL;
+
+ if (origin__nullable &&
+ !mem_cgroup_task_in_hierarchy(task, origin__nullable))
+ return -EINVAL;
+
+ oc.memcg = origin__nullable;
+ oc.constraint = origin__nullable ? CONSTRAINT_MEMCG : CONSTRAINT_NONE;
+
+ lockdep_assert_not_held(&oom_lock);
+ if (flags & BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK) {
+ ret = mutex_lock_killable(&oom_lock);
+ if (ret)
+ return ret;
+ } else if (!mutex_trylock(&oom_lock)) {
+ return -EBUSY;
+ }
+
+ if (oom_killer_disabled) {
+ ret = -EBUSY;
+ goto out_unlock;
+ }
+
+ ret = bpf_oom_kill_process(&oc, task, message__str);
+
+out_unlock:
+ mutex_unlock(&oom_lock);
+ return ret;
+}
+
__bpf_kfunc_end_defs();
BTF_KFUNCS_START(bpf_oom_kfuncs)
@@ -1413,6 +1483,7 @@ static const struct btf_kfunc_id_set bpf_oom_kfunc_set = {
BTF_KFUNCS_START(bpf_declare_oom_kfuncs)
BTF_ID_FLAGS(func, bpf_out_of_memory, KF_SLEEPABLE)
+BTF_ID_FLAGS(func, bpf_oom_proactive_kill, KF_SLEEPABLE)
BTF_KFUNCS_END(bpf_declare_oom_kfuncs)
static const struct btf_kfunc_id_set bpf_declare_oom_syscall_kfunc_set = {
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 12/17] mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention
2026-12-02 21:04 ` [PATCH bpf-next v4 12/17] mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention Ben Gardon
@ 2026-12-02 21:58 ` bot+bpf-ci
0 siblings, 0 replies; 27+ messages in thread
From: bot+bpf-ci @ 2026-12-02 21:58 UTC (permalink / raw)
To: bgardon, ast, daniel, andrii, akpm, hannes, mhocko, shakeel.butt,
roman.gushchin, tj
Cc: jp.kobryn, eddyz87, memxor, martin.lau, song, yonghong.song,
jolsa, emil, ihor.solodrai, rientjes, surenb, joshdon,
sweettea-kernel, zhouchuyi, laoar.shao, benbwgardon, bpf,
linux-mm, cgroups, linux-kernel, bgardon, mhocko, brauner, ast,
andrii, daniel, martin.lau, eddyz87, yonghong.song, mason,
ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 3587 bytes --]
> mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention
TL;DR:
- bpf_oom_proactive_kill() may let a CAP_BPF-only syscall program SIGKILL any
task; KF_PERFMON or capable() check missing?
- Changelog claims direct PSI tracepoint use, but the sleepable kfunc likely
can't be called there
> bpf_out_of_memory() invokes out_of_memory(), which falls back to
> select_bad_process() if no attached bpf_oom_ops policy handles the event.
> It cannot directly terminate a specific task chosen by a proactive
> userspace/BPF policy.
>
> Existing userspace options (pidfd_send_signal(SIGKILL) + process_mrelease()
> or cgroup.kill) cannot atomically honor memory.oom.group expansion from
> a chosen task, do not record memory.events oom_kill / oom_group_kill
> counters or unified kernel OOM logging, and cannot be invoked directly
> from a PSI tracepoint callback.
The changelog lists "cannot be invoked directly from a PSI tracepoint
callback" as a limitation of the userspace options, which implies the new
kfunc can be called directly from such a callback. Is that accurate?
bpf_oom_proactive_kill() is registered KF_SLEEPABLE, and psi_avgs_work_tp
is declared with DECLARE_TRACE(psi_avgs_work, ...), which is not a faultable
tracepoint. A sleepable tp_btf/psi_avgs_work_tp program is refused, and the
verifier rejects a KF_SLEEPABLE call in a non-sleepable context.
The earlier patch in this series says the OOM kfuncs are reached from
tracepoint programs "asynchronously via a sleepable callback (such as
bpf_task_work or bpf_wq)", and Documentation/bpf/bpf_oom.rst says the same.
Could the changelog say that the kill is reached from a PSI tracepoint
program through a bpf_wq/bpf_task_work callback instead of "directly"?
> diff --git a/mm/oom_kill.c b/mm/oom_kill.c
> --- a/mm/oom_kill.c
> +++ b/mm/oom_kill.c
[ ... ]
> @@ -1413,6 +1483,7 @@ static const struct btf_kfunc_id_set bpf_oom_kfunc_set = {
>
> BTF_KFUNCS_START(bpf_declare_oom_kfuncs)
> BTF_ID_FLAGS(func, bpf_out_of_memory, KF_SLEEPABLE)
> +BTF_ID_FLAGS(func, bpf_oom_proactive_kill, KF_SLEEPABLE)
> BTF_KFUNCS_END(bpf_declare_oom_kfuncs)
Should this kfunc be registered with KF_PERFMON (or have an explicit
capable() check), like bpf_send_signal_task()?
bpf_declare_oom_syscall_kfunc_set has no .filter, and a BPF_PROG_TYPE_SYSCALL
program needs only CAP_BPF to load. With that, a program can do:
task = bpf_task_from_pid(pid);
bpf_oom_proactive_kill(NULL, task, "x", 0);
The call chain is:
bpf_oom_proactive_kill()
bpf_oom_kill_process()
oom_kill_process()
__oom_kill_process()
do_send_sig_info(SIGKILL, SEND_SIG_PRIV, victim, PIDTYPE_TGID)
This can SIGKILL any task that is not init, a kthread or oom_score_adj
-1000, including tasks of other users. With a NULL origin,
mem_cgroup_get_oom_group() uses root as the domain, so the highest ancestor
cgroup with memory.oom.group set is killed as well.
bpf_send_signal_task() in the same generic set is registered with
KF_PERFMON, and bpf_oom_kill_process() was previously reachable only from
bpf_oom_ops struct_ops programs, which need CAP_PERFMON. This wrapper
reaches the same kill path with less privilege and without the kill(2)
permission checks. Neither the changelog nor the kfunc documentation
discusses who may call it.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46974333971
^ permalink raw reply [flat|nested] 27+ messages in thread
* [PATCH bpf-next v4 13/17] selftests/bpf: Add bpf_oom_proactive_kill() proactive OOM test
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (11 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 12/17] mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:04 ` [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs Ben Gardon
` (4 subsequent siblings)
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Shuah Khan, linux-kselftest
Add a BPF selftest exercising bpf_oom_proactive_kill() from a
BPF_PROG_TYPE_SYSCALL program.
Verify that OOM_SCORE_ADJ_MIN (-1000) tasks and out-of-hierarchy memcg
attributions return -EINVAL while an eligible task is terminated with
SIGKILL and increments memory.events oom_kill.
Signed-off-by: Ben Gardon <bgardon@google.com>
---
.../bpf/prog_tests/test_oom_proactive_kill.c | 119 ++++++++++++++++++
.../bpf/progs/test_oom_proactive_kill.c | 46 +++++++
.../bpf/progs/test_oom_proactive_kill.h | 12 ++
3 files changed, 177 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h
diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c b/tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c
new file mode 100644
index 000000000000..ca2165f03278
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <errno.h>
+#include <sys/wait.h>
+#include <test_progs.h>
+#include <bpf/bpf.h>
+
+#include "cgroup_helpers.h"
+#include "memory_holder.h"
+#include "progs/test_oom_proactive_kill.h"
+#include "test_oom_proactive_kill.skel.h"
+
+/*
+ * Serialized because bpf_oom_proactive_kill() acquires the global oom_lock
+ * and kills processes via the OOM path, which would collide with other OOM
+ * tests running in parallel under test_progs -j.
+ */
+void serial_test_oom_proactive_kill(void)
+{
+ const char *cg_a = "/oom_proactive_a";
+ const char *cg_b = "/oom_proactive_b";
+ struct test_oom_proactive_kill *skel = NULL;
+ struct memory_holder w_protected, w_target;
+ struct proactive_kill_args args = {};
+ int cg_a_fd = -1, cg_b_fd = -1;
+ unsigned long long id_a, id_b;
+ int prog_fd, status = 0;
+ char buf[4096] = {};
+ char pbuf[32];
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &args,
+ .ctx_size_in = sizeof(args),
+ );
+
+ memory_holder_init(&w_protected);
+ memory_holder_init(&w_target);
+
+ if (!ASSERT_OK(setup_cgroup_environment(), "setup_cgroup_env"))
+ return;
+
+ cg_a_fd = create_and_get_cgroup(cg_a);
+ cg_b_fd = create_and_get_cgroup(cg_b);
+ if (!ASSERT_GE(cg_a_fd, 0, "create cg_a") ||
+ !ASSERT_GE(cg_b_fd, 0, "create cg_b"))
+ goto cleanup;
+
+ id_a = get_cgroup_id(cg_a);
+ id_b = get_cgroup_id(cg_b);
+ if (!ASSERT_GT(id_a, 0, "get_cgroup_id cg_a") ||
+ !ASSERT_GT(id_b, 0, "get_cgroup_id cg_b"))
+ goto cleanup;
+
+ skel = test_oom_proactive_kill__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "open_and_load"))
+ goto cleanup;
+
+ prog_fd = bpf_program__fd(skel->progs.proactive_kill_prog);
+
+ if (!ASSERT_OK(memory_holder_spawn(&w_protected, 0, 0, -1000, false),
+ "spawn_protected") ||
+ !ASSERT_OK(memory_holder_spawn(&w_target, 0, 0, 0, false),
+ "spawn_target"))
+ goto cleanup;
+
+ snprintf(pbuf, sizeof(pbuf), "%d", w_protected.pid);
+ if (!ASSERT_OK(write_cgroup_file(cg_a, "cgroup.procs", pbuf),
+ "place_protected"))
+ goto cleanup;
+ snprintf(pbuf, sizeof(pbuf), "%d", w_target.pid);
+ if (!ASSERT_OK(write_cgroup_file(cg_a, "cgroup.procs", pbuf),
+ "place_target"))
+ goto cleanup;
+
+ if (!ASSERT_OK(memory_holder_start(&w_protected), "start_protected") ||
+ !ASSERT_OK(memory_holder_wait_ready(&w_protected), "wait_protected") ||
+ !ASSERT_OK(memory_holder_start(&w_target), "start_target") ||
+ !ASSERT_OK(memory_holder_wait_ready(&w_target), "wait_target"))
+ goto cleanup;
+
+ /* OOM_SCORE_ADJ_MIN (-1000) task must be rejected with -EINVAL */
+ args.cgroup_id = id_a;
+ args.pid = w_protected.pid;
+ args.wait_on_oom_lock = 1;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_protected"))
+ ASSERT_EQ((int)topts.retval, -EINVAL, "reject_oom_score_adj_min");
+
+ /* Task outside origin memcg hierarchy must be rejected with -EINVAL */
+ args.cgroup_id = id_b;
+ args.pid = w_target.pid;
+ args.wait_on_oom_lock = 1;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_wrong_cg"))
+ ASSERT_EQ((int)topts.retval, -EINVAL, "reject_wrong_hierarchy");
+
+ /* Eligible task inside origin memcg must be terminated via OOM */
+ args.cgroup_id = id_a;
+ args.pid = w_target.pid;
+ args.wait_on_oom_lock = 1;
+ if (!ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_kill") ||
+ !ASSERT_OK((int)topts.retval, "proactive_kill_retval"))
+ goto cleanup;
+
+ ASSERT_EQ(waitpid(w_target.pid, &status, 0), w_target.pid, "waitpid_target");
+ w_target.pid = -1;
+ ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL,
+ "target_sigkill");
+
+ if (ASSERT_OK(read_cgroup_file(cg_a, "memory.events", buf, sizeof(buf)),
+ "read memory.events"))
+ ASSERT_OK_PTR(strstr(buf, "oom_kill 1"), "oom_kill incremented");
+
+cleanup:
+ memory_holder_cleanup(&w_protected);
+ memory_holder_cleanup(&w_target);
+ if (cg_a_fd >= 0)
+ close(cg_a_fd);
+ if (cg_b_fd >= 0)
+ close(cg_b_fd);
+ test_oom_proactive_kill__destroy(skel);
+ cleanup_cgroup_environment();
+}
diff --git a/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c
new file mode 100644
index 000000000000..591a2e0b284d
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include <errno.h>
+#include <bpf/bpf_helpers.h>
+#include "test_oom_proactive_kill.h"
+
+char _license[] SEC("license") = "GPL";
+
+SEC("syscall")
+int proactive_kill_prog(struct proactive_kill_args *args)
+{
+ struct mem_cgroup *memcg = NULL;
+ struct task_struct *task;
+ u64 flags = args->flags;
+ struct cgroup *cgrp;
+ int ret;
+
+ if (args->wait_on_oom_lock)
+ flags |= BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK;
+
+ task = bpf_task_from_pid(args->pid);
+ if (!task)
+ return -ESRCH;
+
+ if (args->cgroup_id) {
+ cgrp = bpf_cgroup_from_id(args->cgroup_id);
+ if (!cgrp) {
+ bpf_task_release(task);
+ return -ENOENT;
+ }
+ memcg = bpf_get_mem_cgroup(&cgrp->self);
+ bpf_cgroup_release(cgrp);
+ if (!memcg) {
+ bpf_task_release(task);
+ return -ENODEV;
+ }
+ }
+
+ ret = bpf_oom_proactive_kill(memcg, task, "bpf proactive oom test",
+ flags);
+
+ if (memcg)
+ bpf_put_mem_cgroup(memcg);
+ bpf_task_release(task);
+ return ret;
+}
diff --git a/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h
new file mode 100644
index 000000000000..d3bf7596de21
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h
@@ -0,0 +1,12 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef __TEST_OOM_PROACTIVE_KILL_H
+#define __TEST_OOM_PROACTIVE_KILL_H
+
+struct proactive_kill_args {
+ __u64 cgroup_id;
+ __u64 flags;
+ __s32 pid;
+ __u32 wait_on_oom_lock;
+};
+
+#endif /* __TEST_OOM_PROACTIVE_KILL_H */
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (12 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 13/17] selftests/bpf: Add bpf_oom_proactive_kill() proactive OOM test Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:15 ` sashiko-bot
2026-12-02 21:58 ` bot+bpf-ci
2026-12-02 21:04 ` [PATCH bpf-next v4 15/17] mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc Ben Gardon
` (3 subsequent siblings)
17 siblings, 2 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Shuah Khan, linux-kselftest
Add selftest coverage for BPF OOM kfunc safety boundaries:
- Verifier rejection of bpf_oom_kill_process() from SEC("syscall"), and
rejection of bpf_out_of_memory() / bpf_oom_proactive_kill() from
bpf_oom_ops struct_ops callbacks (oom_lock deadlock guard).
- Runtime rejection of init (pid 1, -EPERM) and unknown flags (-EINVAL)
in bpf_oom_proactive_kill().
- Global (origin__nullable == NULL) proactive termination.
Signed-off-by: Ben Gardon <bgardon@google.com>
---
.../bpf/prog_tests/test_oom_kfunc_neg.c | 79 +++++++++++++++++++
.../bpf/progs/test_oom_fail_ops_oom.c | 21 +++++
.../bpf/progs/test_oom_fail_ops_proactive.c | 23 ++++++
.../bpf/progs/test_oom_fail_syscall.c | 15 ++++
4 files changed, 138 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c
diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c
new file mode 100644
index 000000000000..8cfe9e3e85bb
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <errno.h>
+#include <sys/wait.h>
+#include <test_progs.h>
+#include <bpf/bpf.h>
+
+#include "memory_holder.h"
+#include "progs/test_oom_proactive_kill.h"
+#include "test_oom_proactive_kill.skel.h"
+#include "test_oom_fail_syscall.skel.h"
+#include "test_oom_fail_ops_oom.skel.h"
+#include "test_oom_fail_ops_proactive.skel.h"
+
+/*
+ * Serialized because the global proactive kill subtest acquires oom_lock and
+ * invokes the OOM killer, which can collide with other OOM tests under -j.
+ */
+void serial_test_oom_kfunc_neg(void)
+{
+ struct test_oom_proactive_kill *skel = NULL;
+ struct proactive_kill_args args = {};
+ struct memory_holder worker;
+ int prog_fd, status = 0;
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &args,
+ .ctx_size_in = sizeof(args),
+ );
+
+ memory_holder_init(&worker);
+
+ /* Verifier rejection checks for kfunc context restrictions */
+ RUN_TESTS(test_oom_fail_syscall);
+ RUN_TESTS(test_oom_fail_ops_oom);
+ RUN_TESTS(test_oom_fail_ops_proactive);
+
+ skel = test_oom_proactive_kill__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "open_and_load"))
+ return;
+
+ prog_fd = bpf_program__fd(skel->progs.proactive_kill_prog);
+
+ /* Init (pid 1) must be rejected with -EPERM via oom_unkillable_task() */
+ args.cgroup_id = 0;
+ args.pid = 1;
+ args.wait_on_oom_lock = 1;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_init"))
+ ASSERT_EQ((int)topts.retval, -EPERM, "reject_init");
+
+ /* Invalid flags must be rejected with -EINVAL */
+ if (!ASSERT_OK(memory_holder_spawn(&worker, 0, 0, 0, false), "spawn_child") ||
+ !ASSERT_OK(memory_holder_start(&worker), "start_child") ||
+ !ASSERT_OK(memory_holder_wait_ready(&worker), "wait_child"))
+ goto cleanup;
+
+ args.cgroup_id = 0;
+ args.pid = worker.pid;
+ args.flags = ~0ULL;
+ args.wait_on_oom_lock = 0;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_bad_flags"))
+ ASSERT_EQ((int)topts.retval, -EINVAL, "reject_bad_flags");
+
+ /* Global proactive kill (origin__nullable == NULL) must succeed */
+ args.cgroup_id = 0;
+ args.pid = worker.pid;
+ args.flags = 0;
+ args.wait_on_oom_lock = 1;
+ if (!ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_global") ||
+ !ASSERT_OK((int)topts.retval, "global_retval"))
+ goto cleanup;
+
+ ASSERT_EQ(waitpid(worker.pid, &status, 0), worker.pid, "waitpid_global");
+ worker.pid = -1;
+ ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL,
+ "global_sigkill");
+
+cleanup:
+ memory_holder_cleanup(&worker);
+ test_oom_proactive_kill__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c
new file mode 100644
index 000000000000..ba6b15c6e407
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_misc.h"
+
+char _license[] SEC("license") = "GPL";
+
+SEC("struct_ops.s/handle_out_of_memory")
+__failure __msg("calling kernel function bpf_out_of_memory is not allowed")
+int BPF_PROG(ops_call_out_of_memory, struct oom_control *oc,
+ struct cgroup *cgrp)
+{
+ return bpf_out_of_memory(oc->memcg, 0, 0);
+}
+
+SEC(".struct_ops.link")
+struct bpf_oom_ops fail_oom_ops = {
+ .name = "fail_ops_oom",
+ .handle_out_of_memory = (void *)ops_call_out_of_memory,
+};
diff --git a/tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c
new file mode 100644
index 000000000000..24ba2bac1d85
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_misc.h"
+
+char _license[] SEC("license") = "GPL";
+
+SEC("struct_ops.s/handle_out_of_memory")
+__failure __msg("calling kernel function bpf_oom_proactive_kill is not allowed")
+int BPF_PROG(ops_call_proactive_kill, struct oom_control *oc,
+ struct cgroup *cgrp)
+{
+ struct task_struct *task = bpf_get_current_task_btf();
+
+ return bpf_oom_proactive_kill(oc->memcg, task, "disallowed", 0);
+}
+
+SEC(".struct_ops.link")
+struct bpf_oom_ops fail_proactive_ops = {
+ .name = "fail_ops_proactive",
+ .handle_out_of_memory = (void *)ops_call_proactive_kill,
+};
diff --git a/tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c b/tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c
new file mode 100644
index 000000000000..e6aa7017f500
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+
+char _license[] SEC("license") = "GPL";
+
+SEC("syscall")
+__failure __msg("calling kernel function bpf_oom_kill_process is not allowed")
+int syscall_call_oom_kill_process(void *ctx)
+{
+ struct task_struct *task = bpf_get_current_task_btf();
+
+ return bpf_oom_kill_process(NULL, task, "disallowed");
+}
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs
2026-12-02 21:04 ` [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs Ben Gardon
@ 2026-12-02 21:15 ` sashiko-bot
2026-12-02 21:58 ` bot+bpf-ci
1 sibling, 0 replies; 27+ messages in thread
From: sashiko-bot @ 2026-12-02 21:15 UTC (permalink / raw)
To: Ben Gardon, Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, Shuah Khan, mkoutny
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] selftests/bpf: duplicate harness in serial_test_oom_kfunc_neg()
--
commit 4efe5c8fa9501edb24e804de6187524dc373a747
Author: Ben Gardon <bgardon@google.com>
selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs
This commit adds BPF selftests covering verifier context restrictions and
runtime checks for BPF OOM kfuncs.
> diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c
> new file mode 100644
> index 0000000000000..8cfe9e3e85bbc
> --- /dev/null
> +++ b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c
> @@ -0,0 +1,79 @@
[ ... ]
> +void serial_test_oom_kfunc_neg(void)
> +{
> + struct test_oom_proactive_kill *skel = NULL;
> + struct proactive_kill_args args = {};
> + struct memory_holder worker;
> + int prog_fd, status = 0;
> + LIBBPF_OPTS(bpf_test_run_opts, topts,
> + .ctx_in = &args,
> + .ctx_size_in = sizeof(args),
> + );
> +
> + memory_holder_init(&worker);
> +
> + /* Verifier rejection checks for kfunc context restrictions */
> + RUN_TESTS(test_oom_fail_syscall);
> + RUN_TESTS(test_oom_fail_ops_oom);
> + RUN_TESTS(test_oom_fail_ops_proactive);
> +
> + skel = test_oom_proactive_kill__open_and_load();
> + if (!ASSERT_OK_PTR(skel, "open_and_load"))
> + return;
[Severity: Low]
Could these test cases be folded into serial_test_oom_proactive_kill() in
tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c and
wrapped in test__start_subtest()?
serial_test_oom_proactive_kill() already loads test_oom_proactive_kill and
sets up the memory_holder and bpf_prog_test_run_opts() harness to test
proactive_kill_prog. Also, because RUN_TESTS() registers subtests while
the runtime checks below run at the top level outside
test__start_subtest(), running test_progs -t oom_kfunc_neg/<subtest> still
executes the runtime checks and invokes the global OOM killer under
oom_lock, and those runtime checks cannot be selected or skipped
individually.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261202210415.517651-1-bgardon@google.com?part=14
^ permalink raw reply [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs
2026-12-02 21:04 ` [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs Ben Gardon
2026-12-02 21:15 ` sashiko-bot
@ 2026-12-02 21:58 ` bot+bpf-ci
1 sibling, 0 replies; 27+ messages in thread
From: bot+bpf-ci @ 2026-12-02 21:58 UTC (permalink / raw)
To: bgardon, ast, daniel, andrii, akpm, hannes, mhocko, shakeel.butt,
roman.gushchin, tj
Cc: jp.kobryn, eddyz87, memxor, martin.lau, song, yonghong.song,
jolsa, emil, ihor.solodrai, rientjes, surenb, joshdon,
sweettea-kernel, zhouchuyi, laoar.shao, benbwgardon, bpf,
linux-mm, cgroups, linux-kernel, bgardon, shuah, linux-kselftest,
ast, andrii, daniel, martin.lau, eddyz87, yonghong.song, mason,
ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 3195 bytes --]
> selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs
TL;DR: Test issue: the global proactive-kill selftest may SIGKILL unrelated
host tasks or whole cgroups (test_progs included) outside the root pid
namespace or with memory.oom.group set; the worker also isn't put in a test
cgroup.
> diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c
> new file mode 100644
> --- /dev/null
> +++ b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c
[ ... ]
> +void serial_test_oom_kfunc_neg(void)
> +{
[ ... ]
> + memory_holder_init(&worker);
[ ... ]
> + /* Global proactive kill (origin__nullable == NULL) must succeed */
> + args.cgroup_id = 0;
> + args.pid = worker.pid;
> + args.flags = 0;
> + args.wait_on_oom_lock = 1;
> + if (!ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_global") ||
> + !ASSERT_OK((int)topts.retval, "global_retval"))
> + goto cleanup;
> +
> + ASSERT_EQ(waitpid(worker.pid, &status, 0), worker.pid, "waitpid_global");
Can this global kill hit processes other than the worker?
With origin == NULL, bpf_oom_proactive_kill() skips the
mem_cgroup_task_in_hierarchy() check, so only the pid lookup and the
bpf_oom_kill_process() checks guard the victim.
proactive_kill_prog() resolves the victim with bpf_task_from_pid(), which
uses find_task_by_pid_ns(pid, &init_pid_ns). worker.pid is the value
fork() returned in test_progs' own pid namespace. If test_progs runs in a
non-root pid namespace, such as a privileged container, whichever host
task has that pid number gets SIGKILL and the call returns 0. The real
worker is never signalled, so waitpid(worker.pid, ...) blocks until the
watchdog fires.
The worker is also never moved into a test cgroup, unlike test_oom.c,
test_oomd.c, test_psi.c and test_oom_proactive_kill.c, which call
setup_cgroup_environment(). It stays in test_progs' memory cgroup. With
oc->memcg == NULL, oom_kill_process() calls mem_cgroup_get_oom_group(victim,
NULL), which walks up to the root:
for (; memcg; memcg = parent_mem_cgroup(memcg)) {
if (READ_ONCE(memcg->oom_group))
oom_group = memcg;
if (memcg == oom_domain)
break;
}
and then mem_cgroup_scan_tasks(oom_group, oom_kill_memcg_member, ...) sends
SIGKILL to every task in that group. If any non-root ancestor of
test_progs' cgroup has memory.oom.group=1, for example a systemd unit with
OOMPolicy=kill, would this kill test_progs and every other process in that
cgroup?
In the usual vmtest setup (root cgroup, root pid namespace) neither case
occurs.
Would it make sense to place the worker in a cgroup created with
setup_cgroup_environment()/create_and_get_cgroup() as the sibling test
does, and either skip the global case when not in the root pid namespace,
or have the BPF program check that the task it found is the caller's child
(or use bpf_task_from_vpid())?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46974333971
^ permalink raw reply [flat|nested] 27+ messages in thread
* [PATCH bpf-next v4 15/17] mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (13 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:45 ` sashiko-bot
2026-12-02 21:04 ` [PATCH bpf-next v4 16/17] selftests/bpf: Add bpf_mem_cgroup_raise_max() OOM test Ben Gardon
` (2 subsequent siblings)
17 siblings, 1 reply; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Muchun Song
Allow bpf_oom_ops handlers and proactive SYSCALL/PSI programs to resolve
memory cgroup pressure by increasing a non-root cgroup's memory.max limit via
bpf_mem_cgroup_raise_max(memcg, max_bytes).
Only strictly higher limits are permitted so updating memory.max never
triggers synchronous reclaim or recursive OOMs while oom_lock is held.
On cgroup v1, memcg1_raise_max() enforces the memory.max <= memsw.max
invariant under memcg_max_mutex and wakes waiters via memcg1_oom_recover().
The kfunc is marked KF_SLEEPABLE because memcg_wb_domain_size_changed()
acquires a spinlock and cgroup v1 acquires memcg_max_mutex.
When invoked from handle_out_of_memory() returning > 0, try_charge_memcg()
immediately retries against the expanded limit and succeeds without
terminating any task.
Suggested-by: Michal Hocko <mhocko@suse.com>
Signed-off-by: Ben Gardon <bgardon@google.com>
---
include/linux/memcontrol.h | 7 +++++++
mm/bpf_memcontrol.c | 24 ++++++++++++++++++++++++
mm/memcontrol-v1.c | 16 ++++++++++++++++
mm/memcontrol-v1.h | 6 ++++++
mm/memcontrol.c | 38 ++++++++++++++++++++++++++++++++++++++
5 files changed, 91 insertions(+)
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index bc30d7baecd7..1dc5176e2682 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -1002,6 +1002,7 @@ void mod_memcg_lruvec_state(struct lruvec *lruvec,
enum node_stat_item idx, int val);
void mem_cgroup_flush_stats(struct mem_cgroup *memcg);
+int mem_cgroup_raise_max(struct mem_cgroup *memcg, unsigned long max_pages);
void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg);
void mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val);
@@ -1533,6 +1534,12 @@ static inline bool mem_cgroup_task_in_hierarchy(struct task_struct *task,
return true;
}
+static inline int mem_cgroup_raise_max(struct mem_cgroup *memcg,
+ unsigned long max_pages)
+{
+ return -EOPNOTSUPP;
+}
+
static inline int mem_cgroup_init(void) { return 0; }
#endif /* CONFIG_MEMCG */
diff --git a/mm/bpf_memcontrol.c b/mm/bpf_memcontrol.c
index d8f579c28560..8c00d98b5826 100644
--- a/mm/bpf_memcontrol.c
+++ b/mm/bpf_memcontrol.c
@@ -206,6 +206,29 @@ __bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,
return nr_reclaimed * PAGE_SIZE;
}
+/**
+ * bpf_mem_cgroup_raise_max() - Increase a memory cgroup's memory.max limit
+ * @memcg: target non-root memory cgroup
+ * @max_bytes: new limit in bytes (truncated to PAGE_SIZE; clamped to
+ * PAGE_COUNTER_MAX, which represents unlimited/"max" -- callers
+ * may pass U64_MAX)
+ *
+ * Allows a BPF OOM policy (or proactive program) to resolve a memcg OOM
+ * non-destructively by raising memory.max instead of terminating a task.
+ * Only strictly higher limits are accepted so no reclaim is needed while
+ * holding oom_lock. On cgroup v1, enforces memory.max <= memsw.max.
+ *
+ * Return: 0 on success, or a negative errno on failure.
+ */
+__bpf_kfunc int bpf_mem_cgroup_raise_max(struct mem_cgroup *memcg,
+ u64 max_bytes)
+{
+ unsigned long max_pages = min_t(u64, max_bytes >> PAGE_SHIFT,
+ PAGE_COUNTER_MAX);
+
+ return mem_cgroup_raise_max(memcg, max_pages);
+}
+
__bpf_kfunc_end_defs();
BTF_KFUNCS_START(bpf_memcontrol_kfuncs)
@@ -218,6 +241,7 @@ BTF_ID_FLAGS(func, bpf_mem_cgroup_memory_events)
BTF_ID_FLAGS(func, bpf_mem_cgroup_usage)
BTF_ID_FLAGS(func, bpf_mem_cgroup_page_state)
BTF_ID_FLAGS(func, bpf_mem_cgroup_flush_stats, KF_SLEEPABLE)
+BTF_ID_FLAGS(func, bpf_mem_cgroup_raise_max, KF_SLEEPABLE)
BTF_KFUNCS_END(bpf_memcontrol_kfuncs)
diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
index b7f286888507..d50fe775f1f3 100644
--- a/mm/memcontrol-v1.c
+++ b/mm/memcontrol-v1.c
@@ -1418,6 +1418,22 @@ void vmpressure_unregister_event(struct mem_cgroup *memcg,
static DEFINE_MUTEX(memcg_max_mutex);
+int memcg1_raise_max(struct mem_cgroup *memcg, unsigned long max_pages)
+{
+ int ret = 0;
+
+ mutex_lock(&memcg_max_mutex);
+ if (max_pages <= memcg->memory.max || max_pages > memcg->memsw.max)
+ ret = -EINVAL;
+ else
+ WRITE_ONCE(memcg->memory.max, max_pages);
+ mutex_unlock(&memcg_max_mutex);
+
+ if (!ret)
+ memcg1_oom_recover(memcg);
+ return ret;
+}
+
static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
unsigned long max, bool memsw)
{
diff --git a/mm/memcontrol-v1.h b/mm/memcontrol-v1.h
index 820139657184..3c22f124a5dc 100644
--- a/mm/memcontrol-v1.h
+++ b/mm/memcontrol-v1.h
@@ -63,6 +63,7 @@ enum res_type {
bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked);
void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked);
void memcg1_oom_recover(struct mem_cgroup *memcg);
+int memcg1_raise_max(struct mem_cgroup *memcg, unsigned long max_pages);
void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg);
void memcg1_uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
@@ -106,6 +107,11 @@ static inline bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked)
}
static inline void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked) {}
static inline void memcg1_oom_recover(struct mem_cgroup *memcg) {}
+static inline int memcg1_raise_max(struct mem_cgroup *memcg,
+ unsigned long max_pages)
+{
+ return -EOPNOTSUPP;
+}
static inline void memcg1_commit_charge(struct folio *folio,
struct mem_cgroup *memcg) {}
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index afbb638e7e1c..8440cca757b9 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -5025,6 +5025,44 @@ static int memory_max_show(struct seq_file *m, void *v)
READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
}
+/**
+ * mem_cgroup_raise_max() - Increase a memory cgroup's hard limit
+ * @memcg: target non-root memory cgroup
+ * @max_pages: new limit in pages (must exceed current memory.max)
+ *
+ * Safe to call from OOM handler context while oom_lock is held: only
+ * increases are permitted, so no stock draining or reclaim is required.
+ * On cgroup v1, enforces the memory.max <= memsw.max invariant under
+ * memcg_max_mutex.
+ *
+ * Return: 0 on success, or -EINVAL if @memcg is root/dying or @max_pages
+ * does not satisfy limit bounds.
+ */
+int mem_cgroup_raise_max(struct mem_cgroup *memcg, unsigned long max_pages)
+{
+ unsigned long old;
+
+ if (!memcg || mem_cgroup_is_root(memcg) || memcg_is_dying(memcg))
+ return -EINVAL;
+
+ max_pages = min_t(unsigned long, max_pages, PAGE_COUNTER_MAX);
+ if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
+ int ret = memcg1_raise_max(memcg, max_pages);
+
+ if (ret)
+ return ret;
+ } else {
+ old = READ_ONCE(memcg->memory.max);
+ do {
+ if (max_pages <= old)
+ return -EINVAL;
+ } while (!try_cmpxchg(&memcg->memory.max, &old, max_pages));
+ }
+
+ memcg_wb_domain_size_changed(memcg);
+ return 0;
+}
+
static ssize_t memory_max_write(struct kernfs_open_file *of,
char *buf, size_t nbytes, loff_t off)
{
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 15/17] mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc
2026-12-02 21:04 ` [PATCH bpf-next v4 15/17] mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc Ben Gardon
@ 2026-12-02 21:45 ` sashiko-bot
0 siblings, 0 replies; 27+ messages in thread
From: sashiko-bot @ 2026-12-02 21:45 UTC (permalink / raw)
To: Ben Gardon, Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, Muchun Song, mkoutny
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] mm: memcontrol-v1: lock ordering inversion in
memcg1_raise_max() under oom_lock
--
commit d797e91b36bda7b1b912733cac44ec80ba2bf974
Author: Ben Gardon <bgardon@google.com>
mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc
This commit introduces the bpf_mem_cgroup_raise_max() kfunc and
mem_cgroup_raise_max() helper to allow BPF OOM handlers and proactive
programs to increase a non-root memory cgroup's hard limit.
> diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
> index b7f2868885071..d50fe775f1f3e 100644
> --- a/mm/memcontrol-v1.c
> +++ b/mm/memcontrol-v1.c
> @@ -1418,6 +1418,22 @@ void vmpressure_unregister_event(struct mem_cgroup *memcg,
>
> static DEFINE_MUTEX(memcg_max_mutex);
>
> +int memcg1_raise_max(struct mem_cgroup *memcg, unsigned long max_pages)
> +{
> + int ret = 0;
> +
> + mutex_lock(&memcg_max_mutex);
> + if (max_pages <= memcg->memory.max || max_pages > memcg->memsw.max)
> + ret = -EINVAL;
> + else
> + WRITE_ONCE(memcg->memory.max, max_pages);
> + mutex_unlock(&memcg_max_mutex);
> +
> + if (!ret)
> + memcg1_oom_recover(memcg);
> + return ret;
> +}
[Severity: Medium]
Can locking memcg_max_mutex here cause a lock ordering inversion when
bpf_mem_cgroup_raise_max() is called from a bpf_oom_ops
handle_out_of_memory() callback under oom_lock?
memcg_update_tcp_max() holds memcg_max_mutex across static_branch_inc(),
which acquires cpu_hotplug_lock via cpus_read_lock():
mm/memcontrol-v1.c:memcg_update_tcp_max() {
mutex_lock(&memcg_max_mutex);
...
if (!memcg->tcpmem_active) {
static_branch_inc(&memcg_sockets_enabled_key);
memcg->tcpmem_active = true;
}
out:
mutex_unlock(&memcg_max_mutex);
}
Elsewhere, cpu_hotplug_lock nests outside cgroup_threadgroup_rwsem and
oom_lock:
CPU0 CPU1
---- ----
lock(cpu_hotplug_lock)
lock(cgroup_threadgroup_rwsem)
lock(memcg_max_mutex)
lock(cpu_hotplug_lock)
lock(oom_lock)
lock(memcg_max_mutex)
*** DEADLOCK ***
CPU0: copy_process() -> cgroup_can_fork() -> futex_hash_allocate_default()
-> try_charge_memcg() -> mem_cgroup_out_of_memory()
-> bpf_handle_oom() -> bpf_mem_cgroup_raise_max()
-> memcg1_raise_max()
(with cpu_hotplug_lock -> cgroup_threadgroup_rwsem established by
cgroup_attach_lock())
CPU1: memcg_update_tcp_max() -> static_branch_inc()
-> static_key_slow_inc() -> cpus_read_lock()
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261202210415.517651-1-bgardon@google.com?part=15
^ permalink raw reply [flat|nested] 27+ messages in thread
* [PATCH bpf-next v4 16/17] selftests/bpf: Add bpf_mem_cgroup_raise_max() OOM test
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (14 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 15/17] mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:04 ` [PATCH bpf-next v4 17/17] Documentation/bpf: Document BPF OOM handling and kfuncs Ben Gardon
2026-12-02 21:38 ` [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Shuah Khan, linux-kselftest
Add a BPF selftest attaching a BPF OOM handler to a small memory
cgroup, which calls bpf_mem_cgroup_raise_max() to expand memory.max
on OOM. This allows a 24 MB allocation to succeed without terminating the
allocating task.
Also verify BPF_PROG_TYPE_SYSCALL negative and boundary cases: equal or
lower limits and root memcg return -EINVAL, while UINT64_MAX clamps
cleanly to "max".
Signed-off-by: Ben Gardon <bgardon@google.com>
---
.../bpf/prog_tests/test_oom_raise_max.c | 135 ++++++++++++++++++
.../selftests/bpf/progs/test_oom_raise_max.c | 55 +++++++
.../selftests/bpf/progs/test_oom_raise_max.h | 10 ++
3 files changed, 200 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom_raise_max.c
create mode 100644 tools/testing/selftests/bpf/progs/test_oom_raise_max.h
diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c b/tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c
new file mode 100644
index 000000000000..6b803d4560e9
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <errno.h>
+#include <stdint.h>
+#include <sys/wait.h>
+#include <test_progs.h>
+#include <bpf/bpf.h>
+
+#include "cgroup_helpers.h"
+#include "memory_holder.h"
+
+#define MB (1024UL * 1024UL)
+#include "progs/test_oom_raise_max.h"
+#include "test_oom_raise_max.skel.h"
+
+/*
+ * Serialized because this test attaches a bpf_oom_ops handler and triggers a
+ * real memcg OOM, which can collide with other OOM tests under test_progs -j.
+ */
+void serial_test_oom_raise_max(void)
+{
+ LIBBPF_OPTS(bpf_cgroup_opts, opts);
+ const char *cg_path = "/oom_raise_test";
+ struct test_oom_raise_max *skel = NULL;
+ struct bpf_link *link = NULL;
+ struct raise_max_args args = {};
+ struct memory_holder worker;
+ int cg_fd = -1, prog_fd, status = 0;
+ unsigned long long cg_id;
+ char buf[256] = {};
+ char pbuf[32];
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &args,
+ .ctx_size_in = sizeof(args),
+ );
+
+ memory_holder_init(&worker);
+
+ if (!ASSERT_OK(setup_cgroup_environment(), "setup_cgroup_env"))
+ return;
+
+ cg_fd = create_and_get_cgroup(cg_path);
+ if (!ASSERT_GE(cg_fd, 0, "create_cgroup"))
+ goto cleanup;
+
+ cg_id = get_cgroup_id(cg_path);
+ if (!ASSERT_GT(cg_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%lu", 16 * MB);
+ if (!ASSERT_OK(write_cgroup_file(cg_path, "memory.max", buf),
+ "set memory.max"))
+ goto cleanup;
+ write_cgroup_file(cg_path, "memory.swap.max", "0");
+
+ skel = test_oom_raise_max__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "open_and_load"))
+ goto cleanup;
+
+ skel->bss->new_max_bytes = 64 * MB;
+
+ link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom_raise,
+ cg_fd, &opts);
+ if (!ASSERT_OK_PTR(link, "attach_cgroup")) {
+ link = NULL;
+ goto cleanup;
+ }
+
+ if (!ASSERT_OK(memory_holder_spawn(&worker, 24 * MB, 0, 0, true),
+ "spawn_worker"))
+ goto cleanup;
+
+ snprintf(pbuf, sizeof(pbuf), "%d", worker.pid);
+ if (!ASSERT_OK(write_cgroup_file(cg_path, "cgroup.procs", pbuf),
+ "place_worker") ||
+ !ASSERT_OK(memory_holder_start(&worker), "start_worker"))
+ goto cleanup;
+
+ ASSERT_EQ(waitpid(worker.pid, &status, 0), worker.pid, "waitpid");
+ worker.pid = -1;
+ ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0,
+ "child_survived");
+
+ if (ASSERT_OK(read_cgroup_file(cg_path, "memory.max", buf, sizeof(buf)),
+ "read memory.max")) {
+ char expected[64];
+
+ snprintf(expected, sizeof(expected), "%lu", 64 * MB);
+ ASSERT_OK_PTR(strstr(buf, expected), "memory.max raised");
+ }
+
+ if (ASSERT_OK(read_cgroup_file(cg_path, "memory.events", buf,
+ sizeof(buf)), "read memory.events")) {
+ ASSERT_OK_PTR(strstr(buf, "oom 1"), "oom event recorded");
+ ASSERT_OK_PTR(strstr(buf, "oom_kill 0"), "no task killed");
+ }
+
+ /* Verify SYSCALL boundary and negative checks */
+ prog_fd = bpf_program__fd(skel->progs.test_raise_max_syscall);
+
+ /* Equal limit must return -EINVAL */
+ args.cgroup_id = cg_id;
+ args.max_bytes = 64 * MB;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_equal"))
+ ASSERT_EQ((int)topts.retval, -EINVAL, "reject_equal");
+
+ /* Lower limit must return -EINVAL */
+ args.cgroup_id = cg_id;
+ args.max_bytes = 32 * MB;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_lower"))
+ ASSERT_EQ((int)topts.retval, -EINVAL, "reject_lower");
+
+ /* Root memcg must return -EINVAL */
+ args.cgroup_id = 0;
+ args.max_bytes = UINT64_MAX;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_root"))
+ ASSERT_EQ((int)topts.retval, -EINVAL, "reject_root");
+
+ /* UINT64_MAX must clamp cleanly to "max" */
+ args.cgroup_id = cg_id;
+ args.max_bytes = UINT64_MAX;
+ if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_max"))
+ ASSERT_OK((int)topts.retval, "raise_to_max");
+
+ if (ASSERT_OK(read_cgroup_file(cg_path, "memory.max", buf, sizeof(buf)),
+ "read memory.max after UINT64_MAX"))
+ ASSERT_OK_PTR(strstr(buf, "max"), "memory.max unlimited");
+
+cleanup:
+ memory_holder_cleanup(&worker);
+ bpf_link__destroy(link);
+ if (cg_fd >= 0)
+ close(cg_fd);
+ test_oom_raise_max__destroy(skel);
+ cleanup_cgroup_environment();
+}
diff --git a/tools/testing/selftests/bpf/progs/test_oom_raise_max.c b/tools/testing/selftests/bpf/progs/test_oom_raise_max.c
new file mode 100644
index 000000000000..e58e382791aa
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom_raise_max.c
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include <errno.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "test_oom_raise_max.h"
+
+char _license[] SEC("license") = "GPL";
+
+__u64 new_max_bytes;
+
+SEC("struct_ops.s/handle_out_of_memory")
+int BPF_PROG(test_raise_max_oom, struct oom_control *oc, struct cgroup *cgrp)
+{
+ struct mem_cgroup *memcg = oc->memcg;
+
+ if (!memcg)
+ return 0;
+
+ if (bpf_mem_cgroup_raise_max(memcg, new_max_bytes))
+ return 0;
+
+ return 1;
+}
+
+SEC("syscall")
+int test_raise_max_syscall(struct raise_max_args *args)
+{
+ struct mem_cgroup *memcg;
+ int ret;
+
+ if (args->cgroup_id) {
+ struct cgroup *cgrp = bpf_cgroup_from_id(args->cgroup_id);
+
+ if (!cgrp)
+ return -ENOENT;
+ memcg = bpf_get_mem_cgroup(&cgrp->self);
+ bpf_cgroup_release(cgrp);
+ } else {
+ memcg = bpf_get_root_mem_cgroup();
+ }
+
+ if (!memcg)
+ return -ENODEV;
+
+ ret = bpf_mem_cgroup_raise_max(memcg, args->max_bytes);
+ bpf_put_mem_cgroup(memcg);
+ return ret;
+}
+
+SEC(".struct_ops.link")
+struct bpf_oom_ops test_bpf_oom_raise = {
+ .name = "bpf_oom_raise_max",
+ .handle_out_of_memory = (void *)test_raise_max_oom,
+};
diff --git a/tools/testing/selftests/bpf/progs/test_oom_raise_max.h b/tools/testing/selftests/bpf/progs/test_oom_raise_max.h
new file mode 100644
index 000000000000..f25bde9a295a
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_oom_raise_max.h
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef __TEST_OOM_RAISE_MAX_H
+#define __TEST_OOM_RAISE_MAX_H
+
+struct raise_max_args {
+ __u64 cgroup_id;
+ __u64 max_bytes;
+};
+
+#endif /* __TEST_OOM_RAISE_MAX_H */
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* [PATCH bpf-next v4 17/17] Documentation/bpf: Document BPF OOM handling and kfuncs
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (15 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 16/17] selftests/bpf: Add bpf_mem_cgroup_raise_max() OOM test Ben Gardon
@ 2026-12-02 21:04 ` Ben Gardon
2026-12-02 21:58 ` bot+bpf-ci
2026-12-02 21:38 ` [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
17 siblings, 1 reply; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:04 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel,
Ben Gardon, Jonathan Corbet, Shuah Khan, Randy Dunlap, linux-doc
Document BPF OOM policy attachment, execution semantics, and kfuncs in
Documentation/bpf/bpf_oom.rst, link it into Documentation/bpf/index.rst,
and add it to the BPF OOM entry in MAINTAINERS.
Signed-off-by: Ben Gardon <bgardon@google.com>
---
Documentation/bpf/bpf_oom.rst | 138 ++++++++++++++++++++++++++++++++++
Documentation/bpf/index.rst | 1 +
MAINTAINERS | 1 +
3 files changed, 140 insertions(+)
create mode 100644 Documentation/bpf/bpf_oom.rst
diff --git a/Documentation/bpf/bpf_oom.rst b/Documentation/bpf/bpf_oom.rst
new file mode 100644
index 000000000000..5fc63269aec5
--- /dev/null
+++ b/Documentation/bpf/bpf_oom.rst
@@ -0,0 +1,138 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================
+BPF OOM Handling
+================
+
+Overview
+========
+
+Linux supports customizing out-of-memory (OOM) handling with BPF in two ways:
+
+1. **Reactive OOM policies** via ``struct bpf_oom_ops`` (cgroup-attached
+ ``struct_ops``) invoked by ``out_of_memory()`` before the kernel's
+ OOM selector. Policies can choose one or more tasks to terminate, raise
+ ``memory.max`` on the cgroup, or back off while an existing OOM
+ target exits.
+2. **Proactive OOM invocation and termination** via BPF kfuncs callable
+ from ``BPF_PROG_TYPE_SYSCALL`` programs and select tracepoints (such as
+ ``tp_btf/psi_avgs_work_tp``) to trigger OOM handling or directly
+ terminate a chosen task without a separate userspace OOM daemon.
+
+BPF OOM handling requires ``CONFIG_CGROUP_BPF=y`` and ``CONFIG_MEMCG=y``.
+PSI tracepoint integration additionally requires ``CONFIG_PSI=y`` and
+``CONFIG_BPF_EVENTS=y``.
+
+Attachment and Execution Order
+==============================
+
+A reactive policy defines a ``struct bpf_oom_ops`` map with
+``SEC(".struct_ops.link")`` and attaches it to a cgroup v2 directory via
+``bpf_map__attach_cgroup_opts()``.
+
+- Attaching to the root cgroup covers system-wide OOMs as well as
+ fallback from descendant memory cgroups.
+- Effective handlers run from the OOMing memory cgroup upward toward the
+ root by default, unless an ancestor attaches with ``BPF_F_PREORDER``.
+- Multiple links on the same cgroup are allowed; relative ordering
+ uses ``BPF_F_BEFORE`` / ``BPF_F_AFTER`` with ``BPF_F_LINK`` (and
+ ``BPF_F_ID`` when specifying ``relative_id``). Do not pass
+ ``BPF_F_ALLOW_MULTI`` (rejected with ``-EINVAL``).
+- Handlers are invoked with ``oom_lock`` held and page faults disabled.
+- Returning a positive value signals that the OOM event has been
+ handled and stops traversal. Returning ``<= 0`` delegates to the
+ next effective handler and ultimately to the in-kernel OOM handler.
+- ``SysRq-f`` (``is_sysrq_oom(oc)``) always bypasses BPF handlers.
+
+Struct Ops Interface
+====================
+
+``struct bpf_oom_ops`` (``include/linux/bpf_oom.h``):
+
+.. code-block:: c
+
+ struct bpf_oom_ops {
+ int (*handle_out_of_memory)(struct oom_control *oc,
+ struct cgroup *cgrp);
+ char name[BPF_OOM_NAME_MAX_LEN];
+ };
+
+- ``handle_out_of_memory(oc, cgrp)``: Sleepable callback
+ (``SEC("struct_ops.s/handle_out_of_memory")``). ``oc`` is a read-only
+ ``struct oom_control *`` whose ``oc->memcg`` field is verified as
+ ``TRUSTED_OR_NULL`` (``NULL`` for global OOMs, trusted pointer for
+ memcg OOMs). ``cgrp`` is the cgroup where this policy instance is
+ attached. ``handle_out_of_memory`` is required and validated at map
+ load time.
+- ``name``: Policy name logged in OOM reports (validated via
+ ``bpf_obj_name_cpy()``; defaults to ``"bpf_defined_policy"`` if empty).
+
+BPF Kfuncs
+==========
+
+Kfuncs for ``struct bpf_oom_ops``
+---------------------------------
+
+``int bpf_oom_kill_process(struct oom_control *oc, struct task_struct *task, const char *message__str)``
+ Sleepable kfunc (restricted via default-deny filter to ``bpf_oom_ops``)
+ that terminates ``task`` through ``oom_kill_process()``, preserving OOM
+ logging, memcg ``memory.events`` accounting, asynchronous OOM memory
+ reclamation, and ``memory.oom.group`` recursive behavior.
+
+ Kernel-enforced constraints:
+
+ - Returns ``-EPERM`` for tasks exempt via ``oom_unkillable_task()`` (such
+ as ``init`` and kernel threads).
+ - Returns ``-EINVAL`` if ``task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN``
+ (``-1000``), or if ``oc->memcg`` is non-NULL and ``task`` is outside
+ ``oc->memcg``'s hierarchy.
+ - Returns ``-ESRCH`` if ``task`` has no live ``mm`` or already has
+ ``MMF_OOM_SKIP`` set.
+
+Kfuncs for Proactive OOM (``BPF_PROG_TYPE_SYSCALL`` & ``tp_btf/psi_avgs_work_tp``)
+----------------------------------------------------------------------------------
+
+Note: ``tp_btf/psi_avgs_work_tp`` runs in non-sleepable tracepoint
+context; schedule a sleepable ``bpf_task_work`` or ``bpf_wq`` callback to
+invoke sleepable OOM kfuncs from PSI handlers.
+
+``int bpf_out_of_memory(struct mem_cgroup *memcg__nullable, int order, u64 flags)``
+ Acquires ``oom_lock`` (waiting interruptibly for fatal signals if
+ ``BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK`` is set, else returning ``-EBUSY`` on
+ contention), accounts ``MEMCG_OOM`` for non-NULL ``memcg``, and runs
+ ``out_of_memory()``, invoking any attached ``bpf_oom_ops`` policies and
+ falling back to ``select_bad_process()`` if unhandled. Root ``memcg`` is
+ normalized to ``NULL``; dying memcgs return ``-EINVAL``. BPF-declared
+ OOMs do not panic the kernel if no eligible task exists, skip
+ ``sysctl_oom_kill_allocating_task``, and omit ``dump_header()`` noise.
+
+``int bpf_oom_proactive_kill(struct mem_cgroup *origin__nullable, struct task_struct *task, const char *message__str, u64 flags)``
+ Directly terminates ``task`` outside of an allocation failure without
+ falling back to ``select_bad_process()``. Synchronizes on ``oom_lock``
+ according to ``enum bpf_oom_flags``, applies the same ``-EPERM`` /
+ ``-EINVAL`` / ``-ESRCH`` protections as ``bpf_oom_kill_process()``,
+ verifies ``task`` is within ``origin__nullable`` when non-NULL (which
+ also scopes ``memory.oom.group`` traversal and ``oom_memcg`` logging),
+ and omits ``dump_header()`` stack/meminfo noise while retaining the
+ single-line ``oom-kill:`` and ``Killed process`` records.
+
+Memory Cgroup Kfuncs
+--------------------
+
+Handlers commonly pair the above with the kfuncs in ``mm/bpf_memcontrol.c``:
+``bpf_get_root_mem_cgroup()``, ``bpf_get_mem_cgroup()``,
+``bpf_put_mem_cgroup()``, ``bpf_mem_cgroup_usage()``,
+``bpf_mem_cgroup_page_state()``, ``bpf_mem_cgroup_vm_events()``,
+``bpf_mem_cgroup_memory_events()``, ``bpf_mem_cgroup_flush_stats()``, and:
+
+``int bpf_mem_cgroup_raise_max(struct mem_cgroup *memcg, u64 max_bytes)``
+ Sleepable kfunc that non-destructively raises ``memcg``'s ``memory.max``
+ limit to ``max_bytes`` (truncated to ``PAGE_SIZE`` and clamped to
+ ``PAGE_COUNTER_MAX``, which represents unlimited/``"max"``; callers may
+ pass ``U64_MAX``). Only strictly higher limits on live, non-root
+ memory cgroups are accepted (returning ``-EINVAL`` otherwise) so no
+ reclaim is triggered while holding ``oom_lock``. On cgroup v1, enforces
+ ``memory.max <= memsw.max``.
+
+To check whether a task is already exiting due to OOM, read
+``BPF_CORE_READ(task, signal, oom_mm) != NULL`` directly via CO-RE.
diff --git a/Documentation/bpf/index.rst b/Documentation/bpf/index.rst
index 638a00d42bc2..f226cfc41dc7 100644
--- a/Documentation/bpf/index.rst
+++ b/Documentation/bpf/index.rst
@@ -22,6 +22,7 @@ that goes into great technical depth about the BPF Architecture.
kfuncs
cpumasks
fs_kfuncs
+ bpf_oom
programs
maps
bpf_prog_run
diff --git a/MAINTAINERS b/MAINTAINERS
index 8bb61211b7f0..039d934d0a02 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -5177,6 +5177,7 @@ M: Shakeel Butt <shakeel.butt@linux.dev>
L: bpf@vger.kernel.org
L: linux-mm@kvack.org
S: Maintained
+F: Documentation/bpf/bpf_oom.rst
F: include/linux/bpf_oom.h
F: mm/bpf_memcontrol.c
F: mm/bpf_oom.c
--
2.56.1.911.g883d8bcb20-goog
^ permalink raw reply related [flat|nested] 27+ messages in thread* Re: [PATCH bpf-next v4 17/17] Documentation/bpf: Document BPF OOM handling and kfuncs
2026-12-02 21:04 ` [PATCH bpf-next v4 17/17] Documentation/bpf: Document BPF OOM handling and kfuncs Ben Gardon
@ 2026-12-02 21:58 ` bot+bpf-ci
0 siblings, 0 replies; 27+ messages in thread
From: bot+bpf-ci @ 2026-12-02 21:58 UTC (permalink / raw)
To: bgardon, ast, daniel, andrii, akpm, hannes, mhocko, shakeel.butt,
roman.gushchin, tj
Cc: jp.kobryn, eddyz87, memxor, martin.lau, song, yonghong.song,
jolsa, emil, ihor.solodrai, rientjes, surenb, joshdon,
sweettea-kernel, zhouchuyi, laoar.shao, benbwgardon, bpf,
linux-mm, cgroups, linux-kernel, bgardon, corbet, skhan, rdunlap,
linux-doc, ast, andrii, daniel, martin.lau, eddyz87,
yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 4090 bytes --]
> Documentation/bpf: Document BPF OOM handling and kfuncs
TL;DR: Documentation-only issues in bpf_oom.rst: it may overstate
dump_header() suppression (no-victim path still dumps), implies multiple
supported tracepoints, and misplaces handler validation (attach, not load).
> diff --git a/Documentation/bpf/bpf_oom.rst b/Documentation/bpf/bpf_oom.rst
> new file mode 100644
> --- /dev/null
> +++ b/Documentation/bpf/bpf_oom.rst
> @@ -0,0 +1,138 @@
[ ... ]
> +2. **Proactive OOM invocation and termination** via BPF kfuncs callable
> + from ``BPF_PROG_TYPE_SYSCALL`` programs and select tracepoints (such as
> + ``tp_btf/psi_avgs_work_tp``) to trigger OOM handling or directly
> + terminate a chosen task without a separate userspace OOM daemon.
Is "select tracepoints (such as tp_btf/psi_avgs_work_tp)" accurate?
bpf_declare_oom_tracing_filter() in mm/oom_kill.c accepts exactly one
tracing attach point and returns -EACCES for any other:
prog->aux->attach_btf_id == bpf_oom_trace_ids[0]
Should the text name psi_avgs_work_tp as the only supported tracepoint
rather than implying a set?
[ ... ]
> +- ``handle_out_of_memory(oc, cgrp)``: Sleepable callback
> + (``SEC("struct_ops.s/handle_out_of_memory")``). ``oc`` is a read-only
> + ``struct oom_control *`` whose ``oc->memcg`` field is verified as
> + ``TRUSTED_OR_NULL`` (``NULL`` for global OOMs, trusted pointer for
> + memcg OOMs). ``cgrp`` is the cgroup where this policy instance is
> + attached. ``handle_out_of_memory`` is required and validated at map
> + load time.
Is "validated at map load time" correct?
bpf_oom_ops_validate() is the struct_ops .validate callback, which is only
called from __bpf_struct_ops_map_update_elem():
if (st_ops->validate) {
err = st_ops->validate(kdata);
That runs on BPF_MAP_UPDATE_ELEM of the struct_ops map, which libbpf issues
from bpf_map__attach_cgroup_opts() rather than from bpf_object__load().
An object that leaves handle_out_of_memory unset (or uses an invalid name)
loads successfully and fails with -EINVAL only at attach.
Could this say the check happens when the struct_ops map is updated or
attached?
[ ... ]
> +``int bpf_out_of_memory(struct mem_cgroup *memcg__nullable, int order, u64 flags)``
> + Acquires ``oom_lock`` (waiting interruptibly for fatal signals if
> + ``BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK`` is set, else returning ``-EBUSY`` on
> + contention), accounts ``MEMCG_OOM`` for non-NULL ``memcg``, and runs
> + ``out_of_memory()``, invoking any attached ``bpf_oom_ops`` policies and
> + falling back to ``select_bad_process()`` if unhandled. Root ``memcg`` is
> + normalized to ``NULL``; dying memcgs return ``-EINVAL``. BPF-declared
> + OOMs do not panic the kernel if no eligible task exists, skip
> + ``sysctl_oom_kill_allocating_task``, and omit ``dump_header()`` noise.
Is the claim that BPF-declared OOMs omit dump_header() correct for the case
where no eligible task exists?
The suppression is only in oom_kill_process() and check_panic_on_oom().
The no-victim path in out_of_memory() still calls it unconditionally:
select_bad_process(oc);
/* Found nothing?!?! */
if (!oc->chosen) {
dump_header(oc);
pr_warn("Out of memory and no killable processes...\n");
...
if (!is_sysrq_oom(oc) && !is_memcg_oom(oc) &&
!is_bpf_declared_oom(oc))
panic("System is deadlocked on memory\n");
}
Only the panic is skipped there. If bpf_out_of_memory() is called on a
memcg whose tasks are all OOM_SCORE_ADJ_MIN (or that has no tasks) and no
bpf_oom_ops handler returns > 0, the full header, including dump_stack()
and meminfo, is printed on every call.
Should the documentation limit the dump_header() claim to the kill path, or
should out_of_memory() get an is_bpf_declared_oom() check before that
dump_header()?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46974333971
^ permalink raw reply [flat|nested] 27+ messages in thread
* Re: [PATCH bpf-next v4 00/17] mm: BPF OOM
2026-12-02 21:03 [PATCH bpf-next v4 00/17] mm: BPF OOM Ben Gardon
` (16 preceding siblings ...)
2026-12-02 21:04 ` [PATCH bpf-next v4 17/17] Documentation/bpf: Document BPF OOM handling and kfuncs Ben Gardon
@ 2026-12-02 21:38 ` Ben Gardon
17 siblings, 0 replies; 27+ messages in thread
From: Ben Gardon @ 2026-12-02 21:38 UTC (permalink / raw)
To: Alexei Starovoitov, Daniel Borkmann, Andrii Nakryiko,
Andrew Morton, Johannes Weiner, Michal Hocko, Shakeel Butt,
Roman Gushchin, Tejun Heo
Cc: JP Kobryn, Eduard Zingerman, Kumar Kartikeya Dwivedi,
Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
Emil Tsalapatis, Ihor Solodrai, David Rientjes,
Suren Baghdasaryan, Josh Don, Sweet Tea Dorminy, Chuyi Zhou,
Yafang Shao, benbwgardon, bpf, linux-mm, cgroups, linux-kernel
On Wed, Dec 2, 2026 at 1:04 PM Ben Gardon <bgardon@google.com> wrote:
>
> Note: I am taking over this patch series from Roman Gushchin.
>
> This series adds support for BPF OOM handling and proactive OOM prevention.
>
> One might want this to:
> 1) Implement custom reactive OOM handling policies with smarter,
> application-specific victim selection.
> 2) Add greater NUMA awareness to task selection.
> 3) Create proactive OOM prevention policies, which terminate tasks before a
> kernel OOM is invoked, to preserve memory QoS.
>
> This creates a generic cgroup struct_ops interface, which is invoked before the
> kernel's OOM selector. A policy linked to the struct_ops can select which task
> to terminate, or expand a memory cgroup's hard limit to resolve the OOM
> non-destructively. Earlier proposals [1] have augmented the in-kernel task
> badness heuristic, but this series goes farther, leaving policy entirely up to
> the BPF program.
>
> Past attempts to standardize a single memory-cgroup-aware OOM policy [2] have
> shown that selection depends heavily on workloads and cgroup hierarchy layout.
> A BPF interface will provide flexibility while keeping the kernel OOM
> handler as a relatively simple and reliable fallback.
>
> To prevent OOMs in the first place, PSI-driven userspace daemons such as
> oomd [3] and systemd-oomd [4] terminate processes before thrashing or hard
> stalls, while leaving the kernel OOM handler as a last resort. Moving some of
> that logic into BPF avoids deploying and monitoring a separate privileged
> daemon that must itself survive severe memory pressure. It also unifies OOM
> accounting and logging, and gives policies direct access to kernel memcg and
> task state.
>
> Series Overview
> ---------------
>
> - Patch 1: Preparation: mark struct oom_control::memcg as
> TRUSTED_OR_NULL in the BPF verifier.
> - Patches 2-5: Reactive BPF OOM infrastructure: CGROUP_OOM_OPS
> struct_ops, bpf_oom_kill_process(), bpf_out_of_memory(), and
> cgroup hierarchy handling selftest.
> - Patches 6-10: PSI integration: psi_avgs_work_tp tracepoint,
> psi_group::cgroup_id, allowing bpf_out_of_memory() from
> tp_btf/psi_avgs_work_tp, and PSI selftest.
> - Patch 11: A systemd-oomd style BPF OOM policy example and selftest.
> - Patches 12-14: Allow proactive BPF policies to directly terminate chosen
> tasks without falling back to select_bad_process().
> This complements bpf_out_of_memory(), which runs the full
> out_of_memory() path and delegates selection to attached bpf_oom_ops
> handlers or the in-kernel selection algorithm.
> - Patches 15-16: Allow OOM handlers to resolve memcg OOMs by raising memory.max,
> as suggested by Michal Hocko.
> - Patch 17: Documentation/bpf/bpf_oom.rst
Apologies, a script mangled this and cut out multiple sections. Here's
the missing content. I will fix if/when I send a v5.
Base Tree, Testing & Tooling
----------------------------
This series is based on bpf-next/master (commit c846c98451b9,
v7.4-rc3-2627-gc846c98451b9).
Testing:
- Built each commit incrementally on bpf-next/master with CONFIG_WERROR=y,
CONFIG_MEMCG_V1=y, CONFIG_PROVE_LOCKING=y, and
CONFIG_DEBUG_ATOMIC_SLEEP=y, including BTF ID resolution
(--fatal_warnings).
- Ran BPF selftests in virtme-ng (--cpus 4, --memory 2G) with
test_progs -j across oom, oomd, oom_kfunc_neg (3 verifier rejection
subtests + runtime boundary checks), oom_proactive_kill,
oom_raise_max, and psi (3/3 consecutive passes on bpf-next/master, no
lockdep, atomic-sleep, or kernel warnings), as well as existing
cgroup* (23/23), task_work*, task_under_cgroup, and
verifier_kfunc_prog_types selftests.
- Verified compilation under non-default Kconfigs with CONFIG_WERROR=y:
CONFIG_MEMCG=n, CONFIG_BPF_EVENTS=n, CONFIG_MEMCG_V1=n, and
CONFIG_CGROUP_BPF=n.
Gemini was used to help rebase, address v3 review feedback, and for
pre-submission reviews. It was used in writing patches 11-17 (kfuncs,
selftests, and documentation), this cover letter, and the v4 changelog.
Everything has been reviewed and verified by hand.
Gemini also pulled from a public, but not shared v4 from Roman's GitHub:
https://github.com/torvalds/linux/compare/master...rgushchin:linux:bpfoom.4.rebased
Many of the responses to v3 feedback were already done in that branch.
[1]: https://lwn.net/ml/linux-kernel/20230810081319.65668-1-zhouchuyi@bytedance.com/
[2]: https://lore.kernel.org/lkml/20171130152824.1591-1-guro@fb.com/
[3]: https://github.com/facebookincubator/oomd
[4]: https://www.freedesktop.org/software/systemd/man/latest/systemd-oomd.service.html
[5]: https://lore.kernel.org/all/20260917200542.3689605-1-ameryhung@gmail.com/
---
Changelog
---------
v4:
1) Taken over from Roman Gushchin by Ben Gardon.
2) Rebased on top of cgroup struct_ops attachment infrastructure.
(commit 369d9dcd8fb8, Martin KaFai Lau, Amery Hung [5]) Dropped custom
cgroup struct_ops link patches, adopted CGROUP_OOM_OPS.
3) Dropped mem_cgroup_get_from_ino() and read_cgroup_file() selftest
helper patches (both merged upstream via Shakeel Butt and Jiayuan
Chen), and split the standalone libbpf -ENOMEM bugfix out to target
the bpf tree separately.
4) Dropped bpf_task_is_oom_victim() kfunc in favor of reading
task->signal->oom_mm directly (Matt Bobrowski, Alexei
Starovoitov, Michal Hocko).
5) Dropped oc->bpf_memory_freed dual-reporting check so handlers can
return > 0 to back off while a previously selected task exits
(Michal Hocko); treat only positive return values as handled so
negative errnos delegate cleanly.
6) Bypassed bpf_handle_oom() on SysRq-triggered OOMs (is_sysrq_oom(oc))
so SysRq-f remains an unconditional failsafe (Michal Hocko).
7) Hardened bpf_oom_ops: added .validate requiring
handle_out_of_memory, validated ops->name with bpf_obj_name_cpy(),
switched bpf_oom_func_proto() from tracing_prog_func_proto() to
curated bpf_base_func_proto(), walked offline cgroups up to the
nearest online ancestor, added lockdep_assert_held(&oom_lock), and
encapsulated sleepable RCU Tasks Trace helpers in
include/linux/bpf-cgroup.h.
8) Hardened bpf_oom_kill_process(): switched to find_lock_task_mm()
with MMF_OOM_SKIP and OOM_SCORE_ADJ_MIN checks under task_lock(),
enforced oc->memcg hierarchy containment via
mem_cgroup_task_in_hierarchy(), and fixed
bpf_oom_kfunc_filter() to check set membership with default-deny
(Martin KaFai Lau).
9) Hardened bpf_out_of_memory(): registered directly on
BPF_PROG_TYPE_SYSCALL and BPF_PROG_TYPE_TRACING (restricted to
BPF_TRACE_RAW_TP on btf_trace_psi_avgs_work_tp under
CONFIG_PSI && CONFIG_BPF_EVENTS), moved BPF_OOM_FLAGS_ALL outside
enum bpf_oom_flags, added oc->bpf_declared to prevent panic() and
sysctl_oom_kill_allocating_task, clamped oc->totalpages in
constrained_alloc(), normalized root_mem_cgroup to NULL, rejected
dying memcgs, and accounted MEMCG_OOM.
10) Switched psi_avgs_work from TRACE_EVENT() to bare DECLARE_TRACE()
(psi_avgs_work_tp) to avoid exporting a pointer-only tracefs ABI,
added include/trace/events/psi.h to MAINTAINERS, and guarded
psi_group::cgroup_id with CONFIG_CGROUPS.
11) Generalized selftests for parallel/multi-CPU execution (serial_test_*,
pipe-synchronized pre-allocation without cgroup freezing, SIGKILL
and runtime PSI checks).
12) Added systemd-oomd style BPF OOM policy selftest (Alexei
Starovoitov, Roman Gushchin).
13) Added bpf_oom_proactive_kill() for proactive OOM prevention without
select_bad_process() fallback or dump_header() noise, with selftest
and negative/verifier kfunc tests.
14) Added bpf_mem_cgroup_raise_max() kfunc in mm/bpf_memcontrol.c for
non-destructive memcg limit expansion during OOM (Michal Hocko),
with cgroup v2 and v1 support and selftest.
15) Added Documentation/bpf/bpf_oom.rst (Michal Hocko, Matt Bobrowski,
Hao Ge).
v3: https://lore.kernel.org/all/20260127024421.494929-1-roman.gushchin@linux.dev/
v3:
1) Replaced bpf_psi struct ops with a tracepoint in psi_avgs_work() (Tejun H.)
2) Updated bpf_oom struct ops:
- removed bpf_oom_ctx, passing bpf_struct_ops_link instead (by Alexei S.)
- removed handle_cgroup_offline callback.
3) Updated kfuncs:
- bpf_out_of_memory() dropped constraint_text argument (by Michal H.)
- bpf_oom_kill_process() added check for OOM_SCORE_ADJ_MIN.
4) Libbpf: updated bpf_map__attach_struct_ops_opts to use target_fd.
(by Alexei S.)
v2: https://lore.kernel.org/all/20251027231727.472628-1-roman.gushchin@linux.dev/
v2:
1) A single bpf_oom can be attached system-wide and a single bpf_oom
per memcg.
(by Alexei Starovoitov)
2) Initial support for attaching struct ops to cgroups (Martin KaFai Lau,
Andrii Nakryiko and others)
3) bpf memcontrol kfuncs enhancements and tests (co-developed by JP Kobryn)
4) Many small-ish fixes and cleanups (suggested by Andrew Morton,
Suren Baghdasaryan,
Andrii Nakryiko and Kumar Kartikeya Dwivedi)
5) bpf_out_of_memory() is taking u64 flags instead of bool wait_on_oom_lock
(suggested by Kumar Kartikeya Dwivedi)
6) bpf_get_mem_cgroup() got KF_RCU flag (suggested by Kumar Kartikeya Dwivedi)
7) cgroup online and offline callbacks for bpf_psi, cgroup offline for bpf_oom
v1: https://lore.kernel.org/all/20250818170136.209169-1-roman.gushchin@linux.dev/
v1:
1) Both OOM and PSI parts are now implemented using bpf struct ops,
providing a path for future extensions (suggested by Kumar
Kartikeya Dwivedi,
Song Liu and Matt Bobrowski)
2) It's possible to create PSI triggers from BPF, no need for an additional
userspace agent. (suggested by Suren Baghdasaryan)
Also there is now a callback for the cgroup release event.
3) Added an ability to block on oom_lock instead of bailing out
(suggested by Michal Hocko)
4) Added bpf_task_is_oom_victim (suggested by Michal Hocko)
5) PSI callbacks are scheduled using a separate workqueue (suggested
by Suren Baghdasaryan)
RFC:
https://lwn.net/ml/all/20250428033617.3797686-1-roman.gushchin@linux.dev/
Ben Gardon (6):
mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention
selftests/bpf: Add bpf_oom_proactive_kill() proactive OOM test
selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs
mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc
selftests/bpf: Add bpf_mem_cgroup_raise_max() OOM test
Documentation/bpf: Document BPF OOM handling and kfuncs
JP Kobryn (1):
selftests/bpf: Enable CONFIG_PSI
Roman Gushchin (10):
bpf: mark struct oom_control's memcg field as TRUSTED_OR_NULL
mm, bpf: introduce BPF OOM struct ops
mm, bpf: introduce bpf_oom_kill_process() BPF kfunc
mm, bpf: introduce bpf_out_of_memory() BPF kfunc
selftests/bpf: Add BPF OOM struct ops test
sched/psi: add a tracepoint to psi_avgs_work()
sched/psi: add cgroup_id field to psi_group structure
mm, bpf: allow calling bpf_out_of_memory() from a PSI tracepoint
selftests/bpf: Add PSI tracepoint OOM test
selftests/bpf: Add systemd-oomd style OOM policy test
Documentation/bpf/bpf_oom.rst | 138 ++++++++
> Documentation/bpf/index.rst | 1 +
> MAINTAINERS | 4 +
> include/linux/bpf-cgroup-defs.h | 1 +
> include/linux/bpf-cgroup.h | 16 +-
> include/linux/bpf.h | 1 +
> include/linux/bpf_oom.h | 44 +++
> include/linux/memcontrol.h | 27 ++
> include/linux/oom.h | 39 +++
> include/linux/psi_types.h | 6 +
> include/trace/events/psi.h | 19 ++
> kernel/bpf/cgroup.c | 1 +
> kernel/bpf/verifier.c | 5 +
> kernel/sched/psi.c | 7 +
> mm/Makefile | 3 +
> mm/bpf_memcontrol.c | 24 ++
> mm/bpf_oom.c | 187 +++++++++++
> mm/memcontrol-v1.c | 16 +
> mm/memcontrol-v1.h | 6 +
> mm/memcontrol.c | 38 +++
> mm/oom_kill.c | 313 ++++++++++++++++++-
> tools/testing/selftests/bpf/config | 1 +
> .../selftests/bpf/prog_tests/memory_holder.h | 158 ++++++++++
> tools/testing/selftests/bpf/prog_tests/test_oom.c | 218 +++++++++++++
> .../selftests/bpf/prog_tests/test_oom_kfunc_neg.c | 79 +++++
> .../bpf/prog_tests/test_oom_proactive_kill.c | 119 +++++++
> .../selftests/bpf/prog_tests/test_oom_raise_max.c | 135 ++++++++
> tools/testing/selftests/bpf/prog_tests/test_oomd.c | 274 ++++++++++++++++
> tools/testing/selftests/bpf/prog_tests/test_psi.c | 107 +++++++
> tools/testing/selftests/bpf/progs/test_oom.c | 132 ++++++++
> .../selftests/bpf/progs/test_oom_fail_ops_oom.c | 21 ++
> .../bpf/progs/test_oom_fail_ops_proactive.c | 23 ++
> .../selftests/bpf/progs/test_oom_fail_syscall.c | 15 +
> .../selftests/bpf/progs/test_oom_proactive_kill.c | 46 +++
> .../selftests/bpf/progs/test_oom_proactive_kill.h | 12 +
> .../selftests/bpf/progs/test_oom_raise_max.c | 55 ++++
> .../selftests/bpf/progs/test_oom_raise_max.h | 10 +
> tools/testing/selftests/bpf/progs/test_oomd.c | 346 +++++++++++++++++++++
> tools/testing/selftests/bpf/progs/test_oomd.h | 33 ++
> tools/testing/selftests/bpf/progs/test_psi.c | 88 ++++++
> 40 files changed, 2760 insertions(+), 8 deletions(-)
>
> --
> 2.56.1.911.g883d8bcb20-goog
>
^ permalink raw reply [flat|nested] 27+ messages in thread