Skip to contentSkip to conversation

bpf: BPF-driven proactive memcg reclaim

PATCH Superseded Hui Zhu 6 participants 10 messages Sep 18 – Sep 19

Subsystems (6)

v12 of 13 Superseded Latest is v13 →

lore
Share & tools
lore

Hui Zhu

author
#0 lore raw

v12 cover bpf: BPF-driven proactive memcg reclaim

From: Hui Zhu <[email protected]>

BPF programs can observe memory pressure on a cgroup (e.g. refault stats via bpf_mem_cgroup_page_state()), but cannot act on it:
triggering reclaim on a chosen cgroup requires writing to memory.reclaim, which BPF cannot do. This series adds bpf_proactive_reclaim(), a sleepable kfunc performing one proactive reclaim pass on a target memcg, so when and how hard to reclaim is BPF policy rather than hard-coded thresholds.

The kfunc is restricted to BPF_PROG_TYPE_SYSCALL so that reclaim always runs in a clean process context: generic sleepable programs may execute with filesystem locks held or in NOFS/NOIO contexts, where the reclaim path could deadlock in filesystem shrinkers. The bpf_wq and task_work callbacks of a SYSCALL program keep its program type and run in process context, so reclaim work can still be queued asynchronously through them, as the selftest does with bpf_wq.

The use case we are looking at is protecting high-priority workloads:
a BPF program monitors the state of a high-priority cgroup and, when it degrades (e.g. PSI rises or refaults increase, as in the selftest), asynchronously reclaims memory from low-priority cgroups via bpf_wq and bpf_proactive_reclaim(), giving the pressured cgroup more free pages.

Another use case: several vendor-maintained kernels carry private implementations that trigger asynchronous reclaim when a memcg enters a certain state. These exist for historical and partly psychological reasons, but the underlying demand is real. We expect BPF-driven proactive reclaim, combined with the BPF hooks for the memory controller currently under discussion and development, to serve these needs in mainline, reducing kernel fragmentation and improving kernel maintainability.

Benchmark numbers from the selftest (TEST_MEMCG_ASYNC_RECLAIM_BENCH=1 runs the workload once without the BPF program and once with it; QEMU VM with 8 GiB RAM and 10 vCPUs, 10 runs): the pressured workload finishes in a median of 2.0s with BPF-driven async reclaim versus 15.3s without, a 62%-94% improvement per run. The harvested workload shares the parent's memory.max with it and finishes in a median of 7.5s versus 12.2s, as it has the limit to itself once the pressured workload finishes early.

Raw benchmark output of the 10 runs (one line per run, all passed):
memcg_async_reclaim: baseline high=15.331030 low=10.662426, reclaim high=2.311867 low=4.912402, high speedup=84.9%
memcg_async_reclaim: baseline high=10.788771 low=15.127507, reclaim high=3.061484 low=4.518388, high speedup=71.6%
memcg_async_reclaim: baseline high=16.553653 low=12.281844, reclaim high=2.586470 low=9.890286, high speedup=84.4%
memcg_async_reclaim: baseline high=18.032006 low=14.058724, reclaim high=1.713115 low=3.967476, high speedup=90.5%
memcg_async_reclaim: baseline high=15.253594 low=12.101572, reclaim high=1.880957 low=4.478044, high speedup=87.7%
memcg_async_reclaim: baseline high=5.454157 low=9.781724, reclaim high=2.035418 low=10.322757, high speedup=62.7%
memcg_async_reclaim: baseline high=10.010656 low=3.029734, reclaim high=1.947231 low=10.162948, high speedup=80.5%
memcg_async_reclaim: baseline high=18.201170 low=15.182740, reclaim high=1.510723 low=9.390685, high speedup=91.7%
memcg_async_reclaim: baseline high=10.772079 low=5.418259, reclaim high=2.325059 low=13.225425, high speedup=78.4%
memcg_async_reclaim: baseline high=16.360502 low=14.506304, reclaim high=0.864310 low=5.624312, high speedup=94.7%

Changelog:
v12:
Redo performance tests and update performance data. According to the comments of Barry, fix comments issue. Based on the AI review and my re-examination of selftests, updated the contents below.
Express RECLAIM_SIZE in bytes so it is right on non-4K page kernels. Drop the local PAGE_SIZE macro, RECLAIM_SIZE is now a byte count. Remove the unused bpf_helpers.h, bpf_tracing.h and bpf_core_read.h. Rename CLOCK_MONOTONIC_ID to CLOCK_MONOTONIC to match the kernel. Drop the CSS_DYING test, it is never set on a cgroup's own css. Document that the lookup fails inside rmdir(), not at last put. Count bpf_timer_start() failures so a stalled loop is visible. Record the kfunc errno so failure is not read as an idle cgroup. Note that an idle tick discards the refault delta.
Reject tmpfs for /tmp and the working dir, else the workload OOMs. Pass the mkstemp() fds to the children so no stale path is reopened. Read the timing file with lseek() and read() on the shared fd. Write the timing with snprintf() and write(), checking truncation. Close the data and time fds on every cleanup path.
Remove fcntl.h, nothing calls open() any more.
Factor disable_swap() out of the two cgroup setups.
Recreate the cgroups between bench runs so both start cold. Guard the speedup calculation against a zero baseline.
Drop the non-bench timing printf, it was noise on passing runs. Assert only TARGET_GONE, the outcome rmdir() actually guarantees. End the wait loop only on target_gone so later events are seen. Compare reclaimed_bytes against 0, a check that can now fail. Poll the keepalive reader with WNOHANG and report its exit code. Clear reader_pid after reaping so cleanup cannot kill a new PID. Rename the ring_buffer__poll() result to n, it counts events. Print timer_failures and last_reclaim_err when an assert fails. Explain why bench_printf() needs the stdout fallback and no # prefix. v11:
According to the comments of Kumar, fix reclaim_cgroup() to not treat a negative bpf_proactive_reclaim() return as reclaimed bytes. According to the comments of Shakeel, shorten the commit message. v10:
According to the comments of JP, drop redundant swap.h include, turn swappiness macros into a BTF-visible enum, and clarify the -1 swappiness semantics in docs and code in code patch.
report each reclaim outcome via ringbuf and wait for events with timeout instead of sleep-polling, log workload timings instead of failing on them, drop a debug printf, and add a TEST_MEMCG_ASYNC_RECLAIM_BENCH baseline-comparison mode in the selftests patch.
Include the benchmark numbers in the cover letter.
v9:
According to the comments of JP, copy the motivation from the cover letter to the commit message, restructure the kfunc documentation to separate the direct and asynchronous calling contexts, fold the fs-lock warning into the SYSCALL-only rationale, soften the "bounded unit of work" wording (only the reclaim target is capped), and drop the redundant comment above the reclaim kfunc set registration. v8:
According to the comments of Andrew, Kumar and Shakeel, drop the bpf_in_reclaim_context() check because the SYSCALL-only restriction already rules out reentrancy.
According to the comments of Kumar, Add the swappiness argument to bpf_proactive_reclaim().
v7:
According to the comments of JP, clamp the reclaim target of one bpf_proactive_reclaim() call to MEMCG_CHARGE_BATCH so each call is a bounded unit of work, and document the batching policy in the kfunc.
selftest: check the target cgroup for dying state before reclaiming from it, and add the memcg_async_reclaim_dying test covering target removal while reclaim is running.
v6:
According to the comments of Kumar and Shakeel, Restrict bpf_proactive_reclaim() to BPF_PROG_TYPE_SYSCALL by moving it to a dedicated kfunc set registered for that program type only, and document the clean-process-context requirement in its kerneldoc. v5:
According to the comments of Andrii, Kumar and Shakeel, remove bpf_proactive_reclaim_swappiness.
v4:
According to the comments of bot+bpf-ci and sashiko, also check current->reclaim_state to close the fentry-on-trace-iter recursion window in bpf_in_reclaim_context.
Return bytes instead of pages ( nr * PAGE_SIZE ) in bpf_proactive_reclaim_pages and bpf_proactive_reclaim_swappiness. Return (unsigned long)-1 on out-of-range swappiness (was 0). Kdoc of both kfuncs: updated Return descriptions; added FS-lock deadlock warning to bpf_proactive_reclaim.
Fix potential child process leak in selftests.
Use _exit() instead of exit() in forked children in selftests. Rename reclaimed_pages to reclaimed_bytes in selftests.
Fix comments issues in selftests.
v3:
According to the comments of bot+bpf-ci, add a shared helper bpf_proactive_reclaim_pages() that is called by bpf_proactive_reclaim and bpf_proactive_reclaim_swappiness.
According to the comments of sashiko and bot+bpf-ci, fix the issues of selftests.
v2:
According to the comments of Shakeel Butt, replace bpf_try_to_free_mem_cgroup_pages() with bpf_proactive_reclaim(memcg, size) and bpf_proactive_reclaim_swappiness(memcg, size, swappiness). According to the comments of Kumar Kartikeya Dwivedi, drop patch 2 and patch 3.
Remove bpf_thread_wq code in patch 4.
According to the comments of sashiko-bot, fix the issues of selftests.

Hui Zhu (2):
mm/bpf: Add bpf_proactive_reclaim kfunc
selftests/bpf: Add memcg async reclaim test

 mm/bpf_memcontrol.c                           |  62 +-
 mm/internal.h                                 |  10 +-
 tools/testing/selftests/bpf/config            |   1 +
 .../bpf/prog_tests/memcg_async_reclaim.c      | 890 ++++++++++++++++++
 .../selftests/bpf/progs/memcg_async_reclaim.c | 327 +++++++
 5 files changed, 1285 insertions(+), 5 deletions(-)
 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
Signature · 1 line
2.43.0
author
#1 lore raw

PATCH v12 1/2 mm/bpf: Add bpf_proactive_reclaim kfunc

From: Hui Zhu <[email protected]>

BPF programs can observe memory pressure on a cgroup, e.g. refault stats via bpf_mem_cgroup_page_state(), but cannot act on it:
triggering reclaim requires writing to memory.reclaim, which BPF cannot do.

Add bpf_proactive_reclaim(), a sleepable kfunc performing one proactive reclaim pass on a memcg, like a write to memory.reclaim but without retrying until the target is reached, so that when and how hard to reclaim is BPF policy rather than hard-coded thresholds. The reclaim target of a single call is capped at MEMCG_CHARGE_BATCH, as high_work_func() does for memory.high; reclaiming more is left to the program, which can call the kfunc once per bpf_wq callback and stop at any point. It is limited to BPF_PROG_TYPE_SYSCALL, because other sleepable programs may run with filesystem locks held, on which the reclaim path could deadlock via filesystem shrinkers.

Convert MIN_SWAPPINESS, MAX_SWAPPINESS and SWAPPINESS_ANON_ONLY from macros to an enum so that they are emitted into BTF and usable from BPF programs via vmlinux.h.

---
 mm/bpf_memcontrol.c | 62 ++++++++++++++++++++++++++++++++++++++++++++-
 mm/internal.h       | 10 +++++---
 2 files changed, 67 insertions(+), 5 deletions(-)
mm/bpf_memcontrol.c +61 -1
index 716df49d7647..c5d7f29ade85 100644
@@ -8,6 +8,8 @@
 #include <linux/memcontrol.h>
 #include <linux/bpf.h>
 
+#include "internal.h"
+
 __bpf_kfunc_start_defs();
 
 /**
@@ -159,6 +161,48 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)
 	mem_cgroup_flush_stats(memcg);
 }
 
+/**
+ * bpf_proactive_reclaim - proactively reclaim memory from a memory cgroup
+ * @memcg: the target memory cgroup to reclaim from.
+ * @size: the amount of memory to reclaim, in bytes, clamped to
+ *        MEMCG_CHARGE_BATCH.
+ * @swappiness: the reclaim swappiness, in the range [MIN_SWAPPINESS,
+ *              SWAPPINESS_ANON_ONLY], or -1 to use the memcg's own
+ *              swappiness.
+ *
+ * Performs one proactive reclaim pass on @memcg, like a write to
+ * memory.reclaim but without retrying until @size is reached. Call it
+ * repeatedly to reclaim more than one batch.
+ *
+ * Only available to BPF_PROG_TYPE_SYSCALL, because other sleepable programs
+ * may run with filesystem locks held, which the reclaim path can deadlock
+ * on via filesystem shrinkers.
+ *
+ * Return: The amount of memory reclaimed, in bytes, or a negative error.
+ */
+__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,
+				       unsigned long size,
+				       int swappiness)
+{
+	unsigned long nr_reclaimed;
+	unsigned long nr_pages;
+
+	if (swappiness < -1 || swappiness > SWAPPINESS_ANON_ONLY)
+		return -EINVAL;
+
+	if (size < PAGE_SIZE)
+		return -EINVAL;
+
+	nr_pages = min(size / PAGE_SIZE, (unsigned long)MEMCG_CHARGE_BATCH);
+
+	nr_reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages, GFP_KERNEL,
+						    MEMCG_RECLAIM_MAY_SWAP |
+						    MEMCG_RECLAIM_PROACTIVE,
+						    swappiness == -1 ? NULL : &swappiness);
+
+	return nr_reclaimed * PAGE_SIZE;
+}
+
 __bpf_kfunc_end_defs();
 
 BTF_KFUNCS_START(bpf_memcontrol_kfuncs)
@@ -174,19 +218,35 @@ BTF_ID_FLAGS(func, bpf_mem_cgroup_flush_stats, KF_SLEEPABLE)
 
 BTF_KFUNCS_END(bpf_memcontrol_kfuncs)
 
+BTF_KFUNCS_START(bpf_memcontrol_reclaim_kfuncs)
+BTF_ID_FLAGS(func, bpf_proactive_reclaim, KF_SLEEPABLE)
+BTF_KFUNCS_END(bpf_memcontrol_reclaim_kfuncs)
+
 static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = {
 	.owner          = THIS_MODULE,
 	.set            = &bpf_memcontrol_kfuncs,
 };
 
+static const struct btf_kfunc_id_set bpf_memcontrol_reclaim_kfunc_set = {
+	.owner          = THIS_MODULE,
+	.set            = &bpf_memcontrol_reclaim_kfuncs,
+};
+
 static int __init bpf_memcontrol_init(void)
 {
 	int err;
 
 	err = register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC,
 					&bpf_memcontrol_kfunc_set);
-	if (err)
+	if (err) {
 		pr_warn("error while registering bpf memcontrol kfuncs: %d", err);
+		return err;
+	}
+
+	err = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
+					&bpf_memcontrol_reclaim_kfunc_set);
+	if (err)
+		pr_warn("error registering bpf reclaim kfuncs: %d\n", err);
 
 	return err;
 }
mm/internal.h +6 -4
index 38b1165212c9..44e95e87e3cd 100644
@@ -74,11 +74,13 @@ unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
 
 #define MEMCG_RECLAIM_MAY_SWAP (1 << 1)
 #define MEMCG_RECLAIM_PROACTIVE (1 << 2)
-#define MIN_SWAPPINESS 0
-#define MAX_SWAPPINESS 200
+enum {
+	MIN_SWAPPINESS = 0,
+	MAX_SWAPPINESS = 200,
 
-/* Just reclaim from anon folios in proactive memory reclaim */
-#define SWAPPINESS_ANON_ONLY (MAX_SWAPPINESS + 1)
+	/* Just reclaim from anon folios in proactive memory reclaim */
+	SWAPPINESS_ANON_ONLY = MAX_SWAPPINESS + 1,
+};
 
 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
 					   unsigned long nr_pages,
Signature · 1 line
2.43.0
author
#6 lore raw

PATCH v12 2/2 selftests/bpf: Add memcg async reclaim test

In reply to Hui Zhu

From: Hui Zhu <[email protected]>

Exercise BPF-driven async proactive reclaim. A BPF program watches the refault stats of a memory-pressured cgroup and, once they grow, reclaims a second cgroup from a bpf_wq callback through bpf_proactive_reclaim(). Pass/fail rests on the reclaim counters. The workload timings are a benchmark, not a criterion, so they are logged only under TEST_MEMCG_ASYNC_RECLAIM_BENCH=1, which also runs a baseline without the BPF program, recreating the cgroups in between so both runs start cold.

A second test removes the reclaim target while the program keeps running and verifies that reclaim stops. The program skips a target whose css has lost CSS_ONLINE, but that window sits inside rmdir() and is too narrow to hit reliably, so the test asserts the post-rmdir outcome and only counts the in-window one.

Add CONFIG_MEMCG to the selftests config fragment because bpf_proactive_reclaim() is built only under it and the program fails to load without it.

---
 tools/testing/selftests/bpf/config            |   1 +
 .../bpf/prog_tests/memcg_async_reclaim.c      | 890 ++++++++++++++++++
 .../selftests/bpf/progs/memcg_async_reclaim.c | 327 +++++++
 3 files changed, 1218 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
tools/testing/selftests/bpf/config +1 -0
index 2f79688dcf7c..1edaa752facb 100644
@@ -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_async_reclaim.c new file +890 -0

890 lines not on this page · raw message

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

327 lines not on this page · raw message

Signature · 1 line
2.43.0
#7 lore raw

Re: [PATCH bpf-next v12 2/2] selftests/bpf: Add memcg async reclaim test

Does this comment accurately describe why the cgroups are recreated?
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +0 -0
new file mode 100644
index 0000000000000..179b64fb6de84

[ ... ]

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +10 -0
+	/*
+	 * Optional baseline for the benchmark numbers below: run the
+	 * same workload once without the BPF program, so the log can
+	 * report how much async reclaim improved the pressured cgroup.
+	 */
+	if (bench) {
+		err = run_high_low_workload(dir, &base_high_time,
+					    &base_low_time, READ_TIMES);
+		if (!ASSERT_OK(err, "run_high_low_workload baseline"))
+			goto out;

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +10 -0
+
+		/*
+		 * The baseline left up to CG_LIMIT of page cache charged to the
+		 * high and low cgroups, and memcg charges outlive the workload
+		 * processes. Recreate the cgroups so that the instrumented run
+		 * below starts from the same cold state the baseline did;
+		 * otherwise the reported speedup compares a cold run against a
+		 * warm one.
+		 */
+		cleanup_cgroup_environment();

Does this comment accurately describe why the cgroups are recreated?

Looking at run_high_low_workload(), its cleanup block closes all four file descriptors and then unlinks all four temp files after both children have been reaped. With link count zero and no remaining open descriptors or mappings, the inodes are evicted, their page cache is truncated, and the memcg charges are released - so memory.current for the high and low cgroups is already back to near zero when control returns here.

What actually survives the baseline is memory.stat, particularly the WORKINGSET_REFAULT_FILE counter that the BPF program samples via should_reclaim_cgroup(). Without recreating the cgroups, wq_prog_init() would start elem->prev_event at 0 while the counter is already large from the baseline, so the very first timer tick would see a huge delta and kick off a reclaim round unconditionally. Recreating the cgroups zeroes those counters.

Could the comment be updated to describe that the recreation clears the WORKINGSET_REFAULT_FILE counters in memory.stat rather than page cache charges, which are already released when the files are unlinked?

[ ... ]

Quoted 41 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +41 -0
+	reader_pid = spawn_keepalive_reader(data_fd);
+	if (!ASSERT_GT(reader_pid, 0, "fork keepalive reader"))
+		goto out;
+
+	/* Wait for reclaim rounds to reach the live target cgroup. */
+	for (i = 0; i < EVENT_POLL_ROUNDS && !seen.called; i++) {
+		n = ring_buffer__poll(rb, EVENT_POLL_TIMEOUT_MS);
+		if (!ASSERT_GE(n, 0, "ring_buffer__poll"))
+			goto out;
+
+		/*
+		 * The reader loops until killed, so finding it already gone
+		 * means the refaults the BPF program waits for never started.
+		 * Report its exit code rather than letting the assert below
+		 * blame the kernel for the full poll window.
+		 */
+		if (waitpid(reader_pid, &status, WNOHANG) == reader_pid) {
+			/* Reaped, so cleanup must not signal a reused PID. */
+			reader_pid = -1;
+			if (WIFEXITED(status))
+				PRINT_FAIL("keepalive reader exited early: %s",
+					   child_exit_str(WEXITSTATUS(status)));
+			else
+				PRINT_FAIL("keepalive reader died, status 0x%x",
+					   status);
+			goto out;
+		}
+	}
+	if (!ASSERT_GT(seen.called, 0, "reclaim events")) {
+		report_timer_failures(skel);
+		goto out;
+	}
+
+	remove_cgroup(CG_DYING_TARGET_DIR);
+
+	/* Let reclaim passes that were already in flight drain. */
+	usleep(DYING_SETTLE_US);
+
+	calls_before = skel->bss->reclaim_calls;
+
+	/*

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +10 -0
+	 * Wait for a reclaim round to hit the removed cgroup. Only TARGET_GONE
+	 * ends the wait: an attempt that lands inside the rmdir window reports
+	 * SKIPPED_DYING first, and stopping there would miss the events that
+	 * follow it.
+	 */
+	for (i = 0; i < EVENT_POLL_ROUNDS && !seen.target_gone; i++) {
+		n = ring_buffer__poll(rb, EVENT_POLL_TIMEOUT_MS);
+		if (!ASSERT_GE(n, 0, "ring_buffer__poll"))
+			goto out;
+	}

The second poll loop here drops the keepalive-reader liveness check that the first loop performs, although both loops depend on the reader equally.

TARGET_GONE is only emitted when a reclaim round actually starts, and a round only starts when should_reclaim_cgroup() sees a fresh WORKINGSET_REFAULT_FILE delta - which only happens while the reader keeps refaulting. If the reader dies during this second window, refaults stop, no TARGET_GONE ever arrives, and the test reports "no reclaim round hit the removed cgroup (gone=0, dying=0)", blaming the kernel for a dead child.

That is exactly the misattribution the first loop added a waitpid(WNOHANG) check to avoid. The reader's exit code is still available here, since a reader that dies during the second loop is left unreaped until the out:
label. Should the second loop include the same liveness check to avoid misattributing a dead reader as a kernel issue?

Quoted 17 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +17 -0
+	/*
+	 * TARGET_GONE is what the test can rely on: by the time rmdir has
+	 * returned, bpf_cgroup_from_id() has stopped resolving the target.
+	 * SKIPPED_DYING only happens if an attempt lands inside the rmdir
+	 * window, so it is reported here rather than asserted.
+	 */
+	if (!seen.target_gone) {
+		report_timer_failures(skel);
+		PRINT_FAIL("no reclaim round hit the removed cgroup (gone=%d, dying=%d)",
+			   seen.target_gone, seen.skipped_dying);
+		goto out;
+	}
+
+	/*
+	 * Reclaim must have stopped with the target. Both counters stay put for
+	 * the same reason: once rmdir has returned, bpf_cgroup_from_id() fails,
+	 * so every attempt takes the TARGET_GONE path before it can reach

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c new file +10 -0
+	 * reclaim_calls++. This therefore checks that reclaim really stops, not
+	 * that cgroup_is_dying() works -- see that function in the BPF program
+	 * for why the dying window cannot be hit reliably from userspace.
+	 *
+	 * reclaimed_bytes is compared against 0 rather than against its
+	 * pre-removal value: the target is empty for the whole test, so
+	 * bpf_proactive_reclaim() has nothing to reclaim and must have returned
+	 * 0 on every call, before and after the removal alike. An "unchanged"
+	 * comparison would be 0 == 0 and could never fail.
+	 */

Does the reclaimed_bytes explanation make sense? The comment argues that comparing reclaimed_bytes against a pre-removal snapshot "would be 0 == 0 and could never fail", but by its own premise that snapshot is 0, so the snapshot comparison is literally the assertion that was written:
ASSERT_EQ(skel->bss->reclaimed_bytes, 0ULL). Both forms read reclaimed_bytes after the removal window and both fail exactly when a post-removal reclaim adds bytes; neither is vacuous and neither is stronger than the other.

As written the comment tells a reader that one of two identical checks cannot fail, which is misleading. Could it just state that bpf_proactive_reclaim() returns 0 on the empty target throughout the test, without the comparison that makes them sound different?

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

#8 lore raw

Re: [PATCH bpf-next v12 2/2] selftests/bpf: Add memcg async reclaim test

In reply to Hui Zhu
Quoted 9 lines · Hui Zhu

From: Hui Zhu <[email protected]>

Exercise BPF-driven async proactive reclaim. A BPF program watches the refault stats of a memory-pressured cgroup and, once they grow, reclaims a second cgroup from a bpf_wq callback through bpf_proactive_reclaim(). Pass/fail rests on the reclaim counters. The workload timings are a benchmark, not a criterion, so they are logged only under TEST_MEMCG_ASYNC_RECLAIM_BENCH=1, which also runs a baseline without the BPF program, recreating the cgroups in between so both runs start cold.

[...]

Quoted 6 lines
---
 tools/testing/selftests/bpf/config            |   1 +
 .../bpf/prog_tests/memcg_async_reclaim.c      | 890 ++++++++++++++++++
 .../selftests/bpf/progs/memcg_async_reclaim.c | 327 +++++++
 3 files changed, 1218 insertions(+)

1200 lines of selftest for a 20 line kfunc ?
Sorry that's an overkill.

pw-
bot: cr

maintainer
#9 lore raw

Re: [PATCH bpf-next v12 2/2] selftests/bpf: Add memcg async reclaim test

Quoted 20 lines · Alexei Starovoitov
Quoted 9 lines · Hui Zhu

From: Hui Zhu <[email protected]>

Exercise BPF-driven async proactive reclaim. A BPF program watches the refault stats of a memory-pressured cgroup and, once they grow, reclaims a second cgroup from a bpf_wq callback through bpf_proactive_reclaim(). Pass/fail rests on the reclaim counters. The workload timings are a benchmark, not a criterion, so they are logged only under TEST_MEMCG_ASYNC_RECLAIM_BENCH=1, which also runs a baseline without the BPF program, recreating the cgroups in between so both runs start cold.

[...]

Quoted 6 lines
---
 tools/testing/selftests/bpf/config            |   1 +
 .../bpf/prog_tests/memcg_async_reclaim.c      | 890 ++++++++++++++++++
 .../selftests/bpf/progs/memcg_async_reclaim.c | 327 +++++++
 3 files changed, 1218 insertions(+)
Quoted 2 lines

1200 lines of selftest for a 20 line kfunc ?
Sorry that's an overkill.

Yeah I agree. Also I understand that BPF would prefer to have very fast and minimal selftests and selftest for a memory reclaim kfunc would not be that.

We have memory.reclaim selftests in cgroup, maybe that would be a better home. Basically whatever we do for memory.reclaim, do the same but using this kfunc. If you don't mind, why not let's just take the patch 1 in bpf tree for now and we will cover the selftest in next release but in cgroup selftests.

Reviewed-by on v12 1/2
#2 lore raw

Re: [PATCH bpf-next v12 1/2] mm/bpf: Add bpf_proactive_reclaim kfunc

In reply to Hui Zhu
Quoted 44 lines · Hui Zhu

From: Hui Zhu <[email protected]>

BPF programs can observe memory pressure on a cgroup, e.g. refault stats via bpf_mem_cgroup_page_state(), but cannot act on it:
triggering reclaim requires writing to memory.reclaim, which BPF cannot do.

Add bpf_proactive_reclaim(), a sleepable kfunc performing one proactive reclaim pass on a memcg, like a write to memory.reclaim but without retrying until the target is reached, so that when and how hard to reclaim is BPF policy rather than hard-coded thresholds. The reclaim target of a single call is capped at MEMCG_CHARGE_BATCH, as high_work_func() does for memory.high; reclaiming more is left to the program, which can call the kfunc once per bpf_wq callback and stop at any point. It is limited to BPF_PROG_TYPE_SYSCALL, because other sleepable programs may run with filesystem locks held, on which the reclaim path could deadlock via filesystem shrinkers.

Convert MIN_SWAPPINESS, MAX_SWAPPINESS and SWAPPINESS_ANON_ONLY from macros to an enum so that they are emitted into BTF and usable from BPF programs via vmlinux.h.

---
  mm/bpf_memcontrol.c | 62 ++++++++++++++++++++++++++++++++++++++++++++-
  mm/internal.h       | 10 +++++---
  2 files changed, 67 insertions(+), 5 deletions(-)
mm/bpf_memcontrol.c +2 -0
index 716df49d7647..c5d7f29ade85 100644
@@ -8,6 +8,8 @@
  #include <linux/memcontrol.h>
  #include <linux/bpf.h>
 
+#include "internal.h"
+
  __bpf_kfunc_start_defs();
 
  /**
@@ -159,6 +161,48 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)
  	mem_cgroup_flush_stats(memcg);

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

Quoted 10 lines
mm/bpf_memcontrol.c +8 -0
  }
 
+/**
+ * bpf_proactive_reclaim - proactively reclaim memory from a memory cgroup
+ * @memcg: the target memory cgroup to reclaim from.
+ * @size: the amount of memory to reclaim, in bytes, clamped to
+ *        MEMCG_CHARGE_BATCH.
+ * @swappiness: the reclaim swappiness, in the range [MIN_SWAPPINESS,
+ *              SWAPPINESS_ANON_ONLY], or -1 to use the memcg's own
+ *              swappiness.

The ANON_ONLY enumerator shouldn't be included as part of the range. I would change this to [MIN_SWAPPINESS, MAX_SWAPPINESS] and then specify that ANON_ONLY is a special mode like -1 is.

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+ *
+ * Performs one proactive reclaim pass on @memcg, like a write to
+ * memory.reclaim but without retrying until @size is reached. Call it
+ * repeatedly to reclaim more than one batch.
+ *
+ * Only available to BPF_PROG_TYPE_SYSCALL, because other sleepable programs
+ * may run with filesystem locks held, which the reclaim path can deadlock
+ * on via filesystem shrinkers.
+ *
+ * Return: The amount of memory reclaimed, in bytes, or a negative error.

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

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+ */
+__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,
+				       unsigned long size,
+				       int swappiness)
+{
+	unsigned long nr_reclaimed;
+	unsigned long nr_pages;
+
+	if (swappiness < -1 || swappiness > SWAPPINESS_ANON_ONLY)
+		return -EINVAL;

Related to the previous comment, you treat the special values as part of the range. It works currently, but creates a layout dependency on the enum. I think it would be more future-proof if you did:

if (swappiness != -1 && swappiness != SWAPPINESS_ANON_ONLY) {
	if (swappiness < MIN_SWAPPINESS || swappiness > MAX_SWAPPINESS)
		return -EINVAL;
}

The previous comments I brought up are now resolved, so assuming you'll make the changes above you can include:

maintainer
#3 lore raw

Re: [PATCH bpf-next v12 1/2] mm/bpf: Add bpf_proactive_reclaim kfunc

Quoted 87 lines · JP Kobryn
Quoted 41 lines · Hui Zhu

From: Hui Zhu <[email protected]>

BPF programs can observe memory pressure on a cgroup, e.g. refault stats via bpf_mem_cgroup_page_state(), but cannot act on it:
triggering reclaim requires writing to memory.reclaim, which BPF cannot do.

Add bpf_proactive_reclaim(), a sleepable kfunc performing one proactive reclaim pass on a memcg, like a write to memory.reclaim but without retrying until the target is reached, so that when and how hard to reclaim is BPF policy rather than hard-coded thresholds. The reclaim target of a single call is capped at MEMCG_CHARGE_BATCH, as high_work_func() does for memory.high; reclaiming more is left to the program, which can call the kfunc once per bpf_wq callback and stop at any point. It is limited to BPF_PROG_TYPE_SYSCALL, because other sleepable programs may run with filesystem locks held, on which the reclaim path could deadlock via filesystem shrinkers.

Convert MIN_SWAPPINESS, MAX_SWAPPINESS and SWAPPINESS_ANON_ONLY from macros to an enum so that they are emitted into BTF and usable from BPF programs via vmlinux.h.

---
  mm/bpf_memcontrol.c | 62 ++++++++++++++++++++++++++++++++++++++++++++-
  mm/internal.h       | 10 +++++---
  2 files changed, 67 insertions(+), 5 deletions(-)
mm/bpf_memcontrol.c +2 -0
index 716df49d7647..c5d7f29ade85 100644
@@ -8,6 +8,8 @@
  #include <linux/memcontrol.h>
  #include <linux/bpf.h>
+#include "internal.h"
+
  __bpf_kfunc_start_defs();
  /**

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

Quoted 10 lines
mm/bpf_memcontrol.c +8 -0
@@ -159,6 +161,48 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)
  	mem_cgroup_flush_stats(memcg);
  }
+/**
+ * bpf_proactive_reclaim - proactively reclaim memory from a memory cgroup
+ * @memcg: the target memory cgroup to reclaim from.
+ * @size: the amount of memory to reclaim, in bytes, clamped to
+ *        MEMCG_CHARGE_BATCH.
+ * @swappiness: the reclaim swappiness, in the range [MIN_SWAPPINESS,
+ *              SWAPPINESS_ANON_ONLY], or -1 to use the memcg's own
+ *              swappiness.

The ANON_ONLY enumerator shouldn't be included as part of the range. I would change this to [MIN_SWAPPINESS, MAX_SWAPPINESS] and then specify that ANON_ONLY is a special mode like -1 is.

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+ *
+ * Performs one proactive reclaim pass on @memcg, like a write to
+ * memory.reclaim but without retrying until @size is reached. Call it
+ * repeatedly to reclaim more than one batch.
+ *
+ * Only available to BPF_PROG_TYPE_SYSCALL, because other sleepable programs
+ * may run with filesystem locks held, which the reclaim path can deadlock
+ * on via filesystem shrinkers.
+ *
+ * Return: The amount of memory reclaimed, in bytes, or a negative error.

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

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+ */
+__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,
+				       unsigned long size,
+				       int swappiness)
+{
+	unsigned long nr_reclaimed;
+	unsigned long nr_pages;
+
+	if (swappiness < -1 || swappiness > SWAPPINESS_ANON_ONLY)
+		return -EINVAL;

Related to the previous comment, you treat the special values as part of the range. It works currently, but creates a layout dependency on the enum. I think it would be more future-proof if you did:

if (swappiness != -1 && swappiness != SWAPPINESS_ANON_ONLY) {
	if (swappiness < MIN_SWAPPINESS || swappiness > MAX_SWAPPINESS)
		return -EINVAL;
}
Quoted 4 lines

The previous comments I brought up are now resolved, so assuming you'll make the changes above you can include:

Hui, please make these changes and just send this patch in next version.

#4 lore raw

Re: [PATCH bpf-next v12 1/2] mm/bpf: Add bpf_proactive_reclaim kfunc

Quoted 89 lines · Shakeel Butt
Quoted 87 lines · JP Kobryn
Quoted 41 lines · Hui Zhu

From: Hui Zhu <[email protected]>

BPF programs can observe memory pressure on a cgroup, e.g. refault stats via bpf_mem_cgroup_page_state(), but cannot act on it:
triggering reclaim requires writing to memory.reclaim, which BPF cannot do.

Add bpf_proactive_reclaim(), a sleepable kfunc performing one proactive reclaim pass on a memcg, like a write to memory.reclaim but without retrying until the target is reached, so that when and how hard to reclaim is BPF policy rather than hard-coded thresholds. The reclaim target of a single call is capped at MEMCG_CHARGE_BATCH, as high_work_func() does for memory.high; reclaiming more is left to the program, which can call the kfunc once per bpf_wq callback and stop at any point. It is limited to BPF_PROG_TYPE_SYSCALL, because other sleepable programs may run with filesystem locks held, on which the reclaim path could deadlock via filesystem shrinkers.

Convert MIN_SWAPPINESS, MAX_SWAPPINESS and SWAPPINESS_ANON_ONLY from macros to an enum so that they are emitted into BTF and usable from BPF programs via vmlinux.h.

---
  mm/bpf_memcontrol.c | 62 ++++++++++++++++++++++++++++++++++++++++++++-
  mm/internal.h       | 10 +++++---
  2 files changed, 67 insertions(+), 5 deletions(-)
mm/bpf_memcontrol.c +2 -0
index 716df49d7647..c5d7f29ade85 100644
@@ -8,6 +8,8 @@
  #include <linux/memcontrol.h>
  #include <linux/bpf.h>
+#include "internal.h"
+
  __bpf_kfunc_start_defs();
  /**

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

Quoted 10 lines
mm/bpf_memcontrol.c +8 -0
@@ -159,6 +161,48 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)
    mem_cgroup_flush_stats(memcg);
  }
+/**
+ * bpf_proactive_reclaim - proactively reclaim memory from a memory cgroup
+ * @memcg: the target memory cgroup to reclaim from.
+ * @size: the amount of memory to reclaim, in bytes, clamped to
+ *        MEMCG_CHARGE_BATCH.
+ * @swappiness: the reclaim swappiness, in the range [MIN_SWAPPINESS,
+ *              SWAPPINESS_ANON_ONLY], or -1 to use the memcg's own
+ *              swappiness.

The ANON_ONLY enumerator shouldn't be included as part of the range. I would change this to [MIN_SWAPPINESS, MAX_SWAPPINESS] and then specify that ANON_ONLY is a special mode like -1 is.

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+ *
+ * Performs one proactive reclaim pass on @memcg, like a write to
+ * memory.reclaim but without retrying until @size is reached. Call it
+ * repeatedly to reclaim more than one batch.
+ *
+ * Only available to BPF_PROG_TYPE_SYSCALL, because other sleepable programs
+ * may run with filesystem locks held, which the reclaim path can deadlock
+ * on via filesystem shrinkers.
+ *
+ * Return: The amount of memory reclaimed, in bytes, or a negative error.

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

Quoted 10 lines
mm/bpf_memcontrol.c +10 -0
+ */
+__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,
+                                  unsigned long size,
+                                  int swappiness)
+{
+   unsigned long nr_reclaimed;
+   unsigned long nr_pages;
+
+   if (swappiness < -1 || swappiness > SWAPPINESS_ANON_ONLY)
+           return -EINVAL;

Related to the previous comment, you treat the special values as part of the range. It works currently, but creates a layout dependency on the enum. I think it would be more future-proof if you did:

if (swappiness != -1 && swappiness != SWAPPINESS_ANON_ONLY) {
      if (swappiness < MIN_SWAPPINESS || swappiness > MAX_SWAPPINESS)
              return -EINVAL;
}
Quoted 6 lines
Quoted 4 lines

The previous comments I brought up are now resolved, so assuming you'll make the changes above you can include:

Hui, please make these changes and just send this patch in next version.

Hi JP and Shakeel,

This feels a bit weird to me, since 0–201 are all valid swappiness values.

201 (SWAPPINESS_ANON_ONLY) is just as valid a swappiness value as 200. In contrast, -1 is a different story, as it indicates completely different semantics.

If 201 is treated as a special value, then 0 (MIN_SWAPPINESS) should be treated the same way for MGLRU, since 0 means file-only reclaim there. This isn't the case for CLRU, where swappiness 0 can still reclaim anon folios.

If possible, I'd vote for keeping Hui's current code :-)

Best Regards
Barry

Reviewed-by
#5 lore raw

Re: [PATCH bpf-next v12 1/2] mm/bpf: Add bpf_proactive_reclaim kfunc

On Sun, Sep 20, 2026 at 6:36 AM Barry Song <[email protected]> wrote:
[...]

Quoted 25 lines
Quoted 9 lines
Quoted 9 lines

Related to the previous comment, you treat the special values as part of the range. It works currently, but creates a layout dependency on the enum. I think it would be more future-proof if you did:

if (swappiness != -1 && swappiness != SWAPPINESS_ANON_ONLY) {
      if (swappiness < MIN_SWAPPINESS || swappiness > MAX_SWAPPINESS)
              return -EINVAL;
}
Quoted 6 lines
Quoted 4 lines

The previous comments I brought up are now resolved, so assuming you'll make the changes above you can include:

Hui, please make these changes and just send this patch in next version.

Hi JP and Shakeel,

This feels a bit weird to me, since 0–201 are all valid swappiness values.

201 (SWAPPINESS_ANON_ONLY) is just as valid a swappiness value as 200. In contrast, -1 is a different story, as it indicates completely different semantics.

Quoted 6 lines

If 201 is treated as a special value, then 0 (MIN_SWAPPINESS) should be treated the same way for MGLRU, since 0 means file-only reclaim there. This isn't the case for CLRU, where swappiness 0 can still reclaim anon folios.

If possible, I'd vote for keeping Hui's current code :-)

On second thought, you might be right, as there could theoretically be a case where SWAPPINESS_ANON_ONLY is not defined as MAX_SWAPPINESS + 1, but as, for example, 400 or some other value.

That said, I find MAX_SWAPPINESS and SWAPPINESS_ANON_ONLY really weird. Somehow, I feel MAX_SWAPPINESS should be SWAPPINESS_ANON_ONLY, since 201 is actually the maximum valid swappiness value, rather than 200.

For the change suggested by JP, I think it is right if we don't clean up MAX_SWAPPINESS and SWAPPINESS_ANON_ONLY properly.

With the change suggested by JP,