selftests and sample for bpf_proactive_reclaim
Subsystems (6)
cover selftests and sample for bpf_proactive_reclaim
From: Hui Zhu <[email protected]>
This series follows the bpf_proactive_reclaim() kfunc patch (v14, acked by Shakeel Butt, reviewed by JP Kobryn and Barry Song). Review feedback on that series was that ~1200 lines of selftest for a ~20 line kfunc is overkill, so the test material is split in two:
1/2 is the minimal selftest. It mirrors the memory.reclaim selftest:
charge a cgroup, call the kfunc once, and check the single bounded pass semantics (one call reclaims at most MEMCG_CHARGE_BATCH pages and, unlike a write to memory.reclaim, does not retry until the goal is reached).
2/2 moves the complex asynchronous scenario out of the selftests and into samples/bpf, where it belongs: a BPF program watches the workingset refaults of a pressured cgroup and, when they grow, reclaims a target cgroup from a bpf_wq callback through bpf_proactive_reclaim(). It runs in two modes: bench recreates the high/low priority benchmark of the old selftest, and watch keeps reclaiming for user-specified cgroups as a simple proactive-reclaim daemon. Besides exercising the kfunc end to end, the sample is meant as a design reference for anyone building their own BPF-driven reclaim policy on bpf_proactive_reclaim(), bpf_wq and the memcg kfuncs.
Hui Zhu (2):
selftests/bpf: Add bpf_proactive_reclaim test
samples/bpf: Add memcg async reclaim example
samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 10 +- samples/bpf/memcg_async_reclaim.bpf.c | 349 +++++ samples/bpf/memcg_async_reclaim.h | 39 + samples/bpf/memcg_async_reclaim_user.c | 1141 +++++++++++++++++ tools/testing/selftests/bpf/config | 1 + .../bpf/prog_tests/memcg_proactive_reclaim.c | 124 ++ .../bpf/progs/memcg_proactive_reclaim.c | 34 + 8 files changed, 1698 insertions(+), 1 deletion(-) create mode 100644 samples/bpf/memcg_async_reclaim.bpf.c create mode 100644 samples/bpf/memcg_async_reclaim.h create mode 100644 samples/bpf/memcg_async_reclaim_user.c create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_proactive_reclaim.c create mode 100644 tools/testing/selftests/bpf/progs/memcg_proactive_reclaim.c
Signature · 1 line
2.43.0
PATCH 1/2 selftests/bpf: Add bpf_proactive_reclaim test
From: Hui Zhu <[email protected]>
bpf_proactive_reclaim() performs one bounded reclaim pass per call and, unlike a write to memory.reclaim, does not retry until the goal is reached.
Charge 32 MiB of page cache to a cgroup, ask for all of it in one call, and check that the result is positive but well below the request: one pass is capped at MEMCG_CHARGE_BATCH pages, far short of 32 MiB on both 4K and 64K page kernels.
Add CONFIG_MEMCG to the config fragment, without which mm/bpf_memcontrol.c is not built at all.
--- tools/testing/selftests/bpf/config | 1 + .../bpf/prog_tests/memcg_proactive_reclaim.c | 124 ++++++++++++++++++ .../bpf/progs/memcg_proactive_reclaim.c | 34 +++++ 3 files changed, 159 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_proactive_reclaim.c create mode 100644 tools/testing/selftests/bpf/progs/memcg_proactive_reclaim.c
tools/testing/selftests/bpf/config +1 -0
@@ -57,6 +57,7 @@ CONFIG_LIRC=y CONFIG_LIVEPATCH=y CONFIG_LWTUNNEL=y CONFIG_LWTUNNEL_BPF=y +CONFIG_MEMCG=y CONFIG_MODULE_SIG=y CONFIG_MODULE_SRCVERSION_ALL=y CONFIG_MODULE_UNLOAD=y
tools/testing/selftests/bpf/prog_tests/memcg_proactive_reclaim.c new file +124 -0
124 lines not on this page · raw message
tools/testing/selftests/bpf/progs/memcg_proactive_reclaim.c new file +34 -0
@@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" +#include <bpf/bpf_helpers.h> + +struct reclaim_args { +__u64 cgroup_id; +__u64 size; +}; + +/* Signed, because bpf_test_run_opts.retval is a __u32. */ +__s64 reclaimed; + +SEC("syscall") +int memcg_proactive_reclaim (struct reclaim_args *ctx) +{ +struct mem_cgroup *memcg; +struct cgroup *cgrp; + + cgrp =bpf_cgroup_from_id (ctx->cgroup_id); +if (!cgrp) +return 0 ; + + memcg =bpf_get_mem_cgroup (&cgrp->self); +if (memcg) { + reclaimed =bpf_proactive_reclaim (memcg, ctx->size,-1 ); +bpf_put_mem_cgroup (memcg); + } +bpf_cgroup_release (cgrp); + +return 0 ; +} + +char _license[] SEC("license") = "GPL";
Signature · 1 line
2.43.0
PATCH 2/2 samples/bpf: Add memcg async reclaim example
In reply to Hui ZhuFrom: Hui Zhu <[email protected]>
Add an example of BPF-driven async proactive reclaim, keeping the complex monitoring scenario out of the selftests. A BPF program arms a bpf_wq/timer chain that watches the workingset refaults (file and anon) of a monitor cgroup; when they grow past a threshold, a round of bpf_proactive_reclaim() batches reclaims a target cgroup, re-arming the work queue until the round budget is spent.
It runs in two modes:
bench: creates a high and a low priority cgroup, drives a page-cache workload in the high one and replicates the old selftest benchmark, with reclaim counters and optional baseline comparison as the result.
watch: takes existing cgroups to monitor and reclaim and runs continuously, printing periodic statistics, so it can serve as a simple proactive-reclaim daemon.
Threshold, interval, batch size, per-round batches and swappiness are all settable on the command line.
--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 10 +- samples/bpf/memcg_async_reclaim.bpf.c | 349 ++++++++ samples/bpf/memcg_async_reclaim.h | 39 + samples/bpf/memcg_async_reclaim_user.c | 1141 ++++++++++++++++++++++++ 5 files changed, 1539 insertions(+), 1 deletion(-) create mode 100644 samples/bpf/memcg_async_reclaim.bpf.c create mode 100644 samples/bpf/memcg_async_reclaim.h create mode 100644 samples/bpf/memcg_async_reclaim_user.c
samples/bpf/.gitignore +1 -0
@@ -6,6 +6,7 @@ ibumad lathist lwt_len_hist map_perf_test +memcg_async_reclaim offwaketime per_socket_stats_example sampleip
samples/bpf/Makefile +9 -1
@@ -37,6 +37,7 @@ tprogs-y += xdp_fwd tprogs-y += task_fd_query tprogs-y += ibumad tprogs-y += hbm +tprogs-y += memcg_async_reclaim # Libbpf dependencies LIBBPF_SRC = $(TOOLS_PATH)/lib/bpf
@@ -78,6 +79,7 @@ xdp_fwd-objs := xdp_fwd_user.o task_fd_query-objs := task_fd_query_user.o $(TRACE_HELPERS) ibumad-objs := ibumad_user.o hbm-objs := hbm.o $(CGROUP_HELPERS) +memcg_async_reclaim-objs := memcg_async_reclaim_user.o $(CGROUP_HELPERS) xdp_router_ipv4-objs := xdp_router_ipv4_user.o $(XDP_SAMPLE)
@@ -122,6 +124,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_async_reclaim.bpf.o COMMON_CFLAGS = $(TPROGS_USER_CFLAGS) TPROGS_LDFLAGS = $(TPROGS_USER_LDFLAGS)
@@ -284,6 +287,10 @@ $(obj)/$(TRACE_HELPERS) $(obj)/$(CGROUP_HELPERS) $(obj)/$(XDP_SAMPLE): | libbpf_ $(obj)/xdp_router_ipv4_user.o: $(obj)/xdp_router_ipv4.skel.h +$(obj)/memcg_async_reclaim_user.o: $(obj)/memcg_async_reclaim.skel.h \ + $(src)/memcg_async_reclaim.h +$(obj)/memcg_async_reclaim.bpf.o: $(src)/memcg_async_reclaim.h + $(obj)/tracex5.bpf.o: $(obj)/syscall_nrs.h $(obj)/hbm_out_kern.o: $(src)/hbm.h $(src)/hbm_kern.h $(obj)/hbm.o: $(src)/hbm.h
@@ -347,10 +354,11 @@ $(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_async_reclaim.skel.h clean-files += $(LINKED_SKELS) xdp_router_ipv4.skel.h-deps := xdp_router_ipv4.bpf.o xdp_sample.bpf.o +memcg_async_reclaim.skel.h-deps := memcg_async_reclaim.bpf.o LINKED_BPF_SRCS := $(patsubst %.bpf.o,%.bpf.c,$(foreach skel,$(LINKED_SKELS),$($(skel)-deps)))
samples/bpf/memcg_async_reclaim.bpf.c new file +349 -0
349 lines not on this page · raw message
samples/bpf/memcg_async_reclaim.h new file +39 -0
@@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Shared between memcg_async_reclaim.bpf.c and memcg_async_reclaim_user.c. +* +* Both sides must have pulled in their type headers first: vmlinux.h for the +* BPF program, <linux/types.h> (via test_progs.h or libbpf) for the loader. +*/ +#ifndef __MEMCG_ASYNC_RECLAIM_H +#define __MEMCG_ASYNC_RECLAIM_H + +struct reclaim_cfg { +/* Cgroup whose refaults are watched, i.e. the one under pressure. */ +__u64 monitor_cgroup_id; +/* Cgroup that gets reclaimed from when the monitor refaults. */ +__u64 target_cgroup_id; +/* Refault delta per tick that starts a reclaim round. */ +__u64 refault_threshold; +/* Monitor tick period, in nanoseconds. */ +__u64 interval_ns; +/* Bytes requested per bpf_wq callback. */ +__u64 batch_bytes; +/* Callbacks per reclaim round. */ +__u64 max_batches; +/* Passed through to bpf_proactive_reclaim(): -1, 0..200, or 201. */ +__s64 swappiness; +}; + +/* Outcome of a single reclaim attempt, reported through the ringbuf. */ +enum reclaim_outcome { +RECLAIM_OUTCOME_CALLED , +RECLAIM_OUTCOME_SKIPPED_DYING , +RECLAIM_OUTCOME_TARGET_GONE , +}; + +struct reclaim_event { +__u64 outcome; +}; + +#endif /* __MEMCG_ASYNC_RECLAIM_H */
samples/bpf/memcg_async_reclaim_user.c new file +1141 -0
1,141 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH bpf-next 1/2] selftests/bpf: Add bpf_proactive_reclaim test
In reply to Hui ZhuThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] bpf: selftest fails instead of skipping on tmpfs-only environments --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] bpf: selftest fails instead of skipping on tmpfs-only environments --
commit 050e765c2f056e2f47574982f5ca0cece0afd7b8
Author: Hui Zhu <[email protected]>
selftests/bpf: Add bpf_proactive_reclaim test
This commit adds a selftest for the bpf_proactive_reclaim kfunc. It verifies the bounded reclaim behavior by charging page cache to a cgroup and requesting eviction of the allocated pages in a single call.
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/memcg_proactive_reclaim.c new file +0
-0
[ ... ]
Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/memcg_proactive_reclaim.c new file +9
-0+void test_memcg_proactive_reclaim (void ) +{ +struct memcg_proactive_reclaim *skel =NULL ; +struct reclaim_args args = {}; + +LIBBPF_OPTS (bpf_test_run_opts, opts, + .ctx_in = &args, + .ctx_size_in = sizeof(args)); +
tools/testing/selftests/bpf/prog_tests/memcg_proactive_reclaim.c line 65
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_proactive_reclaim.c new file +10
-0+char data_file[PATH_MAX ]; +static char buf[BUF_SIZE ]; +__u64 cgroup_id; +const char *dir; +off_t off; +int cg_fd =-1 , data_fd =-1 , err; + + dir =workload_dir (); +if (!ASSERT_OK_PTR (dir,"workload dir on a regular filesystem" )) +return ;
[Severity: Medium]
Will this cause spurious test failures in tmpfs-only environments?
When workload_dir() cannot find a suitable regular filesystem (for instance, when both '.' and '/tmp' are tmpfs/ramfs), it returns NULL.
Using ASSERT_OK_PTR() here unconditionally fails the test. Could this be changed to gracefully skip the test instead via test__skip(), so that CI environments lacking a disk-backed filesystem do not falsely report a failure?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [PATCH bpf-next 2/2] samples/bpf: Add memcg async reclaim example
In reply to Hui ZhuDoes this comment accurately describe max_batches? The BPF side does not count callbacks. It uses max_batches only to size a byte budget and keeps requeueing until that budget is spent:
Quoted 6 lines
samples/bpf/memcg_async_reclaim.h new file +0
-0@@ -0,0 +1,39 @@
[ ... ]
samples/bpf/memcg_async_reclaim.h line 23
Quoted 13 lines
samples/bpf/memcg_async_reclaim.h new file +13
-0+struct reclaim_cfg { +/* Cgroup whose refaults are watched, i.e. the one under pressure. */ +__u64 monitor_cgroup_id; +/* Cgroup that gets reclaimed from when the monitor refaults. */ +__u64 target_cgroup_id; +/* Refault delta per tick that starts a reclaim round. */ +__u64 refault_threshold; +/* Monitor tick period, in nanoseconds. */ +__u64 interval_ns; +/* Bytes requested per bpf_wq callback. */ +__u64 batch_bytes; +/* Callbacks per reclaim round. */ +__u64 max_batches;
^^^^
Does this comment accurately describe max_batches? The BPF side does not count callbacks. It uses max_batches only to size a byte budget and keeps requeueing until that budget is spent:
samples/bpf/memcg_async_reclaim.bpf.c:reclaim_work_fn() {
elem->remaining = elem->max_batches * elem->batch_bytes;
...
if (nr >= elem->remaining)
elem->remaining = 0;
else
elem->remaining -= nr;
if (elem->remaining)
bpf_wq_start(&elem->work, 0);
}bpf_proactive_reclaim() limits each pass to MEMCG_CHARGE_BATCH (64 pages), which is 256 KiB with 4K pages.
With --batch 1M --max-batches 32 each callback reclaims at most about 256 KiB, so the round runs at least 128 callbacks, not 32. A partial reclaim also adds callbacks. An overshoot, or a zero return that ends the round, gives fewer.
Two other comments in the same patch describe it correctly: the .bpf.c comment says "a clamped batch only means a round needs more callbacks, because remaining is decremented by the bytes actually reclaimed", and the loader says "One round budgets max_batches * batch_bytes". The header, which documents the BPF/userspace interface, contradicts both.
The same wording is in the --max-batches help text in memcg_async_reclaim_user.c.
Suggested wording: "Round budget, in units of batch_bytes."
Quoted 6 lines
samples/bpf/memcg_async_reclaim_user.c new file +0
-0@@ -0,0 +1,1141 @@
[ ... ]
samples/bpf/memcg_async_reclaim_user.c line 367
Quoted 9 lines
samples/bpf/memcg_async_reclaim_user.c new file +9
-0+static void session_stop (struct session *s) +{ +unsigned long long failures, last_err; + +if (!s->skel) +return ; + +ring_buffer__free (s->rb); + s->rb =NULL ;
^^^^
In bench mode the reclaim_events ring buffer is never consumed, so the event counters and --verbose output do not work there. s->called, s->skipped_dying and s->target_gone are only updated from on_reclaim_event(), and that callback only runs from ring_buffer__poll().
The only caller of ring_buffer__poll() is session_poll(), and the only caller of session_poll() is do_watch().
do_bench() goes session_start() -> run_workload() -> session_stop(), and session_stop() calls ring_buffer__free(s->rb) without a final ring_buffer__consume().
So every bench run prints "events: called=0 skipped_dying=0 target_gone=0" even when the "total:" line read from .bss shows calls=N > 0.
samples/bpf/memcg_async_reclaim_user.c line 381
Quoted 13 lines
samples/bpf/memcg_async_reclaim_user.c new file +13
-0+ failures = s->skel->bss->timer_failures; + last_err = s->skel->bss->last_reclaim_err; + +printf ("\nran for %.1fs\n" ,now_sec () - s->start); +print_counters (s,"total:" ); +printf ("events: called=%llu skipped_dying=%llu target_gone=%llu\n" , + s->called, s->skipped_dying, s->target_gone); +if (failures) +printf ("WARNING: monitor timer rearm failed %llu time(s), reclaim stopped early\n" , + failures); +if (last_err) +printf ("WARNING: bpf_proactive_reclaim() last failed with -%llu\n" , + last_err);
The -v option, which usage() lists under "Common options" as "print every reclaim event", prints nothing in bench mode.
The same missing final drain also drops any watch-mode events that arrive between the last session_poll() and session_stop().
Should do_bench() poll or consume the ring buffer while the workload runs, or should session_stop() call ring_buffer__consume(s->rb) before freeing it?
[ ... ]
Quoted 6 lines
samples/bpf/memcg_async_reclaim_user.c new file +6
-0+static int do_watch (struct options *o) +{ +struct session s = {}; +__u64 monitor_id, target_id; +double next_stats, deadline =0 ; +int ret =1 ;
[ ... ]
samples/bpf/memcg_async_reclaim_user.c line 924
Quoted 12 lines
samples/bpf/memcg_async_reclaim_user.c new file +12
-0+while (!READ_ONCE (exiting)) { +double now =now_sec (); +int wait_ms; + +if (deadline && now >= deadline) +break ; + + wait_ms = (int )((next_stats - now) *1000 ); +if (wait_ms <0 ) + wait_ms =0 ; + +if (session_poll (&s, wait_ms)) {
^^^^
The --duration option is only checked once per statistics interval, so watch mode can run well past the requested time.
wait_ms is computed only from next_stats and is never clamped to the deadline. session_poll() keeps calling ring_buffer__poll() in 200 ms slices until the whole wait_ms is used up, and it only returns early on a signal or an error.
For example, with the default --stats 10 and --duration 3, nothing is checked until about 10 s have passed on an idle system, so the program runs for about 10 s instead of 3 s. With -s 60 -D 5 it runs for about 60 s.
usage() says "-D, --duration SEC stop after SEC seconds".
Should wait_ms be limited to min(next_stats, deadline) - now?
---
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/35955613591
Re: [PATCH bpf-next 2/2] samples/bpf: Add memcg async reclaim example
In reply to Hui ZhuQuoted 6 lines · Hui Zhu
Add an example of BPF-driven async proactive reclaim, keeping the complex monitoring scenario out of the selftests. A BPF program arms a bpf_wq/timer chain that watches the workingset refaults (file and anon) of a monitor cgroup; when they grow past a threshold, a round of
bpf_proactive_reclaim()batches reclaims a target cgroup, re-arming the work queue until the round budget is spent.
[...]
Quoted 4 lines
samples/bpf/memcg_async_reclaim.bpf.c | 349 ++++++++ samples/bpf/memcg_async_reclaim.h | 39 + samples/bpf/memcg_async_reclaim_user.c | 1141 ++++++++++++++++++++++++ 5 files changed, 1539 insertions(+), 1 deletion(-)
No. We're not adding new samples to samples/bpf. 1200 lines were overkill as a selftest. 1500 lines as a sample are not better.samples/bpf/ are dead. We do not add new things there.
pw-bot: cr