Skip to contentSkip to conversation

mm: BPF OOM

PATCH In review Ben Gardon 5 participants 34 messages Dec 2 – Dec 3

Subsystems (13)
lore
Share & tools
lore

Ben Gardon

author
#0 lore raw

v4 cover mm: BPF OOM

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 | 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(-)
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#1 lore raw

PATCH v4 1/17 bpf: mark struct oom_control's memcg field as TRUSTED_OR_NULL

From: Roman Gushchin <[email protected]>

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.

---
v3 -> v4:
- Fix commit message typo ("It's" -> "Its").

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

 kernel/bpf/verifier.c | 5 +++++
 1 file changed, 5 insertions(+)
kernel/bpf/verifier.c +5 -0
index 8021afe783b6..6e7c5a7b2018 100644
@@ -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");
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#2 lore raw

PATCH v4 2/17 mm, bpf: introduce BPF OOM struct ops

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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().

---
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/[email protected]/

 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
MAINTAINERS +2 -0
index b430b29e3878..d4ef52c5594b 100644
@@ -5177,7 +5177,9 @@ M:	Shakeel Butt <[email protected]>
 L:	[email protected]
 L:	[email protected]
 S:	Maintained
+F:	include/linux/bpf_oom.h
 F:	mm/bpf_memcontrol.c
+F:	mm/bpf_oom.c
 
 BPF [MISC]
 L:	[email protected]
include/linux/bpf-cgroup-defs.h +1 -0
index 671f27ba6a62..ff650a422e36 100644
@@ -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
include/linux/bpf-cgroup.h +14 -2
index 0b63c2cc1399..13a74791be46 100644
@@ -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);
include/linux/bpf.h +1 -0
index 96e249bd00fb..82f99b92c481 100644
@@ -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;
 	};
 };
include/linux/bpf_oom.h new file +44 -0

44 lines not on this page · raw message

include/linux/oom.h +17 -0
index 00da05d227e6..ca3192c42533 100644
@@ -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;
 
kernel/bpf/cgroup.c +1 -0
index e4e680dfb63d..dba22e99197d 100644
@@ -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;
 	}
 
mm/Makefile +3 -0
index 2a3ec53d62ee..66b53e569eed 100644
@@ -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
mm/bpf_oom.c new file +187 -0

187 lines not on this page · raw message

mm/oom_kill.c +10 -0
index 5d48bd862c27..fa9088c965b6 100644
@@ -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) {
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#5 lore raw

PATCH v4 3/17 mm, bpf: introduce bpf_oom_kill_process() BPF kfunc

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
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/[email protected]/

 include/linux/memcontrol.h |  20 ++++++++
 mm/oom_kill.c              | 102 +++++++++++++++++++++++++++++++++++++
 2 files changed, 122 insertions(+)
include/linux/memcontrol.h +20 -0
index 69e1bcc67c58..bc30d7baecd7 100644
@@ -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 */
 
mm/oom_kill.c +102 -0

105 lines not on this page · raw message

Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#7 lore raw

PATCH v4 4/17 mm, bpf: introduce bpf_out_of_memory() BPF kfunc

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
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/[email protected]/

 include/linux/oom.h |  19 +++++++++
 mm/oom_kill.c       | 101 ++++++++++++++++++++++++++++++++++++++++----
 2 files changed, 111 insertions(+), 9 deletions(-)
include/linux/oom.h +19 -0
index ca3192c42533..168b64dfb6ad 100644
@@ -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;
mm/oom_kill.c +92 -9

150 lines not on this page · raw message

Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#10 lore raw

PATCH v4 5/17 selftests/bpf: Add BPF OOM struct ops test

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
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/[email protected]/

 .../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
tools/testing/selftests/bpf/prog_tests/memory_holder.h new file +158 -0
new file mode 100644
index 000000000000..34b408da3958
@@ -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 */
tools/testing/selftests/bpf/prog_tests/test_oom.c new file +218 -0

218 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_oom.c new file +132 -0

132 lines not on this page · raw message

Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#11 lore raw

PATCH v4 6/17 sched/psi: add a tracepoint to psi_avgs_work()

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
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/[email protected]/

 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
MAINTAINERS +1 -0
index d4ef52c5594b..8bb61211b7f0 100644
@@ -22397,6 +22397,7 @@ M:	Suren Baghdasaryan <[email protected]>
 R:	Peter Zijlstra <[email protected]>
 S:	Maintained
 F:	include/linux/psi*
+F:	include/trace/events/psi.h
 F:	kernel/sched/psi.c
 
 PROPELLER BUILD
include/trace/events/psi.h new file +19 -0
new file mode 100644
index 000000000000..838dc95c3401
@@ -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>
kernel/sched/psi.c +6 -0
index 7c5381423334..d89c40902492 100644
@@ -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);
 }
 
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#13 lore raw

PATCH v4 7/17 sched/psi: add cgroup_id field to psi_group structure

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
v3 -> v4:
- Guard cgroup_id with #ifdef CONFIG_CGROUPS and note root/psi_system aliasing (cgroup_id == 0).

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

 include/linux/psi_types.h | 6 ++++++
 kernel/sched/psi.c        | 1 +
 2 files changed, 7 insertions(+)
include/linux/psi_types.h +6 -0
index dd10c22299ab..597f6fabf688 100644
@@ -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 */
kernel/sched/psi.c +1 -0
index d89c40902492..571266028a50 100644
@@ -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);
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#14 lore raw

PATCH v4 8/17 mm, bpf: allow calling bpf_out_of_memory() from a PSI tracepoint

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
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/[email protected]/

 mm/oom_kill.c | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
mm/oom_kill.c +35 -0
index 9b5df00f98ab..21b88332a46a 100644
@@ -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);
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#15 lore raw

PATCH v4 9/17 selftests/bpf: Enable CONFIG_PSI

In reply to Ben Gardon

From: JP Kobryn <[email protected]>

Include CONFIG_PSI to allow dependent tests to build.

---
v3 -> v4:
- Standardized subject prefix.

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

 tools/testing/selftests/bpf/config | 1 +
 1 file changed, 1 insertion(+)
tools/testing/selftests/bpf/config +1 -0
index ce0db4be4d26..36651bf5533c 100644
@@ -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
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#16 lore raw

PATCH v4 10/17 selftests/bpf: Add PSI tracepoint OOM test

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
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/[email protected]/

 .../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
tools/testing/selftests/bpf/prog_tests/test_psi.c new file +107 -0
new file mode 100644
index 000000000000..9f3fdf2d6c5b
@@ -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();
+}
tools/testing/selftests/bpf/progs/test_psi.c new file +88 -0

88 lines not on this page · raw message

Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#17 lore raw

PATCH v4 11/17 selftests/bpf: Add systemd-oomd style OOM policy test

In reply to Ben Gardon

From: Roman Gushchin <[email protected]>

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.

---
 .../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
tools/testing/selftests/bpf/prog_tests/test_oomd.c new file +274 -0
new file mode 100644
index 000000000000..001b2262a2ae
@@ -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);
+}
tools/testing/selftests/bpf/progs/test_oomd.c new file +346 -0

346 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_oomd.h new file +33 -0
new file mode 100644
index 000000000000..cbd0d9a9e928
@@ -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 */
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#19 lore raw

PATCH v4 12/17 mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention

In reply to Ben Gardon

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.

---
 include/linux/oom.h |  3 ++
 mm/oom_kill.c       | 71 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 74 insertions(+)
include/linux/oom.h +3 -0
index 168b64dfb6ad..2725f17c7b40 100644
@@ -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;
mm/oom_kill.c +71 -0

83 lines not on this page · raw message

Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#22 lore raw

PATCH v4 13/17 selftests/bpf: Add bpf_oom_proactive_kill() proactive OOM test

In reply to Ben Gardon

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.

---
 .../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
tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c new file +119 -0
new file mode 100644
index 000000000000..ca2165f03278
@@ -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();
+}
tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c new file +46 -0

46 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h new file +12 -0
new file mode 100644
index 000000000000..d3bf7596de21
@@ -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 */
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#23 lore raw

PATCH v4 14/17 selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs

In reply to Ben Gardon

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.

---
 .../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
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +79 -0
new file mode 100644
index 000000000000..8cfe9e3e85bb
@@ -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);
+}
tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c new file +21 -0
new file mode 100644
index 000000000000..ba6b15c6e407
@@ -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,
+};
tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c new file +23 -0
new file mode 100644
index 000000000000..24ba2bac1d85
@@ -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,
+};
tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c new file +15 -0
new file mode 100644
index 000000000000..e6aa7017f500
@@ -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");
+}
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#26 lore raw

PATCH v4 15/17 mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc

In reply to Ben Gardon

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.

---
 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(+)
include/linux/memcontrol.h +7 -0
index bc30d7baecd7..1dc5176e2682 100644
@@ -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 */
 
mm/bpf_memcontrol.c +24 -0
index d8f579c28560..8c00d98b5826 100644
@@ -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)
 
mm/memcontrol-v1.c +16 -0
index b7f286888507..d50fe775f1f3 100644
@@ -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)
 {
mm/memcontrol-v1.h +6 -0
index 820139657184..3c22f124a5dc 100644
@@ -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) {}
mm/memcontrol.c +38 -0
index afbb638e7e1c..8440cca757b9 100644
@@ -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)
 {
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#29 lore raw

PATCH v4 16/17 selftests/bpf: Add bpf_mem_cgroup_raise_max() OOM test

In reply to Ben Gardon

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".

---
 .../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
tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c new file +135 -0
new file mode 100644
index 000000000000..6b803d4560e9
@@ -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();
+}
tools/testing/selftests/bpf/progs/test_oom_raise_max.c new file +55 -0

55 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_oom_raise_max.h new file +10 -0
new file mode 100644
index 000000000000..f25bde9a295a
@@ -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 */
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
author
#30 lore raw

PATCH v4 17/17 Documentation/bpf: Document BPF OOM handling and kfuncs

In reply to Ben Gardon

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.

---
 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
Documentation/bpf/bpf_oom.rst new file +138 -0
new file mode 100644
index 000000000000..5fc63269aec5
@@ -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.
Documentation/bpf/index.rst +1 -0
index 638a00d42bc2..f226cfc41dc7 100644
@@ -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
MAINTAINERS +1 -0
index 8bb61211b7f0..039d934d0a02 100644
@@ -5177,6 +5177,7 @@ M:	Shakeel Butt <[email protected]>
 L:	[email protected]
 L:	[email protected]
 S:	Maintained
+F:	Documentation/bpf/bpf_oom.rst
 F:	include/linux/bpf_oom.h
 F:	mm/bpf_memcontrol.c
 F:	mm/bpf_oom.c
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
#24 lore raw

Re: [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs

In reply to Ben Gardon
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() --

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 <[email protected]>

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.

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +0 -0
new file mode 100644
index 0000000000000..8cfe9e3e85bbc
@@ -0,0 +1,79 @@

[ ... ]

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +11 -0
+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),
+	);
+

tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c line 38

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +10 -0
+	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.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#12 lore raw

Re: [PATCH bpf-next v4 06/17] sched/psi: add a tracepoint to psi_avgs_work()

In reply to Ben Gardon
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 --

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 <[email protected]>

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.

Quoted 15 lines
include/trace/events/psi.h new file +9 -0
new file mode 100644
index 0000000000000..838dc95c34012
@@ -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>
+

include/trace/events/psi.h line 19

Quoted 10 lines
include/trace/events/psi.h new file +10 -0
+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.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#8 lore raw

Re: [PATCH bpf-next v4 04/17] mm, bpf: introduce bpf_out_of_memory() BPF kfunc

In reply to Ben Gardon
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…

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 <[email protected]>

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.

Quoted 4 lines
mm/oom_kill.c +0 -0
index 85da2a39e18a1..9b5df00f98abd 100644

[ ... ]

Quoted 10 lines
mm/oom_kill.c +2 -1
@@ -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);
 	}
 

[ ... ]

mm/oom_kill.c bool out_of_memory(struct oom_control *oc) · line 1148

Quoted 10 lines
mm/oom_kill.c +2 -1
@@ -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.

mm/oom_kill.c bool out_of_memory(struct oom_control *oc) · line 1176

Quoted 10 lines
mm/oom_kill.c +2 -1
@@ -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.

Quoted 53 lines
mm/oom_kill.c +49 -0
@@ -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;

mm/oom_kill.c __bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc, · line 1385

Quoted 10 lines
mm/oom_kill.c +10 -0
+	}
+
+	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.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author
#32 lore raw
In reply to Ben Gardon
Quoted 44 lines · Ben Gardon

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.

Quoted 8 lines

- 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/[email protected]/
[2]: https://lore.kernel.org/lkml/[email protected]/
[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/[email protected]/
---
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/[email protected]/
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/[email protected]/
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/[email protected]/
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/[email protected]/
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 ++++++++

Quoted 44 lines
 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

#27 lore raw

Re: [PATCH bpf-next v4 15/17] mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc

In reply to Ben Gardon
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 --

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 <[email protected]>

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.

Quoted 13 lines
mm/memcontrol-v1.c +5 -0
index b7f2868885071..d50fe775f1f3e 100644
@@ -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);

mm/memcontrol-v1.c void vmpressure_unregister_event(struct mem_cgroup *memcg, · line 1435

Quoted 10 lines
mm/memcontrol-v1.c +10 -0
+	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()
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
#31 lore raw

Re: [PATCH bpf-next v4 17/17] Documentation/bpf: Document BPF OOM handling and kfuncs

In reply to Ben Gardon
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…
Quoted 1 line

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).

Quoted 5 lines
Documentation/bpf/bpf_oom.rst new file +0 -0
new file mode 100644
@@ -0,0 +1,138 @@

[ ... ]

Documentation/bpf/bpf_oom.rst line 20

Quoted 4 lines

+2. **Proactive OOM invocation and termination** via BPF kfuncs callable

Documentation/bpf/bpf_oom.rst new file +3 -0
+   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?

[ ... ]

Documentation/bpf/bpf_oom.rst line 66

Quoted 7 lines

+- ``handle_out_of_memory(oc, cgrp)``: Sleepable callback

Documentation/bpf/bpf_oom.rst new file +6 -0
+  (``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?

[ ... ]

Documentation/bpf/bpf_oom.rst line 107

Quoted 9 lines

+``int bpf_out_of_memory(struct mem_cgroup *memcg__nullable, int order, u64 flags)``

Documentation/bpf/bpf_oom.rst new file +8 -0
+  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

#18 lore raw

Re: [PATCH bpf-next v4 11/17] selftests/bpf: Add systemd-oomd style OOM policy test

In reply to Ben Gardon
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.
Quoted 1 line

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.

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/test_oomd.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 16 lines
tools/testing/selftests/bpf/prog_tests/test_oomd.c new file +16 -0
+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++) {

tools/testing/selftests/bpf/prog_tests/test_oomd.c line 75

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/test_oomd.c new file +10 -0
+		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?

Quoted 4 lines
tools/testing/selftests/bpf/progs/test_oomd.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 9 lines
tools/testing/selftests/bpf/progs/test_oomd.c new file +9 -0
+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;

[ ... ]

tools/testing/selftests/bpf/progs/test_oomd.c line 195

Quoted 10 lines
tools/testing/selftests/bpf/progs/test_oomd.c new file +10 -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?

[ ... ]

Quoted 7 lines
tools/testing/selftests/bpf/progs/test_oomd.c new file +7 -0
+		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++;

[ ... ]

tools/testing/selftests/bpf/progs/test_oomd.c line 325

Quoted 7 lines
tools/testing/selftests/bpf/progs/test_oomd.c new file +7 -0
+			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

#28 lore raw

Re: [PATCH bpf-next v4 15/17] mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc

In reply to Ben Gardon
TL;DR: bpf_mem_cgroup_raise_max() looks registered for all program types, so any sleepable BPF program may be able to raise memory.max on any non-root memcg, bypassing cgroupfs permission checks…
Quoted 1 line

mm, bpf: introduce bpf_mem_cgroup_raise_max() kfunc

TL;DR: bpf_mem_cgroup_raise_max() looks registered for all program types, so any sleepable BPF program may be able to raise memory.max on any non-root memcg, bypassing cgroupfs permission checks; restricting it like the OOM kfuncs is suggested.

Quoted 3 lines
mm/bpf_memcontrol.c +0 -0

[ ... ]

mm/bpf_memcontrol.c BTF_ID_FLAGS(func, bpf_mem_cgroup_memory_events) · line 246

Quoted 7 lines
mm/bpf_memcontrol.c +1 -0
@@ -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)

This kfunc is added to bpf_memcontrol_kfuncs, which bpf_memcontrol_init() registers with register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, ...) and no .filter. bpf_prog_type_to_kfunc_hook() maps BPF_PROG_TYPE_UNSPEC to BTF_KFUNC_HOOK_COMMON, and btf_kfunc_is_allowed() checks the COMMON hook for every program type.

Can this let any sleepable program of any type (sleepable LSM, fentry/fmod_ret, uprobe, iterators, other struct_ops) raise memory.max on any non-root memcg? The commit message only names bpf_oom_ops handlers and proactive SYSCALL/PSI programs. A program only needs bpf_cgroup_from_id() or bpf_get_mem_cgroup() plus this kfunc, and it bypasses the cgroupfs ownership and delegation checks that apply to writes to memory.max.

The other state-changing kfuncs in this series are restricted. bpf_proactive_reclaim() is in a separate set registered only for BPF_PROG_TYPE_SYSCALL, bpf_oom_kill_process() is limited to bpf_oom_ops by bpf_oom_kfunc_filter(), and bpf_out_of_memory() and bpf_oom_proactive_kill() are registered for SYSCALL plus a tracing set restricted by bpf_declare_oom_tracing_filter(). Neither later commit in the series (the bpf_mem_cgroup_raise_max() selftest or the BPF OOM documentation) narrows the registration.

Should bpf_mem_cgroup_raise_max() go in its own set, registered for BPF_PROG_TYPE_SYSCALL and BPF_PROG_TYPE_STRUCT_OPS with a filter limited to bpf_oom_ops, the way the OOM kfuncs are? If the wider exposure is intended, should the commit message say so?

---
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

#25 lore raw

Re: [PATCH bpf-next v4 14/17] selftests/bpf: Add negative and verifier tests for BPF OOM kfuncs

In reply to Ben Gardon
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…
Quoted 1 line

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.

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +2 -0
+void serial_test_oom_kfunc_neg(void)
+{

[ ... ]

Quoted 1 line
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +1 -0
+	memory_holder_init(&worker);

[ ... ]

tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c line 71

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file +10 -0
+	/* 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

#20 lore raw

Re: [PATCH bpf-next v4 12/17] mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention

In reply to Ben Gardon
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…
Quoted 1 line

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

Quoted 10 lines

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"?

Quoted 3 lines
mm/oom_kill.c +0 -0

[ ... ]

mm/oom_kill.c static const struct btf_kfunc_id_set bpf_oom_kfunc_set = { · line 1487

Quoted 6 lines
mm/oom_kill.c +1 -0
@@ -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

#6 lore raw

Re: [PATCH bpf-next v4 03/17] mm, bpf: introduce bpf_oom_kill_process() BPF kfunc

In reply to Ben Gardon
TL;DR: bpf_oom_kill_process() may kill an OOM_SCORE_ADJ_MIN-protected vfork parent, because it doesn't reject in_vfork() tasks like oom_badness() does. The kill could also free no memory.
Quoted 1 line

mm, bpf: introduce bpf_oom_kill_process() BPF kfunc

TL;DR: bpf_oom_kill_process() may kill an OOM_SCORE_ADJ_MIN-protected vfork parent, because it doesn't reject in_vfork() tasks like oom_badness() does. The kill could also free no memory.

Quoted 3 lines
mm/oom_kill.c +0 -0

[ ... ]

Quoted 22 lines
mm/oom_kill.c +22 -0
+__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)) {

mm/oom_kill.c SYSCALL_DEFINE2(process_mrelease, int, pidfd, unsigned int, flags) · line 1316

Quoted 10 lines
mm/oom_kill.c +10 -0
+		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);

Can this kill a task that is protected with OOM_SCORE_ADJ_MIN? The checks here mirror the exclusions in oom_badness(), but in_vfork() is not among them:

    adj = (long)p->signal->oom_score_adj;
    if (adj == OOM_SCORE_ADJ_MIN ||
            mm_flags_test(MMF_OOM_SKIP, p->mm) ||
            in_vfork(p)) {

__set_oom_adj() skips vfork children, so a vfork child can hold a different oom_score_adj than the parent it shares an mm with. For example:

P has oom_score_adj = OOM_SCORE_ADJ_MIN and calls vfork() child C raises its own oom_score_adj to 0 before exec the bpf_oom_ops handler picks C (it reports the full RSS of P's mm) bpf_oom_kill_process(oc, C, ...) passes every check above

oom_kill_process() then reaches __oom_kill_process(), which sends SIGKILL to every process sharing the victim's mm without checking oom_score_adj:

    for_each_process(p) {
        if (!process_shares_mm(p, mm))
            continue;
        ...
        do_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_TGID);
    }

So P is killed as well, which contradicts the commit message statement that tasks protected with OOM_SCORE_ADJ_MIN "are rejected in the kernel". Killing C also frees no memory, since P still pins the mm.

If init is the vfork parent, __oom_kill_process() sets MMF_OOM_SKIP on init's mm and skips the reaper, so the kill makes no progress.

Should the kfunc also reject in_vfork(p) while holding task_lock(p), as oom_badness() does? bpf_oom_kill_process() is unchanged at the end of the series, so this is not fixed by a later patch.

mm/oom_kill.c SYSCALL_DEFINE2(process_mrelease, int, pidfd, unsigned int, flags) · line 1320

Quoted 4 lines
mm/oom_kill.c +4 -0
+	oc->chosen = NULL;
+
+	return 0;
+}

[ ... ]

---
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

#3 lore raw

Re: [PATCH bpf-next v4 02/17] mm, bpf: introduce BPF OOM struct ops

In reply to Ben Gardon
TL;DR: BPF OOM handlers run under oom_lock but may still call sleepable mm-accessing copy_from_user kfuncs, which look able to deadlock (on mmap_lock or oom_lock); a kfunc filter or non-sleepable…
Quoted 1 line

mm, bpf: introduce BPF OOM struct ops

TL;DR: BPF OOM handlers run under oom_lock but may still call sleepable mm-accessing copy_from_user kfuncs, which look able to deadlock (on mmap_lock or oom_lock); a kfunc filter or non-sleepable handlers may be needed.

Quoted 4 lines
mm/bpf_oom.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 10 lines
mm/bpf_oom.c new file +10 -0
+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();

[ ... ]

mm/bpf_oom.c line 110

Quoted 12 lines
mm/bpf_oom.c new file +12 -0
+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);
+	}
+}

The helpers that can fault in or lock another task's mm are hidden here, and the handler runs under pagefault_disable() with oom_lock held. Can the kfunc versions of the same operations still be reached?

common_btf_ids is registered for BPF_PROG_TYPE_UNSPEC in kfunc_init(), so every struct_ops program can call bpf_copy_from_user_task_str(), bpf_copy_from_user_mm(), bpf_copy_from_user_mm_str(), bpf_copy_from_user_task_dynptr() and bpf_copy_from_user_task_str_dynptr(). All are KF_SLEEPABLE | KF_PERFMON.

Sleepable handlers are accepted because bpf_oom_ops_check_member() exists (check_struct_ops_btf_id() rejects prog->sleepable only when st_ops->check_member is NULL). Later patches in the series need sleepable handlers in practice, since bpf_oom_kill_process() is KF_SLEEPABLE. A trusted task argument can come from bpf_task_from_pid().

These kfuncs go through __copy_remote_mm_str()/__access_remote_vm(), which call mmap_read_lock_killable(mm) and then get_user_page_vma_remote(), which faults pages in via handle_mm_fault(). pagefault_disable() does not stop this, since it only affects the arch exception path.

Two deadlocks look possible. First:

Task A holds mmap_write_lock(A->mm), e.g. in mmap(), and allocates:
__alloc_pages_may_oom()
mutex_trylock(&oom_lock) fails, sleeps, did_some_progress = 1, retries

The BPF handler holds oom_lock and calls bpf_copy_from_user_task_str() on A:
mmap_read_lock_killable(A->mm) <- blocks

Neither side can make progress. The in-kernel OOM code avoids this by never blocking on mmap_lock (the oom reaper uses mmap_read_trylock()).

Second, the handler reads a swapped-out page of a task in a memcg at its limit. GUP faults the page in and charges it to that memcg:

try_charge_memcg()
mem_cgroup_oom()
mem_cgroup_out_of_memory()
mutex_lock_killable(&oom_lock)

which blocks on the mutex the same task already holds.

No later patch in the series changes mm/bpf_oom.c or filters these kfuncs. Should the handler use a kfunc filter that rejects mm-accessing or KF_SLEEPABLE kfuncs other than the OOM-specific ones, or should handlers be non-sleepable apart from an explicit allowlist?

---
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

#9 lore raw

Re: [PATCH bpf-next v4 04/17] mm, bpf: introduce bpf_out_of_memory() BPF kfunc

In reply to Ben Gardon
TL;DR: - bpf_out_of_memory() needs only CAP_BPF, so a SYSCALL program may SIGKILL the largest host process; KF_PERFMON gate? - May ignore cgroup v1 oom_kill_disable - Questions about the retained…
Quoted 1 line

mm, bpf: introduce bpf_out_of_memory() BPF kfunc

TL;DR:
- bpf_out_of_memory() needs only CAP_BPF, so a SYSCALL program may SIGKILL the largest host process; KF_PERFMON gate?
- May ignore cgroup v1 oom_kill_disable
- Questions about the retained WAIT_ON_OOM_LOCK flag

Quoted 3 lines
mm/oom_kill.c +0 -0

[ ... ]

Quoted 3 lines
mm/oom_kill.c +3 -0
+__bpf_kfunc int bpf_out_of_memory(struct mem_cgroup *memcg__nullable,
+				  int order, u64 flags)
+{

[ ... ]

mm/oom_kill.c __bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc, · line 1376

Quoted 9 lines
mm/oom_kill.c +9 -0
+	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;
+	}

Michal Hocko suggested in an earlier version that oom_lock be taken based on oc->memcg, so the behavior is transparent to BPF handlers, instead of adding the BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK flag:

"this OOM invocation is no different from the global one from the locking perspective. Adding an external flag to control the behavior might be slightly more flexible but it adds a new element. Unless there is a very strong reason for that I would go with the existing locking model."

The flag is still present here. Is there a reason to keep it rather than using the existing locking model?

Matt Bobrowski also commented on this path:

"If contended and we end up waiting here, some forward progress could have been made in the interim. Enough such that this pending OOM event initiated by the call into bpf_out_of_memory() may no longer even be warranted. What do you think about adding an escape hatch here, which could simply be in the form of a user-defined function callback?"

After mutex_lock_killable() returns, out_of_memory() is invoked unconditionally. Was this suggestion considered?

mm/oom_kill.c __bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc, · line 1381

Quoted 5 lines
mm/oom_kill.c +5 -0
+
+	if (oc.memcg)
+		memcg_memory_event(oc.memcg, MEMCG_OOM);
+
+	ret = out_of_memory(&oc);

For a memcg-scoped declaration this calls out_of_memory() directly and skips memcg1_oom_prepare(). The in-kernel memcg OOM path goes through mem_cgroup_oom() -> memcg1_oom_prepare() -> mem_cgroup_out_of_memory(), and that is where cgroup v1 handles memory.oom_control:

    if (READ_ONCE(memcg->oom_kill_disable)) {
        ...
        return false;   /* no in-kernel OOM kill */
    }
    mem_cgroup_mark_under_oom(memcg);
    *locked = mem_cgroup_oom_trylock(memcg);
    if (*locked)
        mem_cgroup_oom_notify(memcg);

Consider a v1 memcg with 1 written to memory.oom_control, with OOM handling left to userspace via the eventfd notification. A SYSCALL program can get that memcg with bpf_task_get_cgroup1() and bpf_get_mem_cgroup(&cgrp->self) and call bpf_out_of_memory(memcg, 0, 0). Would select_bad_process() -> mem_cgroup_scan_tasks() -> oom_kill_process() then SIGKILL a task in that memcg despite oom_kill_disable, without setting under_oom or calling mem_cgroup_oom_notify()?

The only other caller that skips memcg1_oom_prepare() is memory_max_write(), which exists only on cgroup v2, and the series handles v1 elsewhere (bpf_oom_cgroup() has a v1 fallback, bpf_mem_cgroup_raise_max() handles v1). Should bpf_out_of_memory() honor oom_kill_disable, or reject v1 memcgs? No later commit in the series appears to address this.

[ ... ]

mm/oom_kill.c static const struct btf_kfunc_id_set bpf_oom_kfunc_set = { · line 1416

Quoted 3 lines
mm/oom_kill.c +3 -0
+BTF_KFUNCS_START(bpf_declare_oom_kfuncs)
+BTF_ID_FLAGS(func, bpf_out_of_memory, KF_SLEEPABLE)
+BTF_KFUNCS_END(bpf_declare_oom_kfuncs)

Should bpf_out_of_memory() carry KF_PERFMON or a stronger gate?

It is registered for BPF_PROG_TYPE_SYSCALL with only KF_SLEEPABLE and its body has no capability check. Loading a SYSCALL program needs only CAP_BPF (or a BPF token delegating the type). In bpf_prog_load(), BPF_PROG_TYPE_SYSCALL is in neither is_perfmon_prog_type() nor is_net_admin_prog_type(), and bpf_prog_test_run() adds no further check. With that alone a task can call bpf_out_of_memory(NULL, 0, 0):

    bpf_prog_test_run_syscall() -> bpf_out_of_memory()
      -> mutex_trylock(&oom_lock) -> out_of_memory(&oc)
      -> select_bad_process()  /* for_each_process, highest badness */
      -> oom_kill_process() -> __oom_kill_process()
      -> do_send_sig_info(SIGKILL, SEND_SIG_PRIV, victim, PIDTYPE_TGID)

That sends SIGKILL to the largest killable process on the host regardless of owner. Repeated calls kill one process after another, the kill path ignores panic_on_oom, and no real memory pressure is needed.

Commit 3e03955a6518 ("bpf: Require CAP_PERFMON for kfuncs that leak pointers or touch tasks") says that "Syscall, tc, XDP and cgroup programs load without CAP_PERFMON and can call kfuncs that give more than CAP_BPF stands for: ... bpf_send_signal_task() and the kfuncs of task work act on any task", and marked bpf_send_signal_task() with KF_PERFMON. bpf_out_of_memory() acts on arbitrary tasks in the same way. The struct_ops path that kills through bpf_oom_kill_process() is stricter, since BPF_PROG_TYPE_STRUCT_OPS is a perfmon program type. The commit message explains the SYSCALL-only registration as deadlock avoidance and says nothing about privilege.

No later commit in the series adds a gate. bpf_oom_proactive_kill(), added in 3beb2d6e2e66 in the same set, has the same exposure.

---
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

#21 lore raw

Re: [PATCH bpf-next v4 12/17] mm, bpf: introduce bpf_oom_proactive_kill() for proactive OOM prevention

In reply to Ben Gardon
Quoted 2 lines · Ben Gardon

It cannot directly terminate a specific task chosen by a proactive userspace/BPF policy.

It can with patches 2-4:

proactive prog bpf_oom_ops handler
store pid in a map
bpf_out_of_memory(memcg)
oc->bpf_declared is set bpf_task_from_pid(pid) bpf_oom_kill_process(oc, task, msg) return 1
Drop this patch ?

#33 lore raw
In reply to Ben Gardon
Quoted 1 line · Ben Gardon

- Patch 11: A systemd-oomd style BPF OOM policy example and selftest.

In v3 we agreed on a production ready policy that users can enable without clang and kernel sources. Roman agreed in for v4:
https://lore.kernel.org/bpf/[email protected]/
but this v4 still doesn't have it.

On bpf infra side we added support for struct-ops in lskel.
So there are no blockers to have builtin bpf_oom policy in vmlinux binary that just works out of the box.
The user should be able to load a different one, of course. Ideally signed bpf.

pw-bot: cr

#4 lore raw

Re: [PATCH bpf-next v4 02/17] mm, bpf: introduce BPF OOM struct ops

In reply to Ben Gardon
kernel test robot noticed the following build warnings:

Hi Ben,

kernel test robot noticed the following build warnings:

[auto build test WARNING on bpf-next/master]
[also build test WARNING on bpf/master linus/master v7.4-rc5 next-20261202] [cannot apply to akpm-mm/mm-everything bpf-next/net]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Ben-Gardon/bpf-mark-struct-oom_control-s-memcg-field-as-TRUSTED_OR_NULL/20261202-130351
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20261202210415.517651-3-bgardon%40google.com
patch subject: [PATCH bpf-next v4 02/17] mm, bpf: introduce BPF OOM struct ops
config: nios2-allmodconfig (https://download.01.org/0day-ci/archive/20261203/[email protected]/config)
compiler: nios2-linux-gcc (GCC) 11.5.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261203/[email protected]/reproduce)

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

All warnings (new ones prefixed by >>):

In file included from include/linux/bpf-cgroup.h:5,

                    from mm/bpf_oom.c:8:
   mm/bpf_oom.c: In function 'bpf_oom_struct_ops_init':
>> include/linux/bpf.h:2505:50: warning: statement with no effect [-Wunused-value]
    2505 | #define register_bpf_struct_ops(st_ops, type) ({ (void *)(st_ops); 0; })
         |                                                  ^~~~~~~~~~~~~~~~
   mm/bpf_oom.c:185:16: note: in expansion of macro 'register_bpf_struct_ops'
     185 |         return register_bpf_struct_ops(&bpf_oom_bpf_ops, bpf_oom_ops);
         |                ^~~~~~~~~~~~~~~~~~~~~~~

vim +2505 include/linux/bpf.h

c196906d50e360d Hou Tao          2021-10-25  2495  
c196906d50e360d Hou Tao          2021-10-25  2496  int bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr,
c196906d50e360d Hou Tao          2021-10-25  2497  			    union bpf_attr __user *uattr);
c196906d50e360d Hou Tao          2021-10-25  2498  #endif
f6be98d19985411 Kui-Feng Lee     2024-01-19  2499  int bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,
f6be98d19985411 Kui-Feng Lee     2024-01-19  2500  			     struct btf *btf,
f6be98d19985411 Kui-Feng Lee     2024-01-19  2501  			     struct bpf_verifier_log *log);
1338b93346587a2 Kui-Feng Lee     2024-01-19  2502  void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map);
1611603537a4b88 Kui-Feng Lee     2024-02-08  2503  void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc);
27ae7997a66174c Martin KaFai Lau 2020-01-08  2504  #else
f6be98d19985411 Kui-Feng Lee     2024-01-19 @2505  #define register_bpf_struct_ops(st_ops, type) ({ (void *)(st_ops); 0; })
85d33df357b6346 Martin KaFai Lau 2020-01-08  2506  static inline bool bpf_try_module_get(const void *data, struct module *owner)
85d33df357b6346 Martin KaFai Lau 2020-01-08  2507  {
85d33df357b6346 Martin KaFai Lau 2020-01-08  2508  	return try_module_get(owner);
85d33df357b6346 Martin KaFai Lau 2020-01-08  2509  }
85d33df357b6346 Martin KaFai Lau 2020-01-08  2510  static inline void bpf_module_put(const void *data, struct module *owner)
85d33df357b6346 Martin KaFai Lau 2020-01-08  2511  {
85d33df357b6346 Martin KaFai Lau 2020-01-08  2512  	module_put(owner);
85d33df357b6346 Martin KaFai Lau 2020-01-08  2513  }
e42ac14180554fa Martin KaFai Lau 2024-07-22  2514  static inline int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff)
e42ac14180554fa Martin KaFai Lau 2024-07-22  2515  {
e42ac14180554fa Martin KaFai Lau 2024-07-22  2516  	return -ENOTSUPP;
e42ac14180554fa Martin KaFai Lau 2024-07-22  2517  }
85d33df357b6346 Martin KaFai Lau 2020-01-08  2518  static inline int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map,
85d33df357b6346 Martin KaFai Lau 2020-01-08  2519  						     void *key,
85d33df357b6346 Martin KaFai Lau 2020-01-08  2520  						     void *value)
85d33df357b6346 Martin KaFai Lau 2020-01-08  2521  {
85d33df357b6346 Martin KaFai Lau 2020-01-08  2522  	return -EINVAL;
85d33df357b6346 Martin KaFai Lau 2020-01-08  2523  }

466ae6570ce8140 Siddharth Nayyar 2026-12-01 2524

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki