From: Roman Gushchin Struct oom_control is used to describe the OOM context. Its memcg field defines the scope of OOM: it's NULL for global OOMs and a valid memcg pointer for memcg-scoped OOMs. Teach bpf verifier to recognize it as trusted or NULL pointer. It will provide the bpf OOM handler a trusted memcg pointer, which for example is required for iterating the memcg's subtree. Signed-off-by: Roman Gushchin Acked-by: Kumar Kartikeya Dwivedi Acked-by: Yafang Shao Acked-by: Matt Bobrowski Signed-off-by: Ben Gardon --- v3 -> v4: - Fix commit message typo ("It's" -> "Its"). v3: https://lore.kernel.org/all/20260127024421.494929-6-roman.gushchin@linux.dev/ kernel/bpf/verifier.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 8021afe783b6..6e7c5a7b2018 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -6978,6 +6978,10 @@ BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { struct file *vm_file; }; +BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct oom_control) { + struct mem_cgroup *memcg; +}; + static bool type_is_rcu(struct bpf_verifier_env *env, struct bpf_reg_state *reg, const char *field_name, u32 btf_id) @@ -7025,6 +7029,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env, BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm)); BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); + BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct oom_control)); return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted_or_null"); -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Introduce cgroup BPF struct_ops (bpf_oom_ops, attach type CGROUP_OOM_OPS) for implementing custom OOM policies. Policies can be attached to a cgroup via bpf_map__attach_cgroup_opts(). Root cgroup attachments cover system-wide OOMs as well as fallback from descendant cgroups. By default, effective handlers run from the OOMing memory cgroup upward toward the root unless an ancestor attaches with BPF_F_PREORDER. The handle_out_of_memory callback receives the oom_control describing the OOM scope and the cgroup where the policy is attached. Returning a positive value signals that the OOM condition has been handled. This could be by terminating a task, expanding a memcg limit, or backing off while a previously selected task exits. Returning <= 0 delegates to the next handler in the effective chain and ultimately to the in-kernel OOM handler. SysRq-triggered OOMs bypass BPF handlers so SysRq-f remains a failsafe. Existing heuristics and sysctls such as panic_on_oom and sysctl_oom_kill_allocating_task continue to run prior to bpf_handle_oom(). Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Adopted mainline cgroup struct_ops attachment (CGROUP_OOM_OPS) and changed handle_out_of_memory() to receive (struct oom_control *, struct cgroup *). - Dropped oc->bpf_memory_freed dual-reporting check so handlers can return > 0 to back off while an existing selected task exits; treat only positive returns (> 0) as handled so negative errnos delegate. - Bypassed bpf_handle_oom() on SysRq-triggered OOMs (is_sysrq_oom(oc)). - Added .validate callback requiring handle_out_of_memory, validated ops->name via bpf_obj_name_cpy(), switched bpf_oom_func_proto() to curated bpf_base_func_proto() (blocking user-copy/stack helpers), walked up offline cgroups to the nearest online ancestor, and encapsulated sleepable RCU Tasks Trace locking in bpf-cgroup.h. v3: https://lore.kernel.org/all/20260127024421.494929-8-roman.gushchin@linux.dev/ MAINTAINERS | 2 + include/linux/bpf-cgroup-defs.h | 1 + include/linux/bpf-cgroup.h | 16 ++- include/linux/bpf.h | 1 + include/linux/bpf_oom.h | 44 ++++++++ include/linux/oom.h | 17 +++ kernel/bpf/cgroup.c | 1 + mm/Makefile | 3 + mm/bpf_oom.c | 187 ++++++++++++++++++++++++++++++++ mm/oom_kill.c | 10 ++ 10 files changed, 280 insertions(+), 2 deletions(-) create mode 100644 include/linux/bpf_oom.h create mode 100644 mm/bpf_oom.c diff --git a/MAINTAINERS b/MAINTAINERS index b430b29e3878..d4ef52c5594b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5177,7 +5177,9 @@ M: Shakeel Butt L: bpf@vger.kernel.org L: linux-mm@kvack.org S: Maintained +F: include/linux/bpf_oom.h F: mm/bpf_memcontrol.c +F: mm/bpf_oom.c BPF [MISC] L: bpf@vger.kernel.org diff --git a/include/linux/bpf-cgroup-defs.h b/include/linux/bpf-cgroup-defs.h index 671f27ba6a62..ff650a422e36 100644 --- a/include/linux/bpf-cgroup-defs.h +++ b/include/linux/bpf-cgroup-defs.h @@ -48,6 +48,7 @@ enum cgroup_bpf_attach_type { CGROUP_UNIX_GETSOCKNAME, CGROUP_INET_SOCK_RELEASE, CGROUP_TCP_SOCK_OPS, + CGROUP_OOM_OPS, CGROUP_LSM_START, CGROUP_LSM_END = CGROUP_LSM_START + CGROUP_LSM_NUM - 1, MAX_CGROUP_BPF_ATTACH_TYPE diff --git a/include/linux/bpf-cgroup.h b/include/linux/bpf-cgroup.h index 0b63c2cc1399..13a74791be46 100644 --- a/include/linux/bpf-cgroup.h +++ b/include/linux/bpf-cgroup.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -112,14 +113,25 @@ struct bpf_prog_list { u32 flags; }; +static inline void bpf_cgroup_struct_ops_lock_sleepable(void) +{ + rcu_read_lock_trace(); +} + +static inline void bpf_cgroup_struct_ops_unlock_sleepable(void) +{ + rcu_read_unlock_trace(); +} + #define bpf_cgroup_struct_ops_foreach(var, item, cgrp, atype) \ - for (item = rcu_dereference((cgrp)->bpf.effective[atype])->items;\ + for (item = rcu_dereference_check((cgrp)->bpf.effective[atype], \ + rcu_read_lock_trace_held())->items;\ ((var) = READ_ONCE(item->kdata)); \ item++) static inline bool cgroup_bpf_is_struct_ops_atype(enum cgroup_bpf_attach_type atype) { - return atype == CGROUP_TCP_SOCK_OPS; + return atype == CGROUP_TCP_SOCK_OPS || atype == CGROUP_OOM_OPS; } void cgroup_bpf_struct_ops_register(int atype, u32 type_id, void *cfi_stubs, bool mult_trace); int cgroup_bpf_struct_ops_attach(struct bpf_map *map, const union bpf_attr *attr); diff --git a/include/linux/bpf.h b/include/linux/bpf.h index 96e249bd00fb..82f99b92c481 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -2761,6 +2761,7 @@ struct bpf_prog_array_item { }; union { struct bpf_cgroup_storage *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE]; + struct cgroup *cgroup; u64 bpf_cookie; }; }; diff --git a/include/linux/bpf_oom.h b/include/linux/bpf_oom.h new file mode 100644 index 000000000000..23e3131a12be --- /dev/null +++ b/include/linux/bpf_oom.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#ifndef __BPF_OOM_H +#define __BPF_OOM_H + +struct cgroup; +struct oom_control; + +#define BPF_OOM_NAME_MAX_LEN 64 + +/** + * struct bpf_oom_ops - BPF operations for customizing OOM handling + */ +struct bpf_oom_ops { + /** + * @handle_out_of_memory: Out of memory BPF handler, invoked before the + * in-kernel OOM selector. + * + * Receives @oc describing the OOM scope/constraint and @cgrp where this + * policy instance is attached. Return a positive value (> 0) if the + * OOM event was handled (either by freeing/expanding memory or + * backing off for an already-exiting task), or <= 0 to defer to the + * next handler in the hierarchy and ultimately the in-kernel OOM + * handler. + */ + int (*handle_out_of_memory)(struct oom_control *oc, + struct cgroup *cgrp); + + /** + * @name: BPF OOM policy name logged in OOM reports. + */ + char name[BPF_OOM_NAME_MAX_LEN]; +}; + +#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG) +bool bpf_handle_oom(struct oom_control *oc); +#else +static inline bool bpf_handle_oom(struct oom_control *oc) +{ + return false; +} +#endif + +#endif /* __BPF_OOM_H */ diff --git a/include/linux/oom.h b/include/linux/oom.h index 00da05d227e6..ca3192c42533 100644 --- a/include/linux/oom.h +++ b/include/linux/oom.h @@ -51,8 +51,25 @@ struct oom_control { /* Used to print the constraint info. */ enum oom_constraint constraint; + +#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG) + /* Active BPF OOM handler name */ + const char *bpf_handler_name; +#endif }; +#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG) +static inline const char *oom_handler_name(const struct oom_control *oc) +{ + return oc->bpf_handler_name; +} +#else +static inline const char *oom_handler_name(const struct oom_control *oc) +{ + return NULL; +} +#endif + extern struct mutex oom_lock; extern struct mutex oom_adj_mutex; diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index e4e680dfb63d..dba22e99197d 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -572,6 +572,7 @@ static void prog_list_init_item(struct bpf_prog_list *pl, struct bpf_prog_array_ { if (prog_list_is_struct_ops(pl)) { item->kdata = bpf_struct_ops_map_kdata(pl->link->map); + item->cgroup = pl->link->cgroup; return; } diff --git a/mm/Makefile b/mm/Makefile index 2a3ec53d62ee..66b53e569eed 100644 --- a/mm/Makefile +++ b/mm/Makefile @@ -107,6 +107,9 @@ obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o ifdef CONFIG_BPF_SYSCALL obj-$(CONFIG_MEMCG) += bpf_memcontrol.o endif +ifdef CONFIG_CGROUP_BPF +obj-$(CONFIG_MEMCG) += bpf_oom.o +endif obj-$(CONFIG_CGROUP_HUGETLB) += hugetlb_cgroup.o obj-$(CONFIG_GUP_TEST) += gup_test.o obj-$(CONFIG_DMAPOOL_TEST) += dmapool_test.o diff --git a/mm/bpf_oom.c b/mm/bpf_oom.c new file mode 100644 index 000000000000..bc0838d55335 --- /dev/null +++ b/mm/bpf_oom.c @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * BPF-driven OOM killer customization + * + * Author: Roman Gushchin + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static int bpf_ops_handle_oom(struct bpf_oom_ops *bpf_oom_ops, + struct cgroup *cgrp, + struct oom_control *oc) +{ + int ret; + + oc->bpf_handler_name = &bpf_oom_ops->name[0]; + pagefault_disable(); + ret = bpf_oom_ops->handle_out_of_memory(oc, cgrp); + pagefault_enable(); + oc->bpf_handler_name = NULL; + + return ret; +} + +static struct cgroup *bpf_oom_cgroup(struct mem_cgroup *memcg) +{ + if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !mem_cgroup_disabled()) { + struct cgroup *cgrp; + + memcg = memcg ?: root_mem_cgroup; + cgrp = READ_ONCE(memcg->css.cgroup); + if (cgrp->root == &cgrp_dfl_root) + return cgrp; + } + + /* + * Fall back to the cgroup v2 root when memory cgroups are disabled or + * mounted on cgroup v1 (cgroup BPF only attaches to the v2 hierarchy). + */ + return &cgrp_dfl_root.cgrp; +} + +/** + * bpf_handle_oom() - Invoke attached cgroup BPF OOM policies + * @oc: OOM control structure describing the OOM event + * + * Return: true if a BPF policy handled the OOM, false to fall back to the + * in-kernel OOM handler. + */ +bool bpf_handle_oom(struct oom_control *oc) +{ + const struct bpf_prog_array_item *item; + struct bpf_oom_ops *bpf_oom_ops; + struct cgroup *cgrp; + int ret = 0; + + lockdep_assert_held(&oom_lock); + + if (!cgroup_bpf_enabled(CGROUP_OOM_OPS)) + return false; + + cgrp = bpf_oom_cgroup(oc->memcg); + + bpf_cgroup_struct_ops_lock_sleepable(); + while (cgrp && !(READ_ONCE(cgrp->self.flags) & CSS_ONLINE)) + cgrp = cgroup_parent(cgrp); + if (!cgrp) + goto out_unlock; + + bpf_cgroup_struct_ops_foreach(bpf_oom_ops, item, cgrp, CGROUP_OOM_OPS) { + ret = bpf_ops_handle_oom(bpf_oom_ops, item->cgroup, oc); + if (ret > 0) + break; + } + +out_unlock: + bpf_cgroup_struct_ops_unlock_sleepable(); + + return ret > 0; +} + +static int __handle_out_of_memory(struct oom_control *oc, + struct cgroup *cgrp) +{ + return 0; +} + +static struct bpf_oom_ops __bpf_oom_ops = { + .handle_out_of_memory = __handle_out_of_memory, +}; + +static const struct bpf_func_proto * +bpf_oom_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) +{ + switch (func_id) { + case BPF_FUNC_copy_from_user: + case BPF_FUNC_copy_from_user_task: + case BPF_FUNC_get_task_stack: + return NULL; + default: + return bpf_base_func_proto(func_id, prog); + } +} + +static bool bpf_oom_ops_is_valid_access(int off, int size, + enum bpf_access_type type, + const struct bpf_prog *prog, + struct bpf_insn_access_aux *info) +{ + return bpf_tracing_btf_ctx_access(off, size, type, prog, info); +} + +static const struct bpf_verifier_ops bpf_oom_verifier_ops = { + .get_func_proto = bpf_oom_func_proto, + .is_valid_access = bpf_oom_ops_is_valid_access, +}; + +static int bpf_oom_ops_check_member(const struct btf_type *t, + const struct btf_member *member, + const struct bpf_prog *prog) +{ + return 0; +} + +static int bpf_oom_ops_init_member(const struct btf_type *t, + const struct btf_member *member, + void *kdata, const void *udata) +{ + const struct bpf_oom_ops *uops = udata; + struct bpf_oom_ops *ops = kdata; + u32 moff = __btf_member_bit_offset(t, member) / 8; + + switch (moff) { + case offsetof(struct bpf_oom_ops, name): + if (uops->name[0]) { + if (bpf_obj_name_cpy(ops->name, uops->name, + sizeof(ops->name)) <= 0) + return -EINVAL; + } else { + strscpy_pad(ops->name, "bpf_defined_policy", + sizeof(ops->name)); + } + return 1; + } + return 0; +} + +static int bpf_oom_ops_validate(void *kdata) +{ + struct bpf_oom_ops *ops = kdata; + + if (!ops->handle_out_of_memory) + return -EINVAL; + + return 0; +} + +static int bpf_oom_ops_init(struct btf *btf) +{ + return 0; +} + +static struct bpf_struct_ops bpf_oom_bpf_ops = { + .verifier_ops = &bpf_oom_verifier_ops, + .check_member = bpf_oom_ops_check_member, + .init_member = bpf_oom_ops_init_member, + .validate = bpf_oom_ops_validate, + .init = bpf_oom_ops_init, + .name = "bpf_oom_ops", + .cgroup_atype = CGROUP_OOM_OPS, + .owner = THIS_MODULE, + .cfi_stubs = &__bpf_oom_ops, + .free_after_mult_rcu_gp = true, +}; + +static int __init bpf_oom_struct_ops_init(void) +{ + return register_bpf_struct_ops(&bpf_oom_bpf_ops, bpf_oom_ops); +} +late_initcall(bpf_oom_struct_ops_init); diff --git a/mm/oom_kill.c b/mm/oom_kill.c index 5d48bd862c27..fa9088c965b6 100644 --- a/mm/oom_kill.c +++ b/mm/oom_kill.c @@ -45,6 +45,7 @@ #include #include #include +#include #include #include "internal.h" @@ -451,6 +452,8 @@ static void dump_header(struct oom_control *oc) pr_warn("%s invoked oom-killer: gfp_mask=%#x(%pGg), order=%d, oom_score_adj=%d\n", current->comm, oc->gfp_mask, &oc->gfp_mask, oc->order, current->signal->oom_score_adj); + if (oom_handler_name(oc)) + pr_warn("oom bpf handler: %s\n", oom_handler_name(oc)); if (!IS_ENABLED(CONFIG_COMPACTION) && oc->order) pr_warn("COMPACTION is disabled!!!\n"); @@ -1145,6 +1148,13 @@ bool out_of_memory(struct oom_control *oc) return true; } + /* + * Let BPF handle the OOM first unless triggered via SysRq, which + * skips to the kernel OOM handler. + */ + if (!is_sysrq_oom(oc) && bpf_handle_oom(oc)) + return true; + select_bad_process(oc); /* Found nothing?!?! */ if (!oc->chosen) { -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Introduce bpf_oom_kill_process() for bpf_oom_ops programs to terminate a chosen process through oom_kill_process(), preserving the existing path used by the kernel OOM implementation. Init/kernel threads (unkillable), tasks protected with OOM_SCORE_ADJ_MIN, tasks with no live mm or MMF_OOM_SKIP set, and tasks outside oc->memcg's hierarchy during a memcg-scoped OOM are rejected in the kernel. Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Guard BPF OOM kfunc block with CONFIG_CGROUP_BPF && CONFIG_MEMCG so !CONFIG_MEMCG builds do not fail resolve_btfids. - Use find_lock_task_mm() and reject tasks with no live mm or MMF_OOM_SKIP set (-ESRCH) in addition to oom_unkillable_task() and OOM_SCORE_ADJ_MIN checks. - Add mem_cgroup_task_in_hierarchy() and reject tasks outside oc->memcg with -EINVAL during memcg-scoped OOMs. - Fix bpf_oom_kfunc_filter() to check btf_id_set8_contains() and use default-deny so BPF_PROG_TYPE_EXT (freplace) on non-OOM struct_ops cannot bypass the filter. v3: https://lore.kernel.org/all/20260127024421.494929-9-roman.gushchin@linux.dev/ include/linux/memcontrol.h | 20 ++++++++ mm/oom_kill.c | 102 +++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h index 69e1bcc67c58..bc30d7baecd7 100644 --- a/include/linux/memcontrol.h +++ b/include/linux/memcontrol.h @@ -892,6 +892,20 @@ static inline bool mem_cgroup_is_descendant(const struct mem_cgroup *memcg, return cgroup_is_descendant(memcg->css.cgroup, root->css.cgroup); } +static inline bool mem_cgroup_task_in_hierarchy(struct task_struct *task, + const struct mem_cgroup *origin) +{ + struct mem_cgroup *memcg; + bool ret = false; + + rcu_read_lock(); + memcg = mem_cgroup_from_task(task); + if (memcg) + ret = mem_cgroup_is_descendant(memcg, origin); + rcu_read_unlock(); + return ret; +} + static inline bool mm_match_cgroup(struct mm_struct *mm, const struct mem_cgroup *memcg) { @@ -1513,6 +1527,12 @@ static inline u64 cgroup_id_from_mm(struct mm_struct *mm) static inline void mem_cgroup_flush_workqueue(void) { } +static inline bool mem_cgroup_task_in_hierarchy(struct task_struct *task, + const struct mem_cgroup *origin) +{ + return true; +} + static inline int mem_cgroup_init(void) { return 0; } #endif /* CONFIG_MEMCG */ diff --git a/mm/oom_kill.c b/mm/oom_kill.c index fa9088c965b6..85da2a39e18a 100644 --- a/mm/oom_kill.c +++ b/mm/oom_kill.c @@ -1258,3 +1258,105 @@ SYSCALL_DEFINE2(process_mrelease, int, pidfd, unsigned int, flags) return -ENOSYS; #endif /* CONFIG_MMU */ } + +#if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG) + +__bpf_kfunc_start_defs(); +/** + * bpf_oom_kill_process() - Terminate a process via the kernel OOM handler + * @oc: pointer to oom_control structure describing the OOM context + * @task: task to be terminated + * @message__str: reason string logged in the OOM report + * + * Terminate @task using the kernel OOM machinery: emit the OOM report, + * update memcg OOM events, trigger asynchronous OOM memory reclamation, + * and honor memory.oom.group recursive behavior. + * + * Kernel-enforced safety constraints: + * - Tasks exempt via oom_unkillable_task() (init and kernel threads) are + * rejected with -EPERM. + * - Tasks with oom_score_adj == OOM_SCORE_ADJ_MIN (-1000), or tasks + * outside @oc->memcg's subtree during a memcg-scoped OOM, are rejected + * with -EINVAL. + * - Tasks with no live mm or with MMF_OOM_SKIP set return -ESRCH. + * + * Return: 0 on success, or a negative errno on failure. + */ +__bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc, + struct task_struct *task, + const char *message__str) +{ + struct task_struct *p; + + if (oom_unkillable_task(task)) + return -EPERM; + + if (oc->memcg && !mem_cgroup_task_in_hierarchy(task, oc->memcg)) + return -EINVAL; + + p = find_lock_task_mm(task); + if (!p) + return -ESRCH; + + if (p->signal->oom_score_adj == OOM_SCORE_ADJ_MIN) { + task_unlock(p); + return -EINVAL; + } + + if (mm_flags_test(MMF_OOM_SKIP, p->mm)) { + task_unlock(p); + return -ESRCH; + } + + /* paired with put_task_struct() in oom_kill_process() */ + get_task_struct(p); + task_unlock(p); + + oc->chosen = p; + oom_kill_process(oc, message__str); + oc->chosen = NULL; + + return 0; +} + +__bpf_kfunc_end_defs(); + +BTF_KFUNCS_START(bpf_oom_kfuncs) +BTF_ID_FLAGS(func, bpf_oom_kill_process, KF_SLEEPABLE) +BTF_KFUNCS_END(bpf_oom_kfuncs) + +BTF_ID_LIST_SINGLE(bpf_oom_ops_ids, struct, bpf_oom_ops) + +static int bpf_oom_kfunc_filter(const struct bpf_prog *prog, u32 kfunc_id) +{ + if (!btf_id_set8_contains(&bpf_oom_kfuncs, kfunc_id)) + return 0; + + if (prog->type == BPF_PROG_TYPE_STRUCT_OPS && + bpf_oom_ops_ids[0] && + prog->aux->attach_btf_id == bpf_oom_ops_ids[0]) + return 0; + + return -EACCES; +} + +static const struct btf_kfunc_id_set bpf_oom_kfunc_set = { + .owner = THIS_MODULE, + .set = &bpf_oom_kfuncs, + .filter = bpf_oom_kfunc_filter, +}; + +static int __init bpf_oom_init(void) +{ + int err; + + err = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, + &bpf_oom_kfunc_set); + if (err) + pr_warn("error while registering bpf oom kfuncs: %d\n", err); + + return err; +} +late_initcall(bpf_oom_init); + +#endif /* CONFIG_CGROUP_BPF && CONFIG_MEMCG */ -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Introduce bpf_out_of_memory() to allow BPF programs to declare an OOM proactively. BPF-declared OOMs are marked via oc->bpf_declared so they do not panic the kernel when no killable tasks remain or panic_on_oom is set. They do not terminate the calling task via sysctl_oom_kill_allocating_task either. Registered directly on BPF_PROG_TYPE_SYSCALL (extended to PSI tracepoints later in the series) so bpf_oom_ops and arbitrary tracing/LSM hooks cannot deadlock on oom_lock. Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Registered directly on BPF_PROG_TYPE_SYSCALL instead of BPF_PROG_TYPE_UNSPEC. - Moved BPF_OOM_FLAGS_ALL outside BTF-exported enum bpf_oom_flags. - Added oc->bpf_declared guard against panic() and sysctl_oom_kill_allocating_task, clamped oc->totalpages in constrained_alloc(), normalized root_mem_cgroup to NULL, rejected dying memcgs, and accounted MEMCG_OOM. v3: https://lore.kernel.org/all/20260127024421.494929-10-roman.gushchin@linux.dev/ include/linux/oom.h | 19 +++++++++ mm/oom_kill.c | 101 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 111 insertions(+), 9 deletions(-) diff --git a/include/linux/oom.h b/include/linux/oom.h index ca3192c42533..168b64dfb6ad 100644 --- a/include/linux/oom.h +++ b/include/linux/oom.h @@ -14,6 +14,12 @@ struct notifier_block; struct mem_cgroup; struct task_struct; +enum bpf_oom_flags { + BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK = BIT(0), +}; + +#define BPF_OOM_FLAGS_ALL BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK + enum oom_constraint { CONSTRAINT_NONE, CONSTRAINT_CPUSET, @@ -55,6 +61,9 @@ struct oom_control { #if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_MEMCG) /* Active BPF OOM handler name */ const char *bpf_handler_name; + + /* Declared via BPF outside an allocation failure */ + bool bpf_declared; #endif }; @@ -63,11 +72,21 @@ static inline const char *oom_handler_name(const struct oom_control *oc) { return oc->bpf_handler_name; } + +static inline bool is_bpf_declared_oom(const struct oom_control *oc) +{ + return oc->bpf_declared; +} #else static inline const char *oom_handler_name(const struct oom_control *oc) { return NULL; } + +static inline bool is_bpf_declared_oom(const struct oom_control *oc) +{ + return false; +} #endif extern struct mutex oom_lock; diff --git a/mm/oom_kill.c b/mm/oom_kill.c index 85da2a39e18a..9b5df00f98ab 100644 --- a/mm/oom_kill.c +++ b/mm/oom_kill.c @@ -256,7 +256,9 @@ static enum oom_constraint constrained_alloc(struct oom_control *oc) int nid; if (is_memcg_oom(oc)) { - oc->totalpages = mem_cgroup_get_max(oc->memcg) ?: 1; + unsigned long max = mem_cgroup_get_max(oc->memcg); + + oc->totalpages = min(max, totalram_pages() + total_swap_pages) ?: 1; return CONSTRAINT_MEMCG; } @@ -1024,7 +1026,8 @@ static void oom_kill_process(struct oom_control *oc, const char *message) task_unlock(victim); if (__ratelimit(&oom_rs)) { - dump_header(oc); + if (!is_bpf_declared_oom(oc)) + dump_header(oc); dump_oom_victim(oc, victim); } @@ -1065,8 +1068,8 @@ static void check_panic_on_oom(struct oom_control *oc) if (oc->constraint != CONSTRAINT_NONE) return; } - /* Do not panic for oom kills triggered by sysrq */ - if (is_sysrq_oom(oc)) + /* Do not panic for oom kills triggered by sysrq or BPF */ + if (is_sysrq_oom(oc) || is_bpf_declared_oom(oc)) return; dump_header(oc); panic("Out of memory: %s panic_on_oom is enabled\n", @@ -1138,7 +1141,8 @@ bool out_of_memory(struct oom_control *oc) oc->nodemask = NULL; check_panic_on_oom(oc); - if (!is_memcg_oom(oc) && sysctl_oom_kill_allocating_task && + if (!is_memcg_oom(oc) && !is_bpf_declared_oom(oc) && + sysctl_oom_kill_allocating_task && current->mm && !oom_unkillable_task(current) && oom_cpuset_eligible(current, oc) && current->signal->oom_score_adj != OOM_SCORE_ADJ_MIN) { @@ -1165,7 +1169,8 @@ bool out_of_memory(struct oom_control *oc) * system level, we cannot survive this and will enter * an endless loop in the allocator. Bail out now. */ - if (!is_sysrq_oom(oc) && !is_memcg_oom(oc)) + if (!is_sysrq_oom(oc) && !is_memcg_oom(oc) && + !is_bpf_declared_oom(oc)) panic("System is deadlocked on memory\n"); } if (oc->chosen && oc->chosen != (void *)-1UL) @@ -1319,6 +1324,66 @@ __bpf_kfunc int bpf_oom_kill_process(struct oom_control *oc, return 0; } +/** + * bpf_out_of_memory() - Declare an OOM condition and invoke OOM handling + * @memcg__nullable: target memory cgroup, or NULL for system-wide OOM + * @order: allocation page order (0..MAX_PAGE_ORDER), passed through to + * bpf_oom_ops handlers as a memory-reclaim size hint + * @flags: bitmask of &enum bpf_oom_flags + * + * Synchronizes on oom_lock: waits (interruptible by fatal signals) when + * BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK is set, or returns -EBUSY immediately if + * oom_lock is contended. Root @memcg__nullable is normalized to NULL + * (system-wide OOM); dying memory cgroups are rejected with -EINVAL. + * + * Return: 1 if forward progress was made, 0 if no process was terminated, or a + * negative errno on failure. + */ +__bpf_kfunc int bpf_out_of_memory(struct mem_cgroup *memcg__nullable, + int order, u64 flags) +{ + struct oom_control oc = { + .gfp_mask = GFP_KERNEL, + .order = order, + .bpf_declared = true, + }; + int ret; + + if (flags & ~BPF_OOM_FLAGS_ALL) + return -EINVAL; + + /* + * Keep order so callers can signal a higher-order memory need to + * reactive bpf_oom_ops handlers (or exercise high-order OOM policies). + */ + if (oc.order < 0 || oc.order > MAX_PAGE_ORDER) + return -EINVAL; + + if (memcg__nullable && mem_cgroup_is_root(memcg__nullable)) + memcg__nullable = NULL; + + if (memcg__nullable && memcg_is_dying(memcg__nullable)) + return -EINVAL; + + oc.memcg = memcg__nullable; + + if (flags & BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK) { + ret = mutex_lock_killable(&oom_lock); + if (ret) + return ret; + } else if (!mutex_trylock(&oom_lock)) { + return -EBUSY; + } + + if (oc.memcg) + memcg_memory_event(oc.memcg, MEMCG_OOM); + + ret = out_of_memory(&oc); + + mutex_unlock(&oom_lock); + return ret; +} + __bpf_kfunc_end_defs(); BTF_KFUNCS_START(bpf_oom_kfuncs) @@ -1346,16 +1411,34 @@ static const struct btf_kfunc_id_set bpf_oom_kfunc_set = { .filter = bpf_oom_kfunc_filter, }; +BTF_KFUNCS_START(bpf_declare_oom_kfuncs) +BTF_ID_FLAGS(func, bpf_out_of_memory, KF_SLEEPABLE) +BTF_KFUNCS_END(bpf_declare_oom_kfuncs) + +static const struct btf_kfunc_id_set bpf_declare_oom_syscall_kfunc_set = { + .owner = THIS_MODULE, + .set = &bpf_declare_oom_kfuncs, +}; + static int __init bpf_oom_init(void) { int err; err = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &bpf_oom_kfunc_set); - if (err) - pr_warn("error while registering bpf oom kfuncs: %d\n", err); + if (err) { + pr_warn("error while registering struct_ops bpf oom kfuncs: %d\n", err); + return err; + } + + err = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, + &bpf_declare_oom_syscall_kfunc_set); + if (err) { + pr_warn("error while registering syscall bpf oom kfuncs: %d\n", err); + return err; + } - return err; + return 0; } late_initcall(bpf_oom_init); -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Implement a kselftest for the OOM handling functionality. This BPF OOM policy terminates all tasks belonging to the largest leaf cgroup (excluding page cache) that contains no exempt tasks (oom_score_adj set to -1000). The test: 1. builds a hierarchy of memory cgroups 2. pre-allocates baseline memory, below memory.max 3. triggers an OOM from the largest eligible leaf 4. verifies that the expected process is selected and terminated with SIGKILL 5. checks the chosen memcg's memory.events oom_kill counter to validate Attaching the same policy to both the subtree root (where it returns 0) and the root cgroup verifies hierarchical delegation. Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Adopted bpf_map__attach_cgroup_opts() and CO-RE task->signal->oom_mm. - Replaced cgroup freezing with pipes to synchronize with workers so multi-CPU runs cannot flake. - Renamed to serial_test_oom() to avoid root-cgroup collisions under test_progs -j. - Scanned the full subtree for in-flight oom_mm, passed acquired task reference to bpf_oom_kill_process(), and checked its return value. v3: https://lore.kernel.org/all/20260127024421.494929-13-roman.gushchin@linux.dev/ .../selftests/bpf/prog_tests/memory_holder.h | 158 +++++++++++++ .../selftests/bpf/prog_tests/test_oom.c | 218 ++++++++++++++++++ tools/testing/selftests/bpf/progs/test_oom.c | 132 +++++++++++ 3 files changed, 508 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/memory_holder.h create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom.c diff --git a/tools/testing/selftests/bpf/prog_tests/memory_holder.h b/tools/testing/selftests/bpf/prog_tests/memory_holder.h new file mode 100644 index 000000000000..34b408da3958 --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/memory_holder.h @@ -0,0 +1,158 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __MEMORY_HOLDER_H +#define __MEMORY_HOLDER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +struct memory_holder { + pid_t pid; + int start_fd; + int done_fd; +}; + +static inline void memory_holder_init(struct memory_holder *w) +{ + w->pid = -1; + w->start_fd = -1; + w->done_fd = -1; +} + +static inline void memory_holder_cleanup(struct memory_holder *w) +{ + if (w->start_fd >= 0) { + close(w->start_fd); + w->start_fd = -1; + } + if (w->done_fd >= 0) { + close(w->done_fd); + w->done_fd = -1; + } + if (w->pid > 0) { + kill(w->pid, SIGKILL); + waitpid(w->pid, NULL, 0); + w->pid = -1; + } +} + +/* + * Fork a child that sets /proc/self/oom_score_adj, waits for a byte on + * start_fd (after the parent places it into a cgroup), faults in @target + * bytes of anonymous memory (in @chunk-byte chunks if @chunk > 0), writes a + * byte to done_fd, and either exits (if @exit_after_alloc is true) or sleeps + * until killed. + */ +static inline int memory_holder_spawn(struct memory_holder *w, size_t target, + size_t chunk, int oom_score_adj, + bool exit_after_alloc) +{ + int start_pipe[2] = { -1, -1 }; + int done_pipe[2] = { -1, -1 }; + int ret = 0; + pid_t pid; + char c; + + memory_holder_init(w); + + if (pipe(start_pipe) < 0) + return -errno; + if (pipe(done_pipe) < 0) { + ret = -errno; + goto err_pipes; + } + + pid = fork(); + if (pid < 0) { + ret = -errno; + goto err_pipes; + } + + if (pid > 0) { + w->pid = pid; + w->start_fd = start_pipe[1]; + w->done_fd = done_pipe[0]; + close(start_pipe[0]); + close(done_pipe[1]); + return 0; + } + + close(start_pipe[1]); + close(done_pipe[0]); + + { + char buf[8]; + int fd = open("/proc/self/oom_score_adj", O_WRONLY); + + if (fd < 0) + _exit(1); + snprintf(buf, sizeof(buf), "%d", oom_score_adj); + if (write(fd, buf, strlen(buf)) < 0) + _exit(1); + close(fd); + } + + /* Wait for parent to place us in the target cgroup and release us */ + if (read(start_pipe[0], &c, 1) != 1) + _exit(1); + close(start_pipe[0]); + + if (target) { + size_t step = chunk ?: target; + size_t done = 0; + + while (done < target) { + size_t sz = target - done < step ? target - done : step; + char *ptr = malloc(sz); + + if (!ptr) + _exit(ENOMEM); + memset(ptr, 'a', sz); + /* Prevent -O2 dead-store elimination before _exit() */ + asm volatile("" : : "r"(ptr) : "memory"); + done += sz; + } + } + + if (write(done_pipe[1], "d", 1) != 1) + _exit(1); + close(done_pipe[1]); + + if (exit_after_alloc) + _exit(0); + + for (;;) + sleep(1000); + +err_pipes: + if (start_pipe[0] >= 0) + close(start_pipe[0]); + if (start_pipe[1] >= 0) + close(start_pipe[1]); + if (done_pipe[0] >= 0) + close(done_pipe[0]); + if (done_pipe[1] >= 0) + close(done_pipe[1]); + return ret; +} + +static inline int memory_holder_start(struct memory_holder *w) +{ + return write(w->start_fd, "g", 1) == 1 ? 0 : -EIO; +} + +static inline int memory_holder_wait_ready(struct memory_holder *w) +{ + char c; + + return read(w->done_fd, &c, 1) == 1 ? 0 : -EIO; +} + +#endif /* __MEMORY_HOLDER_H */ diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom.c b/tools/testing/selftests/bpf/prog_tests/test_oom.c new file mode 100644 index 000000000000..f17742ace1ce --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/test_oom.c @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include + +#include "cgroup_helpers.h" +#include "memory_holder.h" + +#define MB (1024UL * 1024UL) +#include "test_oom.skel.h" + +#define OOM_SCORE_ADJ_MIN (-1000) +#define OOM_SCORE_ADJ_MAX 1000 + +struct cgroup_desc { + const char *path; + int fd; + struct memory_holder worker; + size_t target; + size_t max; + int oom_score_adj; + bool expect_terminated; +}; + +/* + * Baseline workers (cg1 10 MB + cg2 35 MB + cg5 10 MB = 55 MB) allocate first + * and wait under the 80 MB limit. Then cg4 (35 MB) allocates and crosses 80 MB + * at ~25 MB, triggering a single deterministic OOM where cg2 (35 MB) is exempt + * via OOM_SCORE_ADJ_MIN and cg4 (~25 MB) is the largest eligible leaf. + */ +static struct cgroup_desc cgroups[] = { + { .path = "/oom_test", .max = 80 * MB }, + { .path = "/oom_test/cg1", .target = 10 * MB, + .oom_score_adj = OOM_SCORE_ADJ_MAX }, + { .path = "/oom_test/cg2", .target = 35 * MB, + .oom_score_adj = OOM_SCORE_ADJ_MIN }, + { .path = "/oom_test/cg3" }, + { .path = "/oom_test/cg3/cg4", .target = 35 * MB, + .expect_terminated = true }, + { .path = "/oom_test/cg3/cg5", .target = 10 * MB }, +}; + +static void reset_cgroups(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + cgroups[i].fd = -1; + memory_holder_init(&cgroups[i].worker); + } +} + +static void cleanup_workers(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + memory_holder_cleanup(&cgroups[i].worker); + if (cgroups[i].fd >= 0) { + close(cgroups[i].fd); + cgroups[i].fd = -1; + } + } +} + +static int setup_environment(void) +{ + int i, err; + + reset_cgroups(); + + err = setup_cgroup_environment(); + if (!ASSERT_OK(err, "setup_cgroup_environment")) + return -1; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + char buf[64]; + + cgroups[i].fd = create_and_get_cgroup(cgroups[i].path); + if (!ASSERT_GE(cgroups[i].fd, 0, "create_and_get_cgroup")) + return -1; + + if (cgroups[i].target == 0) { + err = write_cgroup_file(cgroups[i].path, + "cgroup.subtree_control", + "+memory"); + if (!ASSERT_OK(err, "enable memory controller")) + return -1; + } + + if (cgroups[i].max) { + snprintf(buf, sizeof(buf), "%zu", cgroups[i].max); + err = write_cgroup_file(cgroups[i].path, "memory.max", + buf); + if (!ASSERT_OK(err, "set memory.max")) + return -1; + write_cgroup_file(cgroups[i].path, "memory.swap.max", + "0"); + } + + if (cgroups[i].target) { + err = memory_holder_spawn(&cgroups[i].worker, + cgroups[i].target, 0, + cgroups[i].oom_score_adj, + cgroups[i].expect_terminated); + if (!ASSERT_OK(err, "spawn worker")) + return -1; + + snprintf(buf, sizeof(buf), "%d", cgroups[i].worker.pid); + err = write_cgroup_file(cgroups[i].path, "cgroup.procs", + buf); + if (!ASSERT_OK(err, "put child into cgroup")) + return -1; + } + } + + /* Pre-allocate all non-trigger baseline workers under memory.max */ + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (!cgroups[i].target || cgroups[i].expect_terminated) + continue; + + if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker), + "start baseline worker")) + return -1; + if (!ASSERT_OK(memory_holder_wait_ready(&cgroups[i].worker), + "wait baseline worker")) + return -1; + } + + return 0; +} + +/* + * Serialized because this test attaches a BPF OOM policy to the root cgroup + * and triggers real memcg OOMs, which would collide with other OOM tests + * running in parallel under test_progs -j. + */ +void serial_test_oom(void) +{ + LIBBPF_OPTS(bpf_cgroup_opts, opts); + struct bpf_link *cgroup_link = NULL, *root_link = NULL; + struct test_oom *skel = NULL; + int root_cg_fd = -1, status = 0, i; + char buf[4096] = {}; + + if (setup_environment()) + goto cleanup; + + skel = test_oom__open_and_load(); + if (!ASSERT_OK_PTR(skel, "open_and_load")) + goto cleanup; + + /* + * Attach to both /oom_test (which returns 0) and root (which handles + * the OOM) to exercise hierarchical delegation. + */ + cgroup_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom, + cgroups[0].fd, &opts); + if (!ASSERT_OK_PTR(cgroup_link, "attach_oom_cgroup")) + goto cleanup; + + root_cg_fd = get_root_cgroup(); + if (!ASSERT_GE(root_cg_fd, 0, "get_root_cgroup")) + goto cleanup; + + root_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom, + root_cg_fd, &opts); + if (!ASSERT_OK_PTR(root_link, "attach_oom_root")) + goto cleanup; + + /* Release the trigger worker (cg4) to cross memory.max */ + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (!cgroups[i].expect_terminated) + continue; + + if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker), + "start trigger worker")) + goto cleanup; + + if (!ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status, 0), + cgroups[i].worker.pid, "waitpid trigger")) + goto cleanup; + cgroups[i].worker.pid = -1; + + if (!ASSERT_TRUE(WIFSIGNALED(status) && + WTERMSIG(status) == SIGKILL, + "expected process was terminated")) + goto cleanup; + + if (!ASSERT_OK(read_cgroup_file(cgroups[i].path, + "memory.events", + buf, sizeof(buf)), + "read memory.events")) + goto cleanup; + + if (!ASSERT_OK_PTR(strstr(buf, "oom_kill 1"), + "oom_kill count check")) + goto cleanup; + } + + /* Verify all other baseline workers survived */ + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (cgroups[i].worker.pid > 0) + ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status, + WNOHANG), 0, + "non-target worker survived"); + } + +cleanup: + bpf_link__destroy(root_link); + bpf_link__destroy(cgroup_link); + if (root_cg_fd >= 0) + close(root_cg_fd); + cleanup_workers(); + cleanup_cgroup_environment(); + test_oom__destroy(skel); +} diff --git a/tools/testing/selftests/bpf/progs/test_oom.c b/tools/testing/selftests/bpf/progs/test_oom.c new file mode 100644 index 000000000000..a752d332f8b7 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom.c @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Example BPF OOM policy for selftests (not intended for production use). + * + * Exercises bpf_oom_ops attachment, hierarchical delegation (returning 0 on + * the subtree root and handling on root), and bpf_oom_kill_process() by + * terminating all tasks in the largest eligible leaf cgroup (similar to + * memory.oom.group semantics). + */ +#include "vmlinux.h" +#include +#include +#include + +char _license[] SEC("license") = "GPL"; + +#define OOM_SCORE_ADJ_MIN (-1000) + +static bool mem_cgroup_has_oom_victim(struct mem_cgroup *memcg) +{ + struct task_struct *task; + + bpf_for_each(css_task, task, &memcg->css, CSS_TASK_ITER_PROCS) + if (BPF_CORE_READ(task, signal, oom_mm)) + return true; + + return false; +} + +static bool mem_cgroup_killable(struct mem_cgroup *memcg) +{ + struct task_struct *task; + + bpf_for_each(css_task, task, &memcg->css, CSS_TASK_ITER_PROCS) + if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN) + return false; + + return true; +} + +/* + * Find the largest leaf cgroup (ignoring page cache) without exempt tasks + * and terminate all belonging tasks. + */ +SEC("struct_ops.s/handle_out_of_memory") +int BPF_PROG(test_out_of_memory, struct oom_control *oc, struct cgroup *cgrp) +{ + struct task_struct *task; + struct mem_cgroup *root_memcg = oc->memcg; + struct mem_cgroup *memcg, *chosen = NULL; + struct cgroup_subsys_state *css_pos, *css; + unsigned long usage, max_usage = 0; + unsigned long pagecache = 0; + int ret = 0; + + if (root_memcg) + root_memcg = bpf_get_mem_cgroup(&root_memcg->css); + else + root_memcg = bpf_get_root_mem_cgroup(); + + if (!root_memcg) + return 0; + + css = &root_memcg->css; + if (css && css->cgroup == cgrp) + goto exit; + + bpf_rcu_read_lock(); + bpf_for_each(css, css_pos, &root_memcg->css, BPF_CGROUP_ITER_DESCENDANTS_POST) { + if (css_pos->cgroup->nr_descendants + css_pos->cgroup->nr_dying_descendants) + continue; + + memcg = bpf_get_mem_cgroup(css_pos); + if (!memcg) + continue; + + /* + * If any task in the subtree is already exiting due to OOM, + * back off and let it release memory. + */ + if (mem_cgroup_has_oom_victim(memcg)) { + bpf_put_mem_cgroup(memcg); + ret = 1; + break; + } + + usage = bpf_mem_cgroup_usage(memcg); + pagecache = bpf_mem_cgroup_page_state(memcg, NR_FILE_PAGES); + + if (usage > pagecache) + usage -= pagecache; + else + usage = 0; + + if (usage > max_usage && mem_cgroup_killable(memcg)) { + max_usage = usage; + if (chosen) + bpf_put_mem_cgroup(chosen); + chosen = bpf_get_mem_cgroup(&memcg->css); + } + + bpf_put_mem_cgroup(memcg); + } + bpf_rcu_read_unlock(); + + if (ret || !chosen) + goto put_chosen; + + bpf_for_each(css_task, task, &chosen->css, CSS_TASK_ITER_PROCS) { + struct task_struct *t = bpf_task_acquire(task); + + if (t) { + if (!bpf_oom_kill_process(oc, t, "bpf oom test")) + ret = 1; + bpf_task_release(t); + } + } + +put_chosen: + if (chosen) + bpf_put_mem_cgroup(chosen); +exit: + bpf_put_mem_cgroup(root_memcg); + + return ret; +} + +SEC(".struct_ops.link") +struct bpf_oom_ops test_bpf_oom = { + .name = "bpf_test_policy", + .handle_out_of_memory = (void *)test_out_of_memory, +}; -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Add a bare tracepoint to psi_avgs_work() to allow BPF programs to monitor memory pressure. Add include/trace/events/psi.h to the PSI entry in MAINTAINERS. Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Switched from TRACE_EVENT() to bare DECLARE_TRACE() (psi_avgs_work_tp) so no pointer-only tracefs event ABI is exported. - Added include/trace/events/psi.h to the PSI entry in MAINTAINERS. v3: https://lore.kernel.org/all/20260127024421.494929-14-roman.gushchin@linux.dev/ MAINTAINERS | 1 + include/trace/events/psi.h | 19 +++++++++++++++++++ kernel/sched/psi.c | 6 ++++++ 3 files changed, 26 insertions(+) create mode 100644 include/trace/events/psi.h diff --git a/MAINTAINERS b/MAINTAINERS index d4ef52c5594b..8bb61211b7f0 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -22397,6 +22397,7 @@ M: Suren Baghdasaryan R: Peter Zijlstra S: Maintained F: include/linux/psi* +F: include/trace/events/psi.h F: kernel/sched/psi.c PROPELLER BUILD diff --git a/include/trace/events/psi.h b/include/trace/events/psi.h new file mode 100644 index 000000000000..838dc95c3401 --- /dev/null +++ b/include/trace/events/psi.h @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#undef TRACE_SYSTEM +#define TRACE_SYSTEM psi + +#if !defined(_TRACE_PSI_H) || defined(TRACE_HEADER_MULTI_READ) +#define _TRACE_PSI_H + +#include + +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 diff --git a/kernel/sched/psi.c b/kernel/sched/psi.c index 7c5381423334..d89c40902492 100644 --- a/kernel/sched/psi.c +++ b/kernel/sched/psi.c @@ -141,6 +141,10 @@ #include #include "sched.h" +#define CREATE_TRACE_POINTS +#include +#undef CREATE_TRACE_POINTS + static int psi_bug __read_mostly; DEFINE_STATIC_KEY_FALSE(psi_disabled); @@ -607,6 +611,8 @@ static void psi_avgs_work(struct work_struct *work) group->avg_next_update - now) + 1); } + trace_psi_avgs_work_tp(group); + mutex_unlock(&group->avgs_lock); } -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Allow a BPF program attached to a PSI tracepoint to identify the associated memory cgroup, store cgroup_id inside struct psi_group. Note that the root cgroup aliases psi_system and keeps cgroup_id == 0. Signed-off-by: Roman Gushchin Signed-off-by: Ben Gardon --- v3 -> v4: - Guard cgroup_id with #ifdef CONFIG_CGROUPS and note root/psi_system aliasing (cgroup_id == 0). v3: https://lore.kernel.org/all/20260127024421.494929-15-roman.gushchin@linux.dev/ include/linux/psi_types.h | 6 ++++++ kernel/sched/psi.c | 1 + 2 files changed, 7 insertions(+) diff --git a/include/linux/psi_types.h b/include/linux/psi_types.h index dd10c22299ab..597f6fabf688 100644 --- a/include/linux/psi_types.h +++ b/include/linux/psi_types.h @@ -159,6 +159,12 @@ struct psi_trigger { struct psi_group { struct psi_group *parent; + +#ifdef CONFIG_CGROUPS + /* Cgroup id for non-root cgroups; 0 for root (aliases psi_system) */ + u64 cgroup_id; +#endif + bool enabled; /* Protects data used by the aggregator */ diff --git a/kernel/sched/psi.c b/kernel/sched/psi.c index d89c40902492..571266028a50 100644 --- a/kernel/sched/psi.c +++ b/kernel/sched/psi.c @@ -1119,6 +1119,7 @@ int psi_cgroup_alloc(struct cgroup *cgroup) if (!cgroup->psi) return -ENOMEM; + cgroup->psi->cgroup_id = cgroup_id(cgroup); cgroup->psi->pcpu = alloc_percpu(struct psi_group_cpu); if (!cgroup->psi->pcpu) { kfree(cgroup->psi); -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Register bpf_declare_oom_kfuncs on BPF_PROG_TYPE_TRACING with a filter restricted to the btf_trace_psi_avgs_work_tp tracepoint. psi_avgs_work() runs in workqueue context outside oom_lock, and because bpf_out_of_memory() is KF_SLEEPABLE, tracepoint programs invoke it asynchronously via a sleepable callback (such as bpf_task_work or bpf_wq), avoiding any deadlock on oom_lock or avgs_lock. Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Registered directly on BPF_PROG_TYPE_TRACING with a tracing-only filter checking BPF_TRACE_RAW_TP and !prog->aux->dst_prog. - Guarded with CONFIG_PSI && CONFIG_BPF_EVENTS and updated to btf_trace_psi_avgs_work_tp. v3: https://lore.kernel.org/all/20260127024421.494929-16-roman.gushchin@linux.dev/ mm/oom_kill.c | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/mm/oom_kill.c b/mm/oom_kill.c index 9b5df00f98ab..21b88332a46a 100644 --- a/mm/oom_kill.c +++ b/mm/oom_kill.c @@ -1420,6 +1420,32 @@ static const struct btf_kfunc_id_set bpf_declare_oom_syscall_kfunc_set = { .set = &bpf_declare_oom_kfuncs, }; +#if defined(CONFIG_PSI) && defined(CONFIG_BPF_EVENTS) +BTF_ID_LIST_SINGLE(bpf_oom_trace_ids, typedef, btf_trace_psi_avgs_work_tp) + +static int bpf_declare_oom_tracing_filter(const struct bpf_prog *prog, + u32 kfunc_id) +{ + if (!btf_id_set8_contains(&bpf_declare_oom_kfuncs, kfunc_id)) + return 0; + + if (prog->type == BPF_PROG_TYPE_TRACING && + prog->expected_attach_type == BPF_TRACE_RAW_TP && + !prog->aux->dst_prog && + bpf_oom_trace_ids[0] && + prog->aux->attach_btf_id == bpf_oom_trace_ids[0]) + return 0; + + return -EACCES; +} + +static const struct btf_kfunc_id_set bpf_declare_oom_tracing_kfunc_set = { + .owner = THIS_MODULE, + .set = &bpf_declare_oom_kfuncs, + .filter = bpf_declare_oom_tracing_filter, +}; +#endif /* CONFIG_PSI && CONFIG_BPF_EVENTS */ + static int __init bpf_oom_init(void) { int err; @@ -1438,6 +1464,15 @@ static int __init bpf_oom_init(void) return err; } +#if defined(CONFIG_PSI) && defined(CONFIG_BPF_EVENTS) + err = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, + &bpf_declare_oom_tracing_kfunc_set); + if (err) { + pr_warn("error while registering tracing bpf oom kfuncs: %d\n", err); + return err; + } +#endif + return 0; } late_initcall(bpf_oom_init); -- 2.56.1.911.g883d8bcb20-goog From: JP Kobryn Include CONFIG_PSI to allow dependent tests to build. Suggested-by: Song Liu Signed-off-by: JP Kobryn Signed-off-by: Roman Gushchin Signed-off-by: Ben Gardon --- v3 -> v4: - Standardized subject prefix. v3: https://lore.kernel.org/all/20260127024421.494929-17-roman.gushchin@linux.dev/ tools/testing/selftests/bpf/config | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config index ce0db4be4d26..36651bf5533c 100644 --- a/tools/testing/selftests/bpf/config +++ b/tools/testing/selftests/bpf/config @@ -121,6 +121,7 @@ CONFIG_IP6_NF_IPTABLES=y CONFIG_IP6_NF_FILTER=y CONFIG_NF_NAT=y CONFIG_PACKET=y +CONFIG_PSI=y CONFIG_RC_CORE=y CONFIG_SAMPLES=y CONFIG_SAMPLE_LIVEPATCH=m -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Add a BPF selftest attaching to the psi_avgs_work_tp tracepoint to monitor memory pressure in a cgroup throttled by memory.high. When full memory stall growth exceeds 50 ms within an update interval, the tracepoint schedules a sleepable bpf_task_work callback that invokes bpf_out_of_memory() for the pressured cgroup, verifying that the allocating task is terminated with SIGKILL and memory.events records oom_kill 1. Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Updated subject/body from stale "PSI struct ops test" to reflect the psi_avgs_work_tp tracepoint design. - Indexed the BTF-flattened group->total array explicitly as total[PSI_AVGS * (NR_PSI_STATES - 1) + PSI_MEM_FULL], added missing SPDX header, removed redundant extern __ksym declarations, and dropped the first-interval skip. - Replaced cgroup freezing and racy fork/migration with a sync pipe, removed dead struct_ops remnants and FD/child leaks, added runtime PSI skip check, verified SIGKILL, and renamed to serial_test_psi(). v3: https://lore.kernel.org/all/20260127024421.494929-18-roman.gushchin@linux.dev/ .../selftests/bpf/prog_tests/test_psi.c | 107 ++++++++++++++++++ tools/testing/selftests/bpf/progs/test_psi.c | 88 ++++++++++++++ 2 files changed, 195 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/test_psi.c create mode 100644 tools/testing/selftests/bpf/progs/test_psi.c diff --git a/tools/testing/selftests/bpf/prog_tests/test_psi.c b/tools/testing/selftests/bpf/prog_tests/test_psi.c new file mode 100644 index 000000000000..9f3fdf2d6c5b --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/test_psi.c @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include + +#include "cgroup_helpers.h" +#include "memory_holder.h" + +#define MB (1024UL * 1024UL) +#include "test_psi.skel.h" + +/* + * Serialized because this test attaches to the global psi_avgs_work_tp + * tracepoint and drives real memory pressure / OOM under memory.high, which + * can interfere with other OOM tests running concurrently under test_progs -j. + */ +void serial_test_psi(void) +{ + const char *parent_cg = "/psi_test"; + const char *target_cg = "/psi_test/cg"; + struct test_psi *skel = NULL; + struct memory_holder worker; + int parent_fd = -1, target_fd = -1; + int status = 0, err; + unsigned long long cg_id; + char buf[4096] = {}; + + memory_holder_init(&worker); + + if (access("/proc/pressure/memory", R_OK) != 0) { + test__skip(); + return; + } + + err = setup_cgroup_environment(); + if (!ASSERT_OK(err, "setup_cgroup_environment")) + return; + + parent_fd = create_and_get_cgroup(parent_cg); + if (!ASSERT_GE(parent_fd, 0, "create parent cgroup")) + goto cleanup; + + err = write_cgroup_file(parent_cg, "cgroup.subtree_control", "+memory"); + if (!ASSERT_OK(err, "enable memory controller")) + goto cleanup; + + target_fd = create_and_get_cgroup(target_cg); + if (!ASSERT_GE(target_fd, 0, "create target cgroup")) + goto cleanup; + + cg_id = get_cgroup_id(target_cg); + if (!ASSERT_GT(cg_id, 0, "get_cgroup_id")) + goto cleanup; + + snprintf(buf, sizeof(buf), "%lu", 40 * MB); + err = write_cgroup_file(target_cg, "memory.high", buf); + if (!ASSERT_OK(err, "set memory.high")) + goto cleanup; + write_cgroup_file(target_cg, "memory.swap.max", "0"); + + err = memory_holder_spawn(&worker, 500 * MB, MB, 0, true); + if (!ASSERT_OK(err, "spawn worker")) + goto cleanup; + + snprintf(buf, sizeof(buf), "%d", worker.pid); + err = write_cgroup_file(target_cg, "cgroup.procs", buf); + if (!ASSERT_OK(err, "put child into cgroup")) + goto cleanup; + + skel = test_psi__open_and_load(); + if (!ASSERT_OK_PTR(skel, "open_and_load")) + goto cleanup; + + skel->bss->high_pressure_cgroup_id = cg_id; + skel->bss->my_pid = getpid(); + + err = test_psi__attach(skel); + if (!ASSERT_OK(err, "attach")) + goto cleanup; + + /* Release worker now that it is inside target_cg and PSI BPF is attached */ + if (!ASSERT_OK(memory_holder_start(&worker), "release worker")) + goto cleanup; + + if (!ASSERT_EQ(waitpid(worker.pid, &status, 0), worker.pid, + "waitpid worker")) + goto cleanup; + worker.pid = -1; + + ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL, + "worker terminated by SIGKILL"); + + if (ASSERT_OK(read_cgroup_file(target_cg, "memory.events", + buf, sizeof(buf)), + "read memory.events")) + ASSERT_OK_PTR(strstr(buf, "oom_kill 1"), "oom_kill count check"); + +cleanup: + memory_holder_cleanup(&worker); + if (target_fd >= 0) + close(target_fd); + if (parent_fd >= 0) + close(parent_fd); + test_psi__destroy(skel); + cleanup_cgroup_environment(); +} diff --git a/tools/testing/selftests/bpf/progs/test_psi.c b/tools/testing/selftests/bpf/progs/test_psi.c new file mode 100644 index 000000000000..927c1b8323d0 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_psi.c @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "vmlinux.h" +#include "bpf_experimental.h" +#include +#include +#include + +char _license[] SEC("license") = "GPL"; + +/* cgroup which will experience the high memory pressure */ +u64 high_pressure_cgroup_id; +u32 my_pid = 0; + +/* last total full memory pressure value */ +u64 last_mem_full_total = 0; + +struct elem { + struct bpf_task_work tw; +}; + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, int); + __type(value, struct elem); +} tw_map SEC(".maps"); + +static int psi_oom_work(struct bpf_map *map, void *key, void *value) +{ + struct cgroup *cgrp; + struct mem_cgroup *memcg; + + cgrp = bpf_cgroup_from_id(high_pressure_cgroup_id); + if (!cgrp) + return 0; + + memcg = bpf_get_mem_cgroup(&cgrp->self); + if (memcg) { + bpf_out_of_memory(memcg, 0, BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK); + bpf_put_mem_cgroup(memcg); + } + + bpf_cgroup_release(cgrp); + return 0; +} + +static void schedule_oom_work(void) +{ + struct task_struct *task; + struct elem *val; + int key = 0; + + task = bpf_task_from_pid(my_pid); + if (task) { + val = bpf_map_lookup_elem(&tw_map, &key); + if (val) + bpf_task_work_schedule_signal(task, &val->tw, + &tw_map, psi_oom_work); + bpf_task_release(task); + } +} + +SEC("tp_btf/psi_avgs_work_tp") +int BPF_PROG(psi_avgs, struct psi_group *group) +{ + u64 current_total; + u64 growth; + + /* Monitor only a single target cgroup */ + if (group->cgroup_id != high_pressure_cgroup_id) + return 0; + + /* + * Check for memory pressure. BTF flattens the 2D array + * total[NR_PSI_AGGREGATORS][NR_PSI_STATES - 1] in vmlinux.h. + */ + current_total = BPF_CORE_READ(group, + total[PSI_AVGS * (NR_PSI_STATES - 1) + + PSI_MEM_FULL]); + growth = current_total - last_mem_full_total; + last_mem_full_total = current_total; + + /* Declare an OOM if growth > 50ms within the update period */ + if (growth > 50000000) + schedule_oom_work(); + + return 0; +} -- 2.56.1.911.g883d8bcb20-goog From: Roman Gushchin Add a BPF OOM policy example that mirrors the core candidate selection rules used by systemd-oomd. The policy treats leaf cgroups and memory.oom.group cgroups as candidates. User-space ManagedOOMPreference-style inputs, are supplied through a cgroup-id keyed map. The policy excludes "omit" candidates, demotes "avoid" candidates, and ranks the rest by memory.stat pgscan delta with memory.current as the tie breaker. The selftest: 1. builds a small systemd-like hierarchy with various types of memory holders: a. omitted b. avoided c. normal d. oom_score_adj=-1000 2. attaches the policy through cgroup struct_ops 3. forces a memcg OOM 4. verifies that the selected cgroup, selected task, skipped-candidate accounting, and BPF OOM status match expectations. Signed-off-by: Roman Gushchin Signed-off-by: Ben Gardon --- .../selftests/bpf/prog_tests/test_oomd.c | 274 ++++++++++++++ tools/testing/selftests/bpf/progs/test_oomd.c | 346 ++++++++++++++++++ tools/testing/selftests/bpf/progs/test_oomd.h | 33 ++ 3 files changed, 653 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oomd.c create mode 100644 tools/testing/selftests/bpf/progs/test_oomd.c create mode 100644 tools/testing/selftests/bpf/progs/test_oomd.h diff --git a/tools/testing/selftests/bpf/prog_tests/test_oomd.c b/tools/testing/selftests/bpf/prog_tests/test_oomd.c new file mode 100644 index 000000000000..001b2262a2ae --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/test_oomd.c @@ -0,0 +1,274 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include + +#include "cgroup_helpers.h" +#include "memory_holder.h" + +#define MB (1024UL * 1024UL) +#include "progs/test_oomd.h" +#include "test_oomd.skel.h" + +struct oomd_cgroup_desc { + const char *path; + int fd; + unsigned long long id; + struct memory_holder worker; + size_t target; + size_t max; + int oom_score_adj; + enum oomd_preference preference; + bool expect_terminated; +}; + +/* + * Baseline workers total 110 MB (critical 30 + batch-a 35 + batch-c 15 + + * exempt 30), under the 135 MB memory.max. Once they are idle, batch-b + * allocates 35 MB and crosses 135 MB at ~25 MB, triggering a single + * deterministic OOM where critical (OMIT), batch-a (AVOID), and exempt + * (OOM_SCORE_ADJ_MIN) are all larger than batch-b, and batch-b (~25 MB) is + * larger than batch-c (15 MB). + */ +static struct oomd_cgroup_desc cgroups[] = { + { .path = "/oomd_test", .max = 135 * MB }, + { .path = "/oomd_test/system.slice" }, + { .path = "/oomd_test/system.slice/critical.service", + .target = 30 * MB, .preference = OOMD_PREFERENCE_OMIT }, + { .path = "/oomd_test/workload.slice" }, + { .path = "/oomd_test/workload.slice/batch-a.service", + .target = 35 * MB, .preference = OOMD_PREFERENCE_AVOID }, + { .path = "/oomd_test/workload.slice/batch-b.service", + .target = 35 * MB, .expect_terminated = true }, + { .path = "/oomd_test/workload.slice/batch-c.service", + .target = 15 * MB }, + { .path = "/oomd_test/workload.slice/exempt.service", + .target = 30 * MB, .oom_score_adj = OOM_SCORE_ADJ_MIN }, +}; + +static void reset_cgroups(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + cgroups[i].fd = -1; + cgroups[i].id = 0; + memory_holder_init(&cgroups[i].worker); + } +} + +static void cleanup_cgroups(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + memory_holder_cleanup(&cgroups[i].worker); + if (cgroups[i].fd >= 0) { + close(cgroups[i].fd); + cgroups[i].fd = -1; + } + } +} + +static int setup_environment(void) +{ + int i, err; + + reset_cgroups(); + + err = setup_cgroup_environment(); + if (!ASSERT_OK(err, "setup_cgroup_environment")) + return -1; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + char buf[64]; + + cgroups[i].fd = create_and_get_cgroup(cgroups[i].path); + if (!ASSERT_GE(cgroups[i].fd, 0, "create_and_get_cgroup")) + return -1; + + cgroups[i].id = get_cgroup_id(cgroups[i].path); + if (!ASSERT_GT(cgroups[i].id, 0, "get_cgroup_id")) + return -1; + + if (cgroups[i].target == 0) { + err = write_cgroup_file(cgroups[i].path, + "cgroup.subtree_control", + "+memory"); + if (!ASSERT_OK(err, "enable memory controller")) + return -1; + } + + if (cgroups[i].max) { + snprintf(buf, sizeof(buf), "%zu", cgroups[i].max); + err = write_cgroup_file(cgroups[i].path, "memory.max", + buf); + if (!ASSERT_OK(err, "set memory.max")) + return -1; + write_cgroup_file(cgroups[i].path, "memory.swap.max", + "0"); + } + + if (cgroups[i].target) { + err = memory_holder_spawn(&cgroups[i].worker, + cgroups[i].target, 0, + cgroups[i].oom_score_adj, + cgroups[i].expect_terminated); + if (!ASSERT_OK(err, "spawn task")) + return -1; + + snprintf(buf, sizeof(buf), "%d", cgroups[i].worker.pid); + err = write_cgroup_file(cgroups[i].path, "cgroup.procs", + buf); + if (!ASSERT_OK(err, "put child into cgroup")) + return -1; + } + } + + /* Pre-allocate all baseline workers under memory.max */ + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (!cgroups[i].target || cgroups[i].expect_terminated) + continue; + + if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker), + "start baseline task")) + return -1; + if (!ASSERT_OK(memory_holder_wait_ready(&cgroups[i].worker), + "wait baseline task")) + return -1; + } + + return 0; +} + +static int configure_policies(struct test_oomd *skel) +{ + int map_fd = bpf_map__fd(skel->maps.oomd_policies); + int i, err; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + struct oomd_policy policy = { + .preference = cgroups[i].preference, + }; + __u64 cgid = cgroups[i].id; + + err = bpf_map_update_elem(map_fd, &cgid, &policy, BPF_ANY); + if (!ASSERT_OK(err, "configure oomd policy")) + return -1; + } + + return 0; +} + +static int run_and_wait_for_oom(struct test_oomd *skel) +{ + int map_fd = bpf_map__fd(skel->maps.oomd_decisions); + struct oomd_decision decision = {}; + struct oomd_cgroup_desc *target = NULL; + __u32 key = 0; + pid_t target_pid; + int status = 0; + int i, err; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (cgroups[i].expect_terminated) { + target = &cgroups[i]; + break; + } + } + if (!ASSERT_OK_PTR(target, "find target cgroup")) + return -1; + + target_pid = target->worker.pid; + + /* Release the trigger worker to cross memory.max */ + if (!ASSERT_OK(memory_holder_start(&target->worker), + "start trigger task")) + return -1; + + if (!ASSERT_EQ(waitpid(target_pid, &status, 0), target_pid, + "waitpid trigger")) + return -1; + target->worker.pid = -1; + + if (!ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL, + "expected process was terminated")) + return -1; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (cgroups[i].worker.pid > 0) { + if (!ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status, + WNOHANG), + 0, "non-target task survived")) + return -1; + } + } + + err = bpf_map_lookup_elem(map_fd, &key, &decision); + if (!ASSERT_OK(err, "lookup oomd decision")) + return -1; + + if (!ASSERT_EQ(decision.victim_cgid, target->id, "selected cgroup")) + return -1; + if (!ASSERT_EQ(decision.killed_pid, target_pid, "selected task")) + return -1; + if (!ASSERT_GE(decision.scanned_candidates, 3, "scanned candidates")) + return -1; + if (!ASSERT_GE(decision.skipped_omit, 1, "skipped omitted cgroup")) + return -1; + if (!ASSERT_GE(decision.skipped_unkillable, 1, "skipped exempt cgroup")) + return -1; + if (!ASSERT_OK(decision.kill_ret, "bpf oom kill")) + return -1; + + return 0; +} + +/* + * Serialized because this test attaches a BPF OOM policy to the root cgroup + * and triggers real memcg OOMs, which would collide with other OOM tests + * running in parallel under test_progs -j. + */ +void serial_test_oomd(void) +{ + LIBBPF_OPTS(bpf_cgroup_opts, opts); + struct bpf_link *cgroup_link = NULL, *root_link = NULL; + struct test_oomd *skel = NULL; + int root_cg_fd = -1; + + if (setup_environment()) + goto cleanup; + + skel = test_oomd__open_and_load(); + if (!ASSERT_OK_PTR(skel, "open_and_load")) + goto cleanup; + + if (configure_policies(skel)) + goto cleanup; + + cgroup_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oomd, + cgroups[0].fd, &opts); + if (!ASSERT_OK_PTR(cgroup_link, "attach_oomd_cgroup")) + goto cleanup; + + root_cg_fd = get_root_cgroup(); + if (!ASSERT_GE(root_cg_fd, 0, "get_root_cgroup")) + goto cleanup; + + root_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oomd, + root_cg_fd, &opts); + if (!ASSERT_OK_PTR(root_link, "attach_oomd_root")) + goto cleanup; + + ASSERT_OK(run_and_wait_for_oom(skel), "run_and_wait_for_oom"); + +cleanup: + bpf_link__destroy(root_link); + bpf_link__destroy(cgroup_link); + if (root_cg_fd >= 0) + close(root_cg_fd); + cleanup_cgroups(); + cleanup_cgroup_environment(); + test_oomd__destroy(skel); +} diff --git a/tools/testing/selftests/bpf/progs/test_oomd.c b/tools/testing/selftests/bpf/progs/test_oomd.c new file mode 100644 index 000000000000..c307fa276c43 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oomd.c @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "vmlinux.h" +#include +#include +#include +#include "test_oomd.h" + +char _license[] SEC("license") = "GPL"; + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 128); + __type(key, __u64); + __type(value, struct oomd_policy); +} oomd_policies SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, struct oomd_decision); +} oomd_decisions SEC(".maps"); + +static __u64 cgroup_id(struct cgroup *cgrp) +{ + return BPF_CORE_READ(cgrp, kn, id); +} + +/* Caller must hold bpf_rcu_read_lock() */ +static bool mem_cgroup_has_oom_victim(struct mem_cgroup *root_memcg) +{ + struct cgroup_subsys_state *pos; + struct task_struct *task; + bool found = false; + + bpf_for_each(css, pos, &root_memcg->css, + BPF_CGROUP_ITER_DESCENDANTS_PRE) { + struct mem_cgroup *m = bpf_get_mem_cgroup(pos); + + if (!m) + continue; + bpf_for_each(css_task, task, &m->css, CSS_TASK_ITER_PROCS) { + if (BPF_CORE_READ(task, signal, oom_mm)) { + found = true; + break; + } + } + bpf_put_mem_cgroup(m); + if (found) + return true; + } + + return false; +} + +/* Caller must hold bpf_rcu_read_lock() */ +static bool mem_cgroup_killable(struct mem_cgroup *memcg) +{ + struct cgroup_subsys_state *pos; + struct task_struct *task; + bool killable = true; + + bpf_for_each(css, pos, &memcg->css, BPF_CGROUP_ITER_DESCENDANTS_PRE) { + struct mem_cgroup *m = bpf_get_mem_cgroup(pos); + + if (!m) + continue; + bpf_for_each(css_task, task, &m->css, CSS_TASK_ITER_PROCS) { + if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN) { + killable = false; + break; + } + } + bpf_put_mem_cgroup(m); + if (!killable) + return false; + } + + return true; +} + +static __u64 memcg_pgscan(struct mem_cgroup *memcg) +{ + int kswapd = bpf_core_enum_value(enum node_stat_item, PGSCAN_KSWAPD); + int direct = bpf_core_enum_value(enum node_stat_item, PGSCAN_DIRECT); + int khugepaged = bpf_core_enum_value(enum node_stat_item, + PGSCAN_KHUGEPAGED); + int proactive = bpf_core_enum_value(enum node_stat_item, + PGSCAN_PROACTIVE); + + return bpf_mem_cgroup_page_state(memcg, kswapd) + + bpf_mem_cgroup_page_state(memcg, direct) + + bpf_mem_cgroup_page_state(memcg, khugepaged) + + bpf_mem_cgroup_page_state(memcg, proactive); +} + +static __u64 oomd_pgscan_delta(struct oomd_policy *policy, __u64 pgscan) +{ + __u64 last_pgscan = 0; + + if (policy) { + last_pgscan = policy->last_pgscan; + policy->last_pgscan = pgscan; + } + + if (last_pgscan > pgscan) + return 0; + + return pgscan - last_pgscan; +} + +static bool oomd_better_candidate(__u8 pref, __u64 delta, __u64 usage, + __u8 best_pref, __u64 best_delta, + __u64 best_usage, bool have_best) +{ + if (!have_best) + return true; + + /* Prefer normal candidates over "avoid" candidates */ + if (pref != best_pref) + return pref < best_pref; + + /* Primary score: pgscan delta; tie breaker: memory.current */ + if (delta != best_delta) + return delta > best_delta; + + return usage > best_usage; +} + +static int oomd_kill_task(struct oom_control *oc, struct task_struct *task, + struct oomd_decision *decision) +{ + struct task_struct *t; + int ret; + + t = bpf_task_acquire(task); + if (!t) + return 0; + + if (BPF_CORE_READ(t, signal, oom_mm)) { + if (decision) + decision->killed_pid = t->pid; + bpf_task_release(t); + return 1; + } + + ret = bpf_oom_kill_process(oc, t, "bpf systemd-oomd policy"); + if (decision) { + decision->kill_ret = ret; + if (!ret) + decision->killed_pid = t->pid; + } + + bpf_task_release(t); + return ret ? 0 : 1; +} + +static int oomd_kill_memcg(struct oom_control *oc, struct mem_cgroup *chosen, + struct oomd_decision *decision) +{ + struct cgroup_subsys_state *pos; + struct task_struct *task, *victim = NULL; + + /* + * Walk descendants as well as chosen itself so non-leaf + * memory.oom.group candidates (which hold no direct tasks in cgroup v2) + * still yield a task for bpf_oom_kill_process() to group-kill. + */ + bpf_rcu_read_lock(); + bpf_for_each(css, pos, &chosen->css, BPF_CGROUP_ITER_DESCENDANTS_PRE) { + struct mem_cgroup *m = bpf_get_mem_cgroup(pos); + + if (!m) + continue; + bpf_for_each(css_task, task, &m->css, CSS_TASK_ITER_PROCS) { + victim = bpf_task_acquire(task); + if (victim) + break; + } + bpf_put_mem_cgroup(m); + if (victim) + break; + } + bpf_rcu_read_unlock(); + + if (!victim) + return 0; + + { + int ret = oomd_kill_task(oc, victim, decision); + + bpf_task_release(victim); + return ret; + } +} + +/* + * A systemd-oomd-style OOM policy: + * + * - candidates are leaf cgroups, or cgroups marked with memory.oom.group; + * - user-space-only systemd inputs such as ManagedOOMPreference/xattrs are + * supplied through oomd_policies, keyed by cgroup id; + * - "omit" cgroups are ignored and "avoid" cgroups are ranked last; + * - the primary score is memory.stat pgscan delta, with memory.current as the + * tie breaker; + * - when memory.oom.group is set, bpf_oom_kill_process() delegates recursive + * group behavior to the kernel OOM handler for the selected task; + * - at hard OOM we still allow the memory.current tie breaker to select a + * cgroup when all pgscan deltas are zero, so the kernel can make progress. + */ +SEC("struct_ops.s/handle_out_of_memory") +int BPF_PROG(test_oomd_out_of_memory, struct oom_control *oc, + struct cgroup *attached_cgrp) +{ + struct mem_cgroup *root_memcg = oc->memcg; + struct mem_cgroup *memcg, *chosen = NULL; + struct cgroup_subsys_state *css_pos, *css; + struct oomd_decision *decision; + __u8 preference, best_preference = OOMD_PREFERENCE_NONE; + __u64 usage, pgscan, delta, swap_usage, cgid; + __u64 best_usage = 0, best_delta = 0; + struct oomd_policy *policy; + bool have_best = false; + __u32 zero = 0; + int swap_item; + int ret = 0; + + if (root_memcg) + root_memcg = bpf_get_mem_cgroup(&root_memcg->css); + else + root_memcg = bpf_get_root_mem_cgroup(); + + if (!root_memcg) + return 0; + + css = &root_memcg->css; + if (css && css->cgroup == attached_cgrp) + goto out_put_root; + + /* Back off without overwriting decision while a prior victim exits */ + bpf_rcu_read_lock(); + if (mem_cgroup_has_oom_victim(root_memcg)) { + bpf_rcu_read_unlock(); + ret = 1; + goto out_put_root; + } + bpf_rcu_read_unlock(); + + decision = bpf_map_lookup_elem(&oomd_decisions, &zero); + if (decision) { + __builtin_memset(decision, 0, sizeof(*decision)); + decision->root_cgid = cgroup_id(css->cgroup); + } + + bpf_mem_cgroup_flush_stats(root_memcg); + swap_item = bpf_core_enum_value(enum memcg_stat_item, MEMCG_SWAP); + + bpf_rcu_read_lock(); + bpf_for_each(css, css_pos, &root_memcg->css, + BPF_CGROUP_ITER_DESCENDANTS_POST) { + struct cgroup *cgrp = css_pos->cgroup; + bool is_leaf, is_oom_group; + + is_leaf = !(cgrp->nr_descendants + cgrp->nr_dying_descendants); + + memcg = bpf_get_mem_cgroup(css_pos); + if (!memcg) + continue; + + is_oom_group = BPF_CORE_READ(memcg, oom_group); + if (!is_leaf && !is_oom_group) { + bpf_put_mem_cgroup(memcg); + continue; + } + + cgid = cgroup_id(cgrp); + policy = bpf_map_lookup_elem(&oomd_policies, &cgid); + preference = policy ? policy->preference : OOMD_PREFERENCE_NONE; + + if (preference == OOMD_PREFERENCE_OMIT) { + if (decision) + decision->skipped_omit++; + bpf_put_mem_cgroup(memcg); + continue; + } + + if (!mem_cgroup_killable(memcg)) { + if (decision) + decision->skipped_unkillable++; + bpf_put_mem_cgroup(memcg); + continue; + } + + usage = bpf_mem_cgroup_usage(memcg); + pgscan = memcg_pgscan(memcg); + delta = oomd_pgscan_delta(policy, pgscan); + swap_usage = bpf_mem_cgroup_page_state(memcg, swap_item); + + if (decision) + decision->scanned_candidates++; + + if (pgscan == 0 && usage == 0) { + bpf_put_mem_cgroup(memcg); + continue; + } + + if (oomd_better_candidate(preference, delta, usage, + best_preference, best_delta, + best_usage, have_best)) { + best_preference = preference; + best_delta = delta; + best_usage = usage; + have_best = true; + + if (chosen) + bpf_put_mem_cgroup(chosen); + chosen = bpf_get_mem_cgroup(&memcg->css); + + if (decision) { + decision->victim_cgid = cgid; + decision->victim_usage = usage; + decision->victim_pgscan = pgscan; + decision->victim_pgscan_delta = delta; + decision->victim_swap_usage = swap_usage; + } + } + + bpf_put_mem_cgroup(memcg); + } + bpf_rcu_read_unlock(); + + if (chosen) { + ret = oomd_kill_memcg(oc, chosen, decision); + bpf_put_mem_cgroup(chosen); + } + +out_put_root: + bpf_put_mem_cgroup(root_memcg); + return ret; +} + +SEC(".struct_ops.link") +struct bpf_oom_ops test_bpf_oomd = { + .name = "bpf_systemd_oomd_policy", + .handle_out_of_memory = (void *)test_oomd_out_of_memory, +}; diff --git a/tools/testing/selftests/bpf/progs/test_oomd.h b/tools/testing/selftests/bpf/progs/test_oomd.h new file mode 100644 index 000000000000..cbd0d9a9e928 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oomd.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __TEST_OOMD_H +#define __TEST_OOMD_H + +#define OOM_SCORE_ADJ_MIN (-1000) + +enum oomd_preference { + OOMD_PREFERENCE_NONE, + OOMD_PREFERENCE_AVOID, + OOMD_PREFERENCE_OMIT, +}; + +struct oomd_policy { + __u8 preference; + __u8 _pad[7]; + __u64 last_pgscan; +}; + +struct oomd_decision { + __u64 root_cgid; + __u64 victim_cgid; + __u64 victim_usage; + __u64 victim_pgscan; + __u64 victim_pgscan_delta; + __u64 victim_swap_usage; + __u64 killed_pid; + __u64 scanned_candidates; + __u64 skipped_omit; + __u64 skipped_unkillable; + __s32 kill_ret; +}; + +#endif /* __TEST_OOMD_H */ -- 2.56.1.911.g883d8bcb20-goog bpf_out_of_memory() invokes out_of_memory(), which falls back to select_bad_process() if no attached bpf_oom_ops policy handles the event. It cannot directly terminate a specific task chosen by a proactive userspace/BPF policy. Existing userspace options (pidfd_send_signal(SIGKILL) + process_mrelease() or cgroup.kill) cannot atomically honor memory.oom.group expansion from a chosen task, do not record memory.events oom_kill / oom_group_kill counters or unified kernel OOM logging, and cannot be invoked directly from a PSI tracepoint callback. Add bpf_oom_proactive_kill to bpf_declare_oom_kfuncs. The function synchronizes on oom_lock, validates that @task resides under a memcg (if specified), and terminates @task through bpf_oom_kill_process(). Thus asynchronous OOM memory reclamation, memcg OOM event counters, and memory.oom.group semantics apply as usual. Set oc->bpf_declared so dump_header() is skipped for proactive terminations since there is no failed allocation stack, meminfo snapshot, or task table to diagnose. dump_oom_victim() and "Killed process" still record the target, origin memcg, and reason string. Signed-off-by: Ben Gardon --- include/linux/oom.h | 3 ++ mm/oom_kill.c | 71 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/include/linux/oom.h b/include/linux/oom.h index 168b64dfb6ad..2725f17c7b40 100644 --- a/include/linux/oom.h +++ b/include/linux/oom.h @@ -64,6 +64,7 @@ struct oom_control { /* Declared via BPF outside an allocation failure */ bool bpf_declared; + #endif }; @@ -77,6 +78,7 @@ static inline bool is_bpf_declared_oom(const struct oom_control *oc) { return oc->bpf_declared; } + #else static inline const char *oom_handler_name(const struct oom_control *oc) { @@ -87,6 +89,7 @@ static inline bool is_bpf_declared_oom(const struct oom_control *oc) { return false; } + #endif extern struct mutex oom_lock; diff --git a/mm/oom_kill.c b/mm/oom_kill.c index 21b88332a46a..42c986ec1520 100644 --- a/mm/oom_kill.c +++ b/mm/oom_kill.c @@ -1384,6 +1384,76 @@ __bpf_kfunc int bpf_out_of_memory(struct mem_cgroup *memcg__nullable, return ret; } +/** + * bpf_oom_proactive_kill() - Terminate a task proactively outside of OOM + * @origin__nullable: memcg bounding OOM group and log attribution, or NULL + * @task: task to be terminated + * @message__str: reason string logged in dmesg + * @flags: bitmask of &enum bpf_oom_flags + * + * Terminate @task through the OOM machinery (asynchronous OOM memory + * reclamation, memcg OOM events, memory.oom.group recursive behavior, and + * single-line summary) without an allocation failure having occurred and + * without falling back to select_bad_process(). The full allocation-failure + * dump_header() report is suppressed because no page allocation failed. + * + * Synchronizes on oom_lock: waits (interruptible by fatal signals) when + * BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK is set, or returns -EBUSY immediately if + * oom_lock is contended. + * + * When @origin__nullable is non-NULL (and not the root memcg), @task must + * belong to @origin__nullable or one of its descendants, and + * mem_cgroup_get_oom_group() bounds any memory.oom.group expansion at + * @origin__nullable. + * + * Return: 0 on success, or a negative errno on failure. + */ +__bpf_kfunc int bpf_oom_proactive_kill(struct mem_cgroup *origin__nullable, + struct task_struct *task, + const char *message__str, + u64 flags) +{ + struct oom_control oc = { + .gfp_mask = GFP_USER, + .order = 0, + .bpf_declared = true, + }; + int ret; + + if (flags & ~BPF_OOM_FLAGS_ALL) + return -EINVAL; + + if (origin__nullable && mem_cgroup_is_root(origin__nullable)) + origin__nullable = NULL; + + if (origin__nullable && + !mem_cgroup_task_in_hierarchy(task, origin__nullable)) + return -EINVAL; + + oc.memcg = origin__nullable; + oc.constraint = origin__nullable ? CONSTRAINT_MEMCG : CONSTRAINT_NONE; + + lockdep_assert_not_held(&oom_lock); + if (flags & BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK) { + ret = mutex_lock_killable(&oom_lock); + if (ret) + return ret; + } else if (!mutex_trylock(&oom_lock)) { + return -EBUSY; + } + + if (oom_killer_disabled) { + ret = -EBUSY; + goto out_unlock; + } + + ret = bpf_oom_kill_process(&oc, task, message__str); + +out_unlock: + mutex_unlock(&oom_lock); + return ret; +} + __bpf_kfunc_end_defs(); BTF_KFUNCS_START(bpf_oom_kfuncs) @@ -1413,6 +1483,7 @@ static const struct btf_kfunc_id_set bpf_oom_kfunc_set = { BTF_KFUNCS_START(bpf_declare_oom_kfuncs) BTF_ID_FLAGS(func, bpf_out_of_memory, KF_SLEEPABLE) +BTF_ID_FLAGS(func, bpf_oom_proactive_kill, KF_SLEEPABLE) BTF_KFUNCS_END(bpf_declare_oom_kfuncs) static const struct btf_kfunc_id_set bpf_declare_oom_syscall_kfunc_set = { -- 2.56.1.911.g883d8bcb20-goog Add a BPF selftest exercising bpf_oom_proactive_kill() from a BPF_PROG_TYPE_SYSCALL program. Verify that OOM_SCORE_ADJ_MIN (-1000) tasks and out-of-hierarchy memcg attributions return -EINVAL while an eligible task is terminated with SIGKILL and increments memory.events oom_kill. Signed-off-by: Ben Gardon --- .../bpf/prog_tests/test_oom_proactive_kill.c | 119 ++++++++++++++++++ .../bpf/progs/test_oom_proactive_kill.c | 46 +++++++ .../bpf/progs/test_oom_proactive_kill.h | 12 ++ 3 files changed, 177 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c b/tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c new file mode 100644 index 000000000000..ca2165f03278 --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/test_oom_proactive_kill.c @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include + +#include "cgroup_helpers.h" +#include "memory_holder.h" +#include "progs/test_oom_proactive_kill.h" +#include "test_oom_proactive_kill.skel.h" + +/* + * Serialized because bpf_oom_proactive_kill() acquires the global oom_lock + * and kills processes via the OOM path, which would collide with other OOM + * tests running in parallel under test_progs -j. + */ +void serial_test_oom_proactive_kill(void) +{ + const char *cg_a = "/oom_proactive_a"; + const char *cg_b = "/oom_proactive_b"; + struct test_oom_proactive_kill *skel = NULL; + struct memory_holder w_protected, w_target; + struct proactive_kill_args args = {}; + int cg_a_fd = -1, cg_b_fd = -1; + unsigned long long id_a, id_b; + int prog_fd, status = 0; + char buf[4096] = {}; + char pbuf[32]; + LIBBPF_OPTS(bpf_test_run_opts, topts, + .ctx_in = &args, + .ctx_size_in = sizeof(args), + ); + + memory_holder_init(&w_protected); + memory_holder_init(&w_target); + + if (!ASSERT_OK(setup_cgroup_environment(), "setup_cgroup_env")) + return; + + cg_a_fd = create_and_get_cgroup(cg_a); + cg_b_fd = create_and_get_cgroup(cg_b); + if (!ASSERT_GE(cg_a_fd, 0, "create cg_a") || + !ASSERT_GE(cg_b_fd, 0, "create cg_b")) + goto cleanup; + + id_a = get_cgroup_id(cg_a); + id_b = get_cgroup_id(cg_b); + if (!ASSERT_GT(id_a, 0, "get_cgroup_id cg_a") || + !ASSERT_GT(id_b, 0, "get_cgroup_id cg_b")) + goto cleanup; + + skel = test_oom_proactive_kill__open_and_load(); + if (!ASSERT_OK_PTR(skel, "open_and_load")) + goto cleanup; + + prog_fd = bpf_program__fd(skel->progs.proactive_kill_prog); + + if (!ASSERT_OK(memory_holder_spawn(&w_protected, 0, 0, -1000, false), + "spawn_protected") || + !ASSERT_OK(memory_holder_spawn(&w_target, 0, 0, 0, false), + "spawn_target")) + goto cleanup; + + snprintf(pbuf, sizeof(pbuf), "%d", w_protected.pid); + if (!ASSERT_OK(write_cgroup_file(cg_a, "cgroup.procs", pbuf), + "place_protected")) + goto cleanup; + snprintf(pbuf, sizeof(pbuf), "%d", w_target.pid); + if (!ASSERT_OK(write_cgroup_file(cg_a, "cgroup.procs", pbuf), + "place_target")) + goto cleanup; + + if (!ASSERT_OK(memory_holder_start(&w_protected), "start_protected") || + !ASSERT_OK(memory_holder_wait_ready(&w_protected), "wait_protected") || + !ASSERT_OK(memory_holder_start(&w_target), "start_target") || + !ASSERT_OK(memory_holder_wait_ready(&w_target), "wait_target")) + goto cleanup; + + /* OOM_SCORE_ADJ_MIN (-1000) task must be rejected with -EINVAL */ + args.cgroup_id = id_a; + args.pid = w_protected.pid; + args.wait_on_oom_lock = 1; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_protected")) + ASSERT_EQ((int)topts.retval, -EINVAL, "reject_oom_score_adj_min"); + + /* Task outside origin memcg hierarchy must be rejected with -EINVAL */ + args.cgroup_id = id_b; + args.pid = w_target.pid; + args.wait_on_oom_lock = 1; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_wrong_cg")) + ASSERT_EQ((int)topts.retval, -EINVAL, "reject_wrong_hierarchy"); + + /* Eligible task inside origin memcg must be terminated via OOM */ + args.cgroup_id = id_a; + args.pid = w_target.pid; + args.wait_on_oom_lock = 1; + if (!ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_kill") || + !ASSERT_OK((int)topts.retval, "proactive_kill_retval")) + goto cleanup; + + ASSERT_EQ(waitpid(w_target.pid, &status, 0), w_target.pid, "waitpid_target"); + w_target.pid = -1; + ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL, + "target_sigkill"); + + if (ASSERT_OK(read_cgroup_file(cg_a, "memory.events", buf, sizeof(buf)), + "read memory.events")) + ASSERT_OK_PTR(strstr(buf, "oom_kill 1"), "oom_kill incremented"); + +cleanup: + memory_holder_cleanup(&w_protected); + memory_holder_cleanup(&w_target); + if (cg_a_fd >= 0) + close(cg_a_fd); + if (cg_b_fd >= 0) + close(cg_b_fd); + test_oom_proactive_kill__destroy(skel); + cleanup_cgroup_environment(); +} diff --git a/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c new file mode 100644 index 000000000000..591a2e0b284d --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.c @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "vmlinux.h" +#include +#include +#include "test_oom_proactive_kill.h" + +char _license[] SEC("license") = "GPL"; + +SEC("syscall") +int proactive_kill_prog(struct proactive_kill_args *args) +{ + struct mem_cgroup *memcg = NULL; + struct task_struct *task; + u64 flags = args->flags; + struct cgroup *cgrp; + int ret; + + if (args->wait_on_oom_lock) + flags |= BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK; + + task = bpf_task_from_pid(args->pid); + if (!task) + return -ESRCH; + + if (args->cgroup_id) { + cgrp = bpf_cgroup_from_id(args->cgroup_id); + if (!cgrp) { + bpf_task_release(task); + return -ENOENT; + } + memcg = bpf_get_mem_cgroup(&cgrp->self); + bpf_cgroup_release(cgrp); + if (!memcg) { + bpf_task_release(task); + return -ENODEV; + } + } + + ret = bpf_oom_proactive_kill(memcg, task, "bpf proactive oom test", + flags); + + if (memcg) + bpf_put_mem_cgroup(memcg); + bpf_task_release(task); + return ret; +} diff --git a/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h new file mode 100644 index 000000000000..d3bf7596de21 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom_proactive_kill.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __TEST_OOM_PROACTIVE_KILL_H +#define __TEST_OOM_PROACTIVE_KILL_H + +struct proactive_kill_args { + __u64 cgroup_id; + __u64 flags; + __s32 pid; + __u32 wait_on_oom_lock; +}; + +#endif /* __TEST_OOM_PROACTIVE_KILL_H */ -- 2.56.1.911.g883d8bcb20-goog Add selftest coverage for BPF OOM kfunc safety boundaries: - Verifier rejection of bpf_oom_kill_process() from SEC("syscall"), and rejection of bpf_out_of_memory() / bpf_oom_proactive_kill() from bpf_oom_ops struct_ops callbacks (oom_lock deadlock guard). - Runtime rejection of init (pid 1, -EPERM) and unknown flags (-EINVAL) in bpf_oom_proactive_kill(). - Global (origin__nullable == NULL) proactive termination. Signed-off-by: Ben Gardon --- .../bpf/prog_tests/test_oom_kfunc_neg.c | 79 +++++++++++++++++++ .../bpf/progs/test_oom_fail_ops_oom.c | 21 +++++ .../bpf/progs/test_oom_fail_ops_proactive.c | 23 ++++++ .../bpf/progs/test_oom_fail_syscall.c | 15 ++++ 4 files changed, 138 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c new file mode 100644 index 000000000000..8cfe9e3e85bb --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/test_oom_kfunc_neg.c @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include + +#include "memory_holder.h" +#include "progs/test_oom_proactive_kill.h" +#include "test_oom_proactive_kill.skel.h" +#include "test_oom_fail_syscall.skel.h" +#include "test_oom_fail_ops_oom.skel.h" +#include "test_oom_fail_ops_proactive.skel.h" + +/* + * Serialized because the global proactive kill subtest acquires oom_lock and + * invokes the OOM killer, which can collide with other OOM tests under -j. + */ +void serial_test_oom_kfunc_neg(void) +{ + struct test_oom_proactive_kill *skel = NULL; + struct proactive_kill_args args = {}; + struct memory_holder worker; + int prog_fd, status = 0; + LIBBPF_OPTS(bpf_test_run_opts, topts, + .ctx_in = &args, + .ctx_size_in = sizeof(args), + ); + + memory_holder_init(&worker); + + /* Verifier rejection checks for kfunc context restrictions */ + RUN_TESTS(test_oom_fail_syscall); + RUN_TESTS(test_oom_fail_ops_oom); + RUN_TESTS(test_oom_fail_ops_proactive); + + skel = test_oom_proactive_kill__open_and_load(); + if (!ASSERT_OK_PTR(skel, "open_and_load")) + return; + + prog_fd = bpf_program__fd(skel->progs.proactive_kill_prog); + + /* Init (pid 1) must be rejected with -EPERM via oom_unkillable_task() */ + args.cgroup_id = 0; + args.pid = 1; + args.wait_on_oom_lock = 1; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_init")) + ASSERT_EQ((int)topts.retval, -EPERM, "reject_init"); + + /* Invalid flags must be rejected with -EINVAL */ + if (!ASSERT_OK(memory_holder_spawn(&worker, 0, 0, 0, false), "spawn_child") || + !ASSERT_OK(memory_holder_start(&worker), "start_child") || + !ASSERT_OK(memory_holder_wait_ready(&worker), "wait_child")) + goto cleanup; + + args.cgroup_id = 0; + args.pid = worker.pid; + args.flags = ~0ULL; + args.wait_on_oom_lock = 0; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_bad_flags")) + ASSERT_EQ((int)topts.retval, -EINVAL, "reject_bad_flags"); + + /* Global proactive kill (origin__nullable == NULL) must succeed */ + args.cgroup_id = 0; + args.pid = worker.pid; + args.flags = 0; + args.wait_on_oom_lock = 1; + if (!ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_global") || + !ASSERT_OK((int)topts.retval, "global_retval")) + goto cleanup; + + ASSERT_EQ(waitpid(worker.pid, &status, 0), worker.pid, "waitpid_global"); + worker.pid = -1; + ASSERT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL, + "global_sigkill"); + +cleanup: + memory_holder_cleanup(&worker); + test_oom_proactive_kill__destroy(skel); +} diff --git a/tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c new file mode 100644 index 000000000000..ba6b15c6e407 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_oom.c @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "vmlinux.h" +#include +#include +#include "bpf_misc.h" + +char _license[] SEC("license") = "GPL"; + +SEC("struct_ops.s/handle_out_of_memory") +__failure __msg("calling kernel function bpf_out_of_memory is not allowed") +int BPF_PROG(ops_call_out_of_memory, struct oom_control *oc, + struct cgroup *cgrp) +{ + return bpf_out_of_memory(oc->memcg, 0, 0); +} + +SEC(".struct_ops.link") +struct bpf_oom_ops fail_oom_ops = { + .name = "fail_ops_oom", + .handle_out_of_memory = (void *)ops_call_out_of_memory, +}; diff --git a/tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c new file mode 100644 index 000000000000..24ba2bac1d85 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom_fail_ops_proactive.c @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "vmlinux.h" +#include +#include +#include "bpf_misc.h" + +char _license[] SEC("license") = "GPL"; + +SEC("struct_ops.s/handle_out_of_memory") +__failure __msg("calling kernel function bpf_oom_proactive_kill is not allowed") +int BPF_PROG(ops_call_proactive_kill, struct oom_control *oc, + struct cgroup *cgrp) +{ + struct task_struct *task = bpf_get_current_task_btf(); + + return bpf_oom_proactive_kill(oc->memcg, task, "disallowed", 0); +} + +SEC(".struct_ops.link") +struct bpf_oom_ops fail_proactive_ops = { + .name = "fail_ops_proactive", + .handle_out_of_memory = (void *)ops_call_proactive_kill, +}; diff --git a/tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c b/tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c new file mode 100644 index 000000000000..e6aa7017f500 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom_fail_syscall.c @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "vmlinux.h" +#include +#include "bpf_misc.h" + +char _license[] SEC("license") = "GPL"; + +SEC("syscall") +__failure __msg("calling kernel function bpf_oom_kill_process is not allowed") +int syscall_call_oom_kill_process(void *ctx) +{ + struct task_struct *task = bpf_get_current_task_btf(); + + return bpf_oom_kill_process(NULL, task, "disallowed"); +} -- 2.56.1.911.g883d8bcb20-goog Allow bpf_oom_ops handlers and proactive SYSCALL/PSI programs to resolve memory cgroup pressure by increasing a non-root cgroup's memory.max limit via bpf_mem_cgroup_raise_max(memcg, max_bytes). Only strictly higher limits are permitted so updating memory.max never triggers synchronous reclaim or recursive OOMs while oom_lock is held. On cgroup v1, memcg1_raise_max() enforces the memory.max <= memsw.max invariant under memcg_max_mutex and wakes waiters via memcg1_oom_recover(). The kfunc is marked KF_SLEEPABLE because memcg_wb_domain_size_changed() acquires a spinlock and cgroup v1 acquires memcg_max_mutex. When invoked from handle_out_of_memory() returning > 0, try_charge_memcg() immediately retries against the expanded limit and succeeds without terminating any task. Suggested-by: Michal Hocko Signed-off-by: Ben Gardon --- include/linux/memcontrol.h | 7 +++++++ mm/bpf_memcontrol.c | 24 ++++++++++++++++++++++++ mm/memcontrol-v1.c | 16 ++++++++++++++++ mm/memcontrol-v1.h | 6 ++++++ mm/memcontrol.c | 38 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 91 insertions(+) diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h index bc30d7baecd7..1dc5176e2682 100644 --- a/include/linux/memcontrol.h +++ b/include/linux/memcontrol.h @@ -1002,6 +1002,7 @@ void mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx, int val); void mem_cgroup_flush_stats(struct mem_cgroup *memcg); +int mem_cgroup_raise_max(struct mem_cgroup *memcg, unsigned long max_pages); void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg); void mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val); @@ -1533,6 +1534,12 @@ static inline bool mem_cgroup_task_in_hierarchy(struct task_struct *task, return true; } +static inline int mem_cgroup_raise_max(struct mem_cgroup *memcg, + unsigned long max_pages) +{ + return -EOPNOTSUPP; +} + static inline int mem_cgroup_init(void) { return 0; } #endif /* CONFIG_MEMCG */ diff --git a/mm/bpf_memcontrol.c b/mm/bpf_memcontrol.c index d8f579c28560..8c00d98b5826 100644 --- a/mm/bpf_memcontrol.c +++ b/mm/bpf_memcontrol.c @@ -206,6 +206,29 @@ __bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg, return nr_reclaimed * PAGE_SIZE; } +/** + * bpf_mem_cgroup_raise_max() - Increase a memory cgroup's memory.max limit + * @memcg: target non-root memory cgroup + * @max_bytes: new limit in bytes (truncated to PAGE_SIZE; clamped to + * PAGE_COUNTER_MAX, which represents unlimited/"max" -- callers + * may pass U64_MAX) + * + * Allows a BPF OOM policy (or proactive program) to resolve a memcg OOM + * non-destructively by raising memory.max instead of terminating a task. + * Only strictly higher limits are accepted so no reclaim is needed while + * holding oom_lock. On cgroup v1, enforces memory.max <= memsw.max. + * + * Return: 0 on success, or a negative errno on failure. + */ +__bpf_kfunc int bpf_mem_cgroup_raise_max(struct mem_cgroup *memcg, + u64 max_bytes) +{ + unsigned long max_pages = min_t(u64, max_bytes >> PAGE_SHIFT, + PAGE_COUNTER_MAX); + + return mem_cgroup_raise_max(memcg, max_pages); +} + __bpf_kfunc_end_defs(); BTF_KFUNCS_START(bpf_memcontrol_kfuncs) @@ -218,6 +241,7 @@ BTF_ID_FLAGS(func, bpf_mem_cgroup_memory_events) BTF_ID_FLAGS(func, bpf_mem_cgroup_usage) BTF_ID_FLAGS(func, bpf_mem_cgroup_page_state) BTF_ID_FLAGS(func, bpf_mem_cgroup_flush_stats, KF_SLEEPABLE) +BTF_ID_FLAGS(func, bpf_mem_cgroup_raise_max, KF_SLEEPABLE) BTF_KFUNCS_END(bpf_memcontrol_kfuncs) diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c index b7f286888507..d50fe775f1f3 100644 --- a/mm/memcontrol-v1.c +++ b/mm/memcontrol-v1.c @@ -1418,6 +1418,22 @@ void vmpressure_unregister_event(struct mem_cgroup *memcg, static DEFINE_MUTEX(memcg_max_mutex); +int memcg1_raise_max(struct mem_cgroup *memcg, unsigned long max_pages) +{ + int ret = 0; + + mutex_lock(&memcg_max_mutex); + if (max_pages <= memcg->memory.max || max_pages > memcg->memsw.max) + ret = -EINVAL; + else + WRITE_ONCE(memcg->memory.max, max_pages); + mutex_unlock(&memcg_max_mutex); + + if (!ret) + memcg1_oom_recover(memcg); + return ret; +} + static int mem_cgroup_resize_max(struct mem_cgroup *memcg, unsigned long max, bool memsw) { diff --git a/mm/memcontrol-v1.h b/mm/memcontrol-v1.h index 820139657184..3c22f124a5dc 100644 --- a/mm/memcontrol-v1.h +++ b/mm/memcontrol-v1.h @@ -63,6 +63,7 @@ enum res_type { bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked); void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked); void memcg1_oom_recover(struct mem_cgroup *memcg); +int memcg1_raise_max(struct mem_cgroup *memcg, unsigned long max_pages); void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg); void memcg1_uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout, @@ -106,6 +107,11 @@ static inline bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked) } static inline void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked) {} static inline void memcg1_oom_recover(struct mem_cgroup *memcg) {} +static inline int memcg1_raise_max(struct mem_cgroup *memcg, + unsigned long max_pages) +{ + return -EOPNOTSUPP; +} static inline void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg) {} diff --git a/mm/memcontrol.c b/mm/memcontrol.c index afbb638e7e1c..8440cca757b9 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -5025,6 +5025,44 @@ static int memory_max_show(struct seq_file *m, void *v) READ_ONCE(mem_cgroup_from_seq(m)->memory.max)); } +/** + * mem_cgroup_raise_max() - Increase a memory cgroup's hard limit + * @memcg: target non-root memory cgroup + * @max_pages: new limit in pages (must exceed current memory.max) + * + * Safe to call from OOM handler context while oom_lock is held: only + * increases are permitted, so no stock draining or reclaim is required. + * On cgroup v1, enforces the memory.max <= memsw.max invariant under + * memcg_max_mutex. + * + * Return: 0 on success, or -EINVAL if @memcg is root/dying or @max_pages + * does not satisfy limit bounds. + */ +int mem_cgroup_raise_max(struct mem_cgroup *memcg, unsigned long max_pages) +{ + unsigned long old; + + if (!memcg || mem_cgroup_is_root(memcg) || memcg_is_dying(memcg)) + return -EINVAL; + + max_pages = min_t(unsigned long, max_pages, PAGE_COUNTER_MAX); + if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { + int ret = memcg1_raise_max(memcg, max_pages); + + if (ret) + return ret; + } else { + old = READ_ONCE(memcg->memory.max); + do { + if (max_pages <= old) + return -EINVAL; + } while (!try_cmpxchg(&memcg->memory.max, &old, max_pages)); + } + + memcg_wb_domain_size_changed(memcg); + return 0; +} + static ssize_t memory_max_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { -- 2.56.1.911.g883d8bcb20-goog Add a BPF selftest attaching a BPF OOM handler to a small memory cgroup, which calls bpf_mem_cgroup_raise_max() to expand memory.max on OOM. This allows a 24 MB allocation to succeed without terminating the allocating task. Also verify BPF_PROG_TYPE_SYSCALL negative and boundary cases: equal or lower limits and root memcg return -EINVAL, while UINT64_MAX clamps cleanly to "max". Signed-off-by: Ben Gardon --- .../bpf/prog_tests/test_oom_raise_max.c | 135 ++++++++++++++++++ .../selftests/bpf/progs/test_oom_raise_max.c | 55 +++++++ .../selftests/bpf/progs/test_oom_raise_max.h | 10 ++ 3 files changed, 200 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom_raise_max.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom_raise_max.h diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c b/tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c new file mode 100644 index 000000000000..6b803d4560e9 --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/test_oom_raise_max.c @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include +#include + +#include "cgroup_helpers.h" +#include "memory_holder.h" + +#define MB (1024UL * 1024UL) +#include "progs/test_oom_raise_max.h" +#include "test_oom_raise_max.skel.h" + +/* + * Serialized because this test attaches a bpf_oom_ops handler and triggers a + * real memcg OOM, which can collide with other OOM tests under test_progs -j. + */ +void serial_test_oom_raise_max(void) +{ + LIBBPF_OPTS(bpf_cgroup_opts, opts); + const char *cg_path = "/oom_raise_test"; + struct test_oom_raise_max *skel = NULL; + struct bpf_link *link = NULL; + struct raise_max_args args = {}; + struct memory_holder worker; + int cg_fd = -1, prog_fd, status = 0; + unsigned long long cg_id; + char buf[256] = {}; + char pbuf[32]; + LIBBPF_OPTS(bpf_test_run_opts, topts, + .ctx_in = &args, + .ctx_size_in = sizeof(args), + ); + + memory_holder_init(&worker); + + if (!ASSERT_OK(setup_cgroup_environment(), "setup_cgroup_env")) + return; + + cg_fd = create_and_get_cgroup(cg_path); + if (!ASSERT_GE(cg_fd, 0, "create_cgroup")) + goto cleanup; + + cg_id = get_cgroup_id(cg_path); + if (!ASSERT_GT(cg_id, 0, "get_cgroup_id")) + goto cleanup; + + snprintf(buf, sizeof(buf), "%lu", 16 * MB); + if (!ASSERT_OK(write_cgroup_file(cg_path, "memory.max", buf), + "set memory.max")) + goto cleanup; + write_cgroup_file(cg_path, "memory.swap.max", "0"); + + skel = test_oom_raise_max__open_and_load(); + if (!ASSERT_OK_PTR(skel, "open_and_load")) + goto cleanup; + + skel->bss->new_max_bytes = 64 * MB; + + link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom_raise, + cg_fd, &opts); + if (!ASSERT_OK_PTR(link, "attach_cgroup")) { + link = NULL; + goto cleanup; + } + + if (!ASSERT_OK(memory_holder_spawn(&worker, 24 * MB, 0, 0, true), + "spawn_worker")) + goto cleanup; + + snprintf(pbuf, sizeof(pbuf), "%d", worker.pid); + if (!ASSERT_OK(write_cgroup_file(cg_path, "cgroup.procs", pbuf), + "place_worker") || + !ASSERT_OK(memory_holder_start(&worker), "start_worker")) + goto cleanup; + + ASSERT_EQ(waitpid(worker.pid, &status, 0), worker.pid, "waitpid"); + worker.pid = -1; + ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0, + "child_survived"); + + if (ASSERT_OK(read_cgroup_file(cg_path, "memory.max", buf, sizeof(buf)), + "read memory.max")) { + char expected[64]; + + snprintf(expected, sizeof(expected), "%lu", 64 * MB); + ASSERT_OK_PTR(strstr(buf, expected), "memory.max raised"); + } + + if (ASSERT_OK(read_cgroup_file(cg_path, "memory.events", buf, + sizeof(buf)), "read memory.events")) { + ASSERT_OK_PTR(strstr(buf, "oom 1"), "oom event recorded"); + ASSERT_OK_PTR(strstr(buf, "oom_kill 0"), "no task killed"); + } + + /* Verify SYSCALL boundary and negative checks */ + prog_fd = bpf_program__fd(skel->progs.test_raise_max_syscall); + + /* Equal limit must return -EINVAL */ + args.cgroup_id = cg_id; + args.max_bytes = 64 * MB; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_equal")) + ASSERT_EQ((int)topts.retval, -EINVAL, "reject_equal"); + + /* Lower limit must return -EINVAL */ + args.cgroup_id = cg_id; + args.max_bytes = 32 * MB; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_lower")) + ASSERT_EQ((int)topts.retval, -EINVAL, "reject_lower"); + + /* Root memcg must return -EINVAL */ + args.cgroup_id = 0; + args.max_bytes = UINT64_MAX; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_root")) + ASSERT_EQ((int)topts.retval, -EINVAL, "reject_root"); + + /* UINT64_MAX must clamp cleanly to "max" */ + args.cgroup_id = cg_id; + args.max_bytes = UINT64_MAX; + if (ASSERT_OK(bpf_prog_test_run_opts(prog_fd, &topts), "run_max")) + ASSERT_OK((int)topts.retval, "raise_to_max"); + + if (ASSERT_OK(read_cgroup_file(cg_path, "memory.max", buf, sizeof(buf)), + "read memory.max after UINT64_MAX")) + ASSERT_OK_PTR(strstr(buf, "max"), "memory.max unlimited"); + +cleanup: + memory_holder_cleanup(&worker); + bpf_link__destroy(link); + if (cg_fd >= 0) + close(cg_fd); + test_oom_raise_max__destroy(skel); + cleanup_cgroup_environment(); +} diff --git a/tools/testing/selftests/bpf/progs/test_oom_raise_max.c b/tools/testing/selftests/bpf/progs/test_oom_raise_max.c new file mode 100644 index 000000000000..e58e382791aa --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom_raise_max.c @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "vmlinux.h" +#include +#include +#include +#include "test_oom_raise_max.h" + +char _license[] SEC("license") = "GPL"; + +__u64 new_max_bytes; + +SEC("struct_ops.s/handle_out_of_memory") +int BPF_PROG(test_raise_max_oom, struct oom_control *oc, struct cgroup *cgrp) +{ + struct mem_cgroup *memcg = oc->memcg; + + if (!memcg) + return 0; + + if (bpf_mem_cgroup_raise_max(memcg, new_max_bytes)) + return 0; + + return 1; +} + +SEC("syscall") +int test_raise_max_syscall(struct raise_max_args *args) +{ + struct mem_cgroup *memcg; + int ret; + + if (args->cgroup_id) { + struct cgroup *cgrp = bpf_cgroup_from_id(args->cgroup_id); + + if (!cgrp) + return -ENOENT; + memcg = bpf_get_mem_cgroup(&cgrp->self); + bpf_cgroup_release(cgrp); + } else { + memcg = bpf_get_root_mem_cgroup(); + } + + if (!memcg) + return -ENODEV; + + ret = bpf_mem_cgroup_raise_max(memcg, args->max_bytes); + bpf_put_mem_cgroup(memcg); + return ret; +} + +SEC(".struct_ops.link") +struct bpf_oom_ops test_bpf_oom_raise = { + .name = "bpf_oom_raise_max", + .handle_out_of_memory = (void *)test_raise_max_oom, +}; diff --git a/tools/testing/selftests/bpf/progs/test_oom_raise_max.h b/tools/testing/selftests/bpf/progs/test_oom_raise_max.h new file mode 100644 index 000000000000..f25bde9a295a --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom_raise_max.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __TEST_OOM_RAISE_MAX_H +#define __TEST_OOM_RAISE_MAX_H + +struct raise_max_args { + __u64 cgroup_id; + __u64 max_bytes; +}; + +#endif /* __TEST_OOM_RAISE_MAX_H */ -- 2.56.1.911.g883d8bcb20-goog Document BPF OOM policy attachment, execution semantics, and kfuncs in Documentation/bpf/bpf_oom.rst, link it into Documentation/bpf/index.rst, and add it to the BPF OOM entry in MAINTAINERS. Signed-off-by: Ben Gardon --- Documentation/bpf/bpf_oom.rst | 138 ++++++++++++++++++++++++++++++++++ Documentation/bpf/index.rst | 1 + MAINTAINERS | 1 + 3 files changed, 140 insertions(+) create mode 100644 Documentation/bpf/bpf_oom.rst diff --git a/Documentation/bpf/bpf_oom.rst b/Documentation/bpf/bpf_oom.rst new file mode 100644 index 000000000000..5fc63269aec5 --- /dev/null +++ b/Documentation/bpf/bpf_oom.rst @@ -0,0 +1,138 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================ +BPF OOM Handling +================ + +Overview +======== + +Linux supports customizing out-of-memory (OOM) handling with BPF in two ways: + +1. **Reactive OOM policies** via ``struct bpf_oom_ops`` (cgroup-attached + ``struct_ops``) invoked by ``out_of_memory()`` before the kernel's + OOM selector. Policies can choose one or more tasks to terminate, raise + ``memory.max`` on the cgroup, or back off while an existing OOM + target exits. +2. **Proactive OOM invocation and termination** via BPF kfuncs callable + from ``BPF_PROG_TYPE_SYSCALL`` programs and select tracepoints (such as + ``tp_btf/psi_avgs_work_tp``) to trigger OOM handling or directly + terminate a chosen task without a separate userspace OOM daemon. + +BPF OOM handling requires ``CONFIG_CGROUP_BPF=y`` and ``CONFIG_MEMCG=y``. +PSI tracepoint integration additionally requires ``CONFIG_PSI=y`` and +``CONFIG_BPF_EVENTS=y``. + +Attachment and Execution Order +============================== + +A reactive policy defines a ``struct bpf_oom_ops`` map with +``SEC(".struct_ops.link")`` and attaches it to a cgroup v2 directory via +``bpf_map__attach_cgroup_opts()``. + +- Attaching to the root cgroup covers system-wide OOMs as well as + fallback from descendant memory cgroups. +- Effective handlers run from the OOMing memory cgroup upward toward the + root by default, unless an ancestor attaches with ``BPF_F_PREORDER``. +- Multiple links on the same cgroup are allowed; relative ordering + uses ``BPF_F_BEFORE`` / ``BPF_F_AFTER`` with ``BPF_F_LINK`` (and + ``BPF_F_ID`` when specifying ``relative_id``). Do not pass + ``BPF_F_ALLOW_MULTI`` (rejected with ``-EINVAL``). +- Handlers are invoked with ``oom_lock`` held and page faults disabled. +- Returning a positive value signals that the OOM event has been + handled and stops traversal. Returning ``<= 0`` delegates to the + next effective handler and ultimately to the in-kernel OOM handler. +- ``SysRq-f`` (``is_sysrq_oom(oc)``) always bypasses BPF handlers. + +Struct Ops Interface +==================== + +``struct bpf_oom_ops`` (``include/linux/bpf_oom.h``): + +.. code-block:: c + + struct bpf_oom_ops { + int (*handle_out_of_memory)(struct oom_control *oc, + struct cgroup *cgrp); + char name[BPF_OOM_NAME_MAX_LEN]; + }; + +- ``handle_out_of_memory(oc, cgrp)``: Sleepable callback + (``SEC("struct_ops.s/handle_out_of_memory")``). ``oc`` is a read-only + ``struct oom_control *`` whose ``oc->memcg`` field is verified as + ``TRUSTED_OR_NULL`` (``NULL`` for global OOMs, trusted pointer for + memcg OOMs). ``cgrp`` is the cgroup where this policy instance is + attached. ``handle_out_of_memory`` is required and validated at map + load time. +- ``name``: Policy name logged in OOM reports (validated via + ``bpf_obj_name_cpy()``; defaults to ``"bpf_defined_policy"`` if empty). + +BPF Kfuncs +========== + +Kfuncs for ``struct bpf_oom_ops`` +--------------------------------- + +``int bpf_oom_kill_process(struct oom_control *oc, struct task_struct *task, const char *message__str)`` + Sleepable kfunc (restricted via default-deny filter to ``bpf_oom_ops``) + that terminates ``task`` through ``oom_kill_process()``, preserving OOM + logging, memcg ``memory.events`` accounting, asynchronous OOM memory + reclamation, and ``memory.oom.group`` recursive behavior. + + Kernel-enforced constraints: + + - Returns ``-EPERM`` for tasks exempt via ``oom_unkillable_task()`` (such + as ``init`` and kernel threads). + - Returns ``-EINVAL`` if ``task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN`` + (``-1000``), or if ``oc->memcg`` is non-NULL and ``task`` is outside + ``oc->memcg``'s hierarchy. + - Returns ``-ESRCH`` if ``task`` has no live ``mm`` or already has + ``MMF_OOM_SKIP`` set. + +Kfuncs for Proactive OOM (``BPF_PROG_TYPE_SYSCALL`` & ``tp_btf/psi_avgs_work_tp``) +---------------------------------------------------------------------------------- + +Note: ``tp_btf/psi_avgs_work_tp`` runs in non-sleepable tracepoint +context; schedule a sleepable ``bpf_task_work`` or ``bpf_wq`` callback to +invoke sleepable OOM kfuncs from PSI handlers. + +``int bpf_out_of_memory(struct mem_cgroup *memcg__nullable, int order, u64 flags)`` + Acquires ``oom_lock`` (waiting interruptibly for fatal signals if + ``BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK`` is set, else returning ``-EBUSY`` on + contention), accounts ``MEMCG_OOM`` for non-NULL ``memcg``, and runs + ``out_of_memory()``, invoking any attached ``bpf_oom_ops`` policies and + falling back to ``select_bad_process()`` if unhandled. Root ``memcg`` is + normalized to ``NULL``; dying memcgs return ``-EINVAL``. BPF-declared + OOMs do not panic the kernel if no eligible task exists, skip + ``sysctl_oom_kill_allocating_task``, and omit ``dump_header()`` noise. + +``int bpf_oom_proactive_kill(struct mem_cgroup *origin__nullable, struct task_struct *task, const char *message__str, u64 flags)`` + Directly terminates ``task`` outside of an allocation failure without + falling back to ``select_bad_process()``. Synchronizes on ``oom_lock`` + according to ``enum bpf_oom_flags``, applies the same ``-EPERM`` / + ``-EINVAL`` / ``-ESRCH`` protections as ``bpf_oom_kill_process()``, + verifies ``task`` is within ``origin__nullable`` when non-NULL (which + also scopes ``memory.oom.group`` traversal and ``oom_memcg`` logging), + and omits ``dump_header()`` stack/meminfo noise while retaining the + single-line ``oom-kill:`` and ``Killed process`` records. + +Memory Cgroup Kfuncs +-------------------- + +Handlers commonly pair the above with the kfuncs in ``mm/bpf_memcontrol.c``: +``bpf_get_root_mem_cgroup()``, ``bpf_get_mem_cgroup()``, +``bpf_put_mem_cgroup()``, ``bpf_mem_cgroup_usage()``, +``bpf_mem_cgroup_page_state()``, ``bpf_mem_cgroup_vm_events()``, +``bpf_mem_cgroup_memory_events()``, ``bpf_mem_cgroup_flush_stats()``, and: + +``int bpf_mem_cgroup_raise_max(struct mem_cgroup *memcg, u64 max_bytes)`` + Sleepable kfunc that non-destructively raises ``memcg``'s ``memory.max`` + limit to ``max_bytes`` (truncated to ``PAGE_SIZE`` and clamped to + ``PAGE_COUNTER_MAX``, which represents unlimited/``"max"``; callers may + pass ``U64_MAX``). Only strictly higher limits on live, non-root + memory cgroups are accepted (returning ``-EINVAL`` otherwise) so no + reclaim is triggered while holding ``oom_lock``. On cgroup v1, enforces + ``memory.max <= memsw.max``. + +To check whether a task is already exiting due to OOM, read +``BPF_CORE_READ(task, signal, oom_mm) != NULL`` directly via CO-RE. diff --git a/Documentation/bpf/index.rst b/Documentation/bpf/index.rst index 638a00d42bc2..f226cfc41dc7 100644 --- a/Documentation/bpf/index.rst +++ b/Documentation/bpf/index.rst @@ -22,6 +22,7 @@ that goes into great technical depth about the BPF Architecture. kfuncs cpumasks fs_kfuncs + bpf_oom programs maps bpf_prog_run diff --git a/MAINTAINERS b/MAINTAINERS index 8bb61211b7f0..039d934d0a02 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5177,6 +5177,7 @@ M: Shakeel Butt L: bpf@vger.kernel.org L: linux-mm@kvack.org S: Maintained +F: Documentation/bpf/bpf_oom.rst F: include/linux/bpf_oom.h F: mm/bpf_memcontrol.c F: mm/bpf_oom.c -- 2.56.1.911.g883d8bcb20-goog