Linux Documentation
 help / color / mirror / Atom feed
From: Ben Gardon <bgardon@google.com>
To: Alexei Starovoitov <ast@kernel.org>,
	Daniel Borkmann <daniel@iogearbox.net>,
	 Andrii Nakryiko <andrii@kernel.org>,
	Andrew Morton <akpm@linux-foundation.org>,
	 Johannes Weiner <hannes@cmpxchg.org>,
	Michal Hocko <mhocko@kernel.org>,
	 Shakeel Butt <shakeel.butt@linux.dev>,
	Roman Gushchin <roman.gushchin@linux.dev>,
	 Tejun Heo <tj@kernel.org>
Cc: JP Kobryn <jp.kobryn@linux.dev>,
	Eduard Zingerman <eddyz87@gmail.com>,
	 Kumar Kartikeya Dwivedi <memxor@gmail.com>,
	Martin KaFai Lau <martin.lau@linux.dev>,
	Song Liu <song@kernel.org>,
	 Yonghong Song <yonghong.song@linux.dev>,
	Jiri Olsa <jolsa@kernel.org>,
	 Emil Tsalapatis <emil@etsalapatis.com>,
	Ihor Solodrai <ihor.solodrai@linux.dev>,
	 David Rientjes <rientjes@google.com>,
	Suren Baghdasaryan <surenb@google.com>,
	Josh Don <joshdon@google.com>,
	 Sweet Tea Dorminy <sweettea-kernel@dorminy.me>,
	Chuyi Zhou <zhouchuyi@bytedance.com>,
	 Yafang Shao <laoar.shao@gmail.com>,
	benbwgardon@gmail.com, bpf@vger.kernel.org,  linux-mm@kvack.org,
	cgroups@vger.kernel.org, linux-kernel@vger.kernel.org,
	 Ben Gardon <bgardon@google.com>,
	Jonathan Corbet <corbet@lwn.net>,
	 Shuah Khan <skhan@linuxfoundation.org>,
	Randy Dunlap <rdunlap@infradead.org>,
	 linux-doc@vger.kernel.org
Subject: [PATCH bpf-next v4 17/17] Documentation/bpf: Document BPF OOM handling and kfuncs
Date: Wed,  2 Dec 2026 13:04:07 -0800	[thread overview]
Message-ID: <20261202210415.517651-18-bgardon@google.com> (raw)
In-Reply-To: <20261202210415.517651-1-bgardon@google.com>

Document BPF OOM policy attachment, execution semantics, and kfuncs in
Documentation/bpf/bpf_oom.rst, link it into Documentation/bpf/index.rst,
and add it to the BPF OOM entry in MAINTAINERS.

Signed-off-by: Ben Gardon <bgardon@google.com>
---
 Documentation/bpf/bpf_oom.rst | 138 ++++++++++++++++++++++++++++++++++
 Documentation/bpf/index.rst   |   1 +
 MAINTAINERS                   |   1 +
 3 files changed, 140 insertions(+)
 create mode 100644 Documentation/bpf/bpf_oom.rst

diff --git a/Documentation/bpf/bpf_oom.rst b/Documentation/bpf/bpf_oom.rst
new file mode 100644
index 000000000000..5fc63269aec5
--- /dev/null
+++ b/Documentation/bpf/bpf_oom.rst
@@ -0,0 +1,138 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================
+BPF OOM Handling
+================
+
+Overview
+========
+
+Linux supports customizing out-of-memory (OOM) handling with BPF in two ways:
+
+1. **Reactive OOM policies** via ``struct bpf_oom_ops`` (cgroup-attached
+   ``struct_ops``) invoked by ``out_of_memory()`` before the kernel's
+   OOM selector. Policies can choose one or more tasks to terminate, raise
+   ``memory.max`` on the cgroup, or back off while an existing OOM
+   target exits.
+2. **Proactive OOM invocation and termination** via BPF kfuncs callable
+   from ``BPF_PROG_TYPE_SYSCALL`` programs and select tracepoints (such as
+   ``tp_btf/psi_avgs_work_tp``) to trigger OOM handling or directly
+   terminate a chosen task without a separate userspace OOM daemon.
+
+BPF OOM handling requires ``CONFIG_CGROUP_BPF=y`` and ``CONFIG_MEMCG=y``.
+PSI tracepoint integration additionally requires ``CONFIG_PSI=y`` and
+``CONFIG_BPF_EVENTS=y``.
+
+Attachment and Execution Order
+==============================
+
+A reactive policy defines a ``struct bpf_oom_ops`` map with
+``SEC(".struct_ops.link")`` and attaches it to a cgroup v2 directory via
+``bpf_map__attach_cgroup_opts()``.
+
+- Attaching to the root cgroup covers system-wide OOMs as well as
+  fallback from descendant memory cgroups.
+- Effective handlers run from the OOMing memory cgroup upward toward the
+  root by default, unless an ancestor attaches with ``BPF_F_PREORDER``.
+- Multiple links on the same cgroup are allowed; relative ordering
+  uses ``BPF_F_BEFORE`` / ``BPF_F_AFTER`` with ``BPF_F_LINK`` (and
+  ``BPF_F_ID`` when specifying ``relative_id``). Do not pass
+  ``BPF_F_ALLOW_MULTI`` (rejected with ``-EINVAL``).
+- Handlers are invoked with ``oom_lock`` held and page faults disabled.
+- Returning a positive value signals that the OOM event has been
+  handled and stops traversal. Returning ``<= 0`` delegates to the
+  next effective handler and ultimately to the in-kernel OOM handler.
+- ``SysRq-f`` (``is_sysrq_oom(oc)``) always bypasses BPF handlers.
+
+Struct Ops Interface
+====================
+
+``struct bpf_oom_ops`` (``include/linux/bpf_oom.h``):
+
+.. code-block:: c
+
+    struct bpf_oom_ops {
+        int (*handle_out_of_memory)(struct oom_control *oc,
+                                    struct cgroup *cgrp);
+        char name[BPF_OOM_NAME_MAX_LEN];
+    };
+
+- ``handle_out_of_memory(oc, cgrp)``: Sleepable callback
+  (``SEC("struct_ops.s/handle_out_of_memory")``). ``oc`` is a read-only
+  ``struct oom_control *`` whose ``oc->memcg`` field is verified as
+  ``TRUSTED_OR_NULL`` (``NULL`` for global OOMs, trusted pointer for
+  memcg OOMs). ``cgrp`` is the cgroup where this policy instance is
+  attached. ``handle_out_of_memory`` is required and validated at map
+  load time.
+- ``name``: Policy name logged in OOM reports (validated via
+  ``bpf_obj_name_cpy()``; defaults to ``"bpf_defined_policy"`` if empty).
+
+BPF Kfuncs
+==========
+
+Kfuncs for ``struct bpf_oom_ops``
+---------------------------------
+
+``int bpf_oom_kill_process(struct oom_control *oc, struct task_struct *task, const char *message__str)``
+  Sleepable kfunc (restricted via default-deny filter to ``bpf_oom_ops``)
+  that terminates ``task`` through ``oom_kill_process()``, preserving OOM
+  logging, memcg ``memory.events`` accounting, asynchronous OOM memory
+  reclamation, and ``memory.oom.group`` recursive behavior.
+
+  Kernel-enforced constraints:
+
+  - Returns ``-EPERM`` for tasks exempt via ``oom_unkillable_task()`` (such
+    as ``init`` and kernel threads).
+  - Returns ``-EINVAL`` if ``task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN``
+    (``-1000``), or if ``oc->memcg`` is non-NULL and ``task`` is outside
+    ``oc->memcg``'s hierarchy.
+  - Returns ``-ESRCH`` if ``task`` has no live ``mm`` or already has
+    ``MMF_OOM_SKIP`` set.
+
+Kfuncs for Proactive OOM (``BPF_PROG_TYPE_SYSCALL`` & ``tp_btf/psi_avgs_work_tp``)
+----------------------------------------------------------------------------------
+
+Note: ``tp_btf/psi_avgs_work_tp`` runs in non-sleepable tracepoint
+context; schedule a sleepable ``bpf_task_work`` or ``bpf_wq`` callback to
+invoke sleepable OOM kfuncs from PSI handlers.
+
+``int bpf_out_of_memory(struct mem_cgroup *memcg__nullable, int order, u64 flags)``
+  Acquires ``oom_lock`` (waiting interruptibly for fatal signals if
+  ``BPF_OOM_FLAGS_WAIT_ON_OOM_LOCK`` is set, else returning ``-EBUSY`` on
+  contention), accounts ``MEMCG_OOM`` for non-NULL ``memcg``, and runs
+  ``out_of_memory()``, invoking any attached ``bpf_oom_ops`` policies and
+  falling back to ``select_bad_process()`` if unhandled. Root ``memcg`` is
+  normalized to ``NULL``; dying memcgs return ``-EINVAL``. BPF-declared
+  OOMs do not panic the kernel if no eligible task exists, skip
+  ``sysctl_oom_kill_allocating_task``, and omit ``dump_header()`` noise.
+
+``int bpf_oom_proactive_kill(struct mem_cgroup *origin__nullable, struct task_struct *task, const char *message__str, u64 flags)``
+  Directly terminates ``task`` outside of an allocation failure without
+  falling back to ``select_bad_process()``. Synchronizes on ``oom_lock``
+  according to ``enum bpf_oom_flags``, applies the same ``-EPERM`` /
+  ``-EINVAL`` / ``-ESRCH`` protections as ``bpf_oom_kill_process()``,
+  verifies ``task`` is within ``origin__nullable`` when non-NULL (which
+  also scopes ``memory.oom.group`` traversal and ``oom_memcg`` logging),
+  and omits ``dump_header()`` stack/meminfo noise while retaining the
+  single-line ``oom-kill:`` and ``Killed process`` records.
+
+Memory Cgroup Kfuncs
+--------------------
+
+Handlers commonly pair the above with the kfuncs in ``mm/bpf_memcontrol.c``:
+``bpf_get_root_mem_cgroup()``, ``bpf_get_mem_cgroup()``,
+``bpf_put_mem_cgroup()``, ``bpf_mem_cgroup_usage()``,
+``bpf_mem_cgroup_page_state()``, ``bpf_mem_cgroup_vm_events()``,
+``bpf_mem_cgroup_memory_events()``, ``bpf_mem_cgroup_flush_stats()``, and:
+
+``int bpf_mem_cgroup_raise_max(struct mem_cgroup *memcg, u64 max_bytes)``
+  Sleepable kfunc that non-destructively raises ``memcg``'s ``memory.max``
+  limit to ``max_bytes`` (truncated to ``PAGE_SIZE`` and clamped to
+  ``PAGE_COUNTER_MAX``, which represents unlimited/``"max"``; callers may
+  pass ``U64_MAX``). Only strictly higher limits on live, non-root
+  memory cgroups are accepted (returning ``-EINVAL`` otherwise) so no
+  reclaim is triggered while holding ``oom_lock``. On cgroup v1, enforces
+  ``memory.max <= memsw.max``.
+
+To check whether a task is already exiting due to OOM, read
+``BPF_CORE_READ(task, signal, oom_mm) != NULL`` directly via CO-RE.
diff --git a/Documentation/bpf/index.rst b/Documentation/bpf/index.rst
index 638a00d42bc2..f226cfc41dc7 100644
--- a/Documentation/bpf/index.rst
+++ b/Documentation/bpf/index.rst
@@ -22,6 +22,7 @@ that goes into great technical depth about the BPF Architecture.
    kfuncs
    cpumasks
    fs_kfuncs
+   bpf_oom
    programs
    maps
    bpf_prog_run
diff --git a/MAINTAINERS b/MAINTAINERS
index 8bb61211b7f0..039d934d0a02 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -5177,6 +5177,7 @@ M:	Shakeel Butt <shakeel.butt@linux.dev>
 L:	bpf@vger.kernel.org
 L:	linux-mm@kvack.org
 S:	Maintained
+F:	Documentation/bpf/bpf_oom.rst
 F:	include/linux/bpf_oom.h
 F:	mm/bpf_memcontrol.c
 F:	mm/bpf_oom.c
-- 
2.56.1.911.g883d8bcb20-goog


           reply	other threads:[~2026-12-02 21:04 UTC|newest]

Thread overview: expand[flat|nested]  mbox.gz  Atom feed
 [parent not found: <20261202210415.517651-1-bgardon@google.com>]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261202210415.517651-18-bgardon@google.com \
    --to=bgardon@google.com \
    --cc=akpm@linux-foundation.org \
    --cc=andrii@kernel.org \
    --cc=ast@kernel.org \
    --cc=benbwgardon@gmail.com \
    --cc=bpf@vger.kernel.org \
    --cc=cgroups@vger.kernel.org \
    --cc=corbet@lwn.net \
    --cc=daniel@iogearbox.net \
    --cc=eddyz87@gmail.com \
    --cc=emil@etsalapatis.com \
    --cc=hannes@cmpxchg.org \
    --cc=ihor.solodrai@linux.dev \
    --cc=jolsa@kernel.org \
    --cc=joshdon@google.com \
    --cc=jp.kobryn@linux.dev \
    --cc=laoar.shao@gmail.com \
    --cc=linux-doc@vger.kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-mm@kvack.org \
    --cc=martin.lau@linux.dev \
    --cc=memxor@gmail.com \
    --cc=mhocko@kernel.org \
    --cc=rdunlap@infradead.org \
    --cc=rientjes@google.com \
    --cc=roman.gushchin@linux.dev \
    --cc=shakeel.butt@linux.dev \
    --cc=skhan@linuxfoundation.org \
    --cc=song@kernel.org \
    --cc=surenb@google.com \
    --cc=sweettea-kernel@dorminy.me \
    --cc=tj@kernel.org \
    --cc=yonghong.song@linux.dev \
    --cc=zhouchuyi@bytedance.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox