Skip to contentSkip to conversation

mm: BPF struct_ops for dynamic memory protection and async reclaim

RFC PATCH In review Hui Zhu 7 participants 34 messages May 26 – May 28

Subsystems (11)
lore
Share & tools
lore

Hui Zhu

author
#0 lore raw

v7 cover mm: BPF struct_ops for dynamic memory protection and async reclaim

From: Hui Zhu <[email protected]>

Overview:
This series introduces BPF struct_ops support for the memory controller, enabling userspace BPF programs to implement custom, dynamic memory management policies per cgroup. The feature allows BPF programs to hook into the core reclaim and charge paths without requiring kernel modifications, providing a flexible alternative to static knobs such as memory.low and memory.min.

The series enables two complementary use cases.

Dynamic memory protection: static memory protection thresholds (memory.low, memory.min) are poor fits for workloads whose actual memory activity varies over time. A high-priority cgroup holding a large working set but temporarily idle will still suppress reclaim on its siblings, wasting available memory. A BPF-driven approach can observe real workload activity -- page faults, charge/uncharge events -- and activate or withdraw protection dynamically. The test results at the end of this letter quantify the difference: in a scenario where the high-priority cgroup is idle, the BPF-controlled low-priority cgroup achieves roughly 37x higher throughput than with static memory.low.

Asynchronous proactive reclaim: the memcg_charged and memcg_uncharged hooks, combined with the BPF workqueue mechanism and the new bpf_try_to_free_mem_cgroup_pages() kfunc, enable BPF programs to perform proactive background reclaim without blocking the charge path. The pattern works as follows: the memcg_charged callback tracks accumulated memory usage; when usage crosses a configurable threshold, it enqueues an asynchronous work item via bpf_wq_start() and returns immediately without throttling the charging task. The workqueue callback then invokes bpf_try_to_free_mem_cgroup_pages() to reclaim pages from the target cgroup; if usage remains elevated after reclaim, the callback re-enqueues itself to continue. This allows a BPF program to keep a cgroup's footprint below its hard limit (memory.max) entirely in the background, avoiding the OOM killer or direct-reclaim stalls that would otherwise occur. The selftest for this feature (patch 10/11) validates the mechanism concretely: a workload that writes and mmaps a 64 MB file inside a 32 MB cgroup reliably triggers memory.events "max" events without BPF; with the async reclaim program attached, the "max" counter does not increase at all across the same workload.

In this patch series, I've incorporated a portion of Roman's patch in
[1] to ensure the entire series can be compiled cleanly with bpf-next.

Patch Breakdown:
Patches 1-4 are from Roman Gushchin's series [1], included here to provide the necessary BPF infrastructure for attaching struct_ops to cgroups.

Patches 5-11 are the new work in this series:

05/11 bpf: Pass flags in bpf_link_create for struct_ops
Stores attr->link_create.flags in struct bpf_struct_ops_link and extends the validation to allow BPF_F_ALLOW_OVERRIDE. Also updates the UAPI comment to reflect that cgroup-bpf attach flags now apply to BPF_LINK_CREATE in addition to BPF_PROG_ATTACH.

06/11 mm: memcontrol: Add BPF struct_ops for memory controller
The core feature patch. Introduces the memcg_bpf_ops struct_ops type with the following hooks:

- memcg_charged(memcg, batch): called on the synchronous charge path. Returns a throttling delay in milliseconds; used as a lower bound for __mem_cgroup_handle_over_high(), effective even when memory.high is not breached.

- memcg_uncharged(memcg, batch): called on uncharge, allowing BPF programs to track memory releases.

- below_low(memcg, elow, usage): overrides the memory.low protection check. Returns true to treat the cgroup as protected regardless of the elow >= usage comparison.

- below_min(memcg, emin, usage): same as below_low but for memory.min protection.

- handle_cgroup_online/offline(memcg): lifecycle callbacks for per-cgroup state management in BPF programs.

BPF_F_ALLOW_OVERRIDE is supported: when a program is registered with this flag, descendant cgroups may attach their own memcg_bpf_ops to override the inherited policy. Registration propagates ops down through the subtree via mem_cgroup_iter; unregistration restores each descendant to the ops its registering ancestor's parent held, correctly preserving override chains.

07/11 mm/bpf: Add bpf_try_to_free_mem_cgroup_pages kfunc
Exposes try_to_free_mem_cgroup_pages() to BPF programs as a KF_SLEEPABLE kfunc. A swappiness parameter controls the override value passed to the core reclaim path (effective only when MEMCG_RECLAIM_PROACTIVE is set in reclaim_options).

08/11 selftests/bpf: Add tests for memcg_bpf_ops
Adds prog_tests/memcg_ops.c covering three scenarios:
memcg_charged-only throttling, below_low + memcg_charged interaction, and below_min + memcg_charged interaction. A tracepoint on memcg:count_memcg_events (PGFAULT) is used to detect memory pressure and trigger hooks accordingly.

09/11 selftests/bpf: Add test for memcg_bpf_ops hierarchies
Validates BPF_F_ALLOW_OVERRIDE attachment semantics across a three-level cgroup hierarchy: attach with ALLOW_OVERRIDE at the root, override at the middle level without the flag, then assert that attaching to the leaf correctly fails with -EBUSY.

10/11 selftests/bpf: Add selftest for memcg async reclaim via BPF
Demonstrates and validates asynchronous memory reclaim: a BPF program uses the memcg_charged/memcg_uncharged hooks to track accumulated usage and, when a threshold is exceeded, enqueues a bpf_wq_start() workqueue item that calls bpf_try_to_free_mem_cgroup_pages() without blocking the charge path. The test asserts that with the BPF program active, memory.events "max" events do not increase under a workload that would otherwise exceed the hard limit.

11/11 samples/bpf: Add memcg priority control and async reclaim example
Adds a complete sample (samples/bpf/memcg.bpf.c + memcg.c) demonstrating both features. The BPF side monitors PGFAULT events on a high-priority cgroup; when the per-second fault count crosses a configurable threshold, it activates below_low or below_min protection for the high-priority cgroup and/or applies a charge delay to the low-priority cgroup. Six struct_ops variants are exported so userspace can attach only the hooks needed. Async reclaim is optionally combined with priority throttling via a shared low-cgroup ops map.

Test Environment:
The following examples run on x86_64 QEMU (10 CPUs, 2 GB RAM), using a tmpfs-backed file on the host as a swap device to reduce I/O impact. Two cgroups are created -- high (high-priority) and low (low-priority) -- and each test runs two concurrent stress-ng workloads, one per cgroup, each requesting 3 GB of memory.

  # mkdir /sys/fs/cgroup/high /sys/fs/cgroup/low
  # free -h
                 total   used    free  shared  buff/cache  available
  Mem:           1.9Gi  317Mi  1.6Gi   1.0Mi       144Mi      1.6Gi
  Swap:          4.0Gi     0B  4.0Gi

Baseline: no memory priority policy:
Both cgroups run without any reclaim protection. Results are roughly equal, as expected:

cgroup bogo ops/s
high 4,979
low 4,927

Test 1: memory.low protection:
Setting memory.low on the high-priority cgroup protects it from reclaim, at the cost of pushing reclaim pressure onto the low-priority cgroup:

  # echo $((3 * 1024 * 1024 * 1024)) > /sys/fs/cgroup/high/memory.low

cgroup bogo ops/s
high 450,290
low 11,307

The high-priority cgroup benefits significantly, but memory.low relies on static usage thresholds and cannot adapt to actual workload behavior.

Test 2: memory.low with an idle high-priority task:
Here the high-priority cgroup runs a Python script that allocates 3 GB and then sleeps, simulating a low-activity but memory-holding workload. Because the process is idle, it generates no page faults and does not actively use its memory. Yet memory.low still protects it, continuing to suppress the low-priority cgroup's performance:

cgroup bogo ops/s
low 14,757

The low-priority cgroup remains significantly throttled despite the high-priority cgroup being effectively idle -- a clear limitation of static memory.low control.

Test 3: memcg eBPF -- dynamic priority control:
memcg is a sample program introduced in this patch series (samples/bpf/memcg.c + memcg.bpf.c). It loads a BPF program that monitors PGFAULT events in the high-priority cgroup. When the per-second fault count exceeds a configured threshold, the hook activates below_min protection for one second; otherwise the cgroup receives no special treatment.

  # ./memcg --low_path=/sys/fs/cgroup/low  \
            --high_path=/sys/fs/cgroup/high \
            --threshold=1 --use_below_min
  Successfully attached!

3a. Both cgroups under active memory pressure:

When both cgroups run stress-ng, the high-priority cgroup generates frequent page faults and the BPF hook activates protection, matching the behavior of memory.low:

cgroup bogo ops/s
high 404,392
low 11,404

3b. High-priority cgroup is idle (Python + sleep):

Because the sleeping Python process generates no page faults, the BPF hook never activates, and the low-priority cgroup is free to reclaim memory normally:

cgroup bogo ops/s
low 551,083

This is a ~37x improvement over the equivalent memory.low scenario (Test 2), demonstrating that eBPF-driven dynamic control can accurately reflect actual workload activity and avoid unnecessary protection of idle high-priority tasks.

Summary:
Scenario low-cgroup bogo ops/s
Baseline (no policy) ~4,927

  memory.low, both active                       ~11,307
  memory.low, high idle                         ~14,757
  memcg eBPF, both active                       ~11,404

memcg eBPF, high idle ~551,083

References:
[1] https://patchew.org/linux/[email protected]/

Changelog:
v7:
Change base commits of "mm: BPF OOM" to v3.
Some fixes according to the comments of bpf-ci.
Rename get_high_delay_ms hook to memcg_charged; add memcg_uncharged hook for tracking uncharge events.
Update below_low and below_min hooks to receive elow/emin and usage as explicit arguments.
Add bpf_try_to_free_mem_cgroup_pages kfunc to expose cgroup reclaim to BPF programs.
Add selftest for BPF-driven asynchronous page reclaim.
Extend samples/bpf/memcg to support async reclaim in addition to priority throttling.
v6:
Based on the bot+bof-ci comments, fixed the following issues. Added fast-path check with unlikely() before SRCU lock acquisition to optimize the no-BPF case in BPF_MEMCG_CALL.
Add missing newline in pr_warn message to bpf_memcontrol_init. Added comprehensive child process exit status checking with WIFEXITED() and WEXITSTATUS(), and added zombie process prevention in real_test_memcg_ops.
Changed malloc() to calloc() for BSS data allocation in all test functions and samples main function.
Change srcu_read_lock(&memcg_bpf_srcu) to lockdep_assert_held(&cgroup_mutex) in function memcontrol_bpf_online and memcontrol_bpf_offline.
v5:
Based on the bot+bof-ci comments, fixed the following issues. Fixed issues in memcg_ops.c and memcg.bpf.c by moving variable declaration to the beginning of need_threshold() function.
The 'u64 current_ts' variable must be declared before any executable statements
Improved input validation in samples/bpf/memcg.c by adding a new parse_u64() helper function. This function properly handles errors from strtoull() and provides better error messages when parsing threshold and over_high_ms command-line arguments.
Move check for prog->sleepable after validating member offsets in mm/bpf_memcontrol.c bpf_memcg_ops_check_member.
Fixed sscanf return value checking in prog_tests/memcg_ops.c. Changed the condition from 'sscanf() < 0' to 'sscanf() != 1' because sscanf returns the number of successfully matched items, not a negative value on error. This makes the test more reliable when reading timing data from temporary files.
v4:
Fix the issues according to the comments from bot+bof-ci. According to JP Kobryn's comments, move exit(0) from real_test_memcg_ops_child_work to real_test_memcg_ops.
Fix issues in the bpf_memcg_ops_reg function.
v3:
According to the comments from Michal Koutný and Chen Ridong, update hooks to get_high_delay_ms, below_low, below_min, handle_cgroup_online, and handle_cgroup_offline.
According to Michal Koutný's comments, add BPF_F_ALLOW_OVERRIDE support to memcg_bpf_ops.
v2:
According to Tejun Heo's comments, rebased on Roman Gushchin's BPF OOM patch series [1] and added hierarchical delegation support. According to the comments from Roman Gushchin and Michal Hocko, designed concrete use case scenarios and provided test results.

Hui Zhu (7):
bpf: Pass flags in bpf_link_create for struct_ops
mm: memcontrol: Add BPF struct_ops for memory controller mm/bpf: Add bpf_try_to_free_mem_cgroup_pages kfunc selftests/bpf: Add tests for memcg_bpf_ops selftests/bpf: Add test for memcg_bpf_ops hierarchies selftests/bpf: Add selftest for memcg async reclaim via BPF samples/bpf: Add memcg priority control and async reclaim example

Roman Gushchin (4):
bpf: move bpf_struct_ops_link into bpf.h
bpf: allow attaching struct_ops to cgroups
libbpf: fix return value on memory allocation failure
libbpf: introduce bpf_map__attach_struct_ops_opts()

 MAINTAINERS                                   |   6 +
 include/linux/bpf-cgroup-defs.h               |   3 +
 include/linux/bpf-cgroup.h                    |  16 +
 include/linux/bpf.h                           |  10 +
 include/linux/memcontrol.h                    | 250 ++++++-
 include/uapi/linux/bpf.h                      |   5 +-
 kernel/bpf/bpf_struct_ops.c                   |  67 +-
 kernel/bpf/cgroup.c                           |  46 ++
 mm/bpf_memcontrol.c                           | 355 +++++++++-
 mm/memcontrol.c                               |  43 +-
 samples/bpf/.gitignore                        |   1 +
 samples/bpf/Makefile                          |   8 +-
 samples/bpf/memcg.bpf.c                       | 380 +++++++++++
 samples/bpf/memcg.c                           | 411 ++++++++++++
 tools/include/uapi/linux/bpf.h                |   3 +-
 tools/lib/bpf/libbpf.c                        |  22 +-
 tools/lib/bpf/libbpf.h                        |  14 +
 tools/lib/bpf/libbpf.map                      |   1 +
 tools/testing/selftests/bpf/cgroup_helpers.c  |  41 ++
 tools/testing/selftests/bpf/cgroup_helpers.h  |   2 +
 .../bpf/prog_tests/memcg_async_reclaim.c      | 333 +++++++++
 .../selftests/bpf/prog_tests/memcg_ops.c      | 634 ++++++++++++++++++
 .../selftests/bpf/progs/memcg_async_reclaim.c | 203 ++++++
 tools/testing/selftests/bpf/progs/memcg_ops.c | 132 ++++
 24 files changed, 2952 insertions(+), 34 deletions(-)
 create mode 100644 samples/bpf/memcg.bpf.c
 create mode 100644 samples/bpf/memcg.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_ops.c
 create mode 100644 tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
 create mode 100644 tools/testing/selftests/bpf/progs/memcg_ops.c
Signature · 1 line
2.43.0
author
#1 lore raw

RFC PATCH v7 1/11 bpf: move bpf_struct_ops_link into bpf.h

From: Roman Gushchin <[email protected]>

Move struct bpf_struct_ops_link's definition into bpf.h, where other custom bpf links definitions are.

It's necessary to access its members from outside of generic bpf_struct_ops implementation, which will be done by following patches in the series.

---
 include/linux/bpf.h         | 6 ++++++
 kernel/bpf/bpf_struct_ops.c | 6 ------
 2 files changed, 6 insertions(+), 6 deletions(-)
include/linux/bpf.h +6 -0
index 1b28cacc3075..01c0bf5a9cd0 100644
@@ -1908,6 +1908,12 @@ struct bpf_raw_tp_link {
 	u64 cookie;
 };
 
+struct bpf_struct_ops_link {
+	struct bpf_link link;
+	struct bpf_map __rcu *map;
+	wait_queue_head_t wait_hup;
+};
+
 struct bpf_link_primer {
 	struct bpf_link *link;
 	struct file *file;
kernel/bpf/bpf_struct_ops.c +0 -6
index 521cb9d7e8c7..cf3c604d48ef 100644
@@ -55,12 +55,6 @@ struct bpf_struct_ops_map {
 	struct bpf_struct_ops_value kvalue;
 };
 
-struct bpf_struct_ops_link {
-	struct bpf_link link;
-	struct bpf_map __rcu *map;
-	wait_queue_head_t wait_hup;
-};
-
 static DEFINE_MUTEX(update_mutex);
 
 #define VALUE_PREFIX "bpf_struct_ops_"
Signature · 1 line
2.43.0
author
#2 lore raw

RFC PATCH v7 2/11 bpf: allow attaching struct_ops to cgroups

In reply to Hui Zhu

From: Roman Gushchin <[email protected]>

Introduce an ability to attach bpf struct_ops'es to cgroups.

Quoted 1 line

From user's standpoint it works in the following way:

a user passes a BPF_F_CGROUP_FD flag and specifies the target cgroup fd while creating a struct_ops link. As the result, the bpf struct_ops link will be created and attached to a cgroup.

The cgroup.bpf structure maintains a list of attached struct ops links. If the cgroup is getting deleted, attached struct ops'es are getting auto-detached and the userspace program gets a notification.

This change doesn't answer the question how bpf programs belonging to these struct ops'es will be executed. It will be done individually for every bpf struct ops which supports this.

Please, note that unlike "normal" bpf programs, struct ops'es are not propagated to cgroup sub-trees.

---
 include/linux/bpf-cgroup-defs.h |  3 ++
 include/linux/bpf-cgroup.h      | 16 +++++++++
 include/linux/bpf.h             |  3 ++
 include/uapi/linux/bpf.h        |  3 ++
 kernel/bpf/bpf_struct_ops.c     | 59 ++++++++++++++++++++++++++++++---
 kernel/bpf/cgroup.c             | 46 +++++++++++++++++++++++++
 tools/include/uapi/linux/bpf.h  |  1 +
 7 files changed, 127 insertions(+), 4 deletions(-)
include/linux/bpf-cgroup-defs.h +3 -0
index c9e6b26abab6..6c5e37190dad 100644
@@ -71,6 +71,9 @@ struct cgroup_bpf {
 	/* temp storage for effective prog array used by prog_attach/detach */
 	struct bpf_prog_array *inactive;
 
+	/* list of bpf struct ops links */
+	struct list_head struct_ops_links;
+
 	/* reference counter used to detach bpf programs after cgroup removal */
 	struct percpu_ref refcnt;
 
include/linux/bpf-cgroup.h +16 -0
index b2e79c2b41d5..88b643568012 100644
@@ -423,6 +423,11 @@ int cgroup_bpf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog);
 int cgroup_bpf_prog_query(const union bpf_attr *attr,
 			  union bpf_attr __user *uattr);
 
+int cgroup_bpf_attach_struct_ops(struct cgroup *cgrp,
+				 struct bpf_struct_ops_link *link);
+void cgroup_bpf_detach_struct_ops(struct cgroup *cgrp,
+				  struct bpf_struct_ops_link *link);
+
 const struct bpf_func_proto *
 cgroup_common_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog);
 #else
@@ -451,6 +456,17 @@ static inline int cgroup_bpf_link_attach(const union bpf_attr *attr,
 	return -EINVAL;
 }
 
+static inline int cgroup_bpf_attach_struct_ops(struct cgroup *cgrp,
+					       struct bpf_struct_ops_link *link)
+{
+	return -EINVAL;
+}
+
+static inline void cgroup_bpf_detach_struct_ops(struct cgroup *cgrp,
+						struct bpf_struct_ops_link *link)
+{
+}
+
 static inline int cgroup_bpf_prog_query(const union bpf_attr *attr,
 					union bpf_attr __user *uattr)
 {
include/linux/bpf.h +3 -0
index 01c0bf5a9cd0..743b4f0546b5 100644
@@ -1911,6 +1911,9 @@ struct bpf_raw_tp_link {
 struct bpf_struct_ops_link {
 	struct bpf_link link;
 	struct bpf_map __rcu *map;
+	struct cgroup *cgroup;
+	bool cgroup_removed;
+	struct list_head list;
 	wait_queue_head_t wait_hup;
 };
 
include/uapi/linux/bpf.h +3 -0
index aec171ccb6ef..f547613986cc 100644
@@ -1246,6 +1246,7 @@ enum bpf_perf_event_type {
 #define BPF_F_AFTER		(1U << 4)
 #define BPF_F_ID		(1U << 5)
 #define BPF_F_PREORDER		(1U << 6)
+#define BPF_F_CGROUP_FD		(1U << 7)
 #define BPF_F_LINK		BPF_F_LINK /* 1 << 13 */
 
 /* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the
@@ -6793,6 +6794,8 @@ struct bpf_link_info {
 		} xdp;
 		struct {
 			__u32 map_id;
+			__u32 :32;
+			__u64 cgroup_id;
 		} struct_ops;
 		struct {
 			__u32 pf;
kernel/bpf/bpf_struct_ops.c +55 -4

135 lines not on this page · raw message

kernel/bpf/cgroup.c +46 -0

79 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +1 -0
index 37142e6d911a..fa075dc3b7eb 100644
@@ -1246,6 +1246,7 @@ enum bpf_perf_event_type {
 #define BPF_F_AFTER		(1U << 4)
 #define BPF_F_ID		(1U << 5)
 #define BPF_F_PREORDER		(1U << 6)
+#define BPF_F_CGROUP_FD		(1U << 7)
 #define BPF_F_LINK		BPF_F_LINK /* 1 << 13 */
 
 /* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the
Signature · 1 line
2.43.0
#3 lore raw

Re: [RFC PATCH bpf-next v7 02/11] bpf: allow attaching struct_ops to cgroups

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] Concurrent execution of cgroup release and link deallocation leads to critical Use-After-Free.…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] Concurrent execution of cgroup release and link deallocation leads to critical Use-After-Free.
- [Critical] Premature publication of the link in the bpf_struct_ops_link_create() error path causes a Use-After-Free if initialization fails.
- [High] A race condition between link creation and cgroup release allows a struct_ops link to bypass auto-detachment when its cgroup is deleted.
- [Medium] Links that survive cgroup_bpf_release() retain list pointers pointing to a destroyed stack frame.
--

commit 4637164a31e8f2395a0e21ae383236036263c3ba
Author: Roman Gushchin <[email protected]>

bpf: allow attaching struct_ops to cgroups

This commit introduces the ability to attach bpf struct_ops to cgroups using the BPF_F_CGROUP_FD flag. The cgroup maintains a list of attached links, which are auto-detached when the cgroup is deleted.

Quoted 5 lines
kernel/bpf/bpf_struct_ops.c +0 -0
index 7ad3b1a49dee8..e63f926d87283 100644

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_link_dealloc(struct bpf_link *link) · line 1266

Quoted 9 lines
kernel/bpf/bpf_struct_ops.c +4 -0
@@ -1256,6 +1258,10 @@ static void bpf_struct_ops_map_link_dealloc(struct bpf_link *link)
 		st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, link);
 		bpf_map_put(&st_map->map);
 	}
+
+	if (st_link->cgroup)
+		cgroup_bpf_detach_struct_ops(st_link->cgroup, st_link);
+
 	kfree(st_link);
 }

[Severity: Critical]
Can this cause a use-after-free if it races with cgroup_bpf_release()?

If a link's file descriptor is closed, this function runs concurrently with cgroup release. cgroup_bpf_release() iterates over the links holding cgroup_lock, sets st_link->cgroup to NULL, and increments their refcount.

If dealloc() checks st_link->cgroup without a lock and sees NULL, it will bypass cgroup_bpf_detach_struct_ops() and proceed directly to kfree(st_link). Meanwhile, cgroup_bpf_release() continues operating on the freed memory.

A similar race appears to exist in bpf_struct_ops_map_link_detach().

[ ... ]

Quoted 11 lines
kernel/bpf/bpf_struct_ops.c +7 -0
@@ -1414,11 +1447,26 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 	bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_map_lops, NULL,
 		      attr->link_create.attach_type);
 
+	init_waitqueue_head(&link->wait_hup);
+
+	if (attr->link_create.flags & BPF_F_CGROUP_FD) {
+		cgrp = cgroup_get_from_fd(attr->link_create.target_fd);
+		if (IS_ERR(cgrp)) {
+			err = PTR_ERR(cgrp);
+			goto err_out;

kernel/bpf/bpf_struct_ops.c int bpf_struct_ops_link_create(union bpf_attr *attr) · line 1466

Quoted 10 lines
kernel/bpf/bpf_struct_ops.c +10 -0
+		}
+		link->cgroup = cgrp;
+		err = cgroup_bpf_attach_struct_ops(cgrp, link);
+		if (err) {
+			cgroup_put(cgrp);
+			link->cgroup = NULL;
+			goto err_out;
+		}
+	}
+

[Severity: High]
Could this allow a struct_ops link to bypass auto-detachment?

The link is published to the cgroup list here before link->map is initialized and the program is fully registered. If the cgroup is deleted during this narrow window, cgroup_bpf_release() will attempt to detach all links.

Because bpf_struct_ops_map_link_detach() observes link->map as NULL, it might silently return 0 and fail to unregister the link. When this create function resumes, it will fully register the program and initialize link->map, leaving the link active in the kernel despite its cgroup being destroyed.

Quoted 6 lines
kernel/bpf/bpf_struct_ops.c +1 -3
 	err = bpf_link_prime(&link->link, &link_primer);
 	if (err)
-		goto err_out;
-
-	init_waitqueue_head(&link->wait_hup);
+		goto err_put_cgroup;

[ ... ]

Quoted 8 lines
kernel/bpf/bpf_struct_ops.c +1 -1
@@ -1429,13 +1477,16 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 		mutex_unlock(&update_mutex);
 		bpf_link_cleanup(&link_primer);
 		link = NULL;
-		goto err_out;
+		goto err_put_cgroup;
 	}
 	RCU_INIT_POINTER(link->map, map);

kernel/bpf/bpf_struct_ops.c int bpf_struct_ops_link_create(union bpf_attr *attr) · line 1492

Quoted 10 lines
kernel/bpf/bpf_struct_ops.c +3 -0
 	mutex_unlock(&update_mutex);
 
 	return bpf_link_settle(&link_primer);
 
+err_put_cgroup:
+	if (link && link->cgroup)
+		cgroup_bpf_detach_struct_ops(link->cgroup, link);
 err_out:
 	bpf_map_put(map);
 	kfree(link);

[Severity: Critical]
Is it safe to directly kfree(link) here after it was published?

If initialization fails, the code jumps to err_put_cgroup and eventually calls kfree(link). However, since the link was made visible to the cgroup earlier, a concurrent cgroup_bpf_release() could have already observed it, grabbed a reference, and queued it for detachment.

If cgroup_bpf_release() already set link->cgroup to NULL, the cleanup bypasses cgroup_bpf_detach_struct_ops(), leading to a direct kfree() while the release path still holds a reference. This will cause a use-after-free when the release path later calls link->ops->detach().

Quoted 5 lines
kernel/bpf/cgroup.c +0 -0
index 876f6a81a9b61..b593ebb30a4e0 100644
@@ -307,12 +308,23 @@ static void cgroup_bpf_release(struct work_struct *work)

[ ... ]

kernel/bpf/cgroup.c static void cgroup_bpf_release(struct work_struct *work) · line 367

Quoted 11 lines
kernel/bpf/cgroup.c +5 -0
@@ -346,6 +358,11 @@ static void cgroup_bpf_release(struct work_struct *work)
 
 	cgroup_unlock();
 
+	list_for_each_entry_safe(st_link, st_tmp, &st_links, list) {
+		st_link->link.ops->detach(&st_link->link);
+		bpf_link_put(&st_link->link);
+	}
+
 	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
 		cgroup_bpf_put(p);

[Severity: Medium]
Should these links be removed from the list before putting them?

The st_links list head is a local stack variable in this function. Links that survive this function (kept alive by userspace file descriptors) are never removed from this list via list_del().

This means the long-lived st_link objects retain list.next and list.prev pointers that point to a destroyed stack frame, which could leak stack addresses or cause memory corruption if the list fields are accessed later.

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

Re: [RFC PATCH bpf-next v7 02/11] bpf: allow attaching struct_ops to cgroups

In reply to Hui Zhu
Yafang Shao raised a design concern about the struct_ops_link structure: The struct has hardcoded cgroup-specific fields. He suggested a more generic solution using 'int type' and 'void *private'…

include/linux/bpf.h struct bpf_raw_tp_link { · line 1929

Quoted 13 lines
include/linux/bpf.h +3 -0
index dd4f34e041ab..bd1b94a618ad 100644
@@ -1922,6 +1922,9 @@ struct bpf_raw_tp_link {
 struct bpf_struct_ops_link {
 	struct bpf_link link;
 	struct bpf_map __rcu *map;
+	struct cgroup *cgroup;
+	bool cgroup_removed;
+	struct list_head list;
 	wait_queue_head_t wait_hup;
 };

Yafang Shao raised a design concern about the struct_ops_link structure:
The struct has hardcoded cgroup-specific fields. He suggested a more generic solution using 'int type' and 'void *private' fields to support other structs (task, etc.) in the future. This design feedback was not addressed or responded to.

Reference: https://lore.kernel.org/bpf/CALOAHbDXmgi=yeB1c2zzQ7-Lz2+MEZvtbxQp1=mWXMJSsg3sgQ@mail.gmail.com/

include/uapi/linux/bpf.h enum bpf_perf_event_type { · line 1250

Quoted 10 lines
include/uapi/linux/bpf.h +1 -0
index aec171ccb6ef..f547613986cc 100644
@@ -1246,6 +1246,7 @@ enum bpf_perf_event_type {
 #define BPF_F_AFTER		(1U << 4)
 #define BPF_F_ID		(1U << 5)
 #define BPF_F_PREORDER		(1U << 6)
+#define BPF_F_CGROUP_FD		(1U << 7)
 #define BPF_F_LINK		BPF_F_LINK /* 1 << 13 */

Since both fdinfo and link_info show the cgroup ID, would BPF_F_CGROUP_ID be a better name than BPF_F_CGROUP_FD for alignment?

This naming suggestion came from Yafang Shao and was not addressed or responded to.

Reference: https://lore.kernel.org/bpf/CALOAHbDXmgi=yeB1c2zzQ7-Lz2+MEZvtbxQp1=mWXMJSsg3sgQ@mail.gmail.com/

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link, · line 1273

Quoted 9 lines
kernel/bpf/bpf_struct_ops.c +1 -0
index 7ad3b1a49dee..e63f926d8728 100644
@@ -1264,6 +1270,7 @@ static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link,
 {
 	struct bpf_struct_ops_link *st_link;
 	struct bpf_map *map;
+	u64 cgrp_id = 0;

Assigning 0 to cgrp_id would technically be incorrect. The cgroup_id() function returns 1 for !CONFIG_CGROUPS, and for CONFIG_CGROUPS the ID allocation via idr_alloc_cyclic() uses a range between 1 and INT_MAX. Would a sentinel value like (u64)-1 be more appropriate?

Matt Bobrowski raised this concern and Roman acknowledged the review, but this was not fixed in the current version.

Reference: https://lore.kernel.org/bpf/[email protected]/

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link, · line 1285

Quoted 9 lines
kernel/bpf/bpf_struct_ops.c +5 -0
@@ -1271,6 +1278,14 @@ static void bpf_struct_ops_map_link_show_fdinfo(const struct bpf_link *link,
 	if (map)
 		seq_printf(seq, "map_id:\t%d\n", map->id);
 	rcu_read_unlock();
+
+	cgroup_lock();
+	if (st_link->cgroup)
+		cgrp_id = cgroup_id(st_link->cgroup);
+	cgroup_unlock();

Could an inline helper be introduced for the cgroup_lock()/cgroup_id()/ cgroup_unlock() pattern? This same dance appears in both bpf_struct_ops_map_link_show_fdinfo() and bpf_struct_ops_map_link_fill_link_info().

Matt Bobrowski suggested this and Roman said he would try, but the helper was not added in the current version.

Reference: https://lore.kernel.org/bpf/[email protected]/

kernel/bpf/bpf_struct_ops.c int bpf_struct_ops_link_create(union bpf_attr *attr) · line 1429

Quoted 9 lines
kernel/bpf/bpf_struct_ops.c +3 -0
@@ -1393,8 +1422,12 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 	struct bpf_link_primer link_primer;
 	struct bpf_struct_ops_map *st_map;
 	struct bpf_map *map;
+	struct cgroup *cgrp;
 	int err;
 
+	if (attr->link_create.flags & ~BPF_F_CGROUP_FD)
+		return -EINVAL;

Should all the cgroup-related logic be protected by CONFIG_CGROUPS ifdef? Both cgroup_get_from_fd() and cgroup_put() lack stubs when building with !CONFIG_CGROUPS. Should BPF_F_CGROUP_FD only be accepted when CONFIG_BPF_CGROUP is enabled, returning -EOPNOTSUPP otherwise?

Matt Bobrowski raised this and Roman acknowledged the review, but these guards were not added in the current version.

Reference: https://lore.kernel.org/bpf/[email protected]/

Quoted 38 lines
kernel/bpf/bpf_struct_ops.c +19 -4
@@ -1414,11 +1447,26 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 	bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_map_lops, NULL,
 		      attr->link_create.attach_type);
 
+	init_waitqueue_head(&link->wait_hup);
+
+	if (attr->link_create.flags & BPF_F_CGROUP_FD) {
+		cgrp = cgroup_get_from_fd(attr->link_create.target_fd);
+		if (IS_ERR(cgrp)) {
+			err = PTR_ERR(cgrp);
+			goto err_out;
+		}
+		link->cgroup = cgrp;
+		err = cgroup_bpf_attach_struct_ops(cgrp, link);
+		if (err) {
+			cgroup_put(cgrp);
+			link->cgroup = NULL;
+			goto err_out;
+		}
+	}
+
 	err = bpf_link_prime(&link->link, &link_primer);
 	if (err)
-		goto err_out;
-
-	init_waitqueue_head(&link->wait_hup);
+		goto err_put_cgroup;
 
 	/* Hold the update_mutex such that the subsystem cannot
 	 * do link->ops->detach() before the link is fully initialized.
@@ -1429,13 +1477,16 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 		mutex_unlock(&update_mutex);
 		bpf_link_cleanup(&link_primer);
 		link = NULL;
-		goto err_out;
+		goto err_put_cgroup;
 	}
 	RCU_INIT_POINTER(link->map, map);

kernel/bpf/bpf_struct_ops.c int bpf_struct_ops_link_create(union bpf_attr *attr) · line 1492

Quoted 10 lines
kernel/bpf/bpf_struct_ops.c +3 -0
 	mutex_unlock(&update_mutex);
 
 	return bpf_link_settle(&link_primer);
 
+err_put_cgroup:
+	if (link && link->cgroup)
+		cgroup_bpf_detach_struct_ops(link->cgroup, link);
 err_out:
 	bpf_map_put(map);
 	kfree(link);

Can the error path here trigger a use-after-free?

After cgroup_bpf_attach_struct_ops() succeeds, the link is added to cgrp->bpf.struct_ops_links and becomes reachable by cgroup_bpf_release(). If bpf_link_prime() then fails (FD exhaustion or memory pressure), the error path checks link->cgroup and calls cgroup_bpf_detach_struct_ops().

However, if the cgroup is concurrently destroyed, cgroup_bpf_release() can run:

cgroup_bpf_release():

    cgroup_lock()
    list_splice_init(&cgrp->bpf.struct_ops_links, &st_links)
    for each st_link in st_links:
      st_link->cgroup = NULL
      st_link->cgroup_removed = true
      bpf_link_inc_not_zero(&st_link->link)  // refcount 1->2
    cgroup_unlock()
    ...
    st_link->link.ops->detach(&st_link->link)
    bpf_link_put(&st_link->link)

At this point link->cgroup is NULL, so the err_put_cgroup check becomes a no-op. Control proceeds to err_out and calls kfree(link), freeing the memory.

Meanwhile, cgroup_bpf_release resumes its second loop and accesses the already-freed link memory via st_link->link.ops->detach() and bpf_link_put().

The error path uses kfree(link) directly, bypassing the bpf_link refcount mechanism. Once the link is added to cgrp->bpf.struct_ops_links, it becomes exposed to concurrent cgroup_bpf_release which can bump the refcount. Direct kfree() ignores the additional reference and frees the memory while the release work still holds a raw pointer.

In contrast, when the post-bpf_link_prime reg() failure occurs, the code uses bpf_link_cleanup() and sets link = NULL, which is safe because it relies on the refcount mechanism.

Quoted 14 lines
kernel/bpf/cgroup.c +2 -0
index 876f6a81a9b6..b593ebb30a4e 100644
@@ -307,12 +308,23 @@ static void cgroup_bpf_release(struct work_struct *work)
 					       bpf.release_work);
 	struct bpf_prog_array *old_array;
 	struct list_head *storages = &cgrp->bpf.storages;
+	struct bpf_struct_ops_link *st_link, *st_tmp;
 	struct bpf_cgroup_storage *storage, *stmp;
+	LIST_HEAD(st_links);
 
 	unsigned int atype;
 

kernel/bpf/cgroup.c static void cgroup_bpf_release(struct work_struct *work) · line 326

Quoted 10 lines
kernel/bpf/cgroup.c +8 -0
 	cgroup_lock();
 
+	list_splice_init(&cgrp->bpf.struct_ops_links, &st_links);
+	list_for_each_entry_safe(st_link, st_tmp, &st_links, list) {
+		st_link->cgroup = NULL;
+		st_link->cgroup_removed = true;
+		cgroup_put(cgrp);
+		if (IS_ERR(bpf_link_inc_not_zero(&st_link->link)))
+			list_del(&st_link->list);
+	}

Does this loop have the correct ordering for concurrent link dealloc?

The first loop writes to st_link memory (st_link->cgroup = NULL, st_link->cgroup_removed = true) before calling bpf_link_inc_not_zero() to take a reference.

Meanwhile, if userspace closes the link FD and the refcount drops to 0, bpf_struct_ops_map_link_dealloc() runs:

  bpf_struct_ops_map_link_dealloc():
    st_map->st_ops_desc->st_ops->unreg(&st_map->kvalue.data, link);
    if (st_link->cgroup)
      cgroup_bpf_detach_struct_ops(st_link->cgroup, st_link);
    kfree(st_link);

The dealloc path reads st_link->cgroup without holding cgroup_mutex. If this read sees the NULL written by cgroup_bpf_release, dealloc skips cgroup_bpf_detach_struct_ops() and proceeds to kfree(st_link).

At that point, cgroup_bpf_release continues and performs use-after-free on the freed st_link memory:

  st_link->cgroup_removed = true         // UAF write
  bpf_link_inc_not_zero(&st_link->link)  // UAF atomic on freed memory
  list_del(&st_link->list)               // UAF / list corruption

The link is on cgrp->bpf.struct_ops_links but list membership does not increment the link refcount. The cgroup_lock would only synchronize the dealloc path if dealloc unconditionally took it, but dealloc takes cgroup_lock conditionally on (st_link->cgroup), which the racing writer just nulled.

Would it be safer to call bpf_link_inc_not_zero() first before touching st_link's other fields?

kernel/bpf/cgroup.c cgroup_common_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) · line 2783

Quoted 12 lines
kernel/bpf/cgroup.c +11 -0
@@ -2755,3 +2773,31 @@ cgroup_common_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
+void cgroup_bpf_detach_struct_ops(struct cgroup *cgrp,
+				  struct bpf_struct_ops_link *link)
+{
+	cgroup_lock();
+	if (link->cgroup == cgrp) {
+		list_del(&link->list);
+		link->cgroup = NULL;
+		cgroup_put(cgrp);
+	}
+	cgroup_unlock();
+}

Is the cgrp parameter needed in cgroup_bpf_attach_struct_ops() and cgroup_bpf_detach_struct_ops()? Both Matt Bobrowski and Josh Don suggested that both functions should operate on link->cgroup instead, with a !link->cgroup being considered -EINVAL. Roman acknowledged with 'Ack' and 'Sure, good point' but the parameter was not removed.

Reference: https://lore.kernel.org/bpf/[email protected]/

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26429228214

author
#5 lore raw

RFC PATCH v7 3/11 libbpf: fix return value on memory allocation failure

In reply to Hui Zhu

From: Roman Gushchin <[email protected]>

bpf_map__attach_struct_ops() returns -EINVAL instead of -ENOMEM on the memory allocation failure. Fix it.

Fixes 590a00888250 ("bpf: libbpf: Add STRUCT_OPS support")
---
 tools/lib/bpf/libbpf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/lib/bpf/libbpf.c +1 -1
index ab2071fdd3e8..1e8688975d16 100644
@@ -13701,7 +13701,7 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
 
 	link = calloc(1, sizeof(*link));
 	if (!link)
-		return libbpf_err_ptr(-EINVAL);
+		return libbpf_err_ptr(-ENOMEM);
 
 	/* kern_vdata should be prepared during the loading phase. */
 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
Signature · 1 line
2.43.0
#6 lore raw

Re: [RFC PATCH bpf-next v7 03/11] libbpf: fix return value on memory allocation failure

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] bpf_map__attach_struct_ops() and bpf_map__init_kern_struct_ops() can dereference a NULL map->st_ops pointer if the map type is manually set to BPF_MAP_TYPE_STRUCT_OPS or maliciously defined in an ELF file. --

commit c643fee98cc31443df8f0acc1fcfd6c87f93a4f8
Author: Roman Gushchin <[email protected]>

libbpf: fix return value on memory allocation failure

This commit fixes the return value of bpf_map__attach_struct_ops() to correctly return -ENOMEM instead of -EINVAL when memory allocation for the link structure fails.

tools/lib/bpf/libbpf.c struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map) · line 13707

Quoted 12 lines
tools/lib/bpf/libbpf.c +1 -1
@@ -13701,7 +13701,7 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
 
 	link = calloc(1, sizeof(*link));
 	if (!link)
-		return libbpf_err_ptr(-EINVAL);
+		return libbpf_err_ptr(-ENOMEM);
 
 	/* kern_vdata should be prepared during the loading phase. */
 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);

[Severity: High]
This is a pre-existing issue, but can this dereference a NULL map->st_ops pointer?

If a user manually changes a map's type to BPF_MAP_TYPE_STRUCT_OPS using bpf_map__set_type(), or if a malformed BPF object file defines a map in the .maps section with this type, map->st_ops is never allocated.

The bpf_object_init_struct_ops() function only allocates st_ops for maps found in the .struct_ops and .struct_ops.link sections.

Because bpf_map__is_struct_ops() only checks map->def.type, could a missing NULL check on map->st_ops here and in bpf_map__init_kern_struct_ops() lead to a crash when privileged daemons parse untrusted BPF ELF files?

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

Re: [RFC PATCH bpf-next v7 03/11] libbpf: fix return value on memory allocation failure

In reply to Hui Zhu
This is a pre-existing issue, but can this dereference a NULL map->st_ops pointer?

tools/lib/bpf/libbpf.c struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map) · line 13707

Quoted 13 lines
tools/lib/bpf/libbpf.c +1 -1
index ab2071fdd3e8..1e8688975d16 100644
@@ -13701,7 +13701,7 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
 
 	link = calloc(1, sizeof(*link));
 	if (!link)
-		return libbpf_err_ptr(-EINVAL);
+		return libbpf_err_ptr(-ENOMEM);
 
 	/* kern_vdata should be prepared during the loading phase. */
 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);

This is a pre-existing issue, but can this dereference a NULL map->st_ops pointer?

If a user manually changes a map's type to BPF_MAP_TYPE_STRUCT_OPS using bpf_map__set_type(), or if a malformed BPF object file defines a map in the .maps section with this type, map->st_ops is never allocated.

The bpf_object_init_struct_ops() function only allocates st_ops for maps found in the .struct_ops and .struct_ops.link sections.

Because bpf_map__is_struct_ops() only checks map->def.type, could a missing NULL check on map->st_ops here and in bpf_map__init_kern_struct_ops() lead to a crash when privileged daemons parse untrusted BPF ELF files?

Reviewed-by lore thread: https://lore.kernel.org/bpf/[email protected]/

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26429228214

author
#8 lore raw

RFC PATCH v7 4/11 libbpf: introduce bpf_map__attach_struct_ops_opts()

In reply to Hui Zhu

From: Roman Gushchin <[email protected]>

Introduce bpf_map__attach_struct_ops_opts(), an extended version of bpf_map__attach_struct_ops(), which takes additional struct bpf_struct_ops_opts argument.

This allows to pass a target_fd argument and the BPF_F_CGROUP_FD flag and attach the struct ops to a cgroup as a result.

---
 tools/lib/bpf/libbpf.c   | 20 +++++++++++++++++---
 tools/lib/bpf/libbpf.h   | 14 ++++++++++++++
 tools/lib/bpf/libbpf.map |  1 +
 3 files changed, 32 insertions(+), 3 deletions(-)
tools/lib/bpf/libbpf.c +17 -3
index 1e8688975d16..a1b54da1ded2 100644
@@ -13683,11 +13683,18 @@ static int bpf_link__detach_struct_ops(struct bpf_link *link)
 	return close(link->fd);
 }
 
-struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
+struct bpf_link *bpf_map__attach_struct_ops_opts(const struct bpf_map *map,
+						 const struct bpf_struct_ops_opts *opts)
 {
+	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts);
 	struct bpf_link_struct_ops *link;
+	int err, fd, target_fd;
 	__u32 zero = 0;
-	int err, fd;
+
+	if (!OPTS_VALID(opts, bpf_struct_ops_opts)) {
+		pr_warn("map '%s': invalid opts\n", map->name);
+		return libbpf_err_ptr(-EINVAL);
+	}
 
 	if (!bpf_map__is_struct_ops(map)) {
 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
@@ -13724,7 +13731,9 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
 		return &link->link;
 	}
 
-	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
+	link_opts.flags = OPTS_GET(opts, flags, 0);
+	target_fd = OPTS_GET(opts, target_fd, 0);
+	fd = bpf_link_create(map->fd, target_fd, BPF_STRUCT_OPS, &link_opts);
 	if (fd < 0) {
 		free(link);
 		return libbpf_err_ptr(fd);
@@ -13736,6 +13745,11 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
 	return &link->link;
 }
 
+struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
+{
+	return bpf_map__attach_struct_ops_opts(map, NULL);
+}
+
 /*
  * Swap the back struct_ops of a link with a new struct_ops map.
  */
tools/lib/bpf/libbpf.h +14 -0
index bba4e8464396..18af178547ad 100644
@@ -945,6 +945,20 @@ bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
 struct bpf_map;
 
 LIBBPF_API struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map);
+
+struct bpf_struct_ops_opts {
+	/* size of this struct, for forward/backward compatibility */
+	size_t sz;
+	__u32 flags;
+	__u32 target_fd;
+	__u64 expected_revision;
+	size_t :0;
+};
+#define bpf_struct_ops_opts__last_field expected_revision
+
+LIBBPF_API struct bpf_link *
+bpf_map__attach_struct_ops_opts(const struct bpf_map *map,
+				const struct bpf_struct_ops_opts *opts);
 LIBBPF_API int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map);
 
 struct bpf_iter_attach_opts {
tools/lib/bpf/libbpf.map +1 -0
index dfed8d60af05..6105619b5ecf 100644
@@ -454,6 +454,7 @@ LIBBPF_1.7.0 {
 		bpf_prog_assoc_struct_ops;
 		bpf_program__assoc_struct_ops;
 		btf__permute;
+		bpf_map__attach_struct_ops_opts;
 } LIBBPF_1.6.0;
 
 LIBBPF_1.8.0 {
Signature · 1 line
2.43.0
#9 lore raw

Re: [RFC PATCH bpf-next v7 04/11] libbpf: introduce bpf_map__attach_struct_ops_opts()

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The `expected_revision` field in `struct bpf_struct_ops_opts` is silently ignored. - [High] Silent…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The expected_revision field in struct bpf_struct_ops_opts is silently ignored.
- [High] Silent fallback to global struct_ops attachment when target_fd is provided but the map lacks BPF_F_LINK. --

commit 38a993fa39aa42f01d7ad014d6fc85b69daffad3
Author: Roman Gushchin <[email protected]>

libbpf: introduce bpf_map__attach_struct_ops_opts()

This commit introduces an extended version of bpf_map__attach_struct_ops() which takes an additional struct bpf_struct_ops_opts argument. This enables passing a target_fd and the BPF_F_CGROUP_FD flag for cgroup attachment.

Quoted 4 lines
tools/lib/bpf/libbpf.c +0 -0
index 1e8688975d16d..a1b54da1ded25 100644

[ ... ]

tools/lib/bpf/libbpf.c struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map) · line 13733

Quoted 4 lines
tools/lib/bpf/libbpf.c +0 -0
@@ -13724,7 +13731,9 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
 		return &link->link;
 	}
 

[Severity: High]
If a user provides a cgroup FD via opts->target_fd to restrict the attachment to a specific cgroup, but the map was not created with BPF_F_LINK, does this silently fall back to global registration?

Looking slightly above this block:

	if (!(map->def.map_flags & BPF_F_LINK)) {
		/* w/o a real link */
		link->link.fd = map->fd;
		link->map_fd = -1;
		return &link->link;
	}

If BPF_F_LINK is missing, it returns early before extracting and applying opts->target_fd. Should we explicitly reject the operation if opts->target_fd or opts->flags are set but the map lacks BPF_F_LINK, to prevent subverting the user's intent to isolate the struct_ops?

tools/lib/bpf/libbpf.c struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map) · line 13735

Quoted 3 lines
tools/lib/bpf/libbpf.c +2 -1
-	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
+	link_opts.flags = OPTS_GET(opts, flags, 0);
+	target_fd = OPTS_GET(opts, target_fd, 0);

[Severity: High]
Is the expected_revision field intended to be extracted here?

It is defined in struct bpf_struct_ops_opts but never extracted via OPTS_GET() or checked. If users attempt to use expected_revision to prevent TOCTOU races during atomic replacements, will they experience silent failures because the field is completely ignored?

Should the library either remove this field from the struct, or explicitly check for OPTS_GET(opts, expected_revision, 0) and return an error?

Quoted 4 lines
tools/lib/bpf/libbpf.c +1 -0
+	fd = bpf_link_create(map->fd, target_fd, BPF_STRUCT_OPS, &link_opts);
 	if (fd < 0) {
 		free(link);
 		return libbpf_err_ptr(fd);

[ ... ]

Quoted 4 lines
tools/lib/bpf/libbpf.h +0 -0
index bba4e84643967..18af178547ad5 100644

[ ... ]

Quoted 13 lines
tools/lib/bpf/libbpf.h +9 -0
@@ -945,6 +945,20 @@ bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
 struct bpf_map;
 
 LIBBPF_API struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map);
+
+struct bpf_struct_ops_opts {
+	/* size of this struct, for forward/backward compatibility */
+	size_t sz;
+	__u32 flags;
+	__u32 target_fd;
+	__u64 expected_revision;
+	size_t :0;
+};
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#10 lore raw

Re: [RFC PATCH bpf-next v7 04/11] libbpf: introduce bpf_map__attach_struct_ops_opts()

In reply to Hui Zhu
The expected_revision field declared in struct bpf_struct_ops_opts is never read or used. The code only reads flags and target_fd from opts, which could cause silent data loss if users set…
Quoted 4 lines
tools/lib/bpf/libbpf.c +0 -0
index 1e8688975d16..a1b54da1ded2 100644

[ ... ]

Quoted 21 lines
tools/lib/bpf/libbpf.c +9 -2
@@ -13683,11 +13683,18 @@ static int bpf_link__detach_struct_ops(struct bpf_link *link)
 	return close(link->fd);
 }
 
-struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
+struct bpf_link *bpf_map__attach_struct_ops_opts(const struct bpf_map *map,
+						 const struct bpf_struct_ops_opts *opts)
 {
+	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts);
 	struct bpf_link_struct_ops *link;
+	int err, fd, target_fd;
 	__u32 zero = 0;
-	int err, fd;
+
+	if (!OPTS_VALID(opts, bpf_struct_ops_opts)) {
+		pr_warn("map '%s': invalid opts\n", map->name);
+		return libbpf_err_ptr(-EINVAL);
+	}
 
 	if (!bpf_map__is_struct_ops(map)) {
 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);

[ ... ]

tools/lib/bpf/libbpf.c struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map) · line 13736

Quoted 8 lines
tools/lib/bpf/libbpf.c +3 -1
@@ -13724,7 +13731,9 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
 		return &link->link;
 	}
 
-	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
+	link_opts.flags = OPTS_GET(opts, flags, 0);
+	target_fd = OPTS_GET(opts, target_fd, 0);
+	fd = bpf_link_create(map->fd, target_fd, BPF_STRUCT_OPS, &link_opts);

The expected_revision field declared in struct bpf_struct_ops_opts is never read or used. The code only reads flags and target_fd from opts, which could cause silent data loss if users set expected_revision expecting it to be honored.

Looking at similar opts structures (bpf_cgroup_opts, bpf_tcx_opts, bpf_netkit_opts), they all pass expected_revision to bpf_link_create_opts. Should expected_revision be propagated here as well?

This was raised by [email protected] in v3:
https://lore.kernel.org/bpf/3af5210f45be4a508e584263a5517781ca762d28d4f6b831b987795662715e61@mail.kernel.org/

Quoted 3 lines
tools/lib/bpf/libbpf.c +0 -0
 	if (fd < 0) {
 		free(link);
 		return libbpf_err_ptr(fd);

[ ... ]

Quoted 15 lines
tools/lib/bpf/libbpf.h +7 -0
index bba4e8464396..18af178547ad 100644
@@ -945,6 +945,20 @@ bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
 struct bpf_map;
 
 LIBBPF_API struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map);
+
+struct bpf_struct_ops_opts {
+	/* size of this struct, for forward/backward compatibility */
+	size_t sz;
+	__u32 flags;
+	__u32 target_fd;
+	__u64 expected_revision;

tools/lib/bpf/libbpf.h bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd, · line 964

Quoted 10 lines
tools/lib/bpf/libbpf.h +7 -0
+	size_t :0;
+};
+#define bpf_struct_ops_opts__last_field expected_revision
+
+LIBBPF_API struct bpf_link *
+bpf_map__attach_struct_ops_opts(const struct bpf_map *map,
+				const struct bpf_struct_ops_opts *opts);
 LIBBPF_API int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map);
 
 struct bpf_iter_attach_opts {

[ ... ]

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26429228214

reviewer
#11 lore raw

Re: [RFC PATCH bpf-next v7 04/11] libbpf: introduce bpf_map__attach_struct_ops_opts()

In reply to Hui Zhu
Quoted 94 lines · Hui Zhu

From: Roman Gushchin <[email protected]>

Introduce bpf_map__attach_struct_ops_opts(), an extended version of bpf_map__attach_struct_ops(), which takes additional struct bpf_struct_ops_opts argument.

This allows to pass a target_fd argument and the BPF_F_CGROUP_FD flag and attach the struct ops to a cgroup as a result.

---
  tools/lib/bpf/libbpf.c   | 20 +++++++++++++++++---
  tools/lib/bpf/libbpf.h   | 14 ++++++++++++++
  tools/lib/bpf/libbpf.map |  1 +
  3 files changed, 32 insertions(+), 3 deletions(-)
tools/lib/bpf/libbpf.c +17 -3
index 1e8688975d16..a1b54da1ded2 100644
@@ -13683,11 +13683,18 @@ static int bpf_link__detach_struct_ops(struct bpf_link *link)
  	return close(link->fd);
  }
 
-struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
+struct bpf_link *bpf_map__attach_struct_ops_opts(const struct bpf_map *map,
+						 const struct bpf_struct_ops_opts *opts)
  {
+	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts);
  	struct bpf_link_struct_ops *link;
+	int err, fd, target_fd;
  	__u32 zero = 0;
-	int err, fd;
+
+	if (!OPTS_VALID(opts, bpf_struct_ops_opts)) {
+		pr_warn("map '%s': invalid opts\n", map->name);
+		return libbpf_err_ptr(-EINVAL);
+	}
 
  	if (!bpf_map__is_struct_ops(map)) {
  		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
@@ -13724,7 +13731,9 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
  		return &link->link;
  	}
 
-	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
+	link_opts.flags = OPTS_GET(opts, flags, 0);
+	target_fd = OPTS_GET(opts, target_fd, 0);
+	fd = bpf_link_create(map->fd, target_fd, BPF_STRUCT_OPS, &link_opts);
  	if (fd < 0) {
  		free(link);
  		return libbpf_err_ptr(fd);
@@ -13736,6 +13745,11 @@ struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
  	return &link->link;
  }
 
+struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
+{
+	return bpf_map__attach_struct_ops_opts(map, NULL);
+}
+
  /*
   * Swap the back struct_ops of a link with a new struct_ops map.
   */
tools/lib/bpf/libbpf.h +14 -0
index bba4e8464396..18af178547ad 100644
@@ -945,6 +945,20 @@ bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
  struct bpf_map;
 
  LIBBPF_API struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map);
+
+struct bpf_struct_ops_opts {
+	/* size of this struct, for forward/backward compatibility */
+	size_t sz;
+	__u32 flags;
+	__u32 target_fd;
+	__u64 expected_revision;
+	size_t :0;
+};
+#define bpf_struct_ops_opts__last_field expected_revision
+
+LIBBPF_API struct bpf_link *
+bpf_map__attach_struct_ops_opts(const struct bpf_map *map,
+				const struct bpf_struct_ops_opts *opts);
  LIBBPF_API int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map);
 
  struct bpf_iter_attach_opts {
tools/lib/bpf/libbpf.map +0 -0
index dfed8d60af05..6105619b5ecf 100644

tools/lib/bpf/libbpf.map LIBBPF_1.7.0 { · line 457

Quoted 4 lines
tools/lib/bpf/libbpf.map +1 -0
@@ -454,6 +454,7 @@ LIBBPF_1.7.0 {
  		bpf_prog_assoc_struct_ops;
  		bpf_program__assoc_struct_ops;
  		btf__permute;
+		bpf_map__attach_struct_ops_opts;

Function bpf_map__attach_struct_ops_opts should be in LIBBPF_1.8.0.

Quoted 3 lines
tools/lib/bpf/libbpf.map +0 -0
  } LIBBPF_1.6.0;
 
  LIBBPF_1.8.0 {
#12 lore raw

Re: [RFC PATCH bpf-next v7 04/11] libbpf: introduce bpf_map__attach_struct_ops_opts()

Quoted 4 lines · Yonghong Song
Quoted 1 line · Hui Zhu

From: Roman Gushchin <[email protected]>

[...]

Quoted 4 lines
Quoted 4 lines
tools/lib/bpf/libbpf.map +0 -0
index dfed8d60af05..6105619b5ecf 100644
Quoted 9 lines

tools/lib/bpf/libbpf.map LIBBPF_1.7.0 { · line 457

Quoted 5 lines
tools/lib/bpf/libbpf.map +1 -0
@@ -454,6 +454,7 @@ LIBBPF_1.7.0 {
           bpf_prog_assoc_struct_ops;
           bpf_program__assoc_struct_ops;
           btf__permute;
+        bpf_map__attach_struct_ops_opts;

Function bpf_map__attach_struct_ops_opts should be in LIBBPF_1.8.0.

Pls also keep it in alphabet order.

Thanks,
Leon

Quoted 5 lines
Quoted 2 lines
tools/lib/bpf/libbpf.map +0 -0
   } LIBBPF_1.6.0;
     LIBBPF_1.8.0 {
author
#13 lore raw

RFC PATCH v7 5/11 bpf: Pass flags in bpf_link_create for struct_ops

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

To support features like allowing overrides in cgroup hierarchies, we need a way to pass flags from userspace to the kernel when attaching a struct_ops.

Extend bpf_struct_ops_link to include a flags field. This field is populated from attr->link_create.flags during link creation. This will allow struct_ops implementations, such as the upcoming memory controller ops, to interpret these flags and modify their attachment behavior accordingly.

The flags validation in bpf_struct_ops_link_create() is updated to explicitly permit BPF_F_ALLOW_OVERRIDE in addition to the already-allowed BPF_F_CGROUP_FD. Any other flag combination will still be rejected with -EINVAL.

UAPI Change:
This patch updates the comment in include/uapi/linux/bpf.h to reflect that the cgroup-bpf attach flags (such as BPF_F_ALLOW_OVERRIDE) are now applicable to both BPF_PROG_ATTACH and BPF_LINK_CREATE commands. Previously, these flags were only documented for BPF_PROG_ATTACH.

The actual flag definitions remain unchanged, so this is a compatible extension of the existing API. Older userspace will continue to work (by not passing flags), and newer userspace can opt-in to the new functionality by setting appropriate flags.

---
 include/linux/bpf.h            | 1 +
 include/uapi/linux/bpf.h       | 2 +-
 kernel/bpf/bpf_struct_ops.c    | 4 +++-
 tools/include/uapi/linux/bpf.h | 2 +-
 4 files changed, 6 insertions(+), 3 deletions(-)
include/linux/bpf.h +1 -0
index 743b4f0546b5..aae7f9837944 100644
@@ -1915,6 +1915,7 @@ struct bpf_struct_ops_link {
 	bool cgroup_removed;
 	struct list_head list;
 	wait_queue_head_t wait_hup;
+	u32 flags;
 };
 
 struct bpf_link_primer {
include/uapi/linux/bpf.h +1 -1
index f547613986cc..85ab5bdf81ac 100644
@@ -1194,7 +1194,7 @@ enum bpf_perf_event_type {
 	BPF_PERF_EVENT_EVENT = 6,
 };
 
-/* cgroup-bpf attach flags used in BPF_PROG_ATTACH command
+/* cgroup-bpf attach flags used in BPF_PROG_ATTACH and BPF_LINK_CREATE command
  *
  * NONE(default): No further bpf programs allowed in the subtree.
  *
kernel/bpf/bpf_struct_ops.c +3 -1
index 5333290957cb..1d15c667a300 100644
@@ -1389,7 +1389,8 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 	struct cgroup *cgrp;
 	int err;
 
-	if (attr->link_create.flags & ~BPF_F_CGROUP_FD)
+	if (attr->link_create.flags & ~(BPF_F_CGROUP_FD |
+					BPF_F_ALLOW_OVERRIDE))
 		return -EINVAL;
 
 	map = bpf_map_get(attr->link_create.map_fd);
@@ -1427,6 +1428,7 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 			goto err_out;
 		}
 	}
+	link->flags = attr->link_create.flags;
 
 	err = bpf_link_prime(&link->link, &link_primer);
 	if (err)
tools/include/uapi/linux/bpf.h +1 -1
index fa075dc3b7eb..8a2b1f865d2b 100644
@@ -1194,7 +1194,7 @@ enum bpf_perf_event_type {
 	BPF_PERF_EVENT_EVENT = 6,
 };
 
-/* cgroup-bpf attach flags used in BPF_PROG_ATTACH command
+/* cgroup-bpf attach flags used in BPF_PROG_ATTACH and BPF_LINK_CREATE command
  *
  * NONE(default): No further bpf programs allowed in the subtree.
  *
Signature · 1 line
2.43.0
#14 lore raw

Re: [RFC PATCH bpf-next v7 05/11] bpf: Pass flags in bpf_link_create for struct_ops

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] Use-after-free of bpf_struct_ops_link on error path due to concurrent cgroup_bpf_release().…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] Use-after-free of bpf_struct_ops_link on error path due to concurrent cgroup_bpf_release().
- [Low] Missing UAPI flag validation allows BPF_F_ALLOW_OVERRIDE for non-cgroup struct_ops. --

commit 0fc91684192f5637c6cbd64910eb1eb3203843c6
Author: Hui Zhu <[email protected]>
Subject: bpf: Pass flags in bpf_link_create for struct_ops

This commit extends bpf_struct_ops_link to include a flags field, populated from attr->link_create.flags during link creation. This allows userspace to pass flags like BPF_F_ALLOW_OVERRIDE when attaching a struct_ops.

kernel/bpf/bpf_struct_ops.c int bpf_struct_ops_link_create(union bpf_attr *attr) · line 1430

Quoted 12 lines
kernel/bpf/bpf_struct_ops.c +2 -1
index e63f926d87283..45a6cc1d86c83 100644
@@ -1425,7 +1425,8 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 	struct cgroup *cgrp;
 	int err;
 
-	if (attr->link_create.flags & ~BPF_F_CGROUP_FD)
+	if (attr->link_create.flags & ~(BPF_F_CGROUP_FD |
+					BPF_F_ALLOW_OVERRIDE))
 		return -EINVAL;

[Severity: Low]
Does this allow userspace to pass BPF_F_ALLOW_OVERRIDE even when BPF_F_CGROUP_FD is not specified?

For non-cgroup struct_ops, this flag would be accepted but silently ignored by the kernel. Should this reject the combination with -EINVAL to safely allow future reuse of the flag bit?

Quoted 2 lines
kernel/bpf/bpf_struct_ops.c +0 -0
 	map = bpf_map_get(attr->link_create.map_fd);

[ ... ]

kernel/bpf/bpf_struct_ops.c int bpf_struct_ops_link_create(union bpf_attr *attr) · line 1470

Quoted 8 lines
kernel/bpf/bpf_struct_ops.c +1 -0
@@ -1463,6 +1464,7 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
 			goto err_out;
 		}
 	}
+	link->flags = attr->link_create.flags;
 
 	err = bpf_link_prime(&link->link, &link_primer);
 	if (err)

[Severity: Critical]
Can this error path trigger a use-after-free on the link object if cgroup_bpf_release() runs concurrently?

If cgroup_bpf_release() iterates the struct_ops_links list and processes the link before bpf_link_prime() returns an error:

Thread 1 (cgroup_bpf_release):

    bpf_link_inc_not_zero(link);
    link->cgroup = NULL;

Thread 2 would see this in the bpf_struct_ops_link_create() error path:

kernel/bpf/bpf_struct_ops.c:bpf_struct_ops_link_create() {
...
err_put_cgroup:

    if (link && link->cgroup)
        cgroup_bpf_detach_struct_ops(link->cgroup, link);
err_out:
    bpf_map_put(map);
    kfree(link);
    return err;
}

Since link->cgroup was set to NULL by Thread 1, the error path incorrectly skips cgroup_bpf_detach_struct_ops() and unconditionally calls kfree(link).

Because Thread 1 still holds a valid refcount, won't it later call st_link->link.ops->detach() and bpf_link_put() on the freed link memory?

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

RFC PATCH v7 6/11 mm: memcontrol: Add BPF struct_ops for memory controller

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

Introduce BPF struct_ops support to the memory controller, enabling custom and dynamic control over memory pressure via a new struct_ops type, memcg_bpf_ops.

The memcg_bpf_ops interface exposes the following hooks:

- memcg_charged: Called on the synchronous blocking charge path after pages have been charged to the cgroup. Returns a custom throttling delay in milliseconds. This value is used as a lower bound for the penalty passed to __mem_cgroup_handle_over_high() and applies even when memory.high is not breached, allowing BPF programs to impose proactive back-pressure on any charge event. Return 0 for no delay.

- memcg_uncharged: Called when pages are uncharged from a cgroup, allowing BPF programs to track or react to memory releases.

- below_low: Overrides the memory.low protection check. Receives the effective low threshold (elow) and current usage as arguments. If it returns true, the cgroup is treated as protected regardless of the standard elow >= usage comparison. Returning false continues to the normal kernel check.

- below_min: Same as below_low, but for memory.min protection. Receives emin and usage as arguments.

- handle_cgroup_online/offline: Callbacks invoked when a cgroup with an attached program comes online or goes offline, allowing BPF programs to manage per-cgroup state.

These hooks are integrated into core memory control logic.

memcg_charged is consulted in try_charge_memcg on the synchronous blocking path. To avoid losing the originally charged cgroup pointer as the charge loop walks up the ancestor chain, orig_memcg is saved before the loop begins. After the loop, the BPF hook is called with orig_memcg and the actual batch size, and its result (converted from milliseconds to jiffies) is stored as bpf_high_delay.

__mem_cgroup_handle_over_high() is then invoked when either bpf_high_delay is non-zero or memcg_nr_pages_over_high exceeds MEMCG_CHARGE_BATCH. Inside the function, the current task's memcg is obtained independently via get_mem_cgroup_from_mm(). Reclaim is attempted first; if reclaim makes forward progress or retries remain, the function loops back to reclaim again rather than throttling immediately. bpf_high_delay serves as a lower bound for the final penalty via max(penalty_jiffies, bpf_high_delay): when memcg_nr_pages_over_high is zero (memory.high not breached), the kernel overage calculation is skipped and bpf_high_delay alone sets the penalty. In all cases, throttling only occurs if the resulting penalty exceeds HZ/100; a BPF-requested delay below this threshold causes no sleep. The deferred user-return path (via mem_cgroup_handle_over_high()) always passes bpf_high_delay=0 since BPF delay is evaluated exactly once, on the synchronous charge path.

below_low and below_min are inserted in their respective inline functions after the unprotected check. The pre-read elow/emin and usage values are forwarded to the BPF hook; on false return the standard kernel comparison (elow >= usage) proceeds as normal.

Support for BPF_F_ALLOW_OVERRIDE is included. When a program is registered with this flag, a descendant cgroup may later attach its own memcg_bpf_ops to override the inherited program. Without this flag, attaching to a cgroup that already has a program (whether attached directly or inherited from an ancestor) will fail with -EBUSY.

On registration, ops are propagated to the cgroup itself and all its descendants via mem_cgroup_iter. A bpf_ops_flags field is added to struct mem_cgroup to persist the attachment flags, which are inherited during css_online and restored to the parent's flags on unregistration. On unregistration, rather than unconditionally clearing bpf_ops to NULL throughout the subtree, each descendant that still holds the unregistered ops pointer has its bpf_ops and bpf_ops_flags restored to the values the registering cgroup's parent held at that time. This correctly handles the override case where a descendant had re-attached over an inherited program.

Lifecycle management ensures programs are inherited by child cgroups on css_online and cleaned up on css_offline. SRCU (memcg_bpf_srcu) protects concurrent read access to the memcg->bpf_ops pointer; all writes are serialized under cgroup_mutex.

---
 include/linux/memcontrol.h | 250 ++++++++++++++++++++++++++++++-
 mm/bpf_memcontrol.c        | 298 ++++++++++++++++++++++++++++++++++++-
 mm/memcontrol.c            |  43 ++++--
 3 files changed, 574 insertions(+), 17 deletions(-)
include/linux/memcontrol.h +244 -6
index dc3fa687759b..30b7b8558ccb 100644
@@ -23,6 +23,7 @@
 #include <linux/writeback.h>
 #include <linux/page-flags.h>
 #include <linux/shrinker.h>
+#include <linux/srcu.h>
 
 struct mem_cgroup;
 struct obj_cgroup;
@@ -192,6 +193,59 @@ struct obj_cgroup {
 	bool is_root;
 };
 
+#ifdef CONFIG_BPF_SYSCALL
+/*
+ * struct memcg_bpf_ops - BPF callbacks for memory cgroup operations
+ *
+ * @handle_cgroup_online:  Called when a cgroup comes online. May be used
+ *                         by a BPF program to initialize per-cgroup state.
+ * @handle_cgroup_offline: Called when a cgroup goes offline. May be used
+ *                         to release per-cgroup state allocated in the
+ *                         online callback.
+ * @below_low:  Override the memory.low protection check.
+ *              Receives the effective low threshold @elow and the current
+ *              memory usage @usage (both in pages). If the callback returns
+ *              true, mem_cgroup_below_low() returns true immediately,
+ *              treating the cgroup as protected regardless of the standard
+ *              elow >= usage comparison. Returning false continues to
+ *              the normal kernel check.
+ * @below_min:  Same as @below_low, but for the memory.min protection check.
+ *              Receives @emin and @usage. Returning true short-circuits the
+ *              standard emin >= usage comparison.
+ * @memcg_charged:   Called on the synchronous blocking charge path after
+ *                   pages have been charged to the cgroup. Returns a custom
+ *                   throttle delay in milliseconds. This delay is taken as
+ *                   a lower bound for the penalty in
+ *                   __mem_cgroup_handle_over_high() and applies even when
+ *                   memory.high is not breached. Return 0 for no extra delay.
+ * @memcg_uncharged: Called when pages are uncharged from the cgroup.
+ *                   Allows BPF programs to track memory releases or update
+ *                   accounting state. No return value.
+ *
+ * This structure defines the interface for BPF programs to customize
+ * memory cgroup behavior through struct_ops programs. All callbacks are
+ * non-sleepable. Concurrent readers are protected by SRCU
+ * (memcg_bpf_srcu); writers hold cgroup_mutex.
+ */
+struct memcg_bpf_ops {
+	void (*handle_cgroup_online)(struct mem_cgroup *memcg);
+
+	void (*handle_cgroup_offline)(struct mem_cgroup *memcg);
+
+	bool (*below_low)(struct mem_cgroup *memcg, unsigned long elow,
+			  unsigned long usage);
+
+	bool (*below_min)(struct mem_cgroup *memcg, unsigned long emin,
+			  unsigned long usage);
+
+	unsigned int (*memcg_charged)(struct mem_cgroup *memcg,
+				      unsigned int nr_pages);
+
+	void (*memcg_uncharged)(struct mem_cgroup *memcg,
+				unsigned int nr_pages);
+};
+#endif /* CONFIG_BPF_SYSCALL */
+
 /*
  * The memory controller data structure. The memory controller controls both
  * page cache and RSS per cgroup. We would eventually like to provide
@@ -323,6 +377,11 @@ struct mem_cgroup {
 	spinlock_t event_list_lock;
 #endif /* CONFIG_MEMCG_V1 */
 
+#ifdef CONFIG_BPF_SYSCALL
+	struct memcg_bpf_ops *bpf_ops;
+	u32 bpf_ops_flags;
+#endif
+
 	struct mem_cgroup_per_node *nodeinfo[];
 };
 
@@ -533,6 +592,165 @@ static inline bool mem_cgroup_disabled(void)
 	return !cgroup_subsys_enabled(memory_cgrp_subsys);
 }
 
+#ifdef CONFIG_BPF_SYSCALL
+
+/* SRCU for protecting concurrent access to memcg->bpf_ops */
+extern struct srcu_struct memcg_bpf_srcu;
+
+/*
+ * BPF_MEMCG_CALL - Safely invoke a BPF memcg callback with return value
+ * @memcg:       The memory cgroup whose bpf_ops to invoke
+ * @op:          The callback name (struct member of memcg_bpf_ops)
+ * @default_val: Value to return if no BPF program is attached or the
+ *               specific callback is not implemented
+ * @...:         Additional arguments forwarded to the callback
+ *
+ * Uses a two-phase READ_ONCE() pattern:
+ *   1. An initial lockless READ_ONCE() provides a fast-path check.
+ *      If bpf_ops is NULL the SRCU lock is never taken, keeping the
+ *      common no-BPF path free of synchronization overhead.
+ *   2. A second READ_ONCE() after srcu_read_lock() ensures a consistent
+ *      view of the pointer under the SRCU read section, guarding against
+ *      a concurrent bpf_memcg_ops_unreg() that may be in progress.
+ */
+#define BPF_MEMCG_CALL(memcg, op, default_val, ...) ({		\
+	typeof(default_val) __ret = (default_val);		\
+	struct memcg_bpf_ops *__ops;				\
+	int __idx;						\
+								\
+	if (unlikely(READ_ONCE((memcg)->bpf_ops))) {		\
+		__idx = srcu_read_lock(&memcg_bpf_srcu);	\
+		__ops = READ_ONCE((memcg)->bpf_ops);		\
+		if (__ops && __ops->op)				\
+			__ret = __ops->op(memcg, ##__VA_ARGS__);\
+		srcu_read_unlock(&memcg_bpf_srcu, __idx);	\
+	}							\
+	__ret;							\
+})
+
+/*
+ * BPF_MEMCG_CALL_VOID - Safely invoke a void BPF memcg callback
+ * @memcg: The memory cgroup whose bpf_ops to invoke
+ * @op:    The callback name (struct member of memcg_bpf_ops)
+ * @...:   Additional arguments forwarded to the callback
+ *
+ * Same SRCU fast-path pattern as BPF_MEMCG_CALL but for callbacks
+ * that have no return value.
+ */
+#define BPF_MEMCG_CALL_VOID(memcg, op, ...) do {		\
+	struct memcg_bpf_ops *__ops;				\
+	int __idx;						\
+								\
+	if (unlikely(READ_ONCE((memcg)->bpf_ops))) {		\
+		__idx = srcu_read_lock(&memcg_bpf_srcu);	\
+		__ops = READ_ONCE((memcg)->bpf_ops);		\
+		if (__ops && __ops->op)				\
+			__ops->op(memcg, ##__VA_ARGS__);	\
+		srcu_read_unlock(&memcg_bpf_srcu, __idx);	\
+	}							\
+} while (0)
+
+static inline bool
+bpf_memcg_below_low(struct mem_cgroup *memcg, unsigned long elow,
+		    unsigned long usage)
+{
+	return BPF_MEMCG_CALL(memcg, below_low, false, elow, usage);
+}
+
+static inline bool
+bpf_memcg_below_min(struct mem_cgroup *memcg, unsigned long emin,
+		    unsigned long usage)
+{
+	return BPF_MEMCG_CALL(memcg, below_min, false, emin, usage);
+}
+
+static inline unsigned long
+bpf_memcg_charged(struct mem_cgroup *memcg, unsigned int nr_pages)
+{
+	unsigned int ret;
+
+	/*
+	 * Retrieve the BPF-specified throttle delay in milliseconds and
+	 * convert to jiffies for use in __mem_cgroup_handle_over_high().
+	 */
+	ret = BPF_MEMCG_CALL(memcg, memcg_charged, 0U, nr_pages);
+	return msecs_to_jiffies(ret);
+}
+
+static inline void
+bpf_memcg_uncharged(struct mem_cgroup *memcg, unsigned int nr_pages)
+{
+	BPF_MEMCG_CALL_VOID(memcg, memcg_uncharged, nr_pages);
+}
+
+#undef BPF_MEMCG_CALL
+#undef BPF_MEMCG_CALL_VOID
+
+/*
+ * memcontrol_bpf_online - Inherit BPF ops for a newly online cgroup.
+ * @memcg: The memory cgroup coming online.
+ *
+ * Called under cgroup_mutex from mem_cgroup_css_online(). Inherits the
+ * parent's bpf_ops pointer and bpf_ops_flags into @memcg so that
+ * BPF-based memory control policies propagate down the hierarchy
+ * automatically.
+ *
+ * If the parent has no bpf_ops, this is a no-op. If it does, the ops
+ * pointer is copied and, if an online handler is implemented, it is
+ * invoked to allow the BPF program to initialize per-cgroup state for
+ * the new child.
+ *
+ * Locking: cgroup_mutex is held by the caller. Because bpf_memcg_ops_reg()
+ * and bpf_memcg_ops_unreg() also hold cgroup_mutex when writing
+ * memcg->bpf_ops, no additional lock on memcg_bpf_srcu is required here.
+ */
+extern void memcontrol_bpf_online(struct mem_cgroup *memcg);
+
+/*
+ * memcontrol_bpf_offline - Run BPF cleanup for a cgroup going offline.
+ * @memcg: The memory cgroup going offline.
+ *
+ * Called under cgroup_mutex from mem_cgroup_css_offline(). If a BPF
+ * program is attached and implements a handle_cgroup_offline callback,
+ * it is invoked so the program can release any per-cgroup state before
+ * the memcg is freed.
+ *
+ * Locking: same as memcontrol_bpf_online() — cgroup_mutex is held.
+ */
+extern void memcontrol_bpf_offline(struct mem_cgroup *memcg);
+
+#else /* CONFIG_BPF_SYSCALL */
+
+static inline unsigned long
+bpf_memcg_charged(struct mem_cgroup *memcg, unsigned int nr_pages)
+{
+	return 0;
+}
+
+static inline void
+bpf_memcg_uncharged(struct mem_cgroup *memcg, unsigned int nr_pages)
+{
+}
+
+static inline bool
+bpf_memcg_below_low(struct mem_cgroup *memcg, unsigned long elow,
+		    unsigned long usage)
+{
+	return false;
+}
+
+static inline bool
+bpf_memcg_below_min(struct mem_cgroup *memcg, unsigned long emin,
+		    unsigned long usage)
+{
+	return false;
+}
+
+static inline void memcontrol_bpf_online(struct mem_cgroup *memcg) { }
+static inline void memcontrol_bpf_offline(struct mem_cgroup *memcg) { }
+
+#endif /* CONFIG_BPF_SYSCALL */
+
 static inline void mem_cgroup_protection(struct mem_cgroup *root,
 					 struct mem_cgroup *memcg,
 					 unsigned long *min,
@@ -603,21 +821,35 @@ static inline bool mem_cgroup_unprotected(struct mem_cgroup *target,
 static inline bool mem_cgroup_below_low(struct mem_cgroup *target,
 					struct mem_cgroup *memcg)
 {
+	unsigned long elow, usage;
+
 	if (mem_cgroup_unprotected(target, memcg))
 		return false;
 
-	return READ_ONCE(memcg->memory.elow) >=
-		page_counter_read(&memcg->memory);
+	elow = READ_ONCE(memcg->memory.elow);
+	usage = page_counter_read(&memcg->memory);
+
+	if (bpf_memcg_below_low(memcg, elow, usage))
+		return true;
+
+	return elow >= usage;
 }
 
 static inline bool mem_cgroup_below_min(struct mem_cgroup *target,
 					struct mem_cgroup *memcg)
 {
+	unsigned long emin, usage;
+
 	if (mem_cgroup_unprotected(target, memcg))
 		return false;
 
-	return READ_ONCE(memcg->memory.emin) >=
-		page_counter_read(&memcg->memory);
+	emin = READ_ONCE(memcg->memory.emin);
+	usage = page_counter_read(&memcg->memory);
+
+	if (bpf_memcg_below_min(memcg, emin, usage))
+		return true;
+
+	return emin >= usage;
 }
 
 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp);
@@ -890,12 +1122,18 @@ unsigned long mem_cgroup_get_zone_lru_size(struct lruvec *lruvec,
 	return READ_ONCE(mz->lru_zone_size[zone_idx][lru]);
 }
 
-void __mem_cgroup_handle_over_high(gfp_t gfp_mask);
+void __mem_cgroup_handle_over_high(gfp_t gfp_mask,
+				   unsigned long bpf_high_delay);
 
 static inline void mem_cgroup_handle_over_high(gfp_t gfp_mask)
 {
 	if (unlikely(current->memcg_nr_pages_over_high))
-		__mem_cgroup_handle_over_high(gfp_mask);
+		/*
+		 * Deferred user-return path: no BPF delay lookup here.
+		 * BPF-provided delay is injected from try_charge_memcg()
+		 * on the synchronous blocking charge path.
+		 */
+		__mem_cgroup_handle_over_high(gfp_mask, 0);
 }
 
 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg);
mm/bpf_memcontrol.c +296 -2

317 lines not on this page · raw message

mm/memcontrol.c +34 -9

99 lines not on this page · raw message

Signature · 1 line
2.43.0
#16 lore raw

Re: [RFC PATCH bpf-next v7 06/11] mm: memcontrol: Add BPF struct_ops for memory controller

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] Using `cgroup_e_css` for target memcg resolution during registration allows the BPF struct_ops…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] Using cgroup_e_css for target memcg resolution during registration allows the BPF struct_ops pointer to outlive the BPF program, leading to a critical Use-After-Free.
- [High] BPF struct_ops attach/detach does not invoke handle_cgroup_online and handle_cgroup_offline for pre-existing cgroups, leading to state initialization failures and resource leaks.
- [High] The bpf_memcg_charged hook is bypassed in force-charge paths, while bpf_memcg_uncharged is unconditionally invoked, causing negative accounting drift.
- [Medium] Injecting bpf_high_delay into __mem_cgroup_handle_over_high creates an unintended 16-iteration loop when the cgroup is not over its memory.high limit. --

commit 1665ba1b3048519410b9675f614ad883e30992b8
Author: Hui Zhu <[email protected]>
Subject: mm: memcontrol: Add BPF struct_ops for memory controller

This commit introduces BPF struct_ops support for the memory controller. It allows BPF programs to hook into charge and uncharge paths to apply custom delays, and provides hooks to override memory.low and memory.min checks.

Quoted 4 lines
mm/bpf_memcontrol.c +0 -0
index 716df49d76477..1f726a7b22e36 100644

[ ... ]

Quoted 1 line
mm/bpf_memcontrol.c +0 -0
@@ -179,15 +182,306 @@ static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = {

[ ... ]

Quoted 7 lines
mm/bpf_memcontrol.c +7 -0
+static int bpf_memcg_ops_reg(void *kdata, struct bpf_link *link)
+{
+	struct bpf_struct_ops_link *ops_link;
+	struct memcg_bpf_ops *ops = kdata, *old_ops;
+	struct cgroup_subsys_state *css;
+	struct mem_cgroup *memcg, *iter;
+	int err = 0;

mm/bpf_memcontrol.c static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = { · line 367

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+
+	if (!link)
+		return -EOPNOTSUPP;
+	ops_link = container_of(link, struct bpf_struct_ops_link, link);
+	if (!ops_link->cgroup)
+		return -EINVAL;
+
+	cgroup_lock();
+
+	css = cgroup_e_css(ops_link->cgroup, &memory_cgrp_subsys);

[Severity: Critical]
Could this use of cgroup_e_css() lead to a use-after-free?

If the memory controller is not enabled on the target cgroup, this resolves to an ancestor's css, attaching the program to the ancestor and all its descendants.

If the memory controller is subsequently enabled on the target cgroup, a new css is created for it. When the program is later detached, bpf_memcg_ops_unreg calls cgroup_e_css() which now returns the target cgroup's newly created css.

The unregistration loop will only clear bpf_ops on this new subtree, leaving stale pointers on the ancestor and all its other descendants. When the BPF program is freed, any memory charge on the ancestor hierarchy will dereference the freed bpf_ops pointer.

Quoted 5 lines
mm/bpf_memcontrol.c +5 -0
+	if (!css) {
+		err = -EINVAL;
+		goto unlock_out;
+	}
+	memcg = mem_cgroup_from_css(css);

[ ... ]

mm/bpf_memcontrol.c static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = { · line 408

Quoted 5 lines
mm/bpf_memcontrol.c +5 -0
+	iter = NULL;
+	while ((iter = mem_cgroup_iter(memcg, iter, NULL))) {
+		WRITE_ONCE(iter->bpf_ops, ops);
+		iter->bpf_ops_flags = ops_link->flags;
+	}

[Severity: High]
Does this bypass handle_cgroup_online() for pre-existing cgroups?

When bpf_memcg_ops_reg() attaches a BPF program, it iterates over all descendants to set the bpf_ops pointer but does not invoke handle_cgroup_online() for existing cgroups.

Conversely, bpf_memcg_ops_unreg() clears the pointer without calling handle_cgroup_offline().

If a BPF program dynamically allocates per-cgroup resources (e.g., maps or memory tracking structures), will those resources be permanently leaked because the offline cleanup callback is bypassed during unregistration, and subsequent cgroup deletion won't invoke the hook since the pointer is already cleared?

Quoted 9 lines
mm/bpf_memcontrol.c +5 -0
+
+unlock_out:
+	cgroup_unlock();
+	return err;
+}
mm/memcontrol.c +0 -0
index 749c128b4fad5..3494f36d792d8 100644

[ ... ]

Quoted 7 lines
mm/memcontrol.c +1 -2
@@ -2516,11 +2522,15 @@ void __mem_cgroup_handle_over_high(gfp_t gfp_mask)
 	 * memory.high is breached and reclaim is unable to keep up. Throttle
 	 * allocators proactively to slow down excessive growth.
 	 */
-	penalty_jiffies = calculate_high_delay(memcg, nr_pages,
-					       mem_find_max_overage(memcg));
+	if (nr_pages) {

mm/memcontrol.c void __mem_cgroup_handle_over_high(gfp_t gfp_mask) · line 2533

Quoted 10 lines
mm/memcontrol.c +7 -2
+		penalty_jiffies = calculate_high_delay(
+			memcg, nr_pages, mem_find_max_overage(memcg));
 
-	penalty_jiffies += calculate_high_delay(memcg, nr_pages,
-						swap_find_max_overage(memcg));
+		penalty_jiffies += calculate_high_delay(
+			memcg, nr_pages, swap_find_max_overage(memcg));
+	} else
+		penalty_jiffies = 0;
+	penalty_jiffies = max(penalty_jiffies, bpf_high_delay);

[Severity: Medium]
Will this force 16 useless iterations of reclaim_high() when not over the memory.high limit?

If a BPF program returns a delay (bpf_high_delay > HZ/100), the assignment above bypasses the penalty_jiffies <= HZ/100 bailout check.

Even if nr_pages == 0, the function falls through to
if (nr_reclaimed || nr_retries--). Since nr_reclaimed is 0, this creates a 16-iteration loop that repeatedly walks the cgroup tree doing nothing.

Quoted 3 lines
mm/memcontrol.c +0 -0
 	/*
 	 * Clamp the max delay per usermode return so as to still keep the

[ ... ]

mm/memcontrol.c static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask, · line 2763

Quoted 6 lines
mm/memcontrol.c +2 -0
@@ -2746,6 +2759,8 @@ static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
 		}
 	} while ((memcg = parent_mem_cgroup(memcg)));
 
+	bpf_high_delay = bpf_memcg_charged(orig_memcg, batch);
+

[Severity: High]
Does this code miss forced allocations, causing negative accounting drift?

If an allocation is forced (e.g., via PF_MEMALLOC, __GFP_NOFAIL, or the OOM path), the code jumps to the force label, charges the memory, and returns 0 without executing the done_restock path where bpf_memcg_charged() is called.

However, when these pages are freed, memcg_uncharge() unconditionally executes bpf_memcg_uncharged(). This imbalance will cause any BPF program that tracks charged memory via these hooks to experience negative accounting drift.

Quoted 3 lines
mm/memcontrol.c +0 -0
 	/*
 	 * Reclaim is set up above to be called from the userland
 	 * return path. But also attempt synchronous reclaim to avoid
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#17 lore raw

Re: [RFC PATCH bpf-next v7 06/11] mm: memcontrol: Add BPF struct_ops for memory controller

In reply to Hui Zhu
Can this early return skip a required synchronize_srcu(&memcg_bpf_srcu)?
Quoted 4 lines
mm/bpf_memcontrol.c +0 -0
index 716df49d7647..1f726a7b22e3 100644

[ ... ]

Quoted 6 lines
mm/bpf_memcontrol.c +6 -0
+/* Unregister the struct ops instance */
+static void bpf_memcg_ops_unreg(void *kdata, struct bpf_link *link)
+{
+	struct bpf_struct_ops_link *ops_link;
+	struct memcg_bpf_ops *ops = kdata;
+	struct cgroup_subsys_state *css;

mm/bpf_memcontrol.c static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = { · line 430

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+	struct mem_cgroup *memcg;
+	struct mem_cgroup *iter;
+	struct memcg_bpf_ops *parent_bpf_ops = NULL;
+	u32 parent_bpf_ops_flags = 0;
+
+	if (!link)
+		return;
+	ops_link = container_of(link, struct bpf_struct_ops_link, link);
+	if (!ops_link->cgroup)
+		return;

Can this early return skip a required synchronize_srcu(&memcg_bpf_srcu)?

When a cgroup that owns a memcg_bpf_ops link is destroyed, cgroup_bpf_release() takes cgroup_mutex, splices the struct_ops_links, sets st_link->cgroup = NULL, drops cgroup_mutex, and then calls link->ops->detach() outside the mutex. detach() (bpf_struct_ops_map_link_detach) invokes unreg() with link->cgroup already NULL, which hits this early return:

	if (!ops_link->cgroup)
		return;

At that point descendants of the destroyed cgroup still hold memcg->bpf_ops pointing at the registered ops (kdata). Memcgs in that subtree are not freed immediately because folios pin them via folio->memcg_data after offline, and uncharge paths (memcg_uncharge() -> bpf_memcg_uncharged()) keep dereferencing those memcgs.

bpf_memcg_uncharged()/bpf_memcg_charged() use the BPF_MEMCG_CALL macros, which take srcu_read_lock(&memcg_bpf_srcu), READ_ONCE(memcg->bpf_ops), and then dereference __ops->op. After unreg() returns, the bpf_struct_ops infrastructure eventually frees kdata via bpf_struct_ops_map_free(), which calls synchronize_rcu_mult(call_rcu, call_rcu_tasks) and waits only for classic RCU and RCU-tasks grace periods, not SRCU.

If the unreg() path returns without calling synchronize_srcu(&memcg_bpf_srcu), can an SRCU reader holding a pointer into the about-to-be-freed kdata observe a use-after-free when invoking __ops->op()?

Would moving the synchronize_srcu(&memcg_bpf_srcu) call so it runs on both early-return paths (or unconditionally before returning) be appropriate here? The other early return (link == NULL) looks benign because reg() returns -EOPNOTSUPP for link == NULL and never writes any memcg->bpf_ops, so no synchronize is required on that path.

Quoted 26 lines
mm/bpf_memcontrol.c +26 -0
+	cgroup_lock();
+
+	css = cgroup_e_css(ops_link->cgroup, &memory_cgrp_subsys);
+	if (!css)
+		goto unlock_out;
+	memcg = mem_cgroup_from_css(css);
+
+	/* Get the parent bpf_ops and bpf_ops_flags */
+	iter = parent_mem_cgroup(memcg);
+	if (iter) {
+		parent_bpf_ops = READ_ONCE(iter->bpf_ops);
+		parent_bpf_ops_flags = iter->bpf_ops_flags;
+	}
+
+	iter = NULL;
+	while ((iter = mem_cgroup_iter(memcg, iter, NULL))) {
+		if (READ_ONCE(iter->bpf_ops) == ops) {
+			WRITE_ONCE(iter->bpf_ops, parent_bpf_ops);
+			iter->bpf_ops_flags = parent_bpf_ops_flags;
+		}
+	}
+
+unlock_out:
+	cgroup_unlock();
+	synchronize_srcu(&memcg_bpf_srcu);
+}

[ ... ]

Quoted 4 lines
mm/memcontrol.c +0 -0
index 749c128b4fad..3494f36d792d 100644

[ ... ]

Quoted 7 lines
mm/memcontrol.c +1 -2
@@ -2516,11 +2522,15 @@ void __mem_cgroup_handle_over_high(gfp_t gfp_mask)
 	 * memory.high is breached and reclaim is unable to keep up. Throttle
 	 * allocators proactively to slow down excessive growth.
 	 */
-	penalty_jiffies = calculate_high_delay(memcg, nr_pages,
-					       mem_find_max_overage(memcg));
+	if (nr_pages) {

mm/memcontrol.c void __mem_cgroup_handle_over_high(gfp_t gfp_mask) · line 2533

Quoted 10 lines
mm/memcontrol.c +7 -2
+		penalty_jiffies = calculate_high_delay(
+			memcg, nr_pages, mem_find_max_overage(memcg));
 
-	penalty_jiffies += calculate_high_delay(memcg, nr_pages,
-						swap_find_max_overage(memcg));
+		penalty_jiffies += calculate_high_delay(
+			memcg, nr_pages, swap_find_max_overage(memcg));
+	} else
+		penalty_jiffies = 0;
+	penalty_jiffies = max(penalty_jiffies, bpf_high_delay);

This isn't a bug, but the if/else here mixes braced and unbraced branches. Documentation/process/coding-style.rst (Placing Braces and Spaces) asks that when one arm of an if/else uses braces, the other arm use them too. Would something like the following be preferable, and quiet checkpatch.pl?

	if (nr_pages) {
		penalty_jiffies = calculate_high_delay(
			memcg, nr_pages, mem_find_max_overage(memcg));

		penalty_jiffies += calculate_high_delay(
			memcg, nr_pages, swap_find_max_overage(memcg));
	} else {
		penalty_jiffies = 0;
	}

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26429228214

author
#18 lore raw

RFC PATCH v7 7/11 mm/bpf: Add bpf_try_to_free_mem_cgroup_pages kfunc

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

Expose the memory cgroup reclaim interface to BPF programs by adding the bpf_try_to_free_mem_cgroup_pages kfunc. This allows BPF to trigger memory reclamation for a specific cgroup.

The kfunc wraps try_to_free_mem_cgroup_pages and introduces a swappiness parameter with the following semantics:
Values in [MIN_SWAPPINESS, SWAPPINESS_ANON_ONLY] are passed through as an explicit swappiness override.
Values below MIN_SWAPPINESS indicate the use of the system default (passed as NULL to the core reclaim path).
Values above SWAPPINESS_ANON_ONLY are rejected as invalid (-EINVAL).

Note that the swappiness override is only respected by the core reclaim path if the MEMCG_RECLAIM_PROACTIVE flag is set in reclaim_options.

Swap usage during reclaim is gated on reclaim_options: swap is considered only when MEMCG_RECLAIM_MAY_SWAP is set. Without this flag, reclaim is restricted to file-backed pages regardless of the swappiness value or the cgroup's swappiness setting.

Also include <linux/swap.h> for the swappiness macro definitions and register the function with the KF_SLEEPABLE flag.

---
 mm/bpf_memcontrol.c | 57 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
mm/bpf_memcontrol.c +57 -0
index 1f726a7b22e3..0353c8736aa5 100644
@@ -6,6 +6,7 @@
  */
 
 #include <linux/memcontrol.h>
+#include <linux/swap.h>
 #include <linux/bpf.h>
 
 /* Protects memcg->bpf_ops pointer for read and write. */
@@ -162,6 +163,60 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)
 	mem_cgroup_flush_stats(memcg);
 }
 
+/**
+ * bpf_try_to_free_mem_cgroup_pages - attempt to reclaim pages from
+ *                                    a memory cgroup
+ * @memcg:           the target memory cgroup to reclaim from
+ * @nr_pages:        the number of pages to reclaim
+ * @gfp_mask:        GFP flags controlling the reclaim behavior
+ * @reclaim_options: bitmask of MEMCG_RECLAIM_* flags to tune
+ *                   reclaim strategy
+ * @swappiness:      swappiness override value, or a sentinel to use
+ *                   the default
+ *
+ * BPF-facing wrapper around try_to_free_mem_cgroup_pages() that
+ * validates and translates the @swappiness argument before
+ * delegating to the core reclaim path.
+ *
+ * The @swappiness parameter follows these semantics:
+ *   - Values in [MIN_SWAPPINESS, SWAPPINESS_ANON_ONLY] are passed
+ *     through as an explicit swappiness override.
+ *   - Values below MIN_SWAPPINESS are treated as "use the system
+ *     default"; the override pointer is set to NULL and the cgroup's
+ *     own swappiness setting takes effect.
+ *   - Values above SWAPPINESS_ANON_ONLY are rejected as invalid.
+ *   - If @reclaim_options does not include MEMCG_RECLAIM_PROACTIVE,
+ *     the @swappiness override is ignored entirely by the core
+ *     reclaim path and the system default is used regardless.
+ *
+ * Swap usage during reclaim is gated on @reclaim_options: swap is
+ * considered only when MEMCG_RECLAIM_MAY_SWAP is set.  Without this
+ * flag, reclaim is restricted to file-backed pages regardless of the
+ * @swappiness value or the cgroup's swappiness setting.
+ *
+ * Return:
+ *   The number of pages actually reclaimed on success, or -%EINVAL
+ *   if @swappiness exceeds SWAPPINESS_ANON_ONLY.
+ */
+unsigned long bpf_try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
+					       unsigned long nr_pages,
+					       gfp_t gfp_mask,
+					       unsigned int reclaim_options,
+					       int swappiness)
+{
+	int *swapiness_ptr;
+
+	if (swappiness > SWAPPINESS_ANON_ONLY)
+		return -EINVAL;
+	else if (swappiness < MIN_SWAPPINESS)
+		swapiness_ptr = NULL;
+	else
+		swapiness_ptr = &swappiness;
+
+	return try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask,
+					    reclaim_options, swapiness_ptr);
+}
+
 __bpf_kfunc_end_defs();
 
 BTF_KFUNCS_START(bpf_memcontrol_kfuncs)
@@ -175,6 +230,8 @@ 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_try_to_free_mem_cgroup_pages, KF_SLEEPABLE)
+
 BTF_KFUNCS_END(bpf_memcontrol_kfuncs)
 
 static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = {
Signature · 1 line
2.43.0
#19 lore raw

Re: [RFC PATCH bpf-next v7 07/11] mm/bpf: Add bpf_try_to_free_mem_cgroup_pages kfunc

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] The kfunc `bpf_try_to_free_mem_cgroup_pages` returns `-EINVAL` on invalid arguments, but its…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] The kfunc bpf_try_to_free_mem_cgroup_pages returns -EINVAL on invalid arguments, but its return type is unsigned long.
- [High] Unsanitized gfp_mask passed from a BPF program to direct memory reclaim creates a potential deadlock with filesystem and IO locks.
- [Medium] The bpf_try_to_free_mem_cgroup_pages function is missing the mandatory __bpf_kfunc annotation in its definition. --

commit b01a6dd524da08098df4a7bba12f4b90457b1089
Author: Hui Zhu <[email protected]>

mm/bpf: Add bpf_try_to_free_mem_cgroup_pages kfunc

This commit introduces the bpf_try_to_free_mem_cgroup_pages kfunc, allowing BPF programs to trigger memory reclamation for a specific memory cgroup. It delegates to the core try_to_free_mem_cgroup_pages function and includes custom swappiness parsing.

Quoted 4 lines
mm/bpf_memcontrol.c +0 -0
index 1f726a7b22e36..0353c8736aa5d 100644

[ ... ]

mm/bpf_memcontrol.c __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg) · line 206

Quoted 6 lines
mm/bpf_memcontrol.c +6 -0
+unsigned long bpf_try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
+					       unsigned long nr_pages,
+					       gfp_t gfp_mask,
+					       unsigned int reclaim_options,
+					       int swappiness)
+{

[Severity: Medium]
Is the __bpf_kfunc macro missing from the function definition? Without this annotation, the compiler might inline or optimize out the function, especially when LTO is enabled, which would prevent the function from appearing in BTF and cause BPF program load failures.

mm/bpf_memcontrol.c __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg) · line 210

Quoted 4 lines
mm/bpf_memcontrol.c +4 -0
+	int *swapiness_ptr;
+
+	if (swappiness > SWAPPINESS_ANON_ONLY)
+		return -EINVAL;

[Severity: High]
Does returning a negative error code from a function with an unsigned long return type cause issues for BPF programs? Returning -EINVAL here will result in a very large positive value. A BPF program might interpret this massive value as a highly successful reclaim operation rather than an error. Should the return type be changed to a signed type like ssize_t, or should it return 0 on validation failure?

mm/bpf_memcontrol.c __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg) · line 217

Quoted 7 lines
mm/bpf_memcontrol.c +7 -0
+	else if (swappiness < MIN_SWAPPINESS)
+		swapiness_ptr = NULL;
+	else
+		swapiness_ptr = &swappiness;
+
+	return try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask,
+					    reclaim_options, swapiness_ptr);

[Severity: High]
Could an arbitrary gfp_mask passed by a BPF program cause a deadlock?

Because the function is KF_SLEEPABLE and gfp_mask is not constrained, a BPF program executing while filesystem or IO locks are held could pass flags like GFP_KERNEL.

If direct reclaim recurses into filesystem shrinkers, it might attempt to acquire the exact same locks, leading to an AB-BA deadlock or system hang. Should the gfp_mask be sanitized to strip flags like __GFP_FS and __GFP_IO before delegating to the core reclaim path?

Quoted 1 line

+}

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

Re: [RFC PATCH bpf-next v7 07/11] mm/bpf: Add bpf_try_to_free_mem_cgroup_pages kfunc

In reply to Hui Zhu
Should this function have the __bpf_kfunc annotation? Every other kfunc in this file (bpf_get_root_mem_cgroup, bpf_get_mem_cgroup, bpf_put_mem_cgroup, bpf_mem_cgroup_vm_events, bpf_mem_cgroup_usage…
Quoted 4 lines
mm/bpf_memcontrol.c +0 -0
index 1f726a7b22e3..0353c8736aa5 100644

[ ... ]

Quoted 30 lines
mm/bpf_memcontrol.c +26 -0
@@ -162,6 +163,60 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)
 	mem_cgroup_flush_stats(memcg);
 }
 
+/**
+ * bpf_try_to_free_mem_cgroup_pages - attempt to reclaim pages from
+ *                                    a memory cgroup
+ * @memcg:           the target memory cgroup to reclaim from
+ * @nr_pages:        the number of pages to reclaim
+ * @gfp_mask:        GFP flags controlling the reclaim behavior
+ * @reclaim_options: bitmask of MEMCG_RECLAIM_* flags to tune
+ *                   reclaim strategy
+ * @swappiness:      swappiness override value, or a sentinel to use
+ *                   the default
+ *
+ * BPF-facing wrapper around try_to_free_mem_cgroup_pages() that
+ * validates and translates the @swappiness argument before
+ * delegating to the core reclaim path.
+ *
+ * The @swappiness parameter follows these semantics:
+ *   - Values in [MIN_SWAPPINESS, SWAPPINESS_ANON_ONLY] are passed
+ *     through as an explicit swappiness override.
+ *   - Values below MIN_SWAPPINESS are treated as "use the system
+ *     default"; the override pointer is set to NULL and the cgroup's
+ *     own swappiness setting takes effect.
+ *   - Values above SWAPPINESS_ANON_ONLY are rejected as invalid.
+ *   - If @reclaim_options does not include MEMCG_RECLAIM_PROACTIVE,
+ *     the @swappiness override is ignored entirely by the core
+ *     reclaim path and the system default is used regardless.
+ *

mm/bpf_memcontrol.c __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg) · line 201

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+ * Swap usage during reclaim is gated on @reclaim_options: swap is
+ * considered only when MEMCG_RECLAIM_MAY_SWAP is set.  Without this
+ * flag, reclaim is restricted to file-backed pages regardless of the
+ * @swappiness value or the cgroup's swappiness setting.
+ *
+ * Return:
+ *   The number of pages actually reclaimed on success, or -%EINVAL
+ *   if @swappiness exceeds SWAPPINESS_ANON_ONLY.
+ */
+unsigned long bpf_try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,

Should this function have the __bpf_kfunc annotation? Every other kfunc in this file (bpf_get_root_mem_cgroup, bpf_get_mem_cgroup, bpf_put_mem_cgroup, bpf_mem_cgroup_vm_events, bpf_mem_cgroup_usage, bpf_mem_cgroup_memory_events, bpf_mem_cgroup_page_state, bpf_mem_cgroup_flush_stats) has it.

Documentation/bpf/kfuncs.rst section 2.5 states that kfunc definitions should always be annotated with the __bpf_kfunc macro to prevent the compiler from inlining the kfunc or the function being elided in an LTO build as it's not used elsewhere in the kernel.

mm/bpf_memcontrol.c __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg) · line 210

Quoted 9 lines
mm/bpf_memcontrol.c +9 -0
+					       unsigned long nr_pages,
+					       gfp_t gfp_mask,
+					       unsigned int reclaim_options,
+					       int swappiness)
+{
+	int *swapiness_ptr;
+
+	if (swappiness > SWAPPINESS_ANON_ONLY)
+		return -EINVAL;

How can BPF callers detect this error? The function returns 'unsigned long' (matching try_to_free_mem_cgroup_pages()'s page count), but here it returns -EINVAL.

Implicit conversion of -EINVAL (int -22) to unsigned long produces 0xFFFFFFFFFFFFFFEA -- a very large positive value, not a negative error code. The kernel-doc above explicitly states "or -%EINVAL if @swappiness exceeds SWAPPINESS_ANON_ONLY", which is impossible for an unsigned return.

A BPF caller cannot distinguish the error from a real reclaim count via 'if (ret < 0)' because ret is unsigned. The sample BPF program later in the series (samples/bpf/memcg.bpf.c in commit 8dcfd8aa3316) checks 'bpf_try_to_free_mem_cgroup_pages(...) <= 0' which would only match 0 and would silently treat the giant 'error' value as 'many pages reclaimed'.

Should this either return 'long' instead (so callers can branch on negative), or use a clearly defined sentinel like (unsigned long)-1 (as the other kfuncs in this file do for errors)?

Quoted 8 lines
mm/bpf_memcontrol.c +8 -0
+	else if (swappiness < MIN_SWAPPINESS)
+		swapiness_ptr = NULL;
+	else
+		swapiness_ptr = &swappiness;
+
+	return try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask,
+					    reclaim_options, swapiness_ptr);
+}

[ ... ]

mm/bpf_memcontrol.c BTF_ID_FLAGS(func, bpf_mem_cgroup_usage) · line 235

Quoted 7 lines
mm/bpf_memcontrol.c +2 -0
@@ -175,6 +230,8 @@ 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_try_to_free_mem_cgroup_pages, KF_SLEEPABLE)
+
 BTF_KFUNCS_END(bpf_memcontrol_kfuncs)

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26429228214

author
#21 lore raw

RFC PATCH v7 8/11 selftests/bpf: Add tests for memcg_bpf_ops

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

Add a comprehensive selftest suite for the memcg_bpf_ops functionality. These tests validate that BPF programs can correctly influence memory cgroup throttling behavior by implementing the new hooks.

The test suite is added in prog_tests/memcg_ops.c and covers several key scenarios:

1. test_memcg_ops_over_high:
Verifies that a BPF program can trigger throttling on a low-priority cgroup by returning a delay from the get_high_delay_ms hook when a high-priority cgroup is under pressure.

2. test_memcg_ops_below_low_over_high:
Tests the combination of the below_low and get_high_delay_ms hooks, ensuring they work together as expected.

3. test_memcg_ops_below_min_over_high:
Validates the interaction between the below_min and get_high_delay_ms hooks.

The test framework sets up a cgroup hierarchy with high and low priority groups, attaches BPF programs, runs memory-intensive workloads, and asserts that the observed throttling (measured by workload execution time) matches expectations.

The BPF program (progs/memcg_ops.c) uses a tracepoint on memcg:count_memcg_events (specifically PGFAULT) to detect memory pressure and trigger the appropriate hooks in response. This test suite provides essential validation for the new memory control mechanisms.

---
 MAINTAINERS                                   |   2 +
 .../selftests/bpf/prog_tests/memcg_ops.c      | 561 ++++++++++++++++++
 tools/testing/selftests/bpf/progs/memcg_ops.c | 132 +++++
 3 files changed, 695 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_ops.c
 create mode 100644 tools/testing/selftests/bpf/progs/memcg_ops.c
MAINTAINERS +2 -0
index dfc621ff629d..1be243e544da 100644
@@ -6567,6 +6567,8 @@ F:	mm/memcontrol-v1.h
 F:	mm/page_counter.c
 F:	mm/swap_cgroup.c
 F:	samples/cgroup/*
+F:	tools/testing/selftests/bpf/prog_tests/memcg_ops.c
+F:	tools/testing/selftests/bpf/progs/memcg_ops.c
 F:	tools/testing/selftests/cgroup/memcg_protection.m
 F:	tools/testing/selftests/cgroup/test_hugetlb_memcg.c
 F:	tools/testing/selftests/cgroup/test_kmem.c
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +561 -0

561 lines not on this page · raw message

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

132 lines not on this page · raw message

Signature · 1 line
2.43.0
#22 lore raw

Re: [RFC PATCH bpf-next v7 08/11] selftests/bpf: Add tests for memcg_bpf_ops

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] The inline assembly in `read_file` fails to actually trigger memory access and page faults.…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] The inline assembly in read_file fails to actually trigger memory access and page faults.
- [Medium] Error paths in real_test_memcg_ops leave child processes orphaned, preventing cgroup cleanup.
- [Medium] The commit message references a get_high_delay_ms hook, but the implemented hook is memcg_charged.
- [Low] Missing file descriptor validation after manual map lookup using bpf_map__fd().
- [Low] TOCTOU race condition from closing temporary file descriptors generated by mkstemp(). --

commit 239c9254e915ce7f13738ad4bc04054bec8bf86e
Author: Hui Zhu <[email protected]>

selftests/bpf: Add tests for memcg_bpf_ops

Add a comprehensive selftest suite for the memcg_bpf_ops functionality. These tests validate that BPF programs can correctly influence memory cgroup throttling behavior by implementing the new hooks.

Quoted 8 lines

The test suite is added in prog_tests/memcg_ops.c and covers several key scenarios:

1. test_memcg_ops_over_high:
Verifies that a BPF program can trigger throttling on a low-priority cgroup by returning a delay from the get_high_delay_ms hook when a high-priority cgroup is under pressure.

Quoted 7 lines

2. test_memcg_ops_below_low_over_high:
Tests the combination of the below_low and get_high_delay_ms hooks, ensuring they work together as expected.

3. test_memcg_ops_below_min_over_high:
Validates the interaction between the below_min and get_high_delay_ms hooks.

[Severity: Medium]
The commit message mentions the get_high_delay_ms hook multiple times, but the code implements memcg_charged_impl which attaches to struct_ops/memcg_charged. Could the commit message be updated to reflect the actual hook name used?

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +0 -0
new file mode 100644
index 0000000000000..19fd4fde22660

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +2 -0
+int read_file(const char *filename, int iterations)
+{

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_ops.c line 158

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +10 -0
+	for (int iter = 0; iter < iterations; iter++) {
+		for (i = 0; i < FILE_SIZE; i += page_size) {
+			/* access a byte to trigger page fault */
+			p = &map[i];
+			__asm__ __volatile__("" : : "r"(p) : "memory");
+		}
+
+		if (env.verbosity >= VERBOSE_NORMAL)
+			printf("%s %d %d done\n", __func__, getpid(), iter);
+	}

[Severity: High]
Does this inline assembly actually trigger a memory access?

The "r"(p) constraint just loads the address into a general-purpose register, but doesn't dereference it. The memory clobber also does not force a read of the pointer's target memory.

Should this be dereferenced, such as "r"(*p) or explicitly via (void)*(volatile char *)p, to ensure a page fault is triggered?

[ ... ]

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +5 -0
+static void real_test_memcg_ops(int read_times)
+{
+	int ret;
+	char data_file1[] = "/tmp/test_data_1_XXXXXX";
+	char data_file2[] = "/tmp/test_data_2_XXXXXX";

tools/testing/selftests/bpf/prog_tests/memcg_ops.c line 257

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +10 -0
+	char time_file1[] = "/tmp/test_time_1_XXXXXX";
+	char time_file2[] = "/tmp/test_time_2_XXXXXX";
+	pid_t pid1, pid2;
+	double time1, time2;
+	int status;
+
+	ret = mkstemp(data_file1);
+	if (!ASSERT_GE(ret, 0, "mkstemp"))
+		return;
+	close(ret);

[Severity: Low]
By closing the file descriptor returned by mkstemp() immediately and then having the child process reopen it later with fopen(), does this introduce a time of check to time of use race condition?

Would it be safer to pass the file descriptor to the child process or use a different mechanism for temporary file handling?

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_ops.c line 302

Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +9 -0
+	ret = waitpid(pid1, &status, 0);
+	if (!ASSERT_GT(ret, 0, "child1 waitpid"))
+		goto cleanup;
+	if (!ASSERT_TRUE(WIFEXITED(status), "child1 exited normally"))
+		goto cleanup;
+	if (!ASSERT_EQ(WEXITSTATUS(status), 0, "child1 exit status"))
+		goto cleanup;
+
+	ret = waitpid(pid2, &status, 0);

[Severity: Medium]
If the waitpid for pid1 fails, or if pid1 exits abnormally or returns a non-zero status, the code jumps to cleanup without waiting for or terminating pid2.

Will this leave pid2 running in the background and attached to the high-priority cgroup, preventing cgroup cleanup and affecting subsequent tests?

[ ... ]

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

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_ops.c line 356

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c new file +6 -0
+	map = bpf_object__find_map_by_name(skel->obj, ".bss");
+	if (!ASSERT_OK_PTR(map, "bpf_object__find_map_by_name .bss"))
+		goto out;
+
+	map_fd = bpf_map__fd(map);
+	bss_data = calloc(1, bpf_map__value_size(map));

[Severity: Low]
Should map_fd be validated before being used?

The BPF subsystem selftest guidelines recommend checking file descriptors returned after manual lookups, for example with ASSERT_GE(map_fd, 0, ...).

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

RFC PATCH v7 9/11 selftests/bpf: Add test for memcg_bpf_ops hierarchies

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

Add a new selftest, test_memcg_ops_hierarchies, to validate the behavior of attaching memcg_bpf_ops in a nested cgroup hierarchy, specifically testing the BPF_F_ALLOW_OVERRIDE flag.

The test case performs the following steps:
1. Creates a three-level deep cgroup hierarchy: /cg, /cg/cg, and /cg/cg/cg.
2. Attaches a BPF struct_ops to the top-level cgroup (/cg) with the BPF_F_ALLOW_OVERRIDE flag.
3. Successfully attaches a new struct_ops to the middle cgroup (/cg/cg) without the flag, overriding the inherited one.
4. Asserts that attaching another struct_ops to the deepest cgroup (/cg/cg/cg) fails with -EBUSY, because its parent did not specify BPF_F_ALLOW_OVERRIDE.

This test ensures that the attachment logic correctly enforces the override rules across a cgroup subtree.

---
 .../selftests/bpf/prog_tests/memcg_ops.c      | 73 +++++++++++++++++++
 1 file changed, 73 insertions(+)
tools/testing/selftests/bpf/prog_tests/memcg_ops.c +73 -0
index 19fd4fde2266..b4084e9327eb 100644
@@ -559,3 +559,76 @@ void test_memcg_ops_below_min_over_high(void)
 	close(low_cgroup_fd);
 	cleanup_cgroup_environment();
 }
+
+void test_memcg_ops_hierarchies(void)
+{
+	int ret, first = -1, second = -1, third = -1;
+	struct memcg_ops *skel = NULL;
+	struct bpf_map *map;
+	struct bpf_link *link1 = NULL, *link2 = NULL, *link3 = NULL;
+	DECLARE_LIBBPF_OPTS(bpf_struct_ops_opts, opts);
+
+	ret = setup_cgroup_environment();
+	if (!ASSERT_OK(ret, "setup_cgroup_environment"))
+		goto cleanup;
+
+	first = create_and_get_cgroup("/cg");
+	if (!ASSERT_GE(first, 0, "create_and_get_cgroup /cg"))
+		goto cleanup;
+	ret = enable_controllers("/cg", "memory");
+	if (!ASSERT_OK(ret, "enable_controllers"))
+		goto cleanup;
+
+	second = create_and_get_cgroup("/cg/cg");
+	if (!ASSERT_GE(second, 0, "create_and_get_cgroup /cg/cg"))
+		goto cleanup;
+	ret = enable_controllers("/cg/cg", "memory");
+	if (!ASSERT_OK(ret, "enable_controllers"))
+		goto cleanup;
+
+	third = create_and_get_cgroup("/cg/cg/cg");
+	if (!ASSERT_GE(third, 0, "create_and_get_cgroup /cg/cg/cg"))
+		goto cleanup;
+	ret = enable_controllers("/cg/cg/cg", "memory");
+	if (!ASSERT_OK(ret, "enable_controllers"))
+		goto cleanup;
+
+	skel = memcg_ops__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "memcg_ops__open_and_load"))
+		goto cleanup;
+
+	map = bpf_object__find_map_by_name(skel->obj, "low_mcg_ops");
+	if (!ASSERT_OK_PTR(map, "bpf_object__find_map_by_name low_mcg_ops"))
+		goto cleanup;
+
+	opts.target_fd = first;
+	opts.flags = BPF_F_ALLOW_OVERRIDE | BPF_F_CGROUP_FD;
+	link1 = bpf_map__attach_struct_ops_opts(map, &opts);
+	if (!ASSERT_OK_PTR(link1, "bpf_map__attach_struct_ops_opts"))
+		goto cleanup;
+
+	opts.target_fd = second;
+	opts.flags = BPF_F_CGROUP_FD;
+	link2 = bpf_map__attach_struct_ops_opts(map, &opts);
+	if (!ASSERT_OK_PTR(link2, "bpf_map__attach_struct_ops_opts"))
+		goto cleanup;
+
+	opts.target_fd = third;
+	opts.flags = BPF_F_CGROUP_FD;
+	link3 = bpf_map__attach_struct_ops_opts(map, &opts);
+	if (!ASSERT_ERR_PTR(link3, "bpf_map__attach_struct_ops_opts"))
+		goto cleanup;
+
+cleanup:
+	bpf_link__destroy(link1);
+	bpf_link__destroy(link2);
+	bpf_link__destroy(link3);
+	if (skel) {
+		memcg_ops__detach(skel);
+		memcg_ops__destroy(skel);
+	}
+	close(first);
+	close(second);
+	close(third);
+	cleanup_cgroup_environment();
+}
Signature · 1 line
2.43.0
#24 lore raw

Re: [RFC PATCH bpf-next v7 09/11] selftests/bpf: Add test for memcg_bpf_ops hierarchies

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] The test reuses the identical `low_mcg_ops` map for both the parent and child overrides, failing…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] The test reuses the identical low_mcg_ops map for both the parent and child overrides, failing to properly test the override mechanism and clobbering its own state during cleanup.
- [Low] The test verifies that the third attachment fails but does not check if it fails with the correct error code (-EBUSY) as claimed in the commit message. --

commit ac1e7b9da1794e345399c9485b390263c35e79df
Author: Hui Zhu <[email protected]> selftests/bpf: Add test for memcg_bpf_ops hierarchies

This commit adds a new selftest, test_memcg_ops_hierarchies, to validate the behavior of attaching memcg_bpf_ops in a nested cgroup hierarchy. It verifies the enforcement of the BPF_F_ALLOW_OVERRIDE flag across a three-level deep cgroup subtree.

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c +0 -0
index 19fd4fde22660..b4084e9327eba 100644
@@ -559,3 +559,76 @@ void test_memcg_ops_below_min_over_high(void)

[ ... ]

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c +7 -0
+	skel = memcg_ops__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "memcg_ops__open_and_load"))
+		goto cleanup;
+
+	map = bpf_object__find_map_by_name(skel->obj, "low_mcg_ops");
+	if (!ASSERT_OK_PTR(map, "bpf_object__find_map_by_name low_mcg_ops"))
+		goto cleanup;

tools/testing/selftests/bpf/prog_tests/memcg_ops.c void test_memcg_ops_below_min_over_high(void) · line 612

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c +10 -0
+
+	opts.target_fd = first;
+	opts.flags = BPF_F_ALLOW_OVERRIDE | BPF_F_CGROUP_FD;
+	link1 = bpf_map__attach_struct_ops_opts(map, &opts);
+	if (!ASSERT_OK_PTR(link1, "bpf_map__attach_struct_ops_opts"))
+		goto cleanup;
+
+	opts.target_fd = second;
+	opts.flags = BPF_F_CGROUP_FD;
+	link2 = bpf_map__attach_struct_ops_opts(map, &opts);

[Severity: Medium]
Is it intentional to reuse the identical low_mcg_ops map for both the parent and child overrides?

Because the overriding pointer is physically identical to the overridden one, this might not genuinely prove that the kernel substituted the operations.

Also, could this clobber the state during cleanup since the kernel's bpf_memcg_ops_unreg() clears descendant cgroups by checking map pointer equality?

Would it be better to retrieve a distinct map, such as high_mcg_ops, for the child cgroup to correctly test overriding?

tools/testing/selftests/bpf/prog_tests/memcg_ops.c void test_memcg_ops_below_min_over_high(void) · line 619

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c +7 -0
+	if (!ASSERT_OK_PTR(link2, "bpf_map__attach_struct_ops_opts"))
+		goto cleanup;
+
+	opts.target_fd = third;
+	opts.flags = BPF_F_CGROUP_FD;
+	link3 = bpf_map__attach_struct_ops_opts(map, &opts);
+	if (!ASSERT_ERR_PTR(link3, "bpf_map__attach_struct_ops_opts"))

[Severity: Low]
The commit message states that attaching another struct_ops to the deepest cgroup fails with -EBUSY. Does ASSERT_ERR_PTR() only check for a generic failure pointer?

Should this test explicitly verify that errno == EBUSY to ensure the hierarchical restriction logic is failing for the exact reason expected?

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/memcg_ops.c +3 -0
+		goto cleanup;
+
+cleanup:
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author
#25 lore raw

RFC PATCH v7 10/11 selftests/bpf: Add selftest for memcg async reclaim via BPF

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

Add a BPF selftest that demonstrates and validates asynchronous memory reclaim for a memory cgroup using BPF struct_ops and the BPF workqueue mechanism.

The BPF program (progs/memcg_async_reclaim.c) registers struct_ops callbacks for memcg_charged and memcg_uncharged to track the memory charge/uncharge events of a target cgroup. When accumulated memory usage exceeds a configured threshold, the memcg_charged callback enqueues an asynchronous workqueue item via bpf_wq_start(). The workqueue callback then invokes bpf_try_to_free_mem_cgroup_pages() to reclaim pages from the target memcg without blocking the charging context.

The test (prog_tests/memcg_async_reclaim.c) verifies the effectiveness of this mechanism by:
1. Running a memory workload (sequential file write + mmap read) without the BPF async reclaim program attached, and asserting that the memcg "max" event counter increases, confirming that the cgroup memory limit is being hit.
2. Repeating the same workload with the BPF async reclaim program active, and asserting that the "max" event counter does NOT increase, confirming that proactive async reclaim successfully kept memory usage below the hard limit.

A new helper read_cgroup_file() is added to cgroup_helpers.c to support reading memcg interface files (e.g. memory.events) from within the test infrastructure.

The new test files are also registered in MAINTAINERS under the Memory Controller section.

---
 MAINTAINERS                                   |   2 +
 tools/testing/selftests/bpf/cgroup_helpers.c  |  41 +++
 tools/testing/selftests/bpf/cgroup_helpers.h  |   2 +
 .../bpf/prog_tests/memcg_async_reclaim.c      | 333 ++++++++++++++++++
 .../selftests/bpf/progs/memcg_async_reclaim.c | 203 +++++++++++
 5 files changed, 581 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
 create mode 100644 tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
MAINTAINERS +2 -0
index 1be243e544da..b2e64ef8c60c 100644
@@ -6567,7 +6567,9 @@ F:	mm/memcontrol-v1.h
 F:	mm/page_counter.c
 F:	mm/swap_cgroup.c
 F:	samples/cgroup/*
+F:	tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
 F:	tools/testing/selftests/bpf/prog_tests/memcg_ops.c
+F:	tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
 F:	tools/testing/selftests/bpf/progs/memcg_ops.c
 F:	tools/testing/selftests/cgroup/memcg_protection.m
 F:	tools/testing/selftests/cgroup/test_hugetlb_memcg.c
tools/testing/selftests/bpf/cgroup_helpers.c +41 -0

47 lines not on this page · raw message

tools/testing/selftests/bpf/cgroup_helpers.h +2 -0
index 3857304be874..d722e8ff8dee 100644
@@ -13,6 +13,8 @@
 int enable_controllers(const char *relative_path, const char *controllers);
 int write_cgroup_file(const char *relative_path, const char *file,
 		      const char *buf);
+int read_cgroup_file(const char *relative_path, const char *file,
+		     char *buf, size_t buf_size);
 int write_cgroup_file_parent(const char *relative_path, const char *file,
 			     const char *buf);
 int cgroup_setup_and_join(const char *relative_path);
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +333 -0

333 lines not on this page · raw message

tools/testing/selftests/bpf/progs/memcg_async_reclaim.c new file +203 -0

203 lines not on this page · raw message

Signature · 1 line
2.43.0
#26 lore raw

Re: [RFC PATCH bpf-next v7 10/11] selftests/bpf: Add selftest for memcg async reclaim via BPF

Thank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider: - [High] The inline assembly intended to trigger page faults evaluates the pointer address but does not…

Thank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider:
- [High] The inline assembly intended to trigger page faults evaluates the pointer address but does not dereference it.
- [High] Hardcoded ONE_MB_PAGE_COUNT assumes a 4KB page size, leading to integer underflow on architectures with larger page sizes.
- [Medium] Test uses /tmp/ for file I/O, which breaks memory reclaim and causes OOM kills if /tmp/ is mounted as tmpfs.
- [Medium] The test is structurally flawed and highly racy because the asynchronous BPF workqueue cannot keep up with the synchronous high-speed file writes.
- [Medium] Failure paths fail to reset the async_free_run lock state, permanently deadlocking the async reclaim mechanism.
- [Medium] The helper get_cgroup_memcg_from_id stores acquired references into a struct passed by pointer, causing verifier rejection if not inlined.
- [Low] Incorrect format specifier %lu used for formatting a u64 variable.
- [Low] Double close of the cgroup_fd during the error handling path for the second test phase.
--

commit 52716fb46cd2997bdfa1c7eea08763279dccc7d6
Author: Hui Zhu <[email protected]>

selftests/bpf: Add selftest for memcg async reclaim via BPF

Add a BPF selftest that demonstrates and validates asynchronous memory reclaim for a memory cgroup using BPF struct_ops and the BPF workqueue mechanism.

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

[ ... ]

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +6 -0
+static int
+setup_max_cgroup(const char *cg_path, u64 cg_max, u64 *cgroup_id,
+		 int *cgroup_fd)
+{
+	int ret;
+	char limit_buf[20];

tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c line 51

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +10 -0
+
+	*cgroup_fd = create_and_get_cgroup(cg_path);
+	if (!ASSERT_GE(*cgroup_fd, 0, "create_and_get_cgroup"))
+		goto cleanup;
+
+	*cgroup_id = get_cgroup_id(cg_path);
+	if (!ASSERT_GT(*cgroup_id, 0, "get_cgroup_id"))
+		goto cleanup;
+
+	snprintf(limit_buf, 20, "%lu", cg_max);

[Severity: Low]
Can this truncate the u64 value on 32-bit architectures? Passing a u64 to "%lu" might be architecturally unsafe. Should "%llu" be used instead to ensure proper formatting across all platforms?

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +2 -0
+static int read_file(const char *filename, int iterations)
+{

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c line 184

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +6 -0
+	for (int iter = 0; iter < iterations; iter++) {
+		for (i = 0; i < FILE_SIZE; i += page_size) {
+			/* access a byte to trigger page fault */
+			p = &map[i];
+			__asm__ __volatile__("" : : "r"(p) : "memory");
+		}

[Severity: High]
Does this inline assembly correctly trigger a page fault? The register constraint "r"(p) loads the pointer address without forcing a memory read, which means the test might fail to generate actual memory pressure. Would it be better to use "r"(*p) or a memory constraint to ensure the address is dereferenced?

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c line 263

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +8 -0
+void test_memcg_async_reclaim(void)
+{
+	u64 cgroup_id, old_max, new_max;
+	int cgroup_fd, ret;
+	struct memcg_async_reclaim *skel;
+	struct bpf_link *link = NULL;
+	char data_file1[] = "/tmp/test_data_1_XXXXXX";
+	char data_file2[] = "/tmp/test_data_2_XXXXXX";

[Severity: Medium]
Will this test run reliably if /tmp/ is mounted as tmpfs? Shmem pages without swap backing are unreclaimable, which might bypass the BPF program entirely and cause OOM kills in test environments using tmpfs. Could migrating to a block-backed path be more robust?

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c line 285

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +7 -0
+	if (!ASSERT_OK(get_cgroup_memory_event(CG_DIR1, "max", &old_max),
+					       "get_cgroup_memory_event"))
+		goto cleanup_data_file1;
+	if (!ASSERT_OK(write_file(data_file1), "write_file"))
+		goto cleanup_data_file1;
+	if (!ASSERT_OK(read_file(data_file1, 2), "read_file"))
+		goto cleanup_data_file1;

[Severity: Medium]
Could this workload cause spurious test failures? Unthrottled file writes might effortlessly outpace the 32-page asynchronous batches from the BPF workqueue, resulting in direct reclaim triggering before the async batches complete. Would throttling the foreground IO or scaling the batch sizes prevent this structural race?

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c line 296

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +5 -0
+	// test with async_reclaim
+	close(cgroup_fd);
+	if (!ASSERT_OK(setup_max_cgroup(CG_DIR2, CG_LIMIT, &cgroup_id,
+					&cgroup_fd), "setup_max_cgroup"))
+		goto cleanup_data_file1;

[Severity: Low]
If setup_max_cgroup() fails, it closes its internal file descriptor on its error path. Jumping to cleanup_data_file1 will eventually fall through to close_cgroup_fd, which closes the fd again. Should the fd be set to -1 after closing, or the cleanup labels restructured to avoid a double-close?

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

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/progs/memcg_async_reclaim.c new file +4 -0
+static int get_cgroup_memcg_from_id(u64 cgroup_id, struct cgroup_memcg *cm)
+{
+	cm->cgrp = bpf_cgroup_from_id(cgroup_id);
+	if (!cm->cgrp)

tools/testing/selftests/bpf/progs/memcg_async_reclaim.c line 63

Quoted 10 lines
tools/testing/selftests/bpf/progs/memcg_async_reclaim.c new file +10 -0
+		return -1;
+
+	cm->memcg = bpf_get_mem_cgroup(&cm->cgrp->self);
+	if (!cm->memcg) {
+		bpf_cgroup_release(cm->cgrp);
+		return -1;
+	}
+
+	return 0;
+}

[Severity: Medium]
Will the BPF verifier reject this program because it stores acquired references into an indirect stack pointer (struct cgroup_memcg *cm) within a subprogram? Applying __always_inline to this helper might resolve the safety violation.

[ ... ]

tools/testing/selftests/bpf/progs/memcg_async_reclaim.c line 82

Quoted 12 lines
tools/testing/selftests/bpf/progs/memcg_async_reclaim.c new file +12 -0
+static int async_free(void *map, int *key, void *value)
+{
+	struct cgroup_memcg cm;
+	bool started_wq = false;
+
+	if (get_cgroup_memcg_from_id(bpf_args.cgroup_id, &cm) != 0)
+		return 0;
+
+	if (bpf_try_to_free_mem_cgroup_pages(cm.memcg, 32, GFP_KERNEL,
+					     0, -1) > 0) {
+		if (bpf_mem_cgroup_usage(cm.memcg) >=
+		    bpf_args.limit_bytes - (ONE_MB_PAGE_COUNT * __PAGE_SIZE)) {

[Severity: High]
Does hardcoding ONE_MB_PAGE_COUNT to 256 cause issues on architectures with page sizes larger than 4KB? For instance, evaluating 256 * 64KB produces a 16MB offset against a 12MB limit, causing massive unsigned integer underflow and completely disabling asynchronous reclaim. Could a dynamic page size calculation be used instead?

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/progs/memcg_async_reclaim.c new file +4 -0
+SEC("struct_ops/memcg_charged")
+unsigned int BPF_PROG(memcg_charged_impl, struct mem_cgroup *memcg,
+		      unsigned int nr_pages)
+{

[ ... ]

Quoted 5 lines
tools/testing/selftests/bpf/progs/memcg_async_reclaim.c new file +5 -0
+	if (__atomic_compare_exchange_n(&async_free_run,
+					&expected, 1,
+					false,
+					__ATOMIC_ACQ_REL,
+					__ATOMIC_RELAXED)) {

tools/testing/selftests/bpf/progs/memcg_async_reclaim.c line 188

Quoted 10 lines
tools/testing/selftests/bpf/progs/memcg_async_reclaim.c new file +10 -0
+		elem = bpf_map_lookup_elem(&wq_map, &key);
+		if (!elem)
+			return 0;
+
+		bpf_wq_start(&elem->work, 0);
+	}
+
+out:
+	return 0;
+}

[Severity: Medium]
Is there a scenario where this code permanently deadlocks the async reclaim mechanism? If bpf_map_lookup_elem() fails, the function returns 0 without resetting the async_free_run lock state, dropping the virtual lock forever. Would it be safer to enforce unconditional flag clearance on all error paths?

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

Re: [RFC PATCH bpf-next v7 10/11] selftests/bpf: Add selftest for memcg async reclaim via BPF

In reply to Hui Zhu
Can skel be dereferenced if it isn't initialized? The skel variable is declared without initialization to NULL, while link is explicitly initialized to NULL. If control reaches the cleanup block…
Quoted 5 lines
MAINTAINERS +0 -0
index c9b3dfe2498b..29de8e2fe55d 100644
@@ -6576,7 +6576,9 @@ F:	mm/memcontrol-v1.h

[ ... ]

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +0 -0
new file mode 100644
index 000000000000..bf25967c911c
@@ -0,0 +1,333 @@

[ ... ]

tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c line 263

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +8 -0
+void test_memcg_async_reclaim(void)
+{
+	u64 cgroup_id, old_max, new_max;
+	int cgroup_fd, ret;
+	struct memcg_async_reclaim *skel;
+	struct bpf_link *link = NULL;
+	char data_file1[] = "/tmp/test_data_1_XXXXXX";
+	char data_file2[] = "/tmp/test_data_2_XXXXXX";

Can skel be dereferenced if it isn't initialized? The skel variable is declared without initialization to NULL, while link is explicitly initialized to NULL. If control reaches the cleanup block without memcg_async_reclaim__open_and_load() succeeding, skel remains uninitialized:

tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c line 324

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +4 -0
+cleanup:
+	bpf_link__destroy(link);
+	memcg_async_reclaim__detach(skel);
+	memcg_async_reclaim__destroy(skel);

The generated detach and destroy helpers will dereference skel through obj->skeleton. Other tests in prog_tests/ check if (skel) before calling detach/destroy to handle this case safely.

This was raised by XIAO WU in v6 review
(https://lore.kernel.org/all/[email protected]/) in the context of memcg_ops hierarchies test, but the same pattern appears in this new async_reclaim test added in v7.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26429228214

author
#28 lore raw

RFC PATCH v7 11/11 samples/bpf: Add memcg priority control and async reclaim example

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

Add a sample program demonstrating two complementary use cases for the memcg_bpf_ops feature: priority-based memory throttling and workqueue-driven asynchronous page reclaim.

The sample consists of a BPF program and a userspace loader:

1. memcg.bpf.c: A BPF program with the following capabilities:
- Monitors PGFAULT events on a high-priority cgroup via a tracepoint. When the per-second PGFAULT sum exceeds a configurable threshold, a trigger timestamp is recorded.
- Priority throttling: uses the below_low / below_min hooks on the high-priority cgroup and the memcg_charged hook on the low-priority cgroup to apply a configurable delay (over_high_ms), protecting the high-priority workload.
- Async reclaim: uses the memcg_charged / memcg_uncharged hooks together with a BPF workqueue to trigger background page reclaim on the low-priority cgroup when its memory usage exceeds a configurable byte threshold (async_trigger_bytes), without blocking the charging context.
- Six struct_ops variants are exported to allow userspace to attach only the hooks needed for the chosen feature combination:
high_mcg_ops, high_mcg_ops_below_low, high_mcg_ops_below_min, low_mcg_ops (combined), low_mcg_ops_high_delay, low_mcg_ops_async.
- A prog_init syscall program initialises the BPF workqueue and copies the configuration from userspace before struct_ops are attached.

2. memcg.c: A userspace loader that parses command-line arguments, resolves cgroup IDs from filesystem inodes, loads the BPF skeleton, calls prog_init via bpf_prog_test_run_opts(), and selects and attaches the appropriate struct_ops map for the requested feature combination. It supports BPF_F_ALLOW_OVERRIDE for stackable policies.

Users can run workloads of different priorities in two cgroups and observe the low-priority workload being throttled or proactively reclaimed to protect the high-priority one.

Example usage:
# Priority throttling only:

  # ./memcg --low_path /sys/fs/cgroup/low \
  #         --high_path /sys/fs/cgroup/high \
  #         --threshold 1000 --over_high_ms 500 --use_below_low

# Async reclaim only:

  # ./memcg --low_path /sys/fs/cgroup/low \
  #         --threshold 1000 --async_trigger_bytes 33554432

# Both features combined:

  # ./memcg --low_path /sys/fs/cgroup/low \
  #         --high_path /sys/fs/cgroup/high \
  #         --threshold 1000 --over_high_ms 500 \
  #         --async_trigger_bytes 33554432
---
 MAINTAINERS             |   2 +
 samples/bpf/.gitignore  |   1 +
 samples/bpf/Makefile    |   8 +-
 samples/bpf/memcg.bpf.c | 380 +++++++++++++++++++++++++++++++++++++
 samples/bpf/memcg.c     | 411 ++++++++++++++++++++++++++++++++++++++++
 5 files changed, 801 insertions(+), 1 deletion(-)
 create mode 100644 samples/bpf/memcg.bpf.c
 create mode 100644 samples/bpf/memcg.c
MAINTAINERS +2 -0
index b2e64ef8c60c..a3f737a506b5 100644
@@ -6566,6 +6566,8 @@ F:	mm/memcontrol-v1.c
 F:	mm/memcontrol-v1.h
 F:	mm/page_counter.c
 F:	mm/swap_cgroup.c
+F:	samples/bpf/memcg.bpf.c
+F:	samples/bpf/memcg.c
 F:	samples/cgroup/*
 F:	tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
 F:	tools/testing/selftests/bpf/prog_tests/memcg_ops.c
samples/bpf/.gitignore +1 -0
index 0002cd359fb1..0de6569cdefd 100644
@@ -49,3 +49,4 @@ iperf.*
 /vmlinux.h
 /bpftool/
 /libbpf/
+memcg
samples/bpf/Makefile +7 -1
index 95a4fa1f1e44..b00698bdc53b 100644
@@ -37,6 +37,7 @@ tprogs-y += xdp_fwd
 tprogs-y += task_fd_query
 tprogs-y += ibumad
 tprogs-y += hbm
+tprogs-y += memcg
 
 # Libbpf dependencies
 LIBBPF_SRC = $(TOOLS_PATH)/lib/bpf
@@ -122,6 +123,7 @@ always-y += task_fd_query_kern.o
 always-y += ibumad_kern.o
 always-y += hbm_out_kern.o
 always-y += hbm_edt_kern.o
+always-y += memcg.bpf.o
 
 COMMON_CFLAGS = $(TPROGS_USER_CFLAGS)
 TPROGS_LDFLAGS = $(TPROGS_USER_LDFLAGS)
@@ -289,6 +291,8 @@ $(obj)/hbm_out_kern.o: $(src)/hbm.h $(src)/hbm_kern.h
 $(obj)/hbm.o: $(src)/hbm.h
 $(obj)/hbm_edt_kern.o: $(src)/hbm.h $(src)/hbm_kern.h
 
+memcg: $(obj)/memcg.skel.h
+
 # Override includes for xdp_sample_user.o because $(srctree)/usr/include in
 # TPROGS_CFLAGS causes conflicts
 XDP_SAMPLE_CFLAGS += -Wall -O2 \
@@ -347,11 +351,13 @@ $(obj)/%.bpf.o: $(src)/%.bpf.c $(obj)/vmlinux.h $(src)/xdp_sample.bpf.h $(src)/x
 		-I$(LIBBPF_INCLUDE) $(CLANG_SYS_INCLUDES) \
 		-c $(filter %.bpf.c,$^) -o $@
 
-LINKED_SKELS := xdp_router_ipv4.skel.h
+LINKED_SKELS := xdp_router_ipv4.skel.h memcg.skel.h
 clean-files += $(LINKED_SKELS)
 
 xdp_router_ipv4.skel.h-deps := xdp_router_ipv4.bpf.o xdp_sample.bpf.o
 
+memcg.skel.h-deps := memcg.bpf.o
+
 LINKED_BPF_SRCS := $(patsubst %.bpf.o,%.bpf.c,$(foreach skel,$(LINKED_SKELS),$($(skel)-deps)))
 
 BPF_SRCS_LINKED := $(notdir $(wildcard $(src)/*.bpf.c))
samples/bpf/memcg.bpf.c new file +380 -0

380 lines not on this page · raw message

samples/bpf/memcg.c new file +411 -0

411 lines not on this page · raw message

Signature · 1 line
2.43.0
#29 lore raw

Re: [RFC PATCH bpf-next v7 11/11] samples/bpf: Add memcg priority control and async reclaim example

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Medium] Non-atomic updates to the global `aggregation_map` in the `handle_count_memcg_events` tracepoint…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] Non-atomic updates to the global aggregation_map in the handle_count_memcg_events tracepoint lead to data races and lost PGFAULT updates.
- [Medium] Atomic one-shot guards permanently leak in error paths, deadlocking the async reclaim functionality.
- [Low] parse_u64 relies entirely on errno and fails to detect completely non-numeric input strings, silently returning 0.
- [Low] Ignoring the return value of __atomic_add_fetch and using a subsequent READ_ONCE introduces an unnecessary race window. --

commit 0eac8db0526f6826e19ed8ba2b922d7d358b6032
Author: Hui Zhu <[email protected]>
Subject: samples/bpf: Add memcg priority control and async reclaim example

This commit adds a sample program demonstrating the memcg_bpf_ops feature. It provides priority-based memory throttling and workqueue-driven asynchronous page reclaim using a BPF program and userspace loader.

Quoted 5 lines
samples/bpf/memcg.bpf.c new file +0 -0
new file mode 100644
index 0000000000000..0995284794ac7

[ ... ]

samples/bpf/memcg.bpf.c line 120

Quoted 8 lines
samples/bpf/memcg.bpf.c new file +8 -0
+static int async_free(void *map, int *key, void *value)
+{
+	struct cgroup_memcg cm;
+	bool started_wq = false;
+	int i;
+
+	if (get_cgroup_memcg_from_id(local_config.low_cgroup_id, &cm) != 0)
+		return 0;

[Severity: Medium]
Can the async_free_run guard permanently leak if get_cgroup_memcg_from_id fails? Returning early here skips the lock release at the end of the function, which would deadlock the async reclaim functionality.

Quoted 2 lines
samples/bpf/memcg.bpf.c new file +2 -0
+
+	for (i = 0; i < ASYNC_FREE_LOOP_MAX; i++) {

[ ... ]

Quoted 8 lines
samples/bpf/memcg.bpf.c new file +8 -0
+	}
+
+	put_cgroup_memcg(&cm);
+
+	if (!started_wq)
+		__atomic_exchange_n(&async_free_run, 0, __ATOMIC_RELEASE);
+	return 0;
+}

[ ... ]

Quoted 4 lines
samples/bpf/memcg.bpf.c new file +4 -0
+SEC("tp/memcg/count_memcg_events")
+int handle_count_memcg_events(
+		struct trace_event_raw_memcg_rstat_events *ctx)
+{

[ ... ]

samples/bpf/memcg.bpf.c line 203

Quoted 4 lines
samples/bpf/memcg.bpf.c new file +4 -0
+	current_ts = bpf_ktime_get_ns();
+
+	if (current_ts - data->window_start_ts < ONE_SECOND_NS) {
+		data->sum += ctx->val;

[Severity: Medium]
Can this non-atomic update to the global aggregation_map lead to data races and lost PGFAULT updates? Since this map is shared across all CPUs, concurrent PGFAULT events executing the tracepoint might perform read, modify, write operations simultaneously.

Should BPF atomic instructions or a bpf_spin_lock be used here?

Quoted 4 lines
samples/bpf/memcg.bpf.c new file +4 -0
+	} else {
+		data->window_start_ts = current_ts;
+		data->sum = ctx->val;
+	}

[ ... ]

samples/bpf/memcg.bpf.c line 283

Quoted 11 lines
samples/bpf/memcg.bpf.c new file +11 -0
+static __always_inline unsigned int
+__memcg_charged_impl(struct mem_cgroup *memcg, unsigned int nr_pages)
+{
+	struct wq_elem *elem;
+	__u32 key = 0;
+	u64 expected = 0;
+	s64 cur_allocated;
+	s64 cur_old_allocated;
+
+	__atomic_add_fetch(&allocated, nr_pages, __ATOMIC_RELAXED);
+	cur_allocated = READ_ONCE(allocated);

[Severity: Low]
Is there a race window introduced by ignoring the return value of __atomic_add_fetch and performing a separate READ_ONCE? A concurrent increment by another CPU between the add and the read could cause cur_allocated to observe an inconsistent or skipped value.

Could the return value of __atomic_add_fetch be assigned directly to eliminate this window?

Quoted 6 lines
samples/bpf/memcg.bpf.c new file +6 -0
+	cur_old_allocated = READ_ONCE(old_allocated);
+	if (abs_diff(cur_allocated, cur_old_allocated) < ONE_MB_PAGE_COUNT)
+		goto out;
+	WRITE_ONCE(old_allocated, cur_allocated);
+
+	if (get_usage() < local_config.async_trigger_bytes)

samples/bpf/memcg.bpf.c line 299

Quoted 10 lines
samples/bpf/memcg.bpf.c new file +10 -0
+		goto out;
+
+	if (__atomic_compare_exchange_n(&async_free_run,
+					&expected, 1,
+					false,
+					__ATOMIC_ACQ_REL,
+					__ATOMIC_RELAXED)) {
+		elem = bpf_map_lookup_elem(&wq_map, &key);
+		if (!elem)
+			return 0;

[Severity: Medium]
Does this early return also leak the async_free_run guard if the map lookup fails? Like the early return in async_free, this skips resetting the guard and could deadlock the state machine.

Quoted 7 lines
samples/bpf/memcg.bpf.c new file +7 -0
+
+		bpf_wq_start(&elem->work, 0);
+	}
+
+out:
+	return 0;
+}

[ ... ]

Quoted 5 lines
samples/bpf/memcg.c new file +0 -0
new file mode 100644
index 0000000000000..0929d868e6d8f

[ ... ]

samples/bpf/memcg.c line 130

Quoted 7 lines
samples/bpf/memcg.c new file +7 -0
+static uint64_t parse_u64(const char *str, const char *prog)
+{
+	uint64_t value;
+
+	errno = 0;
+	value = strtoull(str, NULL, 10);
+	if (errno != 0) {

[Severity: Low]
Does this code silently return 0 for completely non-numeric input strings?

The strtoull function does not set errno if the input string contains no valid digits. Since the endptr argument is NULL, could malformed arguments like --async_trigger_bytes abc silently return 0 instead of raising an error?

Quoted 7 lines
samples/bpf/memcg.c new file +7 -0
+		fprintf(stderr, "ERROR: strtoull '%s' failed: %d\n",
+			str, errno);
+		usage(prog);
+		exit(-errno);
+	}
+	return value;
+}

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#30 lore raw
In reply to Hui Zhu
Quoted 33 lines · On Tue, 26 May 2026 10:20:00 +0800 Hui Zhu <[email protected]> wrote:

From: Hui Zhu <[email protected]>

Overview:
This series introduces BPF struct_ops support for the memory controller, enabling userspace BPF programs to implement custom, dynamic memory management policies per cgroup. The feature allows BPF programs to hook into the core reclaim and charge paths without requiring kernel modifications, providing a flexible alternative to static knobs such as memory.low and memory.min.

The series enables two complementary use cases.

Dynamic memory protection: static memory protection thresholds (memory.low, memory.min) are poor fits for workloads whose actual memory activity varies over time. A high-priority cgroup holding a large working set but temporarily idle will still suppress reclaim on its siblings, wasting available memory. A BPF-driven approach can observe real workload activity -- page faults, charge/uncharge events -- and activate or withdraw protection dynamically. The test results at the end of this letter quantify the difference: in a scenario where the high-priority cgroup is idle, the BPF-controlled low-priority cgroup achieves roughly 37x higher throughput than with static memory.low.

Asynchronous proactive reclaim: the memcg_charged and memcg_uncharged hooks, combined with the BPF workqueue mechanism and the new bpf_try_to_free_mem_cgroup_pages() kfunc, enable BPF programs to perform proactive background reclaim without blocking the charge path. The pattern works as follows: the memcg_charged callback tracks accumulated memory usage; when usage crosses a configurable threshold, it enqueues an asynchronous work item via bpf_wq_start() and returns immediately without throttling the charging task. The workqueue callback then invokes bpf_try_to_free_mem_cgroup_pages() to reclaim pages from the target cgroup; if usage remains elevated after reclaim, the callback re-enqueues

Quoted 9 lines

itself to continue. This allows a BPF program to keep a cgroup's footprint below its hard limit (memory.max) entirely in the background, avoiding the OOM killer or direct-reclaim stalls that would otherwise occur. The selftest for this feature (patch 10/11) validates the mechanism concretely: a workload that writes and mmaps a 64 MB file inside a 32 MB cgroup reliably triggers memory.events "max" events without BPF; with the async reclaim program attached, the "max" counter does not increase at all across the same workload.

Hi Hui,

Thanks for the series.
Would it not be simpler to just have another memcg knob, something like memory.high_async.
When memory usage > memory.high_async, queue a per-memcg work item that calls try_to_free_mem_cgroup_pages() until usage drops back below some threshold. I am not sure I see what programability aspect from bpf you need here.

Thanks

Quoted 244 lines

08/11 selftests/bpf: Add tests for memcg_bpf_ops
Adds prog_tests/memcg_ops.c covering three scenarios:
memcg_charged-only throttling, below_low + memcg_charged interaction, and below_min + memcg_charged interaction. A tracepoint on memcg:count_memcg_events (PGFAULT) is used to detect memory pressure and trigger hooks accordingly.

09/11 selftests/bpf: Add test for memcg_bpf_ops hierarchies
Validates BPF_F_ALLOW_OVERRIDE attachment semantics across a three-level cgroup hierarchy: attach with ALLOW_OVERRIDE at the root, override at the middle level without the flag, then assert that attaching to the leaf correctly fails with -EBUSY.

10/11 selftests/bpf: Add selftest for memcg async reclaim via BPF
Demonstrates and validates asynchronous memory reclaim: a BPF program uses the memcg_charged/memcg_uncharged hooks to track accumulated usage and, when a threshold is exceeded, enqueues a bpf_wq_start() workqueue item that calls bpf_try_to_free_mem_cgroup_pages() without blocking the charge path. The test asserts that with the BPF program active, memory.events "max" events do not increase under a workload that would otherwise exceed the hard limit.

11/11 samples/bpf: Add memcg priority control and async reclaim example
Adds a complete sample (samples/bpf/memcg.bpf.c + memcg.c) demonstrating both features. The BPF side monitors PGFAULT events on a high-priority cgroup; when the per-second fault count crosses a configurable threshold, it activates below_low or below_min protection for the high-priority cgroup and/or applies a charge delay to the low-priority cgroup. Six struct_ops variants are exported so userspace can attach only the hooks needed. Async reclaim is optionally combined with priority throttling via a shared low-cgroup ops map.

Test Environment:
The following examples run on x86_64 QEMU (10 CPUs, 2 GB RAM), using a tmpfs-backed file on the host as a swap device to reduce I/O impact. Two cgroups are created -- high (high-priority) and low (low-priority) -- and each test runs two concurrent stress-ng workloads, one per cgroup, each requesting 3 GB of memory.

  # mkdir /sys/fs/cgroup/high /sys/fs/cgroup/low
  # free -h
                 total   used    free  shared  buff/cache  available
  Mem:           1.9Gi  317Mi  1.6Gi   1.0Mi       144Mi      1.6Gi
  Swap:          4.0Gi     0B  4.0Gi

Baseline: no memory priority policy:
Both cgroups run without any reclaim protection. Results are roughly equal, as expected:

cgroup bogo ops/s
high 4,979
low 4,927

Test 1: memory.low protection:
Setting memory.low on the high-priority cgroup protects it from reclaim, at the cost of pushing reclaim pressure onto the low-priority cgroup:

  # echo $((3 * 1024 * 1024 * 1024)) > /sys/fs/cgroup/high/memory.low

cgroup bogo ops/s
high 450,290
low 11,307

The high-priority cgroup benefits significantly, but memory.low relies on static usage thresholds and cannot adapt to actual workload behavior.

Test 2: memory.low with an idle high-priority task:
Here the high-priority cgroup runs a Python script that allocates 3 GB and then sleeps, simulating a low-activity but memory-holding workload. Because the process is idle, it generates no page faults and does not actively use its memory. Yet memory.low still protects it, continuing to suppress the low-priority cgroup's performance:

cgroup bogo ops/s
low 14,757

The low-priority cgroup remains significantly throttled despite the high-priority cgroup being effectively idle -- a clear limitation of static memory.low control.

Test 3: memcg eBPF -- dynamic priority control:
memcg is a sample program introduced in this patch series (samples/bpf/memcg.c + memcg.bpf.c). It loads a BPF program that monitors PGFAULT events in the high-priority cgroup. When the per-second fault count exceeds a configured threshold, the hook activates below_min protection for one second; otherwise the cgroup receives no special treatment.

  # ./memcg --low_path=/sys/fs/cgroup/low  \
            --high_path=/sys/fs/cgroup/high \
            --threshold=1 --use_below_min
  Successfully attached!

3a. Both cgroups under active memory pressure:

When both cgroups run stress-ng, the high-priority cgroup generates frequent page faults and the BPF hook activates protection, matching the behavior of memory.low:

cgroup bogo ops/s
high 404,392
low 11,404

3b. High-priority cgroup is idle (Python + sleep):

Because the sleeping Python process generates no page faults, the BPF hook never activates, and the low-priority cgroup is free to reclaim memory normally:

cgroup bogo ops/s
low 551,083

This is a ~37x improvement over the equivalent memory.low scenario (Test 2), demonstrating that eBPF-driven dynamic control can accurately reflect actual workload activity and avoid unnecessary protection of idle high-priority tasks.

Summary:
Scenario low-cgroup bogo ops/s
Baseline (no policy) ~4,927

  memory.low, both active                       ~11,307
  memory.low, high idle                         ~14,757
  memcg eBPF, both active                       ~11,404

memcg eBPF, high idle ~551,083

References:
[1] https://patchew.org/linux/[email protected]/

Changelog:
v7:
Change base commits of "mm: BPF OOM" to v3.
Some fixes according to the comments of bpf-ci.
Rename get_high_delay_ms hook to memcg_charged; add memcg_uncharged hook for tracking uncharge events.
Update below_low and below_min hooks to receive elow/emin and usage as explicit arguments.
Add bpf_try_to_free_mem_cgroup_pages kfunc to expose cgroup reclaim to BPF programs.
Add selftest for BPF-driven asynchronous page reclaim.
Extend samples/bpf/memcg to support async reclaim in addition to priority throttling.
v6:
Based on the bot+bof-ci comments, fixed the following issues. Added fast-path check with unlikely() before SRCU lock acquisition to optimize the no-BPF case in BPF_MEMCG_CALL.
Add missing newline in pr_warn message to bpf_memcontrol_init. Added comprehensive child process exit status checking with WIFEXITED() and WEXITSTATUS(), and added zombie process prevention in real_test_memcg_ops.
Changed malloc() to calloc() for BSS data allocation in all test functions and samples main function.
Change srcu_read_lock(&memcg_bpf_srcu) to lockdep_assert_held(&cgroup_mutex) in function memcontrol_bpf_online and memcontrol_bpf_offline.
v5:
Based on the bot+bof-ci comments, fixed the following issues. Fixed issues in memcg_ops.c and memcg.bpf.c by moving variable declaration to the beginning of need_threshold() function.
The 'u64 current_ts' variable must be declared before any executable statements
Improved input validation in samples/bpf/memcg.c by adding a new parse_u64() helper function. This function properly handles errors from strtoull() and provides better error messages when parsing threshold and over_high_ms command-line arguments.
Move check for prog->sleepable after validating member offsets in mm/bpf_memcontrol.c bpf_memcg_ops_check_member.
Fixed sscanf return value checking in prog_tests/memcg_ops.c. Changed the condition from 'sscanf() < 0' to 'sscanf() != 1' because sscanf returns the number of successfully matched items, not a negative value on error. This makes the test more reliable when reading timing data from temporary files.
v4:
Fix the issues according to the comments from bot+bof-ci. According to JP Kobryn's comments, move exit(0) from real_test_memcg_ops_child_work to real_test_memcg_ops.
Fix issues in the bpf_memcg_ops_reg function.
v3:
According to the comments from Michal Koutný and Chen Ridong, update hooks to get_high_delay_ms, below_low, below_min, handle_cgroup_online, and handle_cgroup_offline.
According to Michal Koutný's comments, add BPF_F_ALLOW_OVERRIDE support to memcg_bpf_ops.
v2:
According to Tejun Heo's comments, rebased on Roman Gushchin's BPF OOM patch series [1] and added hierarchical delegation support. According to the comments from Roman Gushchin and Michal Hocko, designed concrete use case scenarios and provided test results.

Hui Zhu (7):
bpf: Pass flags in bpf_link_create for struct_ops
mm: memcontrol: Add BPF struct_ops for memory controller mm/bpf: Add bpf_try_to_free_mem_cgroup_pages kfunc selftests/bpf: Add tests for memcg_bpf_ops selftests/bpf: Add test for memcg_bpf_ops hierarchies selftests/bpf: Add selftest for memcg async reclaim via BPF samples/bpf: Add memcg priority control and async reclaim example

Roman Gushchin (4):
bpf: move bpf_struct_ops_link into bpf.h
bpf: allow attaching struct_ops to cgroups
libbpf: fix return value on memory allocation failure
libbpf: introduce bpf_map__attach_struct_ops_opts()

 MAINTAINERS                                   |   6 +
 include/linux/bpf-cgroup-defs.h               |   3 +
 include/linux/bpf-cgroup.h                    |  16 +
 include/linux/bpf.h                           |  10 +
 include/linux/memcontrol.h                    | 250 ++++++-
 include/uapi/linux/bpf.h                      |   5 +-
 kernel/bpf/bpf_struct_ops.c                   |  67 +-
 kernel/bpf/cgroup.c                           |  46 ++
 mm/bpf_memcontrol.c                           | 355 +++++++++-
 mm/memcontrol.c                               |  43 +-
 samples/bpf/.gitignore                        |   1 +
 samples/bpf/Makefile                          |   8 +-
 samples/bpf/memcg.bpf.c                       | 380 +++++++++++
 samples/bpf/memcg.c                           | 411 ++++++++++++
 tools/include/uapi/linux/bpf.h                |   3 +-
 tools/lib/bpf/libbpf.c                        |  22 +-
 tools/lib/bpf/libbpf.h                        |  14 +
 tools/lib/bpf/libbpf.map                      |   1 +
 tools/testing/selftests/bpf/cgroup_helpers.c  |  41 ++
 tools/testing/selftests/bpf/cgroup_helpers.h  |   2 +
 .../bpf/prog_tests/memcg_async_reclaim.c      | 333 +++++++++
 .../selftests/bpf/prog_tests/memcg_ops.c      | 634 ++++++++++++++++++
 .../selftests/bpf/progs/memcg_async_reclaim.c | 203 ++++++
 tools/testing/selftests/bpf/progs/memcg_ops.c | 132 ++++
 24 files changed, 2952 insertions(+), 34 deletions(-)
 create mode 100644 samples/bpf/memcg.bpf.c
 create mode 100644 samples/bpf/memcg.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_ops.c
 create mode 100644 tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
 create mode 100644 tools/testing/selftests/bpf/progs/memcg_ops.c
Signature · 1 line
2.43.0
author
#31 lore raw
Quoted 16 lines · On Tue, 26 May 2026 10:20:00 +0800 Hui Zhu <[email protected]> wrote:
Quoted 14 lines

From: Hui Zhu <[email protected]>

Overview:
This series introduces BPF struct_ops support for the memory controller, enabling userspace BPF programs to implement custom, dynamic memory management policies per cgroup. The feature allows BPF programs to hook into the core reclaim and charge paths without requiring kernel modifications, providing a flexible alternative to static knobs such as memory.low and memory.min.

The series enables two complementary use cases.

...
...
...

Quoted 22 lines
Quoted 11 lines

Asynchronous proactive reclaim: the memcg_charged and memcg_uncharged hooks, combined with the BPF workqueue mechanism and the new bpf_try_to_free_mem_cgroup_pages() kfunc, enable BPF programs to perform proactive background reclaim without blocking the charge path. The pattern works as follows: the memcg_charged callback tracks accumulated memory usage; when usage crosses a configurable threshold, it enqueues an asynchronous work item via bpf_wq_start() and returns immediately without throttling the charging task. The workqueue callback then invokes bpf_try_to_free_mem_cgroup_pages() to reclaim pages from the target cgroup; if usage remains elevated after reclaim, the callback re-enqueues

Quoted 9 lines

itself to continue. This allows a BPF program to keep a cgroup's footprint below its hard limit (memory.max) entirely in the background, avoiding the OOM killer or direct-reclaim stalls that would otherwise occur. The selftest for this feature (patch 10/11) validates the mechanism concretely: a workload that writes and mmaps a 64 MB file inside a 32 MB cgroup reliably triggers memory.events "max" events without BPF; with the async reclaim program attached, the "max" counter does not increase at all across the same workload.

Hi Hui,

Quoted 8 lines

Thanks for the series.
Would it not be simpler to just have another memcg knob, something like memory.high_async.
When memory usage > memory.high_async, queue a per-memcg work item that calls try_to_free_mem_cgroup_pages() until usage drops back below some threshold. I am not sure I see what programability aspect from bpf you need here.

Thanks

Hi Usama,

That's a good question.

By introducing a new BPF kfunc bpf_try_to_free_mem_cgroup_pages, a BPF program can flexibly control when to start and stop async reclaim, rather than being constrained to trigger and stop based solely on memcg usage or one or two fixed events, as with traditional proactive reclaim interfaces.

For example, async reclaim could be triggered based on PSI, or on the number of page faults, or even on a combination of multiple events working together to decide both when to start and when to stop async reclaim.

That is the motivation behind adding the BPF kfunc bpf_try_to_free_mem_cgroup_pages in this patch set.

I admit the cover letter did not explain this well enough, and the example code does not demonstrate this use case either. I will address both in the next version.

Best,
Hui

Quoted 8 lines
Quoted 8 lines

08/11 selftests/bpf: Add tests for memcg_bpf_ops
Adds prog_tests/memcg_ops.c covering three scenarios:
memcg_charged-only throttling, below_low + memcg_charged interaction, and below_min + memcg_charged interaction. A tracepoint on memcg:count_memcg_events (PGFAULT) is used to detect memory pressure and trigger hooks accordingly.

...
...
...

Quoted 4 lines
Quoted 3 lines

--
2.43.0

#32 lore raw
In reply to Hui Zhu
Quoted 12 lines · Hui Zhu

From: Hui Zhu <[email protected]>

Overview:
This series introduces BPF struct_ops support for the memory controller, enabling userspace BPF programs to implement custom, dynamic memory management policies per cgroup. The feature allows BPF programs to hook into the core reclaim and charge paths without requiring kernel modifications, providing a flexible alternative to static knobs such as memory.low and memory.min.

The series enables two complementary use cases.

Quoted 7 lines

Dynamic memory protection: static memory protection thresholds (memory.low, memory.min) are poor fits for workloads whose actual memory activity varies over time. A high-priority cgroup holding a large working set but temporarily idle will still suppress reclaim on its siblings, wasting available memory. A BPF-driven approach can observe real workload activity -- page faults, charge/uncharge events -- and activate or withdraw protection dynamically.

Why the same cannot be achieved by dynamically changing protection?

Quoted 5 lines

The test results at the end of this
letter quantify the difference: in a scenario where the high-priority cgroup is idle, the BPF-controlled low-priority cgroup achieves roughly 37x higher throughput than with static memory.low.

Quoted 14 lines

Asynchronous proactive reclaim: the memcg_charged and memcg_uncharged hooks, combined with the BPF workqueue mechanism and the new bpf_try_to_free_mem_cgroup_pages() kfunc, enable BPF programs to perform proactive background reclaim without blocking the charge path. The pattern works as follows: the memcg_charged callback tracks accumulated memory usage; when usage crosses a configurable threshold, it enqueues an asynchronous work item via bpf_wq_start() and returns immediately without throttling the charging task. The workqueue callback then invokes bpf_try_to_free_mem_cgroup_pages() to reclaim pages from the target cgroup; if usage remains elevated after reclaim, the callback re-enqueues itself to continue. This allows a BPF program to keep a cgroup's footprint below its hard limit (memory.max) entirely in the background, avoiding the OOM killer or direct-reclaim stalls that would otherwise occur.

How do you account the overall work done to the specific memcg as the large part of the reclaim is done from WQ context?
Also when introducing a BPF hook please focus on describing why existing interfaces fail to achieve what you need. For the async reclaim why it is not practical or feasible to use userspace driven memory reclaim.

Signature · 2 lines
Michal Hocko
SUSE Labs
author
#33 lore raw
Quoted 3 lines · Hui Zhu

Hi Michal,

Quoted 21 lines
Quoted 13 lines

From: Hui Zhu <[email protected]>

Overview:
This series introduces BPF struct_ops support for the memory controller, enabling userspace BPF programs to implement custom, dynamic memory management policies per cgroup. The feature allows BPF programs to hook into the core reclaim and charge paths without requiring kernel modifications, providing a flexible alternative to static knobs such as memory.low and memory.min.

The series enables two complementary use cases.

Quoted 8 lines

Dynamic memory protection: static memory protection thresholds (memory.low, memory.min) are poor fits for workloads whose actual memory activity varies over time. A high-priority cgroup holding a large working set but temporarily idle will still suppress reclaim on its siblings, wasting available memory. A BPF-driven approach can observe real workload activity -- page faults, charge/uncharge events -- and activate or withdraw protection dynamically.

Quoted 1 line

Why the same cannot be achieved by dynamically changing protection?

Dynamically adjusting memory.low or memory.min is indeed an option, but it has a practical drawback: in many production environments these values are managed and pushed down by a cluster-level orchestrator (e.g. a container runtime or resource manager). Modifying them from a separate BPF-based agent risks conflicts with the orchestrator's own control loop and makes the system harder to reason about.

Beyond that, the intended use case requires rapid, short-lived adjustments -- reacting to bursts of page faults or PSI spikes and reverting just as quickly once the pressure subsides. Mutating the static knobs for that purpose feels like the wrong abstraction:
the knobs express policy intent, while what we need is a transient override that sits on top of that policy.

The hooks are therefore not meant to replace the existing limits, but to complement them: the orchestrator continues to own memory.low / memory.min, while a BPF program makes small, brief corrections in response to observed runtime behavior.

Quoted 22 lines
Quoted 7 lines

The test results at the end of this
letter quantify the difference: in a scenario where the high-priority cgroup is idle, the BPF-controlled low-priority cgroup achieves roughly 37x higher throughput than with static memory.low.

Quoted 15 lines

Asynchronous proactive reclaim: the memcg_charged and memcg_uncharged hooks, combined with the BPF workqueue mechanism and the new bpf_try_to_free_mem_cgroup_pages() kfunc, enable BPF programs to perform proactive background reclaim without blocking the charge path. The pattern works as follows: the memcg_charged callback tracks accumulated memory usage; when usage crosses a configurable threshold, it enqueues an asynchronous work item via bpf_wq_start() and returns immediately without throttling the charging task. The workqueue callback then invokes bpf_try_to_free_mem_cgroup_pages() to reclaim pages from the target cgroup; if usage remains elevated after reclaim, the callback re-enqueues itself to continue. This allows a BPF program to keep a cgroup's footprint below its hard limit (memory.max) entirely in the background, avoiding the OOM killer or direct-reclaim stalls that would otherwise occur.

Quoted 2 lines

How do you account the overall work done to the specific memcg as the large part of the reclaim is done from WQ context?

One approach to attribute the reclaim work accurately to the target memcg would be to expose a kfunc that creates a kthread_worker and attaches it to a specific cgroup. Reclaim work enqueued to that worker would then run in a context already associated with the target memcg, so the accounting would naturally fall to the right cgroup without any extra bookkeeping.

The tradeoff is additional complexity: creating a per-cgroup worker introduces resource overhead and lifecycle management concerns (e.g. when should the worker be torn down). Whether that cost is justified depends on how strictly the caller needs the reclaim to be attributed.

That said, I am not certain this is the right direction yet and would welcome your thoughts on whether this is worth pursuing, or whether there is a simpler mechanism I am overlooking.

Quoted 3 lines

Also when introducing a BPF hook please focus on describing why existing interfaces fail to achieve what you need. For the async reclaim why it is not practical or feasible to use userspace driven memory reclaim.

Noted, and thank you for both points. In the next revision I will add a dedicated section to each hook's description covering:

Why existing interfaces are insufficient. For the async reclaim case specifically, I will explain why userspace-driven reclaim (e.g. memory.reclaim, cgroup-aware madvise, or a dedicated reclaim daemon) is not practical: userspace cannot react at the granularity or latency required, and the round-trip through a syscall or procfs write introduces overhead that defeats the purpose of proactive reclaim.
What gap the new hook fills that cannot be closed by tuning existing knobs.

Best,
Hui

Quoted 4 lines
Signature · 2 lines
Michal Hocko
SUSE Labs