| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/09/20 10:02 | flow | patch-triage |
1mArgs:null Results: {
"EnableConfigs": [
"MEMCG",
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_proactive_reclaim"
],
"KMSANReasoning": "The patch introduces a new BPF kfunc, `bpf_proactive_reclaim()`, in `mm/bpf_memcontrol.c` registered for `BPF_PROG_TYPE_SYSCALL`, and exports swappiness constants as an enum in `mm/internal.h`.\n\nKMSAN is not applicable for the following reasons:\n1. No uninitialized memory or info-leak risks: The kfunc operates entirely on scalar arguments (`size`, `swappiness`) and a verified `struct mem_cgroup` pointer, returning a scalar `long` value representing reclaimed bytes. No kernel structures or buffers are copied to userspace via `copy_to_user`, ioctl, netlink, or BPF buffers.\n2. All local variables (`nr_pages`, `nr_reclaimed`) and parameters are explicitly initialized before use. The pointer passed to `try_to_free_mem_cgroup_pages` (`swappiness == -1 ? NULL : \u0026swappiness`) references the function argument passed by value, which is fully initialized.\n3. No complex data structures are allocated or partially initialized.\n\nAny risks associated with this change relate to memory reclaim concurrency, invalid memcg pointer dereferences, or locking/deadlocks in sleepable context, all of which are caught by KASAN and LOCKDEP in standard debugging builds. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false,
"Reasoning": "The patch introduces a new sleepable BPF kfunc, bpf_proactive_reclaim(), which allows BPF programs of type BPF_PROG_TYPE_SYSCALL to trigger proactive memory reclamation on a specified memory cgroup via try_to_free_mem_cgroup_pages(). This modifies reachable core kernel code bridging BPF and the memory management reclaim subsystem, making it worth fuzzing for potential deadlocks, race conditions, or invariant violations.",
"WorthFuzzing": true
} |
| 1/1 | 2026/09/20 10:02 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 7f5fe58e78a00d7fe8315e8a4dae89d0a33c5a20\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Sun Sep 20 10:02:46 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/mm/bpf_memcontrol.c b/mm/bpf_memcontrol.c\nindex 716df49d76477..c5d7f29ade858 100644\n--- a/mm/bpf_memcontrol.c\n+++ b/mm/bpf_memcontrol.c\n@@ -8,6 +8,8 @@\n #include \u003clinux/memcontrol.h\u003e\n #include \u003clinux/bpf.h\u003e\n \n+#include \"internal.h\"\n+\n __bpf_kfunc_start_defs();\n \n /**\n@@ -159,6 +161,48 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)\n \tmem_cgroup_flush_stats(memcg);\n }\n \n+/**\n+ * bpf_proactive_reclaim - proactively reclaim memory from a memory cgroup\n+ * @memcg: the target memory cgroup to reclaim from.\n+ * @size: the amount of memory to reclaim, in bytes, clamped to\n+ * MEMCG_CHARGE_BATCH.\n+ * @swappiness: the reclaim swappiness, in the range [MIN_SWAPPINESS,\n+ * SWAPPINESS_ANON_ONLY], or -1 to use the memcg's own\n+ * swappiness.\n+ *\n+ * Performs one proactive reclaim pass on @memcg, like a write to\n+ * memory.reclaim but without retrying until @size is reached. Call it\n+ * repeatedly to reclaim more than one batch.\n+ *\n+ * Only available to BPF_PROG_TYPE_SYSCALL, because other sleepable programs\n+ * may run with filesystem locks held, which the reclaim path can deadlock\n+ * on via filesystem shrinkers.\n+ *\n+ * Return: The amount of memory reclaimed, in bytes, or a negative error.\n+ */\n+__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,\n+\t\t\t\t unsigned long size,\n+\t\t\t\t int swappiness)\n+{\n+\tunsigned long nr_reclaimed;\n+\tunsigned long nr_pages;\n+\n+\tif (swappiness \u003c -1 || swappiness \u003e SWAPPINESS_ANON_ONLY)\n+\t\treturn -EINVAL;\n+\n+\tif (size \u003c PAGE_SIZE)\n+\t\treturn -EINVAL;\n+\n+\tnr_pages = min(size / PAGE_SIZE, (unsigned long)MEMCG_CHARGE_BATCH);\n+\n+\tnr_reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages, GFP_KERNEL,\n+\t\t\t\t\t\t MEMCG_RECLAIM_MAY_SWAP |\n+\t\t\t\t\t\t MEMCG_RECLAIM_PROACTIVE,\n+\t\t\t\t\t\t swappiness == -1 ? NULL : \u0026swappiness);\n+\n+\treturn nr_reclaimed * PAGE_SIZE;\n+}\n+\n __bpf_kfunc_end_defs();\n \n BTF_KFUNCS_START(bpf_memcontrol_kfuncs)\n@@ -174,19 +218,35 @@ BTF_ID_FLAGS(func, bpf_mem_cgroup_flush_stats, KF_SLEEPABLE)\n \n BTF_KFUNCS_END(bpf_memcontrol_kfuncs)\n \n+BTF_KFUNCS_START(bpf_memcontrol_reclaim_kfuncs)\n+BTF_ID_FLAGS(func, bpf_proactive_reclaim, KF_SLEEPABLE)\n+BTF_KFUNCS_END(bpf_memcontrol_reclaim_kfuncs)\n+\n static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = {\n \t.owner = THIS_MODULE,\n \t.set = \u0026bpf_memcontrol_kfuncs,\n };\n \n+static const struct btf_kfunc_id_set bpf_memcontrol_reclaim_kfunc_set = {\n+\t.owner = THIS_MODULE,\n+\t.set = \u0026bpf_memcontrol_reclaim_kfuncs,\n+};\n+\n static int __init bpf_memcontrol_init(void)\n {\n \tint err;\n \n \terr = register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC,\n \t\t\t\t\t\u0026bpf_memcontrol_kfunc_set);\n-\tif (err)\n+\tif (err) {\n \t\tpr_warn(\"error while registering bpf memcontrol kfuncs: %d\", err);\n+\t\treturn err;\n+\t}\n+\n+\terr = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,\n+\t\t\t\t\t\u0026bpf_memcontrol_reclaim_kfunc_set);\n+\tif (err)\n+\t\tpr_warn(\"error registering bpf reclaim kfuncs: %d\\n\", err);\n \n \treturn err;\n }\ndiff --git a/mm/internal.h b/mm/internal.h\nindex 38b1165212c94..44e95e87e3cd9 100644\n--- a/mm/internal.h\n+++ b/mm/internal.h\n@@ -74,11 +74,13 @@ unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,\n \n #define MEMCG_RECLAIM_MAY_SWAP (1 \u003c\u003c 1)\n #define MEMCG_RECLAIM_PROACTIVE (1 \u003c\u003c 2)\n-#define MIN_SWAPPINESS 0\n-#define MAX_SWAPPINESS 200\n+enum {\n+\tMIN_SWAPPINESS = 0,\n+\tMAX_SWAPPINESS = 200,\n \n-/* Just reclaim from anon folios in proactive memory reclaim */\n-#define SWAPPINESS_ANON_ONLY (MAX_SWAPPINESS + 1)\n+\t/* Just reclaim from anon folios in proactive memory reclaim */\n+\tSWAPPINESS_ANON_ONLY = MAX_SWAPPINESS + 1,\n+};\n \n unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\n \t\t\t\t\t unsigned long nr_pages,\ndiff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config\nindex 2f79688dcf7ce..1edaa752facb2 100644\n--- a/tools/testing/selftests/bpf/config\n+++ b/tools/testing/selftests/bpf/config\n@@ -57,6 +57,7 @@ CONFIG_LIRC=y\n CONFIG_LIVEPATCH=y\n CONFIG_LWTUNNEL=y\n CONFIG_LWTUNNEL_BPF=y\n+CONFIG_MEMCG=y\n CONFIG_MODULE_SIG=y\n CONFIG_MODULE_SRCVERSION_ALL=y\n CONFIG_MODULE_UNLOAD=y\ndiff --git a/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c b/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c\nnew file mode 100644\nindex 0000000000000..179b64fb6de84\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c\n@@ -0,0 +1,890 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Memory controller eBPF async reclaim test\n+ *\n+ * Setting TEST_MEMCG_ASYNC_RECLAIM_BENCH=1 adds a baseline run of the\n+ * workload without the BPF program to memcg_async_reclaim, and prints\n+ * the baseline and reclaim timings, plus the speedup of the pressured\n+ * cgroup, to stdout. The cgroups are recreated between the two runs so\n+ * that both start from the same cold state.\n+ */\n+\n+#include \u003ctest_progs.h\u003e\n+#include \u003csys/mman.h\u003e\n+#include \u003csys/stat.h\u003e\n+#include \u003csys/vfs.h\u003e\n+#include \u003csys/wait.h\u003e\n+#include \u003csignal.h\u003e\n+#include \u003ctime.h\u003e\n+#include \u003cunistd.h\u003e\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003cstring.h\u003e\n+#include \u003climits.h\u003e\n+#include \u003clinux/magic.h\u003e\n+\n+#include \"cgroup_helpers.h\"\n+\n+struct bpf_args {\n+\tu64 high_cgroup_id;\n+\tu64 low_cgroup_id;\n+\tu64 event_delta_threshold;\n+\tu64 check_ns;\n+};\n+\n+/* Reclaim outcomes reported by the BPF program through the ringbuf. */\n+enum reclaim_outcome {\n+\tRECLAIM_OUTCOME_CALLED,\n+\tRECLAIM_OUTCOME_SKIPPED_DYING,\n+\tRECLAIM_OUTCOME_TARGET_GONE,\n+};\n+\n+struct reclaim_event {\n+\tu64 outcome;\n+};\n+\n+#include \"memcg_async_reclaim.skel.h\"\n+\n+#define FILE_SIZE (32 * 1024 * 1024ul)\n+#define BUFFER_SIZE (4096)\n+#define CG_LIMIT (32 * 1024 * 1024ul)\n+#define READ_TIMES 50\n+\n+#define CG_DIR \"/memcg_async_reclaim\"\n+#define CG_HIGH_DIR CG_DIR \"/high\"\n+#define CG_LOW_DIR CG_DIR \"/low\"\n+\n+#define CG_DYING_DIR \"/memcg_async_reclaim_dying\"\n+#define CG_DYING_TRIGGER_DIR CG_DYING_DIR \"/trigger\"\n+#define CG_DYING_TARGET_DIR CG_DYING_DIR \"/target\"\n+\n+#define CHECK_PERIOD_NS (2 * 1000 * 1000ull)\n+#define EVENT_DELTA_THRESHOLD 1\n+\n+/*\n+ * Timing for the dying test: after the target cgroup is removed, give\n+ * in-flight reclaim passes time to drain, then wait for a reclaim round\n+ * to hit the removed target. The keepalive reader keeps the trigger\n+ * cgroup refaulting, and the timer fires every CHECK_PERIOD_NS, so\n+ * such a round must show up within a few timer periods. The BPF\n+ * program reports every reclaim outcome through the ringbuf, so the\n+ * waits just poll it with a timeout.\n+ */\n+#define DYING_SETTLE_US (200 * 1000)\n+#define EVENT_POLL_TIMEOUT_MS (100)\n+#define EVENT_POLL_ROUNDS (50)\n+\n+static bool usable_for_workload_files(const char *dir)\n+{\n+\tstruct statfs st;\n+\n+\tif (statfs(dir, \u0026st))\n+\t\treturn false;\n+\n+\treturn st.f_type != TMPFS_MAGIC \u0026\u0026 st.f_type != RAMFS_MAGIC;\n+}\n+\n+/*\n+ * The workload files must sit on a regular filesystem: with swap\n+ * disabled for the cgroup, tmpfs/ramfs pages are unevictable and would\n+ * OOM the cgroup instead of exercising reclaim; they are also charged\n+ * as anonymous memory, so they never raise the WORKINGSET_REFAULT_FILE\n+ * events the BPF program monitors.\n+ *\n+ * /tmp is tmpfs on many systems, so fall back to the current directory.\n+ * That fallback needs the very same check: test_progs is routinely run\n+ * from a tmpfs working directory, and silently landing there produces an\n+ * OOM that looks like a reclaim failure. Returns NULL when neither\n+ * directory is usable, in which case the workload cannot run at all.\n+ */\n+static const char *workload_files_dir(void)\n+{\n+\tif (usable_for_workload_files(\"/tmp\"))\n+\t\treturn \"/tmp\";\n+\tif (usable_for_workload_files(\".\"))\n+\t\treturn \".\";\n+\n+\treturn NULL;\n+}\n+\n+/*\n+ * Keep the workload from swapping out, so that reclaim has to evict page\n+ * cache instead. memory.swap.max only exists when the kernel is built with\n+ * CONFIG_SWAP, and /proc/swaps is registered by the same CONFIG_SWAP-gated\n+ * code (mm/swapfile.c), so it stands in for the file here. With CONFIG_SWAP=n\n+ * no swap can happen anyway, so skipping the write is the correct behaviour.\n+ */\n+static int disable_swap(const char *cgroup_dir)\n+{\n+\tif (access(\"/proc/swaps\", F_OK))\n+\t\treturn 0;\n+\n+\treturn write_cgroup_file(cgroup_dir, \"memory.swap.max\", \"0\");\n+}\n+\n+/*\n+ * The forked children run after test_progs hijacked stdio, so anything\n+ * they print is lost with their private copy of the hijacked buffer\n+ * unless the test runs under -v. The exit status is the one diagnostics\n+ * channel that always reaches the parent, so each failing step gets its\n+ * own code.\n+ */\n+enum child_exit_code {\n+\tCHILD_EXIT_OK = 0,\n+\tCHILD_EXIT_JOIN_CGROUP,\n+\tCHILD_EXIT_WRITE_FILE,\n+\tCHILD_EXIT_READ_FILE,\n+\tCHILD_EXIT_TIME_FILE,\n+};\n+\n+static const char *child_exit_str(int code)\n+{\n+\tswitch (code) {\n+\tcase CHILD_EXIT_OK:\n+\t\treturn \"success\";\n+\tcase CHILD_EXIT_JOIN_CGROUP:\n+\t\treturn \"join cgroup\";\n+\tcase CHILD_EXIT_WRITE_FILE:\n+\t\treturn \"write data file\";\n+\tcase CHILD_EXIT_READ_FILE:\n+\t\treturn \"read data file\";\n+\tcase CHILD_EXIT_TIME_FILE:\n+\t\treturn \"write time file\";\n+\tdefault:\n+\t\treturn \"unknown\";\n+\t}\n+}\n+\n+static int setup_high_low_cgroups(u64 *high_cgroup_id, u64 *low_cgroup_id)\n+{\n+\tint ret;\n+\tchar limit_buf[20];\n+\n+\tret = setup_cgroup_environment();\n+\tif (!ASSERT_OK(ret, \"setup_cgroup_environment\"))\n+\t\tgoto cleanup;\n+\n+\tret = create_and_get_cgroup(CG_DIR);\n+\tif (!ASSERT_GE(ret, 0, \"create_and_get_cgroup \" CG_DIR))\n+\t\tgoto cleanup;\n+\tclose(ret);\n+\n+\tret = enable_controllers(CG_DIR, \"memory\");\n+\tif (!ASSERT_OK(ret, \"enable_controllers\"))\n+\t\tgoto cleanup;\n+\n+\tsnprintf(limit_buf, sizeof(limit_buf), \"%lu\", CG_LIMIT);\n+\tret = write_cgroup_file(CG_DIR, \"memory.max\", limit_buf);\n+\tif (!ASSERT_OK(ret, \"write_cgroup_file memory.max\"))\n+\t\tgoto cleanup;\n+\n+\tret = disable_swap(CG_DIR);\n+\tif (!ASSERT_OK(ret, \"disable_swap\"))\n+\t\tgoto cleanup;\n+\n+\tret = create_and_get_cgroup(CG_HIGH_DIR);\n+\tif (!ASSERT_GE(ret, 0, \"create_and_get_cgroup \" CG_HIGH_DIR))\n+\t\tgoto cleanup;\n+\tclose(ret);\n+\n+\t*high_cgroup_id = get_cgroup_id(CG_HIGH_DIR);\n+\tif (!ASSERT_GT(*high_cgroup_id, 0, \"get_cgroup_id\"))\n+\t\tgoto cleanup;\n+\n+\tret = create_and_get_cgroup(CG_LOW_DIR);\n+\tif (!ASSERT_GE(ret, 0, \"create_and_get_cgroup \" CG_LOW_DIR))\n+\t\tgoto cleanup;\n+\tclose(ret);\n+\n+\t*low_cgroup_id = get_cgroup_id(CG_LOW_DIR);\n+\tif (!ASSERT_GT(*low_cgroup_id, 0, \"get_cgroup_id\"))\n+\t\tgoto cleanup;\n+\n+\treturn 0;\n+\n+cleanup:\n+\tcleanup_cgroup_environment();\n+\treturn -1;\n+}\n+\n+/*\n+ * The dying test needs an empty reclaim target plus a cgroup that keeps\n+ * refaulting while the target is removed, so reclaim rounds keep\n+ * starting and run into the removed target. The two have to be separate\n+ * cgroups: the target must hold no processes to be removed, and v2's\n+ * no-internal-process constraint keeps the refaulting workload out of\n+ * any parent that has domain children.\n+ */\n+static int setup_dying_cgroups(u64 *trigger_cgroup_id, u64 *target_cgroup_id)\n+{\n+\tint ret;\n+\tchar limit_buf[20];\n+\n+\tret = setup_cgroup_environment();\n+\tif (!ASSERT_OK(ret, \"setup_cgroup_environment\"))\n+\t\tgoto cleanup;\n+\n+\tret = create_and_get_cgroup(CG_DYING_DIR);\n+\tif (!ASSERT_GE(ret, 0, \"create_and_get_cgroup \" CG_DYING_DIR))\n+\t\tgoto cleanup;\n+\tclose(ret);\n+\n+\tret = enable_controllers(CG_DYING_DIR, \"memory\");\n+\tif (!ASSERT_OK(ret, \"enable_controllers\"))\n+\t\tgoto cleanup;\n+\n+\tsnprintf(limit_buf, sizeof(limit_buf), \"%lu\", CG_LIMIT);\n+\tret = write_cgroup_file(CG_DYING_DIR, \"memory.max\", limit_buf);\n+\tif (!ASSERT_OK(ret, \"write_cgroup_file memory.max\"))\n+\t\tgoto cleanup;\n+\n+\tret = disable_swap(CG_DYING_DIR);\n+\tif (!ASSERT_OK(ret, \"disable_swap\"))\n+\t\tgoto cleanup;\n+\n+\tret = create_and_get_cgroup(CG_DYING_TRIGGER_DIR);\n+\tif (!ASSERT_GE(ret, 0, \"create_and_get_cgroup \" CG_DYING_TRIGGER_DIR))\n+\t\tgoto cleanup;\n+\tclose(ret);\n+\n+\t*trigger_cgroup_id = get_cgroup_id(CG_DYING_TRIGGER_DIR);\n+\tif (!ASSERT_GT(*trigger_cgroup_id, 0, \"get_cgroup_id\"))\n+\t\tgoto cleanup;\n+\n+\tret = create_and_get_cgroup(CG_DYING_TARGET_DIR);\n+\tif (!ASSERT_GE(ret, 0, \"create_and_get_cgroup \" CG_DYING_TARGET_DIR))\n+\t\tgoto cleanup;\n+\tclose(ret);\n+\n+\t*target_cgroup_id = get_cgroup_id(CG_DYING_TARGET_DIR);\n+\tif (!ASSERT_GT(*target_cgroup_id, 0, \"get_cgroup_id\"))\n+\t\tgoto cleanup;\n+\n+\treturn 0;\n+\n+cleanup:\n+\tcleanup_cgroup_environment();\n+\treturn -1;\n+}\n+\n+static int write_file(int fd)\n+{\n+\tint ret = -1;\n+\tsize_t written = 0;\n+\tchar *buffer;\n+\n+\tbuffer = malloc(BUFFER_SIZE);\n+\tif (!buffer)\n+\t\tgoto out;\n+\n+\tmemset(buffer, 'A', BUFFER_SIZE);\n+\n+\twhile (written \u003c FILE_SIZE) {\n+\t\tsize_t to_write = FILE_SIZE - written \u003c BUFFER_SIZE ?\n+\t\t\t\t FILE_SIZE - written : BUFFER_SIZE;\n+\t\tssize_t n = write(fd, buffer, to_write);\n+\n+\t\tif (n \u003c= 0)\n+\t\t\tgoto cleanup;\n+\t\twritten += n;\n+\t}\n+\n+\tret = 0;\n+cleanup:\n+\tfree(buffer);\n+out:\n+\treturn ret;\n+}\n+\n+static int read_file(int fd, int iterations)\n+{\n+\tlong page_size = sysconf(_SC_PAGESIZE);\n+\tstruct stat sb;\n+\tchar *map;\n+\tsize_t i;\n+\n+\tif (fstat(fd, \u0026sb) == -1)\n+\t\treturn -1;\n+\n+\tif (sb.st_size != FILE_SIZE) {\n+\t\tfprintf(stderr, \"File size mismatch: expected %lu, got %lu\\n\",\n+\t\t\t(unsigned long)FILE_SIZE, (unsigned long)sb.st_size);\n+\t\treturn -1;\n+\t}\n+\n+\tmap = mmap(NULL, FILE_SIZE, PROT_READ, MAP_PRIVATE, fd, 0);\n+\tif (map == MAP_FAILED)\n+\t\treturn -1;\n+\n+\tfor (int iter = 0; iter \u003c iterations; iter++) {\n+\t\tfor (i = 0; i \u003c FILE_SIZE; i += page_size) {\n+\t\t\t/* access a byte to trigger page fault */\n+\t\t\tvolatile char v = map[i];\n+\t\t\t(void)v;\n+\t\t}\n+\t}\n+\n+\tif (munmap(map, FILE_SIZE) == -1)\n+\t\treturn -1;\n+\n+\treturn 0;\n+}\n+\n+static int real_test_child_work(const char *cgroup_path, int data_fd,\n+\t\t\t\tint time_fd, int read_times)\n+{\n+\tstruct timespec start, end;\n+\tdouble elapsed;\n+\tchar buf[32];\n+\tint len;\n+\n+\tif (join_parent_cgroup(cgroup_path))\n+\t\treturn CHILD_EXIT_JOIN_CGROUP;\n+\n+\tclock_gettime(CLOCK_MONOTONIC, \u0026start);\n+\n+\tif (write_file(data_fd))\n+\t\treturn CHILD_EXIT_WRITE_FILE;\n+\n+\tif (read_file(data_fd, read_times))\n+\t\treturn CHILD_EXIT_READ_FILE;\n+\n+\tclock_gettime(CLOCK_MONOTONIC, \u0026end);\n+\n+\telapsed = (end.tv_sec - start.tv_sec) +\n+\t\t (end.tv_nsec - start.tv_nsec) / 1000000000.0;\n+\n+\tlen = snprintf(buf, sizeof(buf), \"%.6f\", elapsed);\n+\t/* snprintf() returns the untruncated length, so bound it before write() */\n+\tif (len \u003c 0 || len \u003e= (int)sizeof(buf) || write(time_fd, buf, len) != len)\n+\t\treturn CHILD_EXIT_TIME_FILE;\n+\n+\treturn CHILD_EXIT_OK;\n+}\n+\n+static int get_time(int fd, double *time)\n+{\n+\tchar buf[64] = {};\n+\tssize_t n;\n+\n+\t/* The child wrote through the fork-shared description, so rewind. */\n+\tif (lseek(fd, 0, SEEK_SET) == (off_t)-1) {\n+\t\tPRINT_FAIL(\"lseek time file\");\n+\t\treturn -1;\n+\t}\n+\n+\tn = read(fd, buf, sizeof(buf) - 1);\n+\tif (!ASSERT_GT(n, 0, \"read time file\"))\n+\t\treturn -1;\n+\n+\tif (sscanf(buf, \"%lf\", time) != 1) {\n+\t\tPRINT_FAIL(\"sscanf %s\", buf);\n+\t\treturn -1;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static int\n+run_high_low_workload(const char *dir, double *high_elapsed, double *low_elapsed,\n+\t\t int read_times)\n+{\n+\tchar high_data_file[PATH_MAX];\n+\tchar low_data_file[PATH_MAX];\n+\tchar high_time_file[PATH_MAX];\n+\tchar low_time_file[PATH_MAX];\n+\tint high_data_fd = -1, low_data_fd = -1;\n+\tint high_time_fd = -1, low_time_fd = -1;\n+\tpid_t high_pid = -1, low_pid = -1;\n+\tpid_t wait_ret;\n+\tint status;\n+\tint ret = -1;\n+\n+\tsnprintf(high_data_file, sizeof(high_data_file),\n+\t\t \"%s/memcg_async_high_data_XXXXXX\", dir);\n+\tsnprintf(low_data_file, sizeof(low_data_file),\n+\t\t \"%s/memcg_async_low_data_XXXXXX\", dir);\n+\tsnprintf(high_time_file, sizeof(high_time_file),\n+\t\t \"%s/memcg_async_high_time_XXXXXX\", dir);\n+\tsnprintf(low_time_file, sizeof(low_time_file),\n+\t\t \"%s/memcg_async_low_time_XXXXXX\", dir);\n+\n+\t/*\n+\t * The mkstemp() fds are kept and inherited by the children rather\n+\t * than reopened by name: reopening would resolve the path again and\n+\t * follow whatever sits there by then.\n+\t */\n+\thigh_data_fd = mkstemp(high_data_file);\n+\tif (!ASSERT_GE(high_data_fd, 0, \"mkstemp high data\"))\n+\t\tgoto cleanup;\n+\n+\tlow_data_fd = mkstemp(low_data_file);\n+\tif (!ASSERT_GE(low_data_fd, 0, \"mkstemp low data\"))\n+\t\tgoto cleanup;\n+\n+\thigh_time_fd = mkstemp(high_time_file);\n+\tif (!ASSERT_GE(high_time_fd, 0, \"mkstemp high time\"))\n+\t\tgoto cleanup;\n+\n+\tlow_time_fd = mkstemp(low_time_file);\n+\tif (!ASSERT_GE(low_time_fd, 0, \"mkstemp low time\"))\n+\t\tgoto cleanup;\n+\n+\tlow_pid = fork();\n+\tif (!ASSERT_GE(low_pid, 0, \"fork low\"))\n+\t\tgoto cleanup;\n+\tif (low_pid == 0)\n+\t\t_exit(real_test_child_work(CG_LOW_DIR, low_data_fd,\n+\t\t\t\t\t low_time_fd, read_times));\n+\n+\thigh_pid = fork();\n+\tif (!ASSERT_GE(high_pid, 0, \"fork high\"))\n+\t\tgoto cleanup;\n+\tif (high_pid == 0)\n+\t\t_exit(real_test_child_work(CG_HIGH_DIR, high_data_fd,\n+\t\t\t\t\t high_time_fd, read_times));\n+\n+\twait_ret = waitpid(low_pid, \u0026status, 0);\n+\tif (!ASSERT_GT(wait_ret, 0, \"low waitpid\"))\n+\t\tgoto cleanup;\n+\t/*\n+\t * The child has been reaped and its PID can already be reused,\n+\t * so mark it to keep cleanup from signaling an unrelated process.\n+\t */\n+\tlow_pid = -1;\n+\tif (!ASSERT_TRUE(WIFEXITED(status), \"low exited\"))\n+\t\tgoto cleanup;\n+\tif (WEXITSTATUS(status) != CHILD_EXIT_OK) {\n+\t\tPRINT_FAIL(\"low child failed at: %s (exit status %d)\",\n+\t\t\t child_exit_str(WEXITSTATUS(status)),\n+\t\t\t WEXITSTATUS(status));\n+\t\tgoto cleanup;\n+\t}\n+\n+\twait_ret = waitpid(high_pid, \u0026status, 0);\n+\tif (!ASSERT_GT(wait_ret, 0, \"high waitpid\"))\n+\t\tgoto cleanup;\n+\t/* Same as above: the reaped PID must not be signaled again. */\n+\thigh_pid = -1;\n+\tif (!ASSERT_TRUE(WIFEXITED(status), \"high exited\"))\n+\t\tgoto cleanup;\n+\tif (WEXITSTATUS(status) != CHILD_EXIT_OK) {\n+\t\tPRINT_FAIL(\"high child failed at: %s (exit status %d)\",\n+\t\t\t child_exit_str(WEXITSTATUS(status)),\n+\t\t\t WEXITSTATUS(status));\n+\t\tgoto cleanup;\n+\t}\n+\n+\tif (get_time(high_time_fd, high_elapsed))\n+\t\tgoto cleanup;\n+\tif (get_time(low_time_fd, low_elapsed))\n+\t\tgoto cleanup;\n+\n+\tret = 0;\n+\n+cleanup:\n+\t/* On failure, make sure no child process is left behind */\n+\tif (ret) {\n+\t\tif (high_pid \u003e 0) {\n+\t\t\tkill(high_pid, SIGKILL);\n+\t\t\t(void)waitpid(high_pid, NULL, 0);\n+\t\t}\n+\t\tif (low_pid \u003e 0) {\n+\t\t\tkill(low_pid, SIGKILL);\n+\t\t\t(void)waitpid(low_pid, NULL, 0);\n+\t\t}\n+\t}\n+\tif (high_data_fd \u003e= 0)\n+\t\tclose(high_data_fd);\n+\tif (low_data_fd \u003e= 0)\n+\t\tclose(low_data_fd);\n+\tif (high_time_fd \u003e= 0)\n+\t\tclose(high_time_fd);\n+\tif (low_time_fd \u003e= 0)\n+\t\tclose(low_time_fd);\n+\tunlink(low_time_file);\n+\tunlink(high_time_file);\n+\tunlink(low_data_file);\n+\tunlink(high_data_file);\n+\treturn ret;\n+}\n+\n+static int\n+setup_bpf(u64 high_cgroup_id, u64 low_cgroup_id,\n+\t struct memcg_async_reclaim **skel_ptr)\n+{\n+\tstruct memcg_async_reclaim *skel;\n+\tstruct bpf_args args = {\n+\t\t.high_cgroup_id = high_cgroup_id,\n+\t\t.low_cgroup_id = low_cgroup_id,\n+\t\t.event_delta_threshold = EVENT_DELTA_THRESHOLD,\n+\t\t.check_ns = CHECK_PERIOD_NS,\n+\t};\n+\tLIBBPF_OPTS(bpf_test_run_opts, run_opts,\n+\t\t.ctx_in = \u0026args,\n+\t\t.ctx_size_in = sizeof(args));\n+\tint prog_init_fd, err;\n+\n+\tskel = memcg_async_reclaim__open_and_load();\n+\tif (!ASSERT_OK_PTR(skel, \"memcg_async_reclaim__open_and_load\"))\n+\t\treturn -1;\n+\n+\tprog_init_fd = bpf_program__fd(skel-\u003eprogs.wq_prog_init);\n+\n+\terr = bpf_prog_test_run_opts(prog_init_fd, \u0026run_opts);\n+\tif (!ASSERT_OK(err, \"bpf_prog_test_run_opts\"))\n+\t\tgoto error_out;\n+\tif (!ASSERT_EQ(run_opts.retval, 0, \"prog_init retval\"))\n+\t\tgoto error_out;\n+\n+\t*skel_ptr = skel;\n+\treturn 0;\n+\n+error_out:\n+\tmemcg_async_reclaim__destroy(skel);\n+\treturn -1;\n+}\n+\n+/*\n+ * A timer that stopped rearming produces no further reclaim rounds, which\n+ * the \"no events\" failures below would otherwise report as a kernel bug.\n+ * Only call this on a path that is already failing.\n+ */\n+static void report_timer_failures(struct memcg_async_reclaim *skel)\n+{\n+\tu64 failures = skel-\u003ebss-\u003etimer_failures;\n+\n+\tif (failures)\n+\t\tPRINT_FAIL(\"bpf_timer failed to rearm %llu time(s), so the reclaim loop stopped\",\n+\t\t\t (unsigned long long)failures);\n+}\n+\n+/*\n+ * A kfunc that fails on every call is indistinguishable from a cgroup with\n+ * nothing left to reclaim, which the reclaim_calls and reclaimed_bytes\n+ * assertions below cannot tell apart. Only call this on a path that is\n+ * already failing.\n+ */\n+static void report_reclaim_errors(struct memcg_async_reclaim *skel)\n+{\n+\tu64 last_err = skel-\u003ebss-\u003elast_reclaim_err;\n+\n+\tif (last_err)\n+\t\tPRINT_FAIL(\"bpf_proactive_reclaim() last failed with -%llu, nothing was reclaimed\",\n+\t\t\t (unsigned long long)last_err);\n+}\n+\n+/*\n+ * The benchmark numbers are only interesting when the test passes, but\n+ * dump_test_log() drops the captured log unless the test failed or -v was\n+ * given, so they have to bypass the hijack. The ?: stdout fallback is\n+ * required, not defensive: stdio_hijack() returns early in verbose mode and\n+ * never sets env.stdout_saved.\n+ *\n+ * This also bypasses the worker-to-dispatcher log protocol, so under -j the\n+ * line can interleave with the per-test records. It carries no '#' prefix:\n+ * test_progs uses that only for its own result records, and print_test_log()\n+ * dumps free-form test output verbatim.\n+ */\n+static void bench_printf(const char *fmt, ...)\n+{\n+\tva_list ap;\n+\n+\tva_start(ap, fmt);\n+\tvfprintf(env.stdout_saved ?: stdout, fmt, ap);\n+\tva_end(ap);\n+}\n+\n+void test_memcg_async_reclaim(void)\n+{\n+\tu64 high_cgroup_id, low_cgroup_id;\n+\tdouble high_time = 0.0, low_time = 0.0;\n+\tdouble base_high_time = 0.0, base_low_time = 0.0;\n+\tstruct memcg_async_reclaim *skel = NULL;\n+\tconst char *dir;\n+\tint err, bench;\n+\n+\tdir = workload_files_dir();\n+\tif (!ASSERT_TRUE(dir != NULL, \"workload_files_dir\"))\n+\t\treturn;\n+\n+\tbench = !!getenv(\"TEST_MEMCG_ASYNC_RECLAIM_BENCH\");\n+\n+\terr = setup_high_low_cgroups(\u0026high_cgroup_id, \u0026low_cgroup_id);\n+\tif (!ASSERT_OK(err, \"setup_high_low_cgroups reclaim\"))\n+\t\treturn;\n+\n+\t/*\n+\t * Optional baseline for the benchmark numbers below: run the\n+\t * same workload once without the BPF program, so the log can\n+\t * report how much async reclaim improved the pressured cgroup.\n+\t */\n+\tif (bench) {\n+\t\terr = run_high_low_workload(dir, \u0026base_high_time,\n+\t\t\t\t\t \u0026base_low_time, READ_TIMES);\n+\t\tif (!ASSERT_OK(err, \"run_high_low_workload baseline\"))\n+\t\t\tgoto out;\n+\n+\t\t/*\n+\t\t * The baseline left up to CG_LIMIT of page cache charged to the\n+\t\t * high and low cgroups, and memcg charges outlive the workload\n+\t\t * processes. Recreate the cgroups so that the instrumented run\n+\t\t * below starts from the same cold state the baseline did;\n+\t\t * otherwise the reported speedup compares a cold run against a\n+\t\t * warm one.\n+\t\t */\n+\t\tcleanup_cgroup_environment();\n+\t\terr = setup_high_low_cgroups(\u0026high_cgroup_id, \u0026low_cgroup_id);\n+\t\tif (!ASSERT_OK(err, \"setup_high_low_cgroups after baseline\"))\n+\t\t\tgoto out;\n+\t}\n+\n+\terr = setup_bpf(high_cgroup_id, low_cgroup_id, \u0026skel);\n+\tif (!ASSERT_OK(err, \"setup_bpf\"))\n+\t\tgoto out;\n+\n+\terr = run_high_low_workload(dir, \u0026high_time, \u0026low_time, READ_TIMES);\n+\tif (!ASSERT_OK(err, \"run_high_low_workload reclaim\"))\n+\t\tgoto out;\n+\n+\t/*\n+\t * Timing alone cannot distinguish a working reclaim from a no-op\n+\t * one, so require that the BPF program actually reclaimed memory\n+\t * from the low cgroup.\n+\t */\n+\tif (!ASSERT_GT(skel-\u003ebss-\u003ereclaim_calls, 0, \"reclaim_calls\")) {\n+\t\treport_timer_failures(skel);\n+\t\treport_reclaim_errors(skel);\n+\t\tgoto out;\n+\t}\n+\tif (!ASSERT_GT(skel-\u003ebss-\u003ereclaimed_bytes, 0, \"reclaimed_bytes\")) {\n+\t\treport_reclaim_errors(skel);\n+\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * The timing comparison is a benchmark and too flaky to fail CI\n+\t * runs, so it only logs the numbers; the counters above already\n+\t * proved that the BPF program reclaimed memory.\n+\t */\n+\tif (bench \u0026\u0026 base_high_time \u003e 0.0)\n+\t\tbench_printf(\"memcg_async_reclaim: baseline high=%f low=%f, \"\n+\t\t\t \"reclaim high=%f low=%f, high speedup=%.1f%%\\n\",\n+\t\t\t base_high_time, base_low_time, high_time, low_time,\n+\t\t\t 100.0 * (base_high_time - high_time) / base_high_time);\n+\n+out:\n+\tif (skel)\n+\t\tmemcg_async_reclaim__destroy(skel);\n+\tcleanup_cgroup_environment();\n+}\n+\n+/*\n+ * Keep refaults flowing through the trigger cgroup so reclaim rounds\n+ * keep being triggered while the target cgroup is being removed. The\n+ * child joins the trigger cgroup and writes the data file there, so\n+ * that the file pages are charged to the trigger cgroup and actually\n+ * come under its memory limit; then it re-reads the file in a loop\n+ * until it is killed.\n+ */\n+static pid_t spawn_keepalive_reader(int data_fd)\n+{\n+\tpid_t pid = fork();\n+\n+\tif (pid != 0)\n+\t\treturn pid;\n+\n+\tif (join_parent_cgroup(CG_DYING_TRIGGER_DIR))\n+\t\t_exit(CHILD_EXIT_JOIN_CGROUP);\n+\tif (write_file(data_fd))\n+\t\t_exit(CHILD_EXIT_WRITE_FILE);\n+\tfor (;;) {\n+\t\tif (read_file(data_fd, READ_TIMES))\n+\t\t\t_exit(CHILD_EXIT_READ_FILE);\n+\t}\n+}\n+\n+/* Reclaim outcomes observed so far, tallied from ringbuf events. */\n+struct reclaim_events_seen {\n+\tint called;\n+\tint skipped_dying;\n+\tint target_gone;\n+};\n+\n+static int on_reclaim_event(void *ctx, void *data, size_t sz)\n+{\n+\tstruct reclaim_events_seen *seen = ctx;\n+\tconst struct reclaim_event *ev = data;\n+\n+\tif (sz \u003c sizeof(*ev))\n+\t\treturn 0;\n+\n+\tswitch (ev-\u003eoutcome) {\n+\tcase RECLAIM_OUTCOME_CALLED:\n+\t\tseen-\u003ecalled++;\n+\t\tbreak;\n+\tcase RECLAIM_OUTCOME_SKIPPED_DYING:\n+\t\tseen-\u003eskipped_dying++;\n+\t\tbreak;\n+\tcase RECLAIM_OUTCOME_TARGET_GONE:\n+\t\tseen-\u003etarget_gone++;\n+\t\tbreak;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+/*\n+ * Remove the reclaim target while the BPF program keeps running and verify\n+ * that reclaim stops instead of reclaiming from the removed cgroup.\n+ *\n+ * The target stays empty; the workload lives in the trigger cgroup and only\n+ * keeps refaults flowing so that reclaim rounds keep starting, both before\n+ * and after the target is removed. A CALLED event while the target is alive\n+ * proves that rounds really run (the kfunc returns 0 on the empty target, but\n+ * the call is still counted).\n+ *\n+ * Once rmdir has returned, bpf_cgroup_from_id() has already stopped resolving\n+ * the target: kernfs deactivates the directory node inside the rmdir syscall,\n+ * see cgroup_is_dying() in the BPF program. TARGET_GONE is therefore the\n+ * outcome this test can rely on, and the one it asserts. SKIPPED_DYING needs\n+ * an attempt to land in the short window between cgroup_destroy_locked()\n+ * clearing CSS_ONLINE and kernfs_remove() deactivating the node, so it is\n+ * counted and reported on failure but never required.\n+ */\n+void test_memcg_async_reclaim_dying(void)\n+{\n+\tu64 trigger_cgroup_id, target_cgroup_id;\n+\tchar data_file[PATH_MAX] = \"\";\n+\tstruct reclaim_events_seen seen = {};\n+\tstruct memcg_async_reclaim *skel = NULL;\n+\tstruct ring_buffer *rb = NULL;\n+\tu64 calls_before;\n+\tconst char *dir;\n+\tpid_t reader_pid = -1;\n+\tint data_fd = -1;\n+\tint err, status, i, n;\n+\n+\tdir = workload_files_dir();\n+\tif (!ASSERT_TRUE(dir != NULL, \"workload_files_dir\"))\n+\t\treturn;\n+\n+\terr = setup_dying_cgroups(\u0026trigger_cgroup_id, \u0026target_cgroup_id);\n+\tif (!ASSERT_OK(err, \"setup_dying_cgroups\"))\n+\t\treturn;\n+\n+\terr = setup_bpf(trigger_cgroup_id, target_cgroup_id, \u0026skel);\n+\tif (!ASSERT_OK(err, \"setup_bpf\"))\n+\t\tgoto out;\n+\n+\trb = ring_buffer__new(bpf_map__fd(skel-\u003emaps.reclaim_events),\n+\t\t\t on_reclaim_event, \u0026seen, NULL);\n+\tif (!ASSERT_OK_PTR(rb, \"ring_buffer__new\"))\n+\t\tgoto out;\n+\n+\tsnprintf(data_file, sizeof(data_file),\n+\t\t \"%s/memcg_async_dying_XXXXXX\", dir);\n+\t/* Kept open and inherited, see run_high_low_workload(). */\n+\tdata_fd = mkstemp(data_file);\n+\tif (!ASSERT_GE(data_fd, 0, \"mkstemp\"))\n+\t\tgoto out;\n+\n+\treader_pid = spawn_keepalive_reader(data_fd);\n+\tif (!ASSERT_GT(reader_pid, 0, \"fork keepalive reader\"))\n+\t\tgoto out;\n+\n+\t/* Wait for reclaim rounds to reach the live target cgroup. */\n+\tfor (i = 0; i \u003c EVENT_POLL_ROUNDS \u0026\u0026 !seen.called; i++) {\n+\t\tn = ring_buffer__poll(rb, EVENT_POLL_TIMEOUT_MS);\n+\t\tif (!ASSERT_GE(n, 0, \"ring_buffer__poll\"))\n+\t\t\tgoto out;\n+\n+\t\t/*\n+\t\t * The reader loops until killed, so finding it already gone\n+\t\t * means the refaults the BPF program waits for never started.\n+\t\t * Report its exit code rather than letting the assert below\n+\t\t * blame the kernel for the full poll window.\n+\t\t */\n+\t\tif (waitpid(reader_pid, \u0026status, WNOHANG) == reader_pid) {\n+\t\t\t/* Reaped, so cleanup must not signal a reused PID. */\n+\t\t\treader_pid = -1;\n+\t\t\tif (WIFEXITED(status))\n+\t\t\t\tPRINT_FAIL(\"keepalive reader exited early: %s\",\n+\t\t\t\t\t child_exit_str(WEXITSTATUS(status)));\n+\t\t\telse\n+\t\t\t\tPRINT_FAIL(\"keepalive reader died, status 0x%x\",\n+\t\t\t\t\t status);\n+\t\t\tgoto out;\n+\t\t}\n+\t}\n+\tif (!ASSERT_GT(seen.called, 0, \"reclaim events\")) {\n+\t\treport_timer_failures(skel);\n+\t\tgoto out;\n+\t}\n+\n+\tremove_cgroup(CG_DYING_TARGET_DIR);\n+\n+\t/* Let reclaim passes that were already in flight drain. */\n+\tusleep(DYING_SETTLE_US);\n+\n+\tcalls_before = skel-\u003ebss-\u003ereclaim_calls;\n+\n+\t/*\n+\t * Wait for a reclaim round to hit the removed cgroup. Only TARGET_GONE\n+\t * ends the wait: an attempt that lands inside the rmdir window reports\n+\t * SKIPPED_DYING first, and stopping there would miss the events that\n+\t * follow it.\n+\t */\n+\tfor (i = 0; i \u003c EVENT_POLL_ROUNDS \u0026\u0026 !seen.target_gone; i++) {\n+\t\tn = ring_buffer__poll(rb, EVENT_POLL_TIMEOUT_MS);\n+\t\tif (!ASSERT_GE(n, 0, \"ring_buffer__poll\"))\n+\t\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * TARGET_GONE is what the test can rely on: by the time rmdir has\n+\t * returned, bpf_cgroup_from_id() has stopped resolving the target.\n+\t * SKIPPED_DYING only happens if an attempt lands inside the rmdir\n+\t * window, so it is reported here rather than asserted.\n+\t */\n+\tif (!seen.target_gone) {\n+\t\treport_timer_failures(skel);\n+\t\tPRINT_FAIL(\"no reclaim round hit the removed cgroup (gone=%d, dying=%d)\",\n+\t\t\t seen.target_gone, seen.skipped_dying);\n+\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * Reclaim must have stopped with the target. Both counters stay put for\n+\t * the same reason: once rmdir has returned, bpf_cgroup_from_id() fails,\n+\t * so every attempt takes the TARGET_GONE path before it can reach\n+\t * reclaim_calls++. This therefore checks that reclaim really stops, not\n+\t * that cgroup_is_dying() works -- see that function in the BPF program\n+\t * for why the dying window cannot be hit reliably from userspace.\n+\t *\n+\t * reclaimed_bytes is compared against 0 rather than against its\n+\t * pre-removal value: the target is empty for the whole test, so\n+\t * bpf_proactive_reclaim() has nothing to reclaim and must have returned\n+\t * 0 on every call, before and after the removal alike. An \"unchanged\"\n+\t * comparison would be 0 == 0 and could never fail.\n+\t */\n+\tif (!ASSERT_EQ(skel-\u003ebss-\u003ereclaim_calls, calls_before, \"reclaim_calls\"))\n+\t\tgoto out;\n+\tif (!ASSERT_EQ(skel-\u003ebss-\u003ereclaimed_bytes, 0ULL, \"reclaimed_bytes\"))\n+\t\tgoto out;\n+\n+out:\n+\tif (reader_pid \u003e 0) {\n+\t\tkill(reader_pid, SIGKILL);\n+\t\t(void)waitpid(reader_pid, NULL, 0);\n+\t}\n+\tif (data_fd \u003e= 0)\n+\t\tclose(data_fd);\n+\tif (data_file[0])\n+\t\tunlink(data_file);\n+\tif (rb)\n+\t\tring_buffer__free(rb);\n+\tif (skel)\n+\t\tmemcg_async_reclaim__destroy(skel);\n+\tcleanup_cgroup_environment();\n+}\ndiff --git a/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c b/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c\nnew file mode 100644\nindex 0000000000000..d78d547af7bf1\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c\n@@ -0,0 +1,327 @@\n+// SPDX-License-Identifier: GPL-2.0\n+\n+#include \"vmlinux.h\"\n+#include \"bpf_experimental.h\"\n+\n+#define CLOCK_MONOTONIC\t\t1\n+/*\n+ * One reclaim round targets RECLAIM_MAX_ITER batches of RECLAIM_SIZE\n+ * each, i.e. 4 MiB in total. Each bpf_wq callback reclaims a single\n+ * batch and requeues the same work item for the next one, so no callback\n+ * runs longer than one bounded reclaim pass.\n+ *\n+ * RECLAIM_SIZE is a byte count, not a page count: bpf_proactive_reclaim()\n+ * converts it against the running kernel's PAGE_SIZE and returns bytes, so\n+ * this holds on any page size. The kfunc also clamps a batch to the\n+ * kernel's MEMCG_CHARGE_BATCH, which is not visible to BPF; a clamped\n+ * batch only means a round needs more callbacks, because remaining is\n+ * decremented by the bytes actually reclaimed.\n+ */\n+#define RECLAIM_SIZE\t\t(128 * 1024UL)\n+#define RECLAIM_MAX_ITER\t32\n+\n+struct bpf_args {\n+\tu64 high_cgroup_id;\n+\tu64 low_cgroup_id;\n+\tu64 event_delta_threshold;\n+\tu64 check_ns;\n+};\n+\n+struct cgroup_memcg {\n+\tstruct cgroup *cgrp;\n+\tstruct mem_cgroup *memcg;\n+};\n+\n+static u64 wq_high_cgroup_id;\n+static u64 wq_low_cgroup_id;\n+\n+/*\n+ * Statistics exposed to userspace through .bss, so the test can verify\n+ * that reclaim actually happened instead of relying on timing alone.\n+ */\n+u64 reclaim_calls;\n+u64 reclaimed_bytes;\n+\n+/*\n+ * A timer that fails to rearm stops the whole chain, which from userspace\n+ * looks exactly like \"the kernel never reclaimed\". Count it so the test can\n+ * tell the two apart instead of blaming the kernel.\n+ */\n+u64 timer_failures;\n+\n+/*\n+ * bpf_proactive_reclaim() reports failure as a negative return, which is\n+ * otherwise indistinguishable from \"this cgroup has nothing left to\n+ * reclaim\". Keep the last one so a failing kfunc is not mistaken for an\n+ * idle cgroup. Stored as a positive errno.\n+ */\n+u64 last_reclaim_err;\n+\n+/*\n+ * Outcome of a single reclaim attempt, reported to userspace through\n+ * the reclaim_events ringbuf so tests can wait for reclaim events with\n+ * a timeout instead of polling the counters above.\n+ */\n+enum reclaim_outcome {\n+\tRECLAIM_OUTCOME_CALLED,\n+\tRECLAIM_OUTCOME_SKIPPED_DYING,\n+\tRECLAIM_OUTCOME_TARGET_GONE,\n+};\n+\n+struct reclaim_event {\n+\t__u64 outcome;\n+};\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_RINGBUF);\n+\t__uint(max_entries, 1 \u003c\u003c 16);\n+} reclaim_events SEC(\".maps\");\n+\n+/*\n+ * Reports are best effort: when the ringbuf is full, for example when\n+ * userspace does not consume the events, the report is dropped.\n+ */\n+static void emit_reclaim_event(enum reclaim_outcome outcome)\n+{\n+\tstruct reclaim_event *ev;\n+\n+\tev = bpf_ringbuf_reserve(\u0026reclaim_events, sizeof(*ev), 0);\n+\tif (!ev)\n+\t\treturn;\n+\n+\tev-\u003eoutcome = outcome;\n+\tbpf_ringbuf_submit(ev, 0);\n+}\n+\n+static int get_cgroup_memcg_from_id(u64 cgroup_id, struct cgroup_memcg *cm)\n+{\n+\tcm-\u003ecgrp = bpf_cgroup_from_id(cgroup_id);\n+\tif (!cm-\u003ecgrp)\n+\t\treturn -1;\n+\n+\tcm-\u003ememcg = bpf_get_mem_cgroup(\u0026cm-\u003ecgrp-\u003eself);\n+\tif (!cm-\u003ememcg) {\n+\t\tbpf_cgroup_release(cm-\u003ecgrp);\n+\t\treturn -1;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static void put_cgroup_memcg(struct cgroup_memcg *cm)\n+{\n+\tbpf_put_mem_cgroup(cm-\u003ememcg);\n+\tbpf_cgroup_release(cm-\u003ecgrp);\n+}\n+\n+static int get_cgroup_event(u64 cgroup_id, u64 *val)\n+{\n+\tstruct cgroup_memcg cm;\n+\n+\tif (get_cgroup_memcg_from_id(cgroup_id, \u0026cm))\n+\t\treturn -1;\n+\tbpf_mem_cgroup_flush_stats(cm.memcg);\n+\t*val = bpf_mem_cgroup_page_state(cm.memcg,\n+\t\tbpf_core_enum_value(enum node_stat_item,\n+\t\t\t\t WORKINGSET_REFAULT_FILE));\n+\tput_cgroup_memcg(\u0026cm);\n+\n+\treturn 0;\n+}\n+\n+static bool\n+should_reclaim_cgroup(u64 cgroup_id, u64 *prev_event, u64 event_delta_threshold)\n+{\n+\tu64 cur, delta;\n+\n+\tif (get_cgroup_event(cgroup_id, \u0026cur))\n+\t\treturn false;\n+\n+\tdelta = cur - *prev_event;\n+\t*prev_event = cur;\n+\n+\treturn delta \u003e= event_delta_threshold;\n+}\n+\n+/*\n+ * rmdir clears CSS_ONLINE on cgrp-\u003eself in cgroup_destroy_locked() and only\n+ * then deactivates the cgroup's kernfs node with kernfs_remove().\n+ * bpf_cgroup_from_id() resolves an id through\n+ * kernfs_find_and_get_node_by_id(), which refuses deactivated nodes, so the\n+ * lookup starts failing inside the rmdir syscall -- not, as one might expect,\n+ * once the cgroup's last reference has been dropped.\n+ *\n+ * The window in which the lookup still succeeds while the cgroup is already\n+ * dying is therefore just the few statements between those two. An attempt\n+ * that lands in it reports RECLAIM_OUTCOME_SKIPPED_DYING; after rmdir has\n+ * returned, every attempt reports TARGET_GONE instead. The check is kept\n+ * because it is the only thing standing between reclaim and a cgroup that is\n+ * mid-teardown, but it cannot be hit reliably from userspace, so the test\n+ * does not require SKIPPED_DYING.\n+ *\n+ * Only CSS_ONLINE is worth testing. CSS_DYING is raised by kill_css_sync(),\n+ * which dereferences css-\u003ess and so is never called with cgrp-\u003eself; the\n+ * cgroup's own css only ever loses CSS_ONLINE. This is therefore\n+ * cgroup_is_dead() from include/linux/cgroup.h, not css_is_dying().\n+ *\n+ * CSS_ONLINE comes from vmlinux.h: the kernel defines it in an anonymous\n+ * enum, so bpf_core_enum_value() has no enum type to bind to, and\n+ * redeclaring it locally would clash with the vmlinux.h enumerators.\n+ * vmlinux.h is generated from the running kernel's BTF, so the value\n+ * already matches the target kernel.\n+ */\n+static bool cgroup_is_dying(struct cgroup *cgrp)\n+{\n+\treturn !(cgrp-\u003eself.flags \u0026 CSS_ONLINE);\n+}\n+\n+/*\n+ * Reclaim one batch from the target cgroup. Returns the number of\n+ * bytes reclaimed, or 0 if the cgroup is dying or gone, the kfunc\n+ * failed, or nothing was reclaimed. Each attempt reports its outcome\n+ * through the reclaim_events ringbuf, and a failing kfunc additionally\n+ * records its errno in last_reclaim_err.\n+ */\n+static u64 reclaim_cgroup(u64 cgroup_id, u64 size)\n+{\n+\tstruct cgroup_memcg cm;\n+\tlong nr;\n+\n+\tif (get_cgroup_memcg_from_id(cgroup_id, \u0026cm)) {\n+\t\temit_reclaim_event(RECLAIM_OUTCOME_TARGET_GONE);\n+\t\treturn 0;\n+\t}\n+\n+\tif (cgroup_is_dying(cm.cgrp)) {\n+\t\temit_reclaim_event(RECLAIM_OUTCOME_SKIPPED_DYING);\n+\t\tput_cgroup_memcg(\u0026cm);\n+\t\treturn 0;\n+\t}\n+\n+\treclaim_calls++;\n+\tnr = bpf_proactive_reclaim(cm.memcg, size, -1);\n+\tif (nr \u003c 0)\n+\t\tlast_reclaim_err = -nr;\n+\telse if (nr \u003e 0)\n+\t\treclaimed_bytes += nr;\n+\temit_reclaim_event(RECLAIM_OUTCOME_CALLED);\n+\n+\tput_cgroup_memcg(\u0026cm);\n+\n+\treturn nr \u003e 0 ? nr : 0;\n+}\n+\n+struct wq_elem {\n+\tstruct bpf_timer timer;\n+\tstruct bpf_wq work;\n+\tu64 prev_event;\n+\tu64 event_delta_threshold;\n+\tu64 check_ns;\n+\t/*\n+\t * Bytes still to reclaim in the current round, carried across\n+\t * requeues. 0 means no round is in progress; the timer path\n+\t * starts a new round by resetting it, requeued work only looks\n+\t * at it.\n+\t */\n+\tu64 remaining;\n+};\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_ARRAY);\n+\t__uint(max_entries, 1);\n+\t__type(key, __u32);\n+\t__type(value, struct wq_elem);\n+} wq_map SEC(\".maps\");\n+\n+static int reclaim_work_fn(void *map, int *key, void *value)\n+{\n+\tstruct wq_elem *elem = value;\n+\tu64 nr, size;\n+\n+\tif (!elem-\u003eremaining) {\n+\t\t/*\n+\t\t * Timer-triggered entry: start a new round only when the\n+\t\t * high cgroup refaults enough. Requeued entries skip this\n+\t\t * check and only look at remaining, so a round consumes the\n+\t\t * refault delta only on the tick that starts it; ticks that\n+\t\t * find no round in progress consume and discard it.\n+\t\t */\n+\t\tif (!should_reclaim_cgroup(wq_high_cgroup_id, \u0026elem-\u003eprev_event,\n+\t\t\telem-\u003eevent_delta_threshold))\n+\t\t\treturn 0;\n+\t\telem-\u003eremaining = RECLAIM_MAX_ITER * RECLAIM_SIZE;\n+\t}\n+\n+\t/* One bounded reclaim pass per callback */\n+\tsize = elem-\u003eremaining \u003c RECLAIM_SIZE ? elem-\u003eremaining : RECLAIM_SIZE;\n+\tnr = reclaim_cgroup(wq_low_cgroup_id, size);\n+\tif (!nr) {\n+\t\telem-\u003eremaining = 0;\n+\t\treturn 0;\n+\t}\n+\n+\t/* try_to_free_mem_cgroup_pages() may reclaim more than requested */\n+\tif (nr \u003e= elem-\u003eremaining)\n+\t\telem-\u003eremaining = 0;\n+\telse\n+\t\telem-\u003eremaining -= nr;\n+\n+\t/* Requeue the same work item for the next batch */\n+\tif (elem-\u003eremaining)\n+\t\tbpf_wq_start(\u0026elem-\u003ework, 0);\n+\n+\treturn 0;\n+}\n+\n+static int wq_timer_cb(void *map, int *key, struct wq_elem *elem)\n+{\n+\t/*\n+\t * A failed bpf_wq_start() self-heals on the next tick; a failed\n+\t * rearm does not, so only the latter is worth reporting.\n+\t */\n+\tbpf_wq_start(\u0026elem-\u003ework, 0);\n+\tif (bpf_timer_start(\u0026elem-\u003etimer, elem-\u003echeck_ns, 0))\n+\t\ttimer_failures++;\n+\n+\treturn 0;\n+}\n+\n+SEC(\"syscall\")\n+int wq_prog_init(struct bpf_args *ctx)\n+{\n+\tstruct wq_elem *elem;\n+\t__u32 key = 0;\n+\tint ret;\n+\n+\telem = bpf_map_lookup_elem(\u0026wq_map, \u0026key);\n+\tif (!elem)\n+\t\treturn -1;\n+\n+\tret = bpf_wq_init(\u0026elem-\u003ework, \u0026wq_map, 0);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tret = bpf_wq_set_callback(\u0026elem-\u003ework, reclaim_work_fn, 0);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tret = bpf_timer_init(\u0026elem-\u003etimer, \u0026wq_map, CLOCK_MONOTONIC);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tret = bpf_timer_set_callback(\u0026elem-\u003etimer, wq_timer_cb);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\telem-\u003eprev_event = 0;\n+\telem-\u003eremaining = 0;\n+\telem-\u003eevent_delta_threshold = ctx-\u003eevent_delta_threshold;\n+\telem-\u003echeck_ns = ctx-\u003echeck_ns;\n+\n+\twq_high_cgroup_id = ctx-\u003ehigh_cgroup_id;\n+\twq_low_cgroup_id = ctx-\u003elow_cgroup_id;\n+\n+\treturn bpf_timer_start(\u0026elem-\u003etimer, elem-\u003echeck_ns, 0);\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\n"
} |
| 2/1 | 2026/09/20 10:02 | agent | patch-evaluator |
1mModel:core Args: null Results: {
"EnableConfigs": [
"MEMCG",
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_proactive_reclaim"
],
"Reasoning": "The patch introduces a new sleepable BPF kfunc, bpf_proactive_reclaim(), which allows BPF programs of type BPF_PROG_TYPE_SYSCALL to trigger proactive memory reclamation on a specified memory cgroup via try_to_free_mem_cgroup_pages(). This modifies reachable core kernel code bridging BPF and the memory management reclaim subsystem, making it worth fuzzing for potential deadlocks, race conditions, or invariant violations.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 7f5fe58e78a00d7fe8315e8a4dae89d0a33c5a20
Author: syz-cluster <triage@syzkaller.com>
Date: Sun Sep 20 10:02:46 2026 +0000
syz-cluster: applied patch under review
diff --git a/mm/bpf_memcontrol.c b/mm/bpf_memcontrol.c
index 716df49d76477..c5d7f29ade858 100644
--- a/mm/bpf_memcontrol.c
+++ b/mm/bpf_memcontrol.c
@@ -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;
}
diff --git a/mm/internal.h b/mm/internal.h
index 38b1165212c94..44e95e87e3cd9 100644
--- a/mm/internal.h
+++ b/mm/internal.h
@@ -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,
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2f79688dcf7ce..1edaa752facb2 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -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
diff --git a/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c b/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
new file mode 100644
index 0000000000000..179b64fb6de84
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
@@ -0,0 +1,890 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Memory controller eBPF async reclaim test
+ *
+ * Setting TEST_MEMCG_ASYNC_RECLAIM_BENCH=1 adds a baseline run of the
+ * workload without the BPF program to memcg_async_reclaim, and prints
+ * the baseline and reclaim timings, plus the speedup of the pressured
+ * cgroup, to stdout. The cgroups are recreated between the two runs so
+ * that both start from the same cold state.
+ */
+
+#include <test_progs.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/vfs.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <time.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <linux/magic.h>
+
+#include "cgroup_helpers.h"
+
+struct bpf_args {
+ u64 high_cgroup_id;
+ u64 low_cgroup_id;
+ u64 event_delta_threshold;
+ u64 check_ns;
+};
+
+/* Reclaim outcomes reported by the BPF program through the ringbuf. */
+enum reclaim_outcome {
+ RECLAIM_OUTCOME_CALLED,
+ RECLAIM_OUTCOME_SKIPPED_DYING,
+ RECLAIM_OUTCOME_TARGET_GONE,
+};
+
+struct reclaim_event {
+ u64 outcome;
+};
+
+#include "memcg_async_reclaim.skel.h"
+
+#define FILE_SIZE (32 * 1024 * 1024ul)
+#define BUFFER_SIZE (4096)
+#define CG_LIMIT (32 * 1024 * 1024ul)
+#define READ_TIMES 50
+
+#define CG_DIR "/memcg_async_reclaim"
+#define CG_HIGH_DIR CG_DIR "/high"
+#define CG_LOW_DIR CG_DIR "/low"
+
+#define CG_DYING_DIR "/memcg_async_reclaim_dying"
+#define CG_DYING_TRIGGER_DIR CG_DYING_DIR "/trigger"
+#define CG_DYING_TARGET_DIR CG_DYING_DIR "/target"
+
+#define CHECK_PERIOD_NS (2 * 1000 * 1000ull)
+#define EVENT_DELTA_THRESHOLD 1
+
+/*
+ * Timing for the dying test: after the target cgroup is removed, give
+ * in-flight reclaim passes time to drain, then wait for a reclaim round
+ * to hit the removed target. The keepalive reader keeps the trigger
+ * cgroup refaulting, and the timer fires every CHECK_PERIOD_NS, so
+ * such a round must show up within a few timer periods. The BPF
+ * program reports every reclaim outcome through the ringbuf, so the
+ * waits just poll it with a timeout.
+ */
+#define DYING_SETTLE_US (200 * 1000)
+#define EVENT_POLL_TIMEOUT_MS (100)
+#define EVENT_POLL_ROUNDS (50)
+
+static bool usable_for_workload_files(const char *dir)
+{
+ struct statfs st;
+
+ if (statfs(dir, &st))
+ return false;
+
+ return st.f_type != TMPFS_MAGIC && st.f_type != RAMFS_MAGIC;
+}
+
+/*
+ * The workload files must sit on a regular filesystem: with swap
+ * disabled for the cgroup, tmpfs/ramfs pages are unevictable and would
+ * OOM the cgroup instead of exercising reclaim; they are also charged
+ * as anonymous memory, so they never raise the WORKINGSET_REFAULT_FILE
+ * events the BPF program monitors.
+ *
+ * /tmp is tmpfs on many systems, so fall back to the current directory.
+ * That fallback needs the very same check: test_progs is routinely run
+ * from a tmpfs working directory, and silently landing there produces an
+ * OOM that looks like a reclaim failure. Returns NULL when neither
+ * directory is usable, in which case the workload cannot run at all.
+ */
+static const char *workload_files_dir(void)
+{
+ if (usable_for_workload_files("/tmp"))
+ return "/tmp";
+ if (usable_for_workload_files("."))
+ return ".";
+
+ return NULL;
+}
+
+/*
+ * Keep the workload from swapping out, so that reclaim has to evict page
+ * cache instead. memory.swap.max only exists when the kernel is built with
+ * CONFIG_SWAP, and /proc/swaps is registered by the same CONFIG_SWAP-gated
+ * code (mm/swapfile.c), so it stands in for the file here. With CONFIG_SWAP=n
+ * no swap can happen anyway, so skipping the write is the correct behaviour.
+ */
+static int disable_swap(const char *cgroup_dir)
+{
+ if (access("/proc/swaps", F_OK))
+ return 0;
+
+ return write_cgroup_file(cgroup_dir, "memory.swap.max", "0");
+}
+
+/*
+ * The forked children run after test_progs hijacked stdio, so anything
+ * they print is lost with their private copy of the hijacked buffer
+ * unless the test runs under -v. The exit status is the one diagnostics
+ * channel that always reaches the parent, so each failing step gets its
+ * own code.
+ */
+enum child_exit_code {
+ CHILD_EXIT_OK = 0,
+ CHILD_EXIT_JOIN_CGROUP,
+ CHILD_EXIT_WRITE_FILE,
+ CHILD_EXIT_READ_FILE,
+ CHILD_EXIT_TIME_FILE,
+};
+
+static const char *child_exit_str(int code)
+{
+ switch (code) {
+ case CHILD_EXIT_OK:
+ return "success";
+ case CHILD_EXIT_JOIN_CGROUP:
+ return "join cgroup";
+ case CHILD_EXIT_WRITE_FILE:
+ return "write data file";
+ case CHILD_EXIT_READ_FILE:
+ return "read data file";
+ case CHILD_EXIT_TIME_FILE:
+ return "write time file";
+ default:
+ return "unknown";
+ }
+}
+
+static int setup_high_low_cgroups(u64 *high_cgroup_id, u64 *low_cgroup_id)
+{
+ int ret;
+ char limit_buf[20];
+
+ ret = setup_cgroup_environment();
+ if (!ASSERT_OK(ret, "setup_cgroup_environment"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DIR))
+ goto cleanup;
+ close(ret);
+
+ ret = enable_controllers(CG_DIR, "memory");
+ if (!ASSERT_OK(ret, "enable_controllers"))
+ goto cleanup;
+
+ snprintf(limit_buf, sizeof(limit_buf), "%lu", CG_LIMIT);
+ ret = write_cgroup_file(CG_DIR, "memory.max", limit_buf);
+ if (!ASSERT_OK(ret, "write_cgroup_file memory.max"))
+ goto cleanup;
+
+ ret = disable_swap(CG_DIR);
+ if (!ASSERT_OK(ret, "disable_swap"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_HIGH_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_HIGH_DIR))
+ goto cleanup;
+ close(ret);
+
+ *high_cgroup_id = get_cgroup_id(CG_HIGH_DIR);
+ if (!ASSERT_GT(*high_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_LOW_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_LOW_DIR))
+ goto cleanup;
+ close(ret);
+
+ *low_cgroup_id = get_cgroup_id(CG_LOW_DIR);
+ if (!ASSERT_GT(*low_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ return 0;
+
+cleanup:
+ cleanup_cgroup_environment();
+ return -1;
+}
+
+/*
+ * The dying test needs an empty reclaim target plus a cgroup that keeps
+ * refaulting while the target is removed, so reclaim rounds keep
+ * starting and run into the removed target. The two have to be separate
+ * cgroups: the target must hold no processes to be removed, and v2's
+ * no-internal-process constraint keeps the refaulting workload out of
+ * any parent that has domain children.
+ */
+static int setup_dying_cgroups(u64 *trigger_cgroup_id, u64 *target_cgroup_id)
+{
+ int ret;
+ char limit_buf[20];
+
+ ret = setup_cgroup_environment();
+ if (!ASSERT_OK(ret, "setup_cgroup_environment"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DYING_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DYING_DIR))
+ goto cleanup;
+ close(ret);
+
+ ret = enable_controllers(CG_DYING_DIR, "memory");
+ if (!ASSERT_OK(ret, "enable_controllers"))
+ goto cleanup;
+
+ snprintf(limit_buf, sizeof(limit_buf), "%lu", CG_LIMIT);
+ ret = write_cgroup_file(CG_DYING_DIR, "memory.max", limit_buf);
+ if (!ASSERT_OK(ret, "write_cgroup_file memory.max"))
+ goto cleanup;
+
+ ret = disable_swap(CG_DYING_DIR);
+ if (!ASSERT_OK(ret, "disable_swap"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DYING_TRIGGER_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DYING_TRIGGER_DIR))
+ goto cleanup;
+ close(ret);
+
+ *trigger_cgroup_id = get_cgroup_id(CG_DYING_TRIGGER_DIR);
+ if (!ASSERT_GT(*trigger_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DYING_TARGET_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DYING_TARGET_DIR))
+ goto cleanup;
+ close(ret);
+
+ *target_cgroup_id = get_cgroup_id(CG_DYING_TARGET_DIR);
+ if (!ASSERT_GT(*target_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ return 0;
+
+cleanup:
+ cleanup_cgroup_environment();
+ return -1;
+}
+
+static int write_file(int fd)
+{
+ int ret = -1;
+ size_t written = 0;
+ char *buffer;
+
+ buffer = malloc(BUFFER_SIZE);
+ if (!buffer)
+ goto out;
+
+ memset(buffer, 'A', BUFFER_SIZE);
+
+ while (written < FILE_SIZE) {
+ size_t to_write = FILE_SIZE - written < BUFFER_SIZE ?
+ FILE_SIZE - written : BUFFER_SIZE;
+ ssize_t n = write(fd, buffer, to_write);
+
+ if (n <= 0)
+ goto cleanup;
+ written += n;
+ }
+
+ ret = 0;
+cleanup:
+ free(buffer);
+out:
+ return ret;
+}
+
+static int read_file(int fd, int iterations)
+{
+ long page_size = sysconf(_SC_PAGESIZE);
+ struct stat sb;
+ char *map;
+ size_t i;
+
+ if (fstat(fd, &sb) == -1)
+ return -1;
+
+ if (sb.st_size != FILE_SIZE) {
+ fprintf(stderr, "File size mismatch: expected %lu, got %lu\n",
+ (unsigned long)FILE_SIZE, (unsigned long)sb.st_size);
+ return -1;
+ }
+
+ map = mmap(NULL, FILE_SIZE, PROT_READ, MAP_PRIVATE, fd, 0);
+ if (map == MAP_FAILED)
+ return -1;
+
+ for (int iter = 0; iter < iterations; iter++) {
+ for (i = 0; i < FILE_SIZE; i += page_size) {
+ /* access a byte to trigger page fault */
+ volatile char v = map[i];
+ (void)v;
+ }
+ }
+
+ if (munmap(map, FILE_SIZE) == -1)
+ return -1;
+
+ return 0;
+}
+
+static int real_test_child_work(const char *cgroup_path, int data_fd,
+ int time_fd, int read_times)
+{
+ struct timespec start, end;
+ double elapsed;
+ char buf[32];
+ int len;
+
+ if (join_parent_cgroup(cgroup_path))
+ return CHILD_EXIT_JOIN_CGROUP;
+
+ clock_gettime(CLOCK_MONOTONIC, &start);
+
+ if (write_file(data_fd))
+ return CHILD_EXIT_WRITE_FILE;
+
+ if (read_file(data_fd, read_times))
+ return CHILD_EXIT_READ_FILE;
+
+ clock_gettime(CLOCK_MONOTONIC, &end);
+
+ elapsed = (end.tv_sec - start.tv_sec) +
+ (end.tv_nsec - start.tv_nsec) / 1000000000.0;
+
+ len = snprintf(buf, sizeof(buf), "%.6f", elapsed);
+ /* snprintf() returns the untruncated length, so bound it before write() */
+ if (len < 0 || len >= (int)sizeof(buf) || write(time_fd, buf, len) != len)
+ return CHILD_EXIT_TIME_FILE;
+
+ return CHILD_EXIT_OK;
+}
+
+static int get_time(int fd, double *time)
+{
+ char buf[64] = {};
+ ssize_t n;
+
+ /* The child wrote through the fork-shared description, so rewind. */
+ if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
+ PRINT_FAIL("lseek time file");
+ return -1;
+ }
+
+ n = read(fd, buf, sizeof(buf) - 1);
+ if (!ASSERT_GT(n, 0, "read time file"))
+ return -1;
+
+ if (sscanf(buf, "%lf", time) != 1) {
+ PRINT_FAIL("sscanf %s", buf);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int
+run_high_low_workload(const char *dir, double *high_elapsed, double *low_elapsed,
+ int read_times)
+{
+ char high_data_file[PATH_MAX];
+ char low_data_file[PATH_MAX];
+ char high_time_file[PATH_MAX];
+ char low_time_file[PATH_MAX];
+ int high_data_fd = -1, low_data_fd = -1;
+ int high_time_fd = -1, low_time_fd = -1;
+ pid_t high_pid = -1, low_pid = -1;
+ pid_t wait_ret;
+ int status;
+ int ret = -1;
+
+ snprintf(high_data_file, sizeof(high_data_file),
+ "%s/memcg_async_high_data_XXXXXX", dir);
+ snprintf(low_data_file, sizeof(low_data_file),
+ "%s/memcg_async_low_data_XXXXXX", dir);
+ snprintf(high_time_file, sizeof(high_time_file),
+ "%s/memcg_async_high_time_XXXXXX", dir);
+ snprintf(low_time_file, sizeof(low_time_file),
+ "%s/memcg_async_low_time_XXXXXX", dir);
+
+ /*
+ * The mkstemp() fds are kept and inherited by the children rather
+ * than reopened by name: reopening would resolve the path again and
+ * follow whatever sits there by then.
+ */
+ high_data_fd = mkstemp(high_data_file);
+ if (!ASSERT_GE(high_data_fd, 0, "mkstemp high data"))
+ goto cleanup;
+
+ low_data_fd = mkstemp(low_data_file);
+ if (!ASSERT_GE(low_data_fd, 0, "mkstemp low data"))
+ goto cleanup;
+
+ high_time_fd = mkstemp(high_time_file);
+ if (!ASSERT_GE(high_time_fd, 0, "mkstemp high time"))
+ goto cleanup;
+
+ low_time_fd = mkstemp(low_time_file);
+ if (!ASSERT_GE(low_time_fd, 0, "mkstemp low time"))
+ goto cleanup;
+
+ low_pid = fork();
+ if (!ASSERT_GE(low_pid, 0, "fork low"))
+ goto cleanup;
+ if (low_pid == 0)
+ _exit(real_test_child_work(CG_LOW_DIR, low_data_fd,
+ low_time_fd, read_times));
+
+ high_pid = fork();
+ if (!ASSERT_GE(high_pid, 0, "fork high"))
+ goto cleanup;
+ if (high_pid == 0)
+ _exit(real_test_child_work(CG_HIGH_DIR, high_data_fd,
+ high_time_fd, read_times));
+
+ wait_ret = waitpid(low_pid, &status, 0);
+ if (!ASSERT_GT(wait_ret, 0, "low waitpid"))
+ goto cleanup;
+ /*
+ * The child has been reaped and its PID can already be reused,
+ * so mark it to keep cleanup from signaling an unrelated process.
+ */
+ low_pid = -1;
+ if (!ASSERT_TRUE(WIFEXITED(status), "low exited"))
+ goto cleanup;
+ if (WEXITSTATUS(status) != CHILD_EXIT_OK) {
+ PRINT_FAIL("low child failed at: %s (exit status %d)",
+ child_exit_str(WEXITSTATUS(status)),
+ WEXITSTATUS(status));
+ goto cleanup;
+ }
+
+ wait_ret = waitpid(high_pid, &status, 0);
+ if (!ASSERT_GT(wait_ret, 0, "high waitpid"))
+ goto cleanup;
+ /* Same as above: the reaped PID must not be signaled again. */
+ high_pid = -1;
+ if (!ASSERT_TRUE(WIFEXITED(status), "high exited"))
+ goto cleanup;
+ if (WEXITSTATUS(status) != CHILD_EXIT_OK) {
+ PRINT_FAIL("high child failed at: %s (exit status %d)",
+ child_exit_str(WEXITSTATUS(status)),
+ WEXITSTATUS(status));
+ goto cleanup;
+ }
+
+ if (get_time(high_time_fd, high_elapsed))
+ goto cleanup;
+ if (get_time(low_time_fd, low_elapsed))
+ goto cleanup;
+
+ ret = 0;
+
+cleanup:
+ /* On failure, make sure no child process is left behind */
+ if (ret) {
+ if (high_pid > 0) {
+ kill(high_pid, SIGKILL);
+ (void)waitpid(high_pid, NULL, 0);
+ }
+ if (low_pid > 0) {
+ kill(low_pid, SIGKILL);
+ (void)waitpid(low_pid, NULL, 0);
+ }
+ }
+ if (high_data_fd >= 0)
+ close(high_data_fd);
+ if (low_data_fd >= 0)
+ close(low_data_fd);
+ if (high_time_fd >= 0)
+ close(high_time_fd);
+ if (low_time_fd >= 0)
+ close(low_time_fd);
+ unlink(low_time_file);
+ unlink(high_time_file);
+ unlink(low_data_file);
+ unlink(high_data_file);
+ return ret;
+}
+
+static int
+setup_bpf(u64 high_cgroup_id, u64 low_cgroup_id,
+ struct memcg_async_reclaim **skel_ptr)
+{
+ struct memcg_async_reclaim *skel;
+ struct bpf_args args = {
+ .high_cgroup_id = high_cgroup_id,
+ .low_cgroup_id = low_cgroup_id,
+ .event_delta_threshold = EVENT_DELTA_THRESHOLD,
+ .check_ns = CHECK_PERIOD_NS,
+ };
+ LIBBPF_OPTS(bpf_test_run_opts, run_opts,
+ .ctx_in = &args,
+ .ctx_size_in = sizeof(args));
+ int prog_init_fd, err;
+
+ skel = memcg_async_reclaim__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "memcg_async_reclaim__open_and_load"))
+ return -1;
+
+ prog_init_fd = bpf_program__fd(skel->progs.wq_prog_init);
+
+ err = bpf_prog_test_run_opts(prog_init_fd, &run_opts);
+ if (!ASSERT_OK(err, "bpf_prog_test_run_opts"))
+ goto error_out;
+ if (!ASSERT_EQ(run_opts.retval, 0, "prog_init retval"))
+ goto error_out;
+
+ *skel_ptr = skel;
+ return 0;
+
+error_out:
+ memcg_async_reclaim__destroy(skel);
+ return -1;
+}
+
+/*
+ * A timer that stopped rearming produces no further reclaim rounds, which
+ * the "no events" failures below would otherwise report as a kernel bug.
+ * Only call this on a path that is already failing.
+ */
+static void report_timer_failures(struct memcg_async_reclaim *skel)
+{
+ u64 failures = skel->bss->timer_failures;
+
+ if (failures)
+ PRINT_FAIL("bpf_timer failed to rearm %llu time(s), so the reclaim loop stopped",
+ (unsigned long long)failures);
+}
+
+/*
+ * A kfunc that fails on every call is indistinguishable from a cgroup with
+ * nothing left to reclaim, which the reclaim_calls and reclaimed_bytes
+ * assertions below cannot tell apart. Only call this on a path that is
+ * already failing.
+ */
+static void report_reclaim_errors(struct memcg_async_reclaim *skel)
+{
+ u64 last_err = skel->bss->last_reclaim_err;
+
+ if (last_err)
+ PRINT_FAIL("bpf_proactive_reclaim() last failed with -%llu, nothing was reclaimed",
+ (unsigned long long)last_err);
+}
+
+/*
+ * The benchmark numbers are only interesting when the test passes, but
+ * dump_test_log() drops the captured log unless the test failed or -v was
+ * given, so they have to bypass the hijack. The ?: stdout fallback is
+ * required, not defensive: stdio_hijack() returns early in verbose mode and
+ * never sets env.stdout_saved.
+ *
+ * This also bypasses the worker-to-dispatcher log protocol, so under -j the
+ * line can interleave with the per-test records. It carries no '#' prefix:
+ * test_progs uses that only for its own result records, and print_test_log()
+ * dumps free-form test output verbatim.
+ */
+static void bench_printf(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprintf(env.stdout_saved ?: stdout, fmt, ap);
+ va_end(ap);
+}
+
+void test_memcg_async_reclaim(void)
+{
+ u64 high_cgroup_id, low_cgroup_id;
+ double high_time = 0.0, low_time = 0.0;
+ double base_high_time = 0.0, base_low_time = 0.0;
+ struct memcg_async_reclaim *skel = NULL;
+ const char *dir;
+ int err, bench;
+
+ dir = workload_files_dir();
+ if (!ASSERT_TRUE(dir != NULL, "workload_files_dir"))
+ return;
+
+ bench = !!getenv("TEST_MEMCG_ASYNC_RECLAIM_BENCH");
+
+ err = setup_high_low_cgroups(&high_cgroup_id, &low_cgroup_id);
+ if (!ASSERT_OK(err, "setup_high_low_cgroups reclaim"))
+ return;
+
+ /*
+ * 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;
+
+ /*
+ * 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();
+ err = setup_high_low_cgroups(&high_cgroup_id, &low_cgroup_id);
+ if (!ASSERT_OK(err, "setup_high_low_cgroups after baseline"))
+ goto out;
+ }
+
+ err = setup_bpf(high_cgroup_id, low_cgroup_id, &skel);
+ if (!ASSERT_OK(err, "setup_bpf"))
+ goto out;
+
+ err = run_high_low_workload(dir, &high_time, &low_time, READ_TIMES);
+ if (!ASSERT_OK(err, "run_high_low_workload reclaim"))
+ goto out;
+
+ /*
+ * Timing alone cannot distinguish a working reclaim from a no-op
+ * one, so require that the BPF program actually reclaimed memory
+ * from the low cgroup.
+ */
+ if (!ASSERT_GT(skel->bss->reclaim_calls, 0, "reclaim_calls")) {
+ report_timer_failures(skel);
+ report_reclaim_errors(skel);
+ goto out;
+ }
+ if (!ASSERT_GT(skel->bss->reclaimed_bytes, 0, "reclaimed_bytes")) {
+ report_reclaim_errors(skel);
+ goto out;
+ }
+
+ /*
+ * The timing comparison is a benchmark and too flaky to fail CI
+ * runs, so it only logs the numbers; the counters above already
+ * proved that the BPF program reclaimed memory.
+ */
+ if (bench && base_high_time > 0.0)
+ bench_printf("memcg_async_reclaim: baseline high=%f low=%f, "
+ "reclaim high=%f low=%f, high speedup=%.1f%%\n",
+ base_high_time, base_low_time, high_time, low_time,
+ 100.0 * (base_high_time - high_time) / base_high_time);
+
+out:
+ if (skel)
+ memcg_async_reclaim__destroy(skel);
+ cleanup_cgroup_environment();
+}
+
+/*
+ * Keep refaults flowing through the trigger cgroup so reclaim rounds
+ * keep being triggered while the target cgroup is being removed. The
+ * child joins the trigger cgroup and writes the data file there, so
+ * that the file pages are charged to the trigger cgroup and actually
+ * come under its memory limit; then it re-reads the file in a loop
+ * until it is killed.
+ */
+static pid_t spawn_keepalive_reader(int data_fd)
+{
+ pid_t pid = fork();
+
+ if (pid != 0)
+ return pid;
+
+ if (join_parent_cgroup(CG_DYING_TRIGGER_DIR))
+ _exit(CHILD_EXIT_JOIN_CGROUP);
+ if (write_file(data_fd))
+ _exit(CHILD_EXIT_WRITE_FILE);
+ for (;;) {
+ if (read_file(data_fd, READ_TIMES))
+ _exit(CHILD_EXIT_READ_FILE);
+ }
+}
+
+/* Reclaim outcomes observed so far, tallied from ringbuf events. */
+struct reclaim_events_seen {
+ int called;
+ int skipped_dying;
+ int target_gone;
+};
+
+static int on_reclaim_event(void *ctx, void *data, size_t sz)
+{
+ struct reclaim_events_seen *seen = ctx;
+ const struct reclaim_event *ev = data;
+
+ if (sz < sizeof(*ev))
+ return 0;
+
+ switch (ev->outcome) {
+ case RECLAIM_OUTCOME_CALLED:
+ seen->called++;
+ break;
+ case RECLAIM_OUTCOME_SKIPPED_DYING:
+ seen->skipped_dying++;
+ break;
+ case RECLAIM_OUTCOME_TARGET_GONE:
+ seen->target_gone++;
+ break;
+ }
+
+ return 0;
+}
+
+/*
+ * Remove the reclaim target while the BPF program keeps running and verify
+ * that reclaim stops instead of reclaiming from the removed cgroup.
+ *
+ * The target stays empty; the workload lives in the trigger cgroup and only
+ * keeps refaults flowing so that reclaim rounds keep starting, both before
+ * and after the target is removed. A CALLED event while the target is alive
+ * proves that rounds really run (the kfunc returns 0 on the empty target, but
+ * the call is still counted).
+ *
+ * Once rmdir has returned, bpf_cgroup_from_id() has already stopped resolving
+ * the target: kernfs deactivates the directory node inside the rmdir syscall,
+ * see cgroup_is_dying() in the BPF program. TARGET_GONE is therefore the
+ * outcome this test can rely on, and the one it asserts. SKIPPED_DYING needs
+ * an attempt to land in the short window between cgroup_destroy_locked()
+ * clearing CSS_ONLINE and kernfs_remove() deactivating the node, so it is
+ * counted and reported on failure but never required.
+ */
+void test_memcg_async_reclaim_dying(void)
+{
+ u64 trigger_cgroup_id, target_cgroup_id;
+ char data_file[PATH_MAX] = "";
+ struct reclaim_events_seen seen = {};
+ struct memcg_async_reclaim *skel = NULL;
+ struct ring_buffer *rb = NULL;
+ u64 calls_before;
+ const char *dir;
+ pid_t reader_pid = -1;
+ int data_fd = -1;
+ int err, status, i, n;
+
+ dir = workload_files_dir();
+ if (!ASSERT_TRUE(dir != NULL, "workload_files_dir"))
+ return;
+
+ err = setup_dying_cgroups(&trigger_cgroup_id, &target_cgroup_id);
+ if (!ASSERT_OK(err, "setup_dying_cgroups"))
+ return;
+
+ err = setup_bpf(trigger_cgroup_id, target_cgroup_id, &skel);
+ if (!ASSERT_OK(err, "setup_bpf"))
+ goto out;
+
+ rb = ring_buffer__new(bpf_map__fd(skel->maps.reclaim_events),
+ on_reclaim_event, &seen, NULL);
+ if (!ASSERT_OK_PTR(rb, "ring_buffer__new"))
+ goto out;
+
+ snprintf(data_file, sizeof(data_file),
+ "%s/memcg_async_dying_XXXXXX", dir);
+ /* Kept open and inherited, see run_high_low_workload(). */
+ data_fd = mkstemp(data_file);
+ if (!ASSERT_GE(data_fd, 0, "mkstemp"))
+ goto out;
+
+ 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;
+
+ /*
+ * 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;
+ }
+
+ /*
+ * 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
+ * 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.
+ */
+ if (!ASSERT_EQ(skel->bss->reclaim_calls, calls_before, "reclaim_calls"))
+ goto out;
+ if (!ASSERT_EQ(skel->bss->reclaimed_bytes, 0ULL, "reclaimed_bytes"))
+ goto out;
+
+out:
+ if (reader_pid > 0) {
+ kill(reader_pid, SIGKILL);
+ (void)waitpid(reader_pid, NULL, 0);
+ }
+ if (data_fd >= 0)
+ close(data_fd);
+ if (data_file[0])
+ unlink(data_file);
+ if (rb)
+ ring_buffer__free(rb);
+ if (skel)
+ memcg_async_reclaim__destroy(skel);
+ cleanup_cgroup_environment();
+}
diff --git a/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c b/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
new file mode 100644
index 0000000000000..d78d547af7bf1
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
@@ -0,0 +1,327 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include "vmlinux.h"
+#include "bpf_experimental.h"
+
+#define CLOCK_MONOTONIC 1
+/*
+ * One reclaim round targets RECLAIM_MAX_ITER batches of RECLAIM_SIZE
+ * each, i.e. 4 MiB in total. Each bpf_wq callback reclaims a single
+ * batch and requeues the same work item for the next one, so no callback
+ * runs longer than one bounded reclaim pass.
+ *
+ * RECLAIM_SIZE is a byte count, not a page count: bpf_proactive_reclaim()
+ * converts it against the running kernel's PAGE_SIZE and returns bytes, so
+ * this holds on any page size. The kfunc also clamps a batch to the
+ * kernel's MEMCG_CHARGE_BATCH, which is not visible to BPF; a clamped
+ * batch only means a round needs more callbacks, because remaining is
+ * decremented by the bytes actually reclaimed.
+ */
+#define RECLAIM_SIZE (128 * 1024UL)
+#define RECLAIM_MAX_ITER 32
+
+struct bpf_args {
+ u64 high_cgroup_id;
+ u64 low_cgroup_id;
+ u64 event_delta_threshold;
+ u64 check_ns;
+};
+
+struct cgroup_memcg {
+ struct cgroup *cgrp;
+ struct mem_cgroup *memcg;
+};
+
+static u64 wq_high_cgroup_id;
+static u64 wq_low_cgroup_id;
+
+/*
+ * Statistics exposed to userspace through .bss, so the test can verify
+ * that reclaim actually happened instead of relying on timing alone.
+ */
+u64 reclaim_calls;
+u64 reclaimed_bytes;
+
+/*
+ * A timer that fails to rearm stops the whole chain, which from userspace
+ * looks exactly like "the kernel never reclaimed". Count it so the test can
+ * tell the two apart instead of blaming the kernel.
+ */
+u64 timer_failures;
+
+/*
+ * bpf_proactive_reclaim() reports failure as a negative return, which is
+ * otherwise indistinguishable from "this cgroup has nothing left to
+ * reclaim". Keep the last one so a failing kfunc is not mistaken for an
+ * idle cgroup. Stored as a positive errno.
+ */
+u64 last_reclaim_err;
+
+/*
+ * Outcome of a single reclaim attempt, reported to userspace through
+ * the reclaim_events ringbuf so tests can wait for reclaim events with
+ * a timeout instead of polling the counters above.
+ */
+enum reclaim_outcome {
+ RECLAIM_OUTCOME_CALLED,
+ RECLAIM_OUTCOME_SKIPPED_DYING,
+ RECLAIM_OUTCOME_TARGET_GONE,
+};
+
+struct reclaim_event {
+ __u64 outcome;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(max_entries, 1 << 16);
+} reclaim_events SEC(".maps");
+
+/*
+ * Reports are best effort: when the ringbuf is full, for example when
+ * userspace does not consume the events, the report is dropped.
+ */
+static void emit_reclaim_event(enum reclaim_outcome outcome)
+{
+ struct reclaim_event *ev;
+
+ ev = bpf_ringbuf_reserve(&reclaim_events, sizeof(*ev), 0);
+ if (!ev)
+ return;
+
+ ev->outcome = outcome;
+ bpf_ringbuf_submit(ev, 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)
+ return -1;
+
+ cm->memcg = bpf_get_mem_cgroup(&cm->cgrp->self);
+ if (!cm->memcg) {
+ bpf_cgroup_release(cm->cgrp);
+ return -1;
+ }
+
+ return 0;
+}
+
+static void put_cgroup_memcg(struct cgroup_memcg *cm)
+{
+ bpf_put_mem_cgroup(cm->memcg);
+ bpf_cgroup_release(cm->cgrp);
+}
+
+static int get_cgroup_event(u64 cgroup_id, u64 *val)
+{
+ struct cgroup_memcg cm;
+
+ if (get_cgroup_memcg_from_id(cgroup_id, &cm))
+ return -1;
+ bpf_mem_cgroup_flush_stats(cm.memcg);
+ *val = bpf_mem_cgroup_page_state(cm.memcg,
+ bpf_core_enum_value(enum node_stat_item,
+ WORKINGSET_REFAULT_FILE));
+ put_cgroup_memcg(&cm);
+
+ return 0;
+}
+
+static bool
+should_reclaim_cgroup(u64 cgroup_id, u64 *prev_event, u64 event_delta_threshold)
+{
+ u64 cur, delta;
+
+ if (get_cgroup_event(cgroup_id, &cur))
+ return false;
+
+ delta = cur - *prev_event;
+ *prev_event = cur;
+
+ return delta >= event_delta_threshold;
+}
+
+/*
+ * rmdir clears CSS_ONLINE on cgrp->self in cgroup_destroy_locked() and only
+ * then deactivates the cgroup's kernfs node with kernfs_remove().
+ * bpf_cgroup_from_id() resolves an id through
+ * kernfs_find_and_get_node_by_id(), which refuses deactivated nodes, so the
+ * lookup starts failing inside the rmdir syscall -- not, as one might expect,
+ * once the cgroup's last reference has been dropped.
+ *
+ * The window in which the lookup still succeeds while the cgroup is already
+ * dying is therefore just the few statements between those two. An attempt
+ * that lands in it reports RECLAIM_OUTCOME_SKIPPED_DYING; after rmdir has
+ * returned, every attempt reports TARGET_GONE instead. The check is kept
+ * because it is the only thing standing between reclaim and a cgroup that is
+ * mid-teardown, but it cannot be hit reliably from userspace, so the test
+ * does not require SKIPPED_DYING.
+ *
+ * Only CSS_ONLINE is worth testing. CSS_DYING is raised by kill_css_sync(),
+ * which dereferences css->ss and so is never called with cgrp->self; the
+ * cgroup's own css only ever loses CSS_ONLINE. This is therefore
+ * cgroup_is_dead() from include/linux/cgroup.h, not css_is_dying().
+ *
+ * CSS_ONLINE comes from vmlinux.h: the kernel defines it in an anonymous
+ * enum, so bpf_core_enum_value() has no enum type to bind to, and
+ * redeclaring it locally would clash with the vmlinux.h enumerators.
+ * vmlinux.h is generated from the running kernel's BTF, so the value
+ * already matches the target kernel.
+ */
+static bool cgroup_is_dying(struct cgroup *cgrp)
+{
+ return !(cgrp->self.flags & CSS_ONLINE);
+}
+
+/*
+ * Reclaim one batch from the target cgroup. Returns the number of
+ * bytes reclaimed, or 0 if the cgroup is dying or gone, the kfunc
+ * failed, or nothing was reclaimed. Each attempt reports its outcome
+ * through the reclaim_events ringbuf, and a failing kfunc additionally
+ * records its errno in last_reclaim_err.
+ */
+static u64 reclaim_cgroup(u64 cgroup_id, u64 size)
+{
+ struct cgroup_memcg cm;
+ long nr;
+
+ if (get_cgroup_memcg_from_id(cgroup_id, &cm)) {
+ emit_reclaim_event(RECLAIM_OUTCOME_TARGET_GONE);
+ return 0;
+ }
+
+ if (cgroup_is_dying(cm.cgrp)) {
+ emit_reclaim_event(RECLAIM_OUTCOME_SKIPPED_DYING);
+ put_cgroup_memcg(&cm);
+ return 0;
+ }
+
+ reclaim_calls++;
+ nr = bpf_proactive_reclaim(cm.memcg, size, -1);
+ if (nr < 0)
+ last_reclaim_err = -nr;
+ else if (nr > 0)
+ reclaimed_bytes += nr;
+ emit_reclaim_event(RECLAIM_OUTCOME_CALLED);
+
+ put_cgroup_memcg(&cm);
+
+ return nr > 0 ? nr : 0;
+}
+
+struct wq_elem {
+ struct bpf_timer timer;
+ struct bpf_wq work;
+ u64 prev_event;
+ u64 event_delta_threshold;
+ u64 check_ns;
+ /*
+ * Bytes still to reclaim in the current round, carried across
+ * requeues. 0 means no round is in progress; the timer path
+ * starts a new round by resetting it, requeued work only looks
+ * at it.
+ */
+ u64 remaining;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, struct wq_elem);
+} wq_map SEC(".maps");
+
+static int reclaim_work_fn(void *map, int *key, void *value)
+{
+ struct wq_elem *elem = value;
+ u64 nr, size;
+
+ if (!elem->remaining) {
+ /*
+ * Timer-triggered entry: start a new round only when the
+ * high cgroup refaults enough. Requeued entries skip this
+ * check and only look at remaining, so a round consumes the
+ * refault delta only on the tick that starts it; ticks that
+ * find no round in progress consume and discard it.
+ */
+ if (!should_reclaim_cgroup(wq_high_cgroup_id, &elem->prev_event,
+ elem->event_delta_threshold))
+ return 0;
+ elem->remaining = RECLAIM_MAX_ITER * RECLAIM_SIZE;
+ }
+
+ /* One bounded reclaim pass per callback */
+ size = elem->remaining < RECLAIM_SIZE ? elem->remaining : RECLAIM_SIZE;
+ nr = reclaim_cgroup(wq_low_cgroup_id, size);
+ if (!nr) {
+ elem->remaining = 0;
+ return 0;
+ }
+
+ /* try_to_free_mem_cgroup_pages() may reclaim more than requested */
+ if (nr >= elem->remaining)
+ elem->remaining = 0;
+ else
+ elem->remaining -= nr;
+
+ /* Requeue the same work item for the next batch */
+ if (elem->remaining)
+ bpf_wq_start(&elem->work, 0);
+
+ return 0;
+}
+
+static int wq_timer_cb(void *map, int *key, struct wq_elem *elem)
+{
+ /*
+ * A failed bpf_wq_start() self-heals on the next tick; a failed
+ * rearm does not, so only the latter is worth reporting.
+ */
+ bpf_wq_start(&elem->work, 0);
+ if (bpf_timer_start(&elem->timer, elem->check_ns, 0))
+ timer_failures++;
+
+ return 0;
+}
+
+SEC("syscall")
+int wq_prog_init(struct bpf_args *ctx)
+{
+ struct wq_elem *elem;
+ __u32 key = 0;
+ int ret;
+
+ elem = bpf_map_lookup_elem(&wq_map, &key);
+ if (!elem)
+ return -1;
+
+ ret = bpf_wq_init(&elem->work, &wq_map, 0);
+ if (ret)
+ return ret;
+
+ ret = bpf_wq_set_callback(&elem->work, reclaim_work_fn, 0);
+ if (ret)
+ return ret;
+
+ ret = bpf_timer_init(&elem->timer, &wq_map, CLOCK_MONOTONIC);
+ if (ret)
+ return ret;
+
+ ret = bpf_timer_set_callback(&elem->timer, wq_timer_cb);
+ if (ret)
+ return ret;
+
+ elem->prev_event = 0;
+ elem->remaining = 0;
+ elem->event_delta_threshold = ctx->event_delta_threshold;
+ elem->check_ns = ctx->check_ns;
+
+ wq_high_cgroup_id = ctx->high_cgroup_id;
+ wq_low_cgroup_id = ctx->low_cgroup_id;
+
+ return bpf_timer_start(&elem->timer, elem->check_ns, 0);
+}
+
+char _license[] SEC("license") = "GPL";
|
| 3/2 | 2026/09/20 10:02 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 18260 output: 27 thoughts: 164 Thoughts: **Analyzing the BPF Memory Control Patch** Okay, so this patch is touching `mm/bpf_memcontrol.c` and `mm/internal.h`, plus some selftests – interesting. Let's dig in. I see a new `bpf_proactive_reclaim()` kfunc is being added to `mm/bpf_memcontrol.c`. And it looks like this is the workhorse of the patch. The arguments are the memory cgroup, a size, and a swappiness value. Makes sense. This suggests some proactive memory reclamation functionality controlled by BPF, which is exactly the kind of thing I'd expect given the file. Furthermore, I see it's being registered using `register_btf_kfunc_id_set` with `BPF_PROG_TYPE_SYSCALL` and `bpf_memcontrol_reclaim_kfunc_set`. Right, so this is allowing BPF programs of the syscall type to call this function. This is significant. Now, I need to understand the surrounding code. Time to scrutinize `mm/bpf_memcontrol.c` and other files within `mm/` to get a good picture of how the whole thing is set up, configured, and interacts with other memory management subsystems. Gotta understand the bigger picture of this architecture. |
| 4/2 | 2026/09/20 10:02 | tool | grepper |
0mArgs:{
"Expression": "bpf_memcontrol",
"PathPrefix": "mm/"
}Results: {
"Output": "mm/Makefile=106=ifdef CONFIG_BPF_SYSCALL\nmm/Makefile:107:obj-$(CONFIG_MEMCG) += bpf_memcontrol.o\nmm/Makefile-108-endif\n--\nmm/bpf_memcontrol.c=206=__bpf_kfunc_end_defs();\nmm/bpf_memcontrol.c-207-\nmm/bpf_memcontrol.c:208:BTF_KFUNCS_START(bpf_memcontrol_kfuncs)\nmm/bpf_memcontrol.c-209-BTF_ID_FLAGS(func, bpf_get_root_mem_cgroup, KF_ACQUIRE | KF_RET_NULL)\n--\nmm/bpf_memcontrol.c=217=BTF_ID_FLAGS(func, bpf_mem_cgroup_flush_stats, KF_SLEEPABLE)\nmm/bpf_memcontrol.c-218-\nmm/bpf_memcontrol.c:219:BTF_KFUNCS_END(bpf_memcontrol_kfuncs)\nmm/bpf_memcontrol.c-220-\nmm/bpf_memcontrol.c:221:BTF_KFUNCS_START(bpf_memcontrol_reclaim_kfuncs)\nmm/bpf_memcontrol.c-222-BTF_ID_FLAGS(func, bpf_proactive_reclaim, KF_SLEEPABLE)\nmm/bpf_memcontrol.c:223:BTF_KFUNCS_END(bpf_memcontrol_reclaim_kfuncs)\nmm/bpf_memcontrol.c-224-\nmm/bpf_memcontrol.c:225:static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set = {\nmm/bpf_memcontrol.c-226-\t.owner = THIS_MODULE,\nmm/bpf_memcontrol.c:227:\t.set = \u0026bpf_memcontrol_kfuncs,\nmm/bpf_memcontrol.c-228-};\nmm/bpf_memcontrol.c-229-\nmm/bpf_memcontrol.c:230:static const struct btf_kfunc_id_set bpf_memcontrol_reclaim_kfunc_set = {\nmm/bpf_memcontrol.c-231-\t.owner = THIS_MODULE,\nmm/bpf_memcontrol.c:232:\t.set = \u0026bpf_memcontrol_reclaim_kfuncs,\nmm/bpf_memcontrol.c-233-};\nmm/bpf_memcontrol.c-234-\nmm/bpf_memcontrol.c:235:static int __init bpf_memcontrol_init(void)\nmm/bpf_memcontrol.c-236-{\n--\nmm/bpf_memcontrol.c-239-\terr = register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC,\nmm/bpf_memcontrol.c:240:\t\t\t\t\t\u0026bpf_memcontrol_kfunc_set);\nmm/bpf_memcontrol.c-241-\tif (err) {\n--\nmm/bpf_memcontrol.c-246-\terr = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,\nmm/bpf_memcontrol.c:247:\t\t\t\t\t\u0026bpf_memcontrol_reclaim_kfunc_set);\nmm/bpf_memcontrol.c-248-\tif (err)\n--\nmm/bpf_memcontrol.c-252-}\nmm/bpf_memcontrol.c:253:late_initcall(bpf_memcontrol_init);\n"
} |
| 5/2 | 2026/09/20 10:02 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 19688 output: 37 thoughts: 26 Thoughts: Here's my take on the thought process, as requested: **Diving into `bpf_proactive_reclaim` in `mm/bpf_memcontrol.c`** Okay, time to dig into the BPF memory control code, specifically around the `bpf_proactive_reclaim` function. I'm already pretty familiar with the general memory management landscape, and the challenges of integrating BPF into it. I'm expecting this function to be the core of how we're attempting to proactively reclaim memory based on BPF program signals. I'll want to see how it's hooked into the core VM, what triggers it, and the strategies it employs. I'll be looking for how it handles different types of memory (page cache, anonymous pages, etc.) and, importantly, how it interacts with the rest of the memory management subsystem to avoid contention or creating new bottlenecks. I'll pay close attention to the lock usage and how that affects concurrent access. I’m thinking there will be a subtle dance here between reclaiming aggressively and avoiding excessive thrashing. Let's see how they've handled it. Hopefully, the code is well-commented, as it's such a critical and complex area! |
| 6/2 | 2026/09/20 10:03 | tool | read-file |
0mArgs:{
"File": "mm/bpf_memcontrol.c",
"FirstLine": 150,
"LineCount": 60
}Results: {
"Contents": " 150:\t\treturn memcg_page_state_output(memcg, idx);\n 151:\t}\n 152:\t\n 153:\t/**\n 154:\t * bpf_mem_cgroup_flush_stats - Flush memory cgroup's statistics\n 155:\t * @memcg: memory cgroup\n 156:\t *\n 157:\t * Propagate memory cgroup's statistics up the cgroup tree.\n 158:\t */\n 159:\t__bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)\n 160:\t{\n 161:\t\tmem_cgroup_flush_stats(memcg);\n 162:\t}\n 163:\t\n 164:\t/**\n 165:\t * bpf_proactive_reclaim - proactively reclaim memory from a memory cgroup\n 166:\t * @memcg: the target memory cgroup to reclaim from.\n 167:\t * @size: the amount of memory to reclaim, in bytes, clamped to\n 168:\t * MEMCG_CHARGE_BATCH.\n 169:\t * @swappiness: the reclaim swappiness, in the range [MIN_SWAPPINESS,\n 170:\t * SWAPPINESS_ANON_ONLY], or -1 to use the memcg's own\n 171:\t * swappiness.\n 172:\t *\n 173:\t * Performs one proactive reclaim pass on @memcg, like a write to\n 174:\t * memory.reclaim but without retrying until @size is reached. Call it\n 175:\t * repeatedly to reclaim more than one batch.\n 176:\t *\n 177:\t * Only available to BPF_PROG_TYPE_SYSCALL, because other sleepable programs\n 178:\t * may run with filesystem locks held, which the reclaim path can deadlock\n 179:\t * on via filesystem shrinkers.\n 180:\t *\n 181:\t * Return: The amount of memory reclaimed, in bytes, or a negative error.\n 182:\t */\n 183:\t__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,\n 184:\t\t\t\t\t unsigned long size,\n 185:\t\t\t\t\t int swappiness)\n 186:\t{\n 187:\t\tunsigned long nr_reclaimed;\n 188:\t\tunsigned long nr_pages;\n 189:\t\n 190:\t\tif (swappiness \u003c -1 || swappiness \u003e SWAPPINESS_ANON_ONLY)\n 191:\t\t\treturn -EINVAL;\n 192:\t\n 193:\t\tif (size \u003c PAGE_SIZE)\n 194:\t\t\treturn -EINVAL;\n 195:\t\n 196:\t\tnr_pages = min(size / PAGE_SIZE, (unsigned long)MEMCG_CHARGE_BATCH);\n 197:\t\n 198:\t\tnr_reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages, GFP_KERNEL,\n 199:\t\t\t\t\t\t\t MEMCG_RECLAIM_MAY_SWAP |\n 200:\t\t\t\t\t\t\t MEMCG_RECLAIM_PROACTIVE,\n 201:\t\t\t\t\t\t\t swappiness == -1 ? NULL : \u0026swappiness);\n 202:\t\n 203:\t\treturn nr_reclaimed * PAGE_SIZE;\n 204:\t}\n 205:\t\n 206:\t__bpf_kfunc_end_defs();\n 207:\t\n 208:\tBTF_KFUNCS_START(bpf_memcontrol_kfuncs)\n 209:\tBTF_ID_FLAGS(func, bpf_get_root_mem_cgroup, KF_ACQUIRE | KF_RET_NULL)\n"
} |
| 7/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 21013 output: 34 thoughts: 27 Thoughts: Here's my take on the thought process, as if it were my own: **Diving into `try_to_free_mem_cgroup_pages`** Okay, so I need to understand how memory reclaim behaves within cgroups. The obvious first step is to trace the execution from where the reclaim process is initiated. I'm going to start by looking at `try_to_free_mem_cgroup_pages` in `mm/vmscan.c`. It's a key function for reclaim, so it is a good starting place to find out how the reclaim interacts with cgroups. From there, I can get a clearer picture of the control and policies. I want to understand the specifics of how cgroup limits impact the memory reclaiming process. |
| 8/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "try_to_free_mem_cgroup_pages",
"PathPrefix": "mm/"
}Results: {
"Output": "mm/bpf_memcontrol.c=183=__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,\n--\nmm/bpf_memcontrol.c-197-\nmm/bpf_memcontrol.c:198:\tnr_reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages, GFP_KERNEL,\nmm/bpf_memcontrol.c-199-\t\t\t\t\t\t MEMCG_RECLAIM_MAY_SWAP |\n--\nmm/internal.h=77=enum {\n--\nmm/internal.h-84-\nmm/internal.h:85:unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\nmm/internal.h-86-\t\t\t\t\t unsigned long nr_pages,\n--\nmm/memcontrol-v1.c=1771=static int mem_cgroup_resize_max(struct mem_cgroup *memcg,\n--\nmm/memcontrol-v1.c-1815-\nmm/memcontrol-v1.c:1816:\t\tif (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,\nmm/memcontrol-v1.c-1817-\t\t\t\tmemsw ? 0 : MEMCG_RECLAIM_MAY_SWAP, NULL)) {\n--\nmm/memcontrol-v1.c=1834=static int mem_cgroup_force_empty(struct mem_cgroup *memcg)\n--\nmm/memcontrol-v1.c-1851-\nmm/memcontrol-v1.c:1852:\t\tif (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,\nmm/memcontrol-v1.c-1853-\t\t\t\t\t\t MEMCG_RECLAIM_MAY_SWAP, NULL))\n--\nmm/memcontrol.c=2378=static unsigned long reclaim_high(struct mem_cgroup *memcg,\n--\nmm/memcontrol.c-2393-\t\tpsi_memstall_enter(\u0026pflags);\nmm/memcontrol.c:2394:\t\tnr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,\nmm/memcontrol.c-2395-\t\t\t\t\t\t\tgfp_mask,\n--\nmm/memcontrol.c=2645=static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,\n--\nmm/memcontrol.c-2717-\tpsi_memstall_enter(\u0026pflags);\nmm/memcontrol.c:2718:\tnr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,\nmm/memcontrol.c-2719-\t\t\t\t\t\t gfp_mask, reclaim_options, NULL);\n--\nmm/memcontrol.c=4838=static ssize_t memory_high_write(struct kernfs_open_file *of,\n--\nmm/memcontrol.c-4879-\nmm/memcontrol.c:4880:\t\treclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,\nmm/memcontrol.c-4881-\t\t\t\t\tGFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);\n--\nmm/memcontrol.c=4897=static ssize_t memory_max_write(struct kernfs_open_file *of,\n--\nmm/memcontrol.c-4938-\t\tif (nr_reclaims) {\nmm/memcontrol.c:4939:\t\t\tif (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,\nmm/memcontrol.c-4940-\t\t\t\t\tGFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))\n--\nmm/vmscan.c=6815=unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,\n--\nmm/vmscan.c-6854-\nmm/vmscan.c:6855:unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\nmm/vmscan.c-6856-\t\t\t\t\t unsigned long nr_pages,\n--\nmm/vmscan.c-6895-#else\nmm/vmscan.c:6896:unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\nmm/vmscan.c-6897-\t\t\t\t\t unsigned long nr_pages,\n--\nmm/vmscan.c=7958=int user_proactive_reclaim(char *buf,\n--\nmm/vmscan.c-8029-\t\t\t\t\t MEMCG_RECLAIM_PROACTIVE;\nmm/vmscan.c:8030:\t\t\treclaimed = try_to_free_mem_cgroup_pages(memcg,\nmm/vmscan.c-8031-\t\t\t\t\t\t batch_size, gfp_mask,\n"
} |
| 9/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 22511 output: 35 thoughts: 344 Thoughts: **My Initial Assessment of the New `bpf_proactive_reclaim` Kfunc and Fuzzing Potential** Okay, so there's this new `bpf_proactive_reclaim` kfunc. That's interesting; it's opening up proactive memory cgroup reclaim to BPF programs, specifically those running as `BPF_PROG_TYPE_SYSCALL`. The first thing I'm thinking is, "Is this actually reachable and fuzzable?" Always gotta assess the attack surface and if we can actually get in there. I'm going to start with a section-by-section review to ensure the attack vectors are indeed there: First, the core subsystems are the most relevant: memory management, synchronization, BPF, scheduler, networking, VFS, and syscall handling. This seems pretty clear since we're directly impacting memory management with a BPF kfunc. Wait, the more I think about it, `BPF_PROG_TYPE_SYSCALL` *can* call kfuncs, right? Yeah, `sys_bpf` is the bridge here. Alright, that looks promising for fuzzing. This `bpf_proactive_reclaim` kfunc is a direct connection between BPF and the memory management's proactive reclaim path. So next I should probably check the configurations: First, I know that `CONFIG_MEMCG` is required for this. And according to `mm/Makefile` there seems to be a conditional dependency there: ```make ifdef CONFIG_BPF_SYSCALL obj-$(CONFIG_MEMCG) += bpf_memcontrol.o endif ``` It looks like we also need `CONFIG_BPF_SYSCALL`. Are there any other config options? I need to check `mm/bpf_memcontrol.c` for any dependencies, and then `init/Kconfig` or `kernel/bpf/Kconfig` to confirm `register_btf_kfunc_id_set` and BTF support. With these configs, there's some potential. |
| 10/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "register_btf_kfunc_id_set",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/arena.c=1131=static int __init kfunc_init(void)\nkernel/bpf/arena.c-1132-{\nkernel/bpf/arena.c:1133:\treturn register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, \u0026common_kfunc_set);\nkernel/bpf/arena.c-1134-}\n--\nkernel/bpf/btf.c=9002=static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,\n--\nkernel/bpf/btf.c-9048-\tset = tab-\u003esets[hook];\nkernel/bpf/btf.c:9049:\t/* Warn when register_btf_kfunc_id_set is called twice for the same hook\nkernel/bpf/btf.c-9050-\t * for module sets.\n--\nkernel/bpf/btf.c=9273=u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,\n--\nkernel/bpf/btf.c-9281-\nkernel/bpf/btf.c:9282:static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,\nkernel/bpf/btf.c-9283-\t\t\t\t const struct btf_kfunc_id_set *kset)\n--\nkernel/bpf/btf.c-9308-/* This function must be invoked only from initcalls/module init functions */\nkernel/bpf/btf.c:9309:int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,\nkernel/bpf/btf.c-9310-\t\t\t const struct btf_kfunc_id_set *kset)\n--\nkernel/bpf/btf.c-9322-\thook = bpf_prog_type_to_kfunc_hook(prog_type);\nkernel/bpf/btf.c:9323:\treturn __register_btf_kfunc_id_set(hook, kset);\nkernel/bpf/btf.c-9324-}\nkernel/bpf/btf.c:9325:EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);\nkernel/bpf/btf.c-9326-\n--\nkernel/bpf/btf.c=9328=int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)\nkernel/bpf/btf.c-9329-{\nkernel/bpf/btf.c:9330:\treturn __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);\nkernel/bpf/btf.c-9331-}\n--\nkernel/bpf/cpumask.c=515=static int __init cpumask_kfunc_init(void)\n--\nkernel/bpf/cpumask.c-525-\tret = bpf_mem_alloc_init(\u0026bpf_cpumask_ma, sizeof(struct bpf_cpumask), false);\nkernel/bpf/cpumask.c:526:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, \u0026cpumask_kfunc_set);\nkernel/bpf/cpumask.c:527:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, \u0026cpumask_kfunc_set);\nkernel/bpf/cpumask.c:528:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, \u0026cpumask_kfunc_set);\nkernel/bpf/cpumask.c-529-\treturn ret ?: register_btf_id_dtor_kfuncs(cpumask_dtors,\n--\nkernel/bpf/crypto.c=379=static int __init crypto_kfunc_init(void)\n--\nkernel/bpf/crypto.c-388-\nkernel/bpf/crypto.c:389:\tret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, \u0026crypt_kfunc_set);\nkernel/bpf/crypto.c:390:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_ACT, \u0026crypt_kfunc_set);\nkernel/bpf/crypto.c:391:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, \u0026crypt_kfunc_set);\nkernel/bpf/crypto.c:392:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,\nkernel/bpf/crypto.c-393-\t\t\t\t\t \u0026crypt_init_kfunc_set);\n--\nkernel/bpf/helpers.c=4983=static int __init kfunc_init(void)\n--\nkernel/bpf/helpers.c-4998-\nkernel/bpf/helpers.c:4999:\tret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, \u0026generic_kfunc_set);\nkernel/bpf/helpers.c:5000:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, \u0026generic_kfunc_set);\nkernel/bpf/helpers.c:5001:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, \u0026generic_kfunc_set);\nkernel/bpf/helpers.c:5002:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, \u0026generic_kfunc_set);\nkernel/bpf/helpers.c:5003:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, \u0026generic_kfunc_set);\nkernel/bpf/helpers.c:5004:\tret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, \u0026generic_kfunc_set);\nkernel/bpf/helpers.c-5005-\tret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,\n--\nkernel/bpf/helpers.c-5007-\t\t\t\t\t\t THIS_MODULE);\nkernel/bpf/helpers.c:5008:\treturn ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, \u0026common_kfunc_set);\nkernel/bpf/helpers.c-5009-}\n--\nkernel/bpf/map_iter.c=230=static int init_subsystem(void)\nkernel/bpf/map_iter.c-231-{\nkernel/bpf/map_iter.c:232:\treturn register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, \u0026bpf_map_iter_kfunc_set);\nkernel/bpf/map_iter.c-233-}\n--\nkernel/bpf/rqspinlock.c=759=static __init int rqspinlock_register_kfuncs(void)\nkernel/bpf/rqspinlock.c-760-{\nkernel/bpf/rqspinlock.c:761:\treturn register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, \u0026rqspinlock_kfunc_set);\nkernel/bpf/rqspinlock.c-762-}\n"
} |
| 11/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25362 output: 28 thoughts: 53 Thoughts: Okay, here's my take on those thoughts, framed as my own mental process, given my expertise: **Checking BPF Compilation Guards** Right, let's dive into the kernel build system and verify some crucial configuration dependencies. My first stop will be `kernel/bpf/Makefile` and `kernel/bpf/btf.c`. I need to ensure that the compilation guards are set up correctly, especially concerning `CONFIG_BPF_SYSCALL`. The key question is whether the build of `btf.c` actually depends on `CONFIG_BPF_SYSCALL` being enabled. I know from experience that improperly defined dependencies in these areas can lead to perplexing build failures and, worse, silently broken functionality if you're not careful. I'll need to check the preprocessor directives in the code to ensure everything is as it should be. Let's dig in and make sure the preprocessor logic reflects the correct dependencies. This is a common point of oversight so I'll be thorough. |
| 12/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "btf.o",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/Makefile=13=obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o\nkernel/bpf/Makefile:14:obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o\nkernel/bpf/Makefile-15-obj-${CONFIG_BPF_LSM}\t += bpf_inode_storage.o\n--\nkernel/bpf/Makefile=17=obj-$(CONFIG_BPF_JIT) += trampoline.o\nkernel/bpf/Makefile:18:obj-$(CONFIG_BPF_SYSCALL) += btf.o memalloc.o rqspinlock.o stream.o\nkernel/bpf/Makefile-19-ifeq ($(CONFIG_MMU)$(CONFIG_64BIT),yy)\n--\nkernel/bpf/Makefile=43=ifeq ($(CONFIG_SYSFS),y)\nkernel/bpf/Makefile:44:obj-$(CONFIG_DEBUG_INFO_BTF) += sysfs_btf.o\nkernel/bpf/Makefile-45-endif\n--\nkernel/bpf/bpf_struct_ops.c=1084=static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/bpf_struct_ops.c-1096-\t\t/* The map holds btf for its whole life time. */\nkernel/bpf/bpf_struct_ops.c:1097:\t\tbtf = btf_get_by_fd(attr-\u003evalue_type_btf_obj_fd);\nkernel/bpf/bpf_struct_ops.c-1098-\t\tif (IS_ERR(btf))\n--\nkernel/bpf/bpf_struct_ops.c=1564=void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map)\n--\nkernel/bpf/bpf_struct_ops.c-1567-\nkernel/bpf/bpf_struct_ops.c:1568:\tinfo-\u003ebtf_vmlinux_id = btf_obj_id(st_map-\u003ebtf);\nkernel/bpf/bpf_struct_ops.c-1569-}\n--\nkernel/bpf/btf.c=8548=int btf_get_fd_by_id(u32 id)\n--\nkernel/bpf/btf.c-8568-\nkernel/bpf/btf.c:8569:u32 btf_obj_id(const struct btf *btf)\nkernel/bpf/btf.c-8570-{\n--\nkernel/bpf/btf.c=8800=BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)\n--\nkernel/bpf/btf.c-8802-\tstruct btf *btf = NULL;\nkernel/bpf/btf.c:8803:\tint btf_obj_fd = 0;\nkernel/bpf/btf.c-8804-\tlong ret;\n--\nkernel/bpf/btf.c-8813-\tif (ret \u003e 0 \u0026\u0026 btf_is_module(btf)) {\nkernel/bpf/btf.c:8814:\t\tbtf_obj_fd = __btf_new_fd(btf);\nkernel/bpf/btf.c:8815:\t\tif (btf_obj_fd \u003c 0) {\nkernel/bpf/btf.c-8816-\t\t\tbtf_put(btf);\nkernel/bpf/btf.c:8817:\t\t\treturn btf_obj_fd;\nkernel/bpf/btf.c-8818-\t\t}\nkernel/bpf/btf.c:8819:\t\treturn ret | (((u64)btf_obj_fd) \u003c\u003c 32);\nkernel/bpf/btf.c-8820-\t}\n--\nkernel/bpf/btf.c=9396=int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,\n--\nkernel/bpf/btf.c-9403-\nkernel/bpf/btf.c:9404:\tbtf = btf_get_module_btf(owner);\nkernel/bpf/btf.c-9405-\tif (!btf)\n--\nkernel/bpf/syscall.c=2917=static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)\n--\nkernel/bpf/syscall.c-2994-\nkernel/bpf/syscall.c:2995:\t/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog\nkernel/bpf/syscall.c-2996-\t * or btf, we need to check which one it is\n--\nkernel/bpf/syscall.c-3001-\t\t\tdst_prog = NULL;\nkernel/bpf/syscall.c:3002:\t\t\tattach_btf = btf_get_by_fd(attr-\u003eattach_btf_obj_fd);\nkernel/bpf/syscall.c-3003-\t\t\tif (IS_ERR(attach_btf)) {\n--\nkernel/bpf/syscall.c=5099=static int bpf_prog_get_info_by_fd(struct file *file,\n--\nkernel/bpf/syscall.c-5160-\tif (prog-\u003eaux-\u003ebtf)\nkernel/bpf/syscall.c:5161:\t\tinfo.btf_id = btf_obj_id(prog-\u003eaux-\u003ebtf);\nkernel/bpf/syscall.c-5162-\n--\nkernel/bpf/syscall.c-5309-\tif (attach_btf)\nkernel/bpf/syscall.c:5310:\t\tinfo.attach_btf_obj_id = btf_obj_id(attach_btf);\nkernel/bpf/syscall.c-5311-\n--\nkernel/bpf/syscall.c=5389=static int bpf_map_get_info_by_fd(struct file *file,\n--\nkernel/bpf/syscall.c-5418-\tif (map-\u003ebtf) {\nkernel/bpf/syscall.c:5419:\t\tinfo.btf_id = btf_obj_id(map-\u003ebtf);\nkernel/bpf/syscall.c-5420-\t\tinfo.btf_key_type_id = map-\u003ebtf_key_type_id;\n--\nkernel/bpf/verifier.c=20399=int bpf_check_attach_target(struct bpf_verifier_log *log,\n--\nkernel/bpf/verifier.c-20597-\t\tif (!fname || ret \u003c 0) {\nkernel/bpf/verifier.c:20598:\t\t\tbpf_log(log, \"Cannot find btf of tracepoint template, fall back to %s%s.\\n\",\nkernel/bpf/verifier.c-20599-\t\t\t\tprefix, tname);\n"
} |
| 13/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27534 output: 29 thoughts: 99 Thoughts: **My Investigation into BTF Kfunc Registration** Okay, so I need to make sure `DEBUG_INFO_BTF` is enabled because it looks like BTF kfuncs, as they're implemented, need that to have BTF available for vmlinux. That's a critical prerequisite. Now, before I jump to any conclusions, I should double-check the `kernel/bpf/btf.c` file. I'm wondering if `DEBUG_INFO_BTF` is strictly required for the function `register_btf_kfunc_id_set`. It's possible there are subtle dependencies I'm missing. Time to consult the source. To confirm the configuration options, I'll need to look at either `init/Kconfig` or `lib/Kconfig.debug` to nail down the exact dependencies. |
| 14/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "config DEBUG_INFO_BTF",
"PathPrefix": "lib/"
}Results: {
"Output": "lib/Kconfig.debug=378=config DEBUG_INFO_SPLIT\n--\nlib/Kconfig.debug-397-\nlib/Kconfig.debug:398:config DEBUG_INFO_BTF\nlib/Kconfig.debug-399-\tbool \"Generate BTF type information\"\n--\nlib/Kconfig.debug=419=config PAHOLE_HAS_LANG_EXCLUDE\n--\nlib/Kconfig.debug-427-\nlib/Kconfig.debug:428:config DEBUG_INFO_BTF_MODULES\nlib/Kconfig.debug-429-\tbool \"Generate BTF type information for kernel modules\"\n"
} |
| 15/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 28011 output: 38 thoughts: 42 Thoughts: Here's my summary, as if I were thinking these thoughts: **Analyzing BTF Registration** Alright, time to dig into the kernel's BTF handling. My focus is going to be on the module BTF registration process. I need to refresh my understanding of how the BTF data is associated with kernel modules and functions. Specifically, I'm going to navigate to `kernel/bpf/btf.c`. I figure the functions `btf_get_module_btf` and `__register_btf_kfunc_id_set` are key starting points for understanding the flow of this data. I want to see how the BTF data gets fetched for a module, and how those kfunc IDs are registered. This should give me a good handle on where things are defined and how they're interconnected. |
| 16/2 | 2026/09/20 10:03 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 9280,
"LineCount": 40
}Results: {
"Contents": "9280:\t}\n9281:\t\n9282:\tstatic int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,\n9283:\t\t\t\t\t const struct btf_kfunc_id_set *kset)\n9284:\t{\n9285:\t\tstruct btf *btf;\n9286:\t\tint ret, i;\n9287:\t\n9288:\t\tbtf = btf_get_module_btf(kset-\u003eowner);\n9289:\t\tif (!btf)\n9290:\t\t\treturn check_btf_kconfigs(kset-\u003eowner, \"kfunc\");\n9291:\t\tif (IS_ERR(btf))\n9292:\t\t\treturn PTR_ERR(btf);\n9293:\t\n9294:\t\tfor (i = 0; i \u003c kset-\u003eset-\u003ecnt; i++) {\n9295:\t\t\tret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset-\u003eset-\u003epairs[i].id),\n9296:\t\t\t\t\t\t kset-\u003eset-\u003epairs[i].flags);\n9297:\t\t\tif (ret)\n9298:\t\t\t\tgoto err_out;\n9299:\t\t}\n9300:\t\n9301:\t\tret = btf_populate_kfunc_set(btf, hook, kset);\n9302:\t\n9303:\terr_out:\n9304:\t\tbtf_put(btf);\n9305:\t\treturn ret;\n9306:\t}\n9307:\t\n9308:\t/* This function must be invoked only from initcalls/module init functions */\n9309:\tint register_btf_kfunc_id_set(enum bpf_prog_type prog_type,\n9310:\t\t\t\t const struct btf_kfunc_id_set *kset)\n9311:\t{\n9312:\t\tenum btf_kfunc_hook hook;\n9313:\t\n9314:\t\t/* All kfuncs need to be tagged as such in BTF.\n9315:\t\t * WARN() for initcall registrations that do not check errors.\n9316:\t\t */\n9317:\t\tif (!(kset-\u003eset-\u003eflags \u0026 BTF_SET8_KFUNCS)) {\n9318:\t\t\tWARN_ON(!kset-\u003eowner);\n9319:\t\t\treturn -EINVAL;\n"
} |
| 17/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 28916 output: 33 thoughts: 99 Thoughts: **My Analysis of BTF Retrieval** Okay, so I'm diving into this `btf_get_module_btf` function, specifically within the context of a `kset`. I'm immediately noticing that for built-in modules, `kset->owner` is going to be `THIS_MODULE`, which, as we know, translates to NULL or represents a built-in module. That's key. This implies that if BTF (BTF - BPF Type Format) isn't available or enabled, the subsequent call to `check_btf_kconfigs` is the path we need to analyze. My thought process is: what will `btf_get_module_btf` return in this scenario where BTF is *disabled*? What are the potential return values and why? I'm going to dig into the source code of `btf_get_module_btf` itself to find the answer. I have a feeling the logic might hinge on how it handles this NULL or built-in module case when BTF isn't explicitly available. I know this function is crucial to BTF processing and understanding how it handles the fundamental cases will inform how I process these. I must investigate how BTF is handled when it is not present. |
| 18/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "btf_get_module_btf",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/btf.c=8729=struct module *btf_try_get_module(const struct btf *btf)\n--\nkernel/bpf/btf.c-8758- */\nkernel/bpf/btf.c:8759:struct btf *btf_get_module_btf(const struct module *module)\nkernel/bpf/btf.c-8760-{\n--\nkernel/bpf/btf.c=9282=static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,\n--\nkernel/bpf/btf.c-9287-\nkernel/bpf/btf.c:9288:\tbtf = btf_get_module_btf(kset-\u003eowner);\nkernel/bpf/btf.c-9289-\tif (!btf)\n--\nkernel/bpf/btf.c=9396=int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,\n--\nkernel/bpf/btf.c-9403-\nkernel/bpf/btf.c:9404:\tbtf = btf_get_module_btf(owner);\nkernel/bpf/btf.c-9405-\tif (!btf)\n--\nkernel/bpf/btf.c=10076=int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n--\nkernel/bpf/btf.c-10081-\nkernel/bpf/btf.c:10082:\tbtf = btf_get_module_btf(st_ops-\u003eowner);\nkernel/bpf/btf.c-10083-\tif (!btf)\n"
} |
| 19/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29803 output: 38 thoughts: 15 Thoughts: Okay, here's my interpretation of "Let's check `btf_get_module_btf`", presented from the first-person expert perspective, formatted as requested: **Diving into BTF Retrieval** Alright, time to dive into `btf_get_module_btf`. This is a crucial function, and I need to remind myself of its role in the bigger picture. I'm assuming we're dealing with a module BTF here. So, the question is how this function retrieves the BTF (BPF Type Format) information for a specific kernel module. I need to refresh my memory on the underlying data structures it utilizes – specifically, how it interacts with the module's section containing the BTF data, and how it handles potential errors. Am I thinking about what happens if the module isn't loaded or doesn't have BTF info? It is important to remember what happens when no BTF data is available, as this is a common case. Are there fallback mechanisms I should consider? Let's trace through the code. I will probably want to see how it handles references to other BTF data, in order to check dependencies. I am hoping to get a clearer understanding of the retrieval path and, as a follow-up, the error handling involved. I'm interested in the efficiency of the lookup. Let's see how well it performs in different scenarios, especially under load. This is a critical building block for any tooling or analysis that relies on BTF, so any performance bottlenecks here are going to be felt downstream. |
| 20/2 | 2026/09/20 10:03 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 8758,
"LineCount": 25
}Results: {
"Contents": "8758:\t */\n8759:\tstruct btf *btf_get_module_btf(const struct module *module)\n8760:\t{\n8761:\t#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n8762:\t\tstruct btf_module *btf_mod, *tmp;\n8763:\t#endif\n8764:\t\tstruct btf *btf = NULL;\n8765:\t\n8766:\t\tif (!module) {\n8767:\t\t\tbtf = bpf_get_btf_vmlinux();\n8768:\t\t\tif (!IS_ERR_OR_NULL(btf))\n8769:\t\t\t\tbtf_get(btf);\n8770:\t\t\treturn btf;\n8771:\t\t}\n8772:\t\n8773:\t#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n8774:\t\tmutex_lock(\u0026btf_module_mutex);\n8775:\t\tlist_for_each_entry_safe(btf_mod, tmp, \u0026btf_modules, list) {\n8776:\t\t\tif (btf_mod-\u003emodule != module)\n8777:\t\t\t\tcontinue;\n8778:\t\n8779:\t\t\tbtf_get(btf_mod-\u003ebtf);\n8780:\t\t\tbtf = btf_mod-\u003ebtf;\n8781:\t\t\tbreak;\n8782:\t\t}\n"
} |
| 21/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 30567 output: 35 thoughts: 17 Thoughts: Okay, here's my attempt at summarizing that thought process, keeping in mind I'm speaking to a fellow expert: **Concerning `bpf_get_btf_vmlinux()`** Right, so I'm thinking about the kernel BTF data retrieval... specifically, that `bpf_get_btf_vmlinux()` call. It's the standard entry-point for getting the BTF data for the running kernel, right? I'm immediately running through the implications. I'm considering the scenarios where I need this. Is it a core function that must be always used? My mind is running through the different contexts where I'd need to interact with that function. Are there potential gotchas around symbol versions, kernel module compatibility, or even the subtle nuances of how BTF data is handled in different kernel configurations? I need to think about that when I am using this function. |
| 22/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "bpf_get_btf_vmlinux",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/bpf_struct_ops.c=1084=static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/bpf_struct_ops.c-1112-\t} else {\nkernel/bpf/bpf_struct_ops.c:1113:\t\tbtf = bpf_get_btf_vmlinux();\nkernel/bpf/bpf_struct_ops.c-1114-\t\tif (IS_ERR(btf))\n--\nkernel/bpf/btf.c=679=s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)\n--\nkernel/bpf/btf.c-684-\nkernel/bpf/btf.c:685:\tbtf = bpf_get_btf_vmlinux();\nkernel/bpf/btf.c-686-\tif (IS_ERR(btf))\n--\nkernel/bpf/btf.c=6511=static struct btf *btf_parse_module(const char *module_name, const void *data,\n--\nkernel/bpf/btf.c-6519-\nkernel/bpf/btf.c:6520:\tvmlinux_btf = bpf_get_btf_vmlinux();\nkernel/bpf/btf.c-6521-\tif (IS_ERR(vmlinux_btf))\n--\nkernel/bpf/btf.c=8055=int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)\n--\nkernel/bpf/btf.c-8218-\nkernel/bpf/btf.c:8219:\t\t\tvmlinux_btf = bpf_get_btf_vmlinux();\nkernel/bpf/btf.c-8220-\t\t\tref_t = btf_type_by_id(vmlinux_btf, kern_type_id);\n--\nkernel/bpf/btf.c=8759=struct btf *btf_get_module_btf(const struct module *module)\n--\nkernel/bpf/btf.c-8766-\tif (!module) {\nkernel/bpf/btf.c:8767:\t\tbtf = bpf_get_btf_vmlinux();\nkernel/bpf/btf.c-8768-\t\tif (!IS_ERR_OR_NULL(btf))\n--\nkernel/bpf/btf.c=8937=static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind)\n--\nkernel/bpf/btf.c-8946-\nkernel/bpf/btf.c:8947:\tid = btf_find_by_name_kind(bpf_get_btf_vmlinux(), func_name, kind);\nkernel/bpf/btf.c-8948-\tif (id \u003e= 0) {\n--\nkernel/bpf/btf.c=9721=bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)\n--\nkernel/bpf/btf.c-9731-\nkernel/bpf/btf.c:9732:\tmain_btf = bpf_get_btf_vmlinux();\nkernel/bpf/btf.c-9733-\tif (IS_ERR(main_btf))\n--\nkernel/bpf/inode.c=661=static int find_bpffs_btf_enums(struct bpffs_btf_enums *info)\n--\nkernel/bpf/inode.c-676-\nkernel/bpf/inode.c:677:\tbtf = bpf_get_btf_vmlinux();\nkernel/bpf/inode.c-678-\tif (IS_ERR(btf))\n--\nkernel/bpf/syscall.c=2917=static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)\n--\nkernel/bpf/syscall.c-3017-\t\t/* fall back to vmlinux BTF, if BTF type ID is specified */\nkernel/bpf/syscall.c:3018:\t\tattach_btf = bpf_get_btf_vmlinux();\nkernel/bpf/syscall.c-3019-\t\tif (IS_ERR(attach_btf)) {\n--\nkernel/bpf/verifier.c=19783=static int do_check_common(struct bpf_verifier_env *env, int subprog)\n--\nkernel/bpf/verifier.c-19878-\t\t\t\tmark_reg_known_zero(env, regs, i);\nkernel/bpf/verifier.c:19879:\t\t\t\treg-\u003ebtf = bpf_get_btf_vmlinux(); /* can't fail at this point */\nkernel/bpf/verifier.c-19880-\t\t\t\treg-\u003ebtf_id = arg-\u003ebtf_id;\n--\nkernel/bpf/verifier.c=20922=int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,\n--\nkernel/bpf/verifier.c-20978-\nkernel/bpf/verifier.c:20979:struct btf *bpf_get_btf_vmlinux(void)\nkernel/bpf/verifier.c-20980-{\n--\nkernel/bpf/verifier.c=21511=int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n--\nkernel/bpf/verifier.c-21572-\nkernel/bpf/verifier.c:21573:\tbpf_get_btf_vmlinux();\nkernel/bpf/verifier.c-21574-\n"
} |
| 23/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 32383 output: 38 thoughts: 17 Thoughts: Okay, let's dive into this `bpf_get_btf_vmlinux` function. As an expert in this, I know this is going to be about retrieving BTF information from the vmlinux image. My initial thought is about the challenges involved. Getting BTF data is absolutely crucial for BPF programs to understand kernel structures and function signatures, which is a key part of how BPF provides its dynamic capabilities. I need to quickly assess how it handles potential errors. What are the fallback mechanisms if BTF isn't available? Is it graceful or does it just fail? I want to pay attention to how it actually accesses the vmlinux image. Is it using the standard debugfs or some other mechanism? This part is crucial for performance. Are they doing some sort of lazy loading or eager parsing? I'm also curious about how it handles different kernel versions. Does this function have logic to adapt to potential changes in the vmlinux format across different kernel releases? If so, is this version checking robust? And does it handle symbols as well, or just BTF? Finally, I need to look at what structures and function calls are being used to actually get this BTF out. Is this going to be an efficient implementation or is this a naive one? Let's get reading! |
| 24/2 | 2026/09/20 10:03 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 20979,
"LineCount": 20
}Results: {
"Contents": "20979:\tstruct btf *bpf_get_btf_vmlinux(void)\n20980:\t{\n20981:\t\t/* Pairs with the smp_store_release() on the parse path below. */\n20982:\t\tstruct btf *btf = smp_load_acquire(\u0026btf_vmlinux);\n20983:\t\n20984:\t\tif (!btf \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {\n20985:\t\t\tmutex_lock(\u0026btf_vmlinux_lock);\n20986:\t\t\tbtf = btf_vmlinux;\n20987:\t\t\tif (!btf) {\n20988:\t\t\t\tbtf = btf_parse_vmlinux();\n20989:\t\t\t\t/*\n20990:\t\t\t\t * Order the parsed BTF contents and the globals the\n20991:\t\t\t\t * parse populated (e.g. bpf_ctx_convert.t) before\n20992:\t\t\t\t * the pointer publication. Pairs with the acquire\n20993:\t\t\t\t * on the lockless fast path above.\n20994:\t\t\t\t */\n20995:\t\t\t\tsmp_store_release(\u0026btf_vmlinux, btf);\n20996:\t\t\t}\n20997:\t\t\tmutex_unlock(\u0026btf_vmlinux_lock);\n20998:\t\t}\n"
} |
| 25/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33083 output: 25 thoughts: 158 Thoughts: **My Analysis of BTF and BPF Dependencies** Alright, let's break this down. First, I see that conditional statement: `if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF))`. Essentially, if `CONFIG_DEBUG_INFO_BTF` is *not* enabled, then the `btf_vmlinux` variable will be null. That's a critical dependency; without BTF information, the kfunc sets can't be registered or populated, which I've seen cause headaches in the past, especially when tracing or instrumenting kernel code. Then, there's the `bpf_memcontrol.o` module. The code explicitly shows that its compilation is gated by both `CONFIG_MEMCG` and `CONFIG_BPF_SYSCALL`, making it another potential bottleneck. Specifically, the line `obj-$(CONFIG_MEMCG) += bpf_memcontrol.o` highlights that its inclusion is directly tied to the MEMCG configuration. So now I need to check the Kconfig file for `MEMCG` to understand how that's configured. I'll head over to `init/Kconfig` for that. |
| 26/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "config MEMCG",
"PathPrefix": "init/"
}Results: {
"Output": "init/Kconfig=1075=config CGROUP_FAVOR_DYNMODS\n--\ninit/Kconfig-1084-\ninit/Kconfig:1085:config MEMCG\ninit/Kconfig-1086-\tbool \"Memory controller\"\n--\ninit/Kconfig-1093-\ninit/Kconfig:1094:config MEMCG_NMI_UNSAFE\ninit/Kconfig-1095-\tbool\n--\ninit/Kconfig-1100-\ninit/Kconfig:1101:config MEMCG_NMI_SAFETY_REQUIRES_ATOMIC\ninit/Kconfig-1102-\tbool\n--\ninit/Kconfig-1107-\ninit/Kconfig:1108:config MEMCG_V1\ninit/Kconfig-1109-\tbool \"Legacy cgroup v1 memory controller\"\n"
} |
| 27/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33747 output: 29 thoughts: 1104 Thoughts: **Analyzing the `bpf_proactive_reclaim` BPF KFunc for Fuzzing Potential** Okay, so I'm looking at this patch and my initial thought is, "Let's dig into this `bpf_proactive_reclaim` function." The diff shows that `CONFIG_MEMCG` is now enabled, which is the cornerstone for this feature, and that this new BPF kfunc is being introduced. Specifically, `mm/bpf_memcontrol.c` has this new `bpf_proactive_reclaim` function, which allows BPF programs, loaded via `BPF_PROG_TYPE_SYSCALL`, to trigger memory reclamation within a memcg. It's essentially a controlled, BPF-driven way to invoke memory pressure. The code itself looks straightforward enough, taking a memcg pointer, a size, and a "swappiness" value, and then calling `try_to_free_mem_cgroup_pages`. This function is then registered for use in the BPF syscall program. They also updated the swappiness enum to make it available to BPF/BTF. Now, from a fuzzing perspective, the first thing I need to do is determine reachability. Is this function accessible? Absolutely! BPF syscall programs can call it. Userspace can load a BPF syscall program, which calls `bpf_proactive_reclaim()` and execute it. Furthermore, Syzkaller, which is perfect for this task, natively supports loading and executing BPF programs and calling kfuncs. This is a clear path to interaction. The fact that BPF and the memory management subsystem are core components just adds to the appeal. Then, is this function worth fuzzing? YES! This is a prime target. Core subsystem logic exposed through BPF, reachable from userspace is like a siren song to any fuzzing expert! Proactive reclaim, as the patch suggests, has the potential for deadlocks, memory reclaim issues, race conditions with cgroup teardown, memory corruption, or even panics if `memcg/try_to_free_mem_cgroup_pages` invariants are violated. The parameters and concurrent cgroup state changes are also of interest. Finally, I need to focus on what to test, as per the triage guidelines. I need to focus on specific logic, and I need to AVOID ubiquitous life-cycle hot paths. I know that `bpf_proactive_reclaim` is the exact new entrypoint and logic added, so that is the function to fuzz. Is it non-static? Looks like it is. `__bpf_kfunc` expands to nothing or `__attribute__...`. |
| 28/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "define __bpf_kfunc",
"PathPrefix": "include/"
}Results: {
"Output": "include/linux/btf.h-89- */\ninclude/linux/btf.h:90:#define __bpf_kfunc __used __retain __noclone noinline\ninclude/linux/btf.h-91-\ninclude/linux/btf.h:92:#define __bpf_kfunc_start_defs()\t\t\t\t\t \\\ninclude/linux/btf.h-93-\t__diag_push();\t\t\t\t\t\t\t \\\n--\ninclude/linux/btf.h-98-\ninclude/linux/btf.h:99:#define __bpf_kfunc_end_defs() __diag_pop()\ninclude/linux/btf.h-100-#define __bpf_hook_start() __bpf_kfunc_start_defs()\n"
} |
| 29/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35648 output: 31 thoughts: 420 Thoughts: **My Analysis of Kernel Symbol Availability and Configuration**
Okay, so I'm looking at this `__bpf_kfunc` and the implications of it being marked `noinline`. This means that `bpf_proactive_reclaim`, the function called by it, is a publicly available symbol within the vmlinux kernel image – it’s not inlined. That's the key takeaway here, but I need to make sure I'm not missing anything else that might have been impacted by the patch. I need to keep an eye on other functions which may have been modified or added.
Specifically, in `bpf_memcontrol.c`, I see `bpf_proactive_reclaim` and `bpf_memcontrol_init`. I see that `bpf_memcontrol_init` is an initcall, specifically a `late_initcall`. This tells me that it’s only executed once, at boot, which further solidifies my focus on `bpf_proactive_reclaim` as the primary symbol of interest.
Now, let's nail down what kernel configurations are *required* for `bpf_proactive_reclaim` to be both compiled into the kernel and functional. I know that `bpf_memcontrol.o` is built if `CONFIG_BPF_SYSCALL` is set, and it is guarded by `ifdef CONFIG_BPF_SYSCALL`, and within `mm/Makefile`. This means that `BPF_SYSCALL` *and* `MEMCG` must be enabled.
The next question is whether `DEBUG_INFO_BTF` is also necessary for kfuncs to work. I’m thinking, let's examine `kernel/bpf/btf.c`. Looking at the code:
```c
btf = btf_get_module_btf(kset->owner);
if (!btf)
return check_btf_kconfigs(kset->owner, "kfunc");
```
I can see that `btf_get_module_btf(NULL)` eventually calls `bpf_get_btf_vmlinux()`. The latter function *only* returns a BTF (Berkeley Type Format) if `CONFIG_DEBUG_INFO_BTF` is enabled. If `CONFIG_DEBUG_INFO_BTF` is *not* enabled, then `btf_get_module_btf` returns NULL. This means that if it's not set, then the code will fall through to `check_btf_kconfigs(NULL, "kfunc")`. I need to figure out what `check_btf_kconfigs` does.
|
| 30/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "check_btf_kconfigs",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/btf.c=8759=struct btf *btf_get_module_btf(const struct module *module)\n--\nkernel/bpf/btf.c-8788-\nkernel/bpf/btf.c:8789:static int check_btf_kconfigs(const struct module *module, const char *feature)\nkernel/bpf/btf.c-8790-{\n--\nkernel/bpf/btf.c=9282=static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,\n--\nkernel/bpf/btf.c-9289-\tif (!btf)\nkernel/bpf/btf.c:9290:\t\treturn check_btf_kconfigs(kset-\u003eowner, \"kfunc\");\nkernel/bpf/btf.c-9291-\tif (IS_ERR(btf))\n--\nkernel/bpf/btf.c=9396=int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,\n--\nkernel/bpf/btf.c-9405-\tif (!btf)\nkernel/bpf/btf.c:9406:\t\treturn check_btf_kconfigs(owner, \"dtor kfuncs\");\nkernel/bpf/btf.c-9407-\tif (IS_ERR(btf))\n--\nkernel/bpf/btf.c=10076=int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n--\nkernel/bpf/btf.c-10083-\tif (!btf)\nkernel/bpf/btf.c:10084:\t\treturn check_btf_kconfigs(st_ops-\u003eowner, \"struct_ops\");\nkernel/bpf/btf.c-10085-\tif (IS_ERR(btf))\n"
} |
| 31/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37193 output: 38 thoughts: 13 Thoughts: Okay, let's dive into this. Here's my take on those thoughts, as if they're my own: **Initial Assessment: Diving into `check_btf_kconfigs`** Alright, time to get to work. Let's see... the task is `check_btf_kconfigs`. Okay, I know what BTF is – it's crucial for debugging and introspection in the kernel, and Kconfigs are the source of truth for kernel configuration. Given my expertise, I'm already forming an internal map of what this function *probably* does. I'm imagining it's designed to validate the build and availability of BTF information based on the configured kernel options. It's likely checking for dependencies, ensuring the necessary modules or settings are enabled to generate or access BTF data. I'm expecting to find conditional logic, probably using the Kconfig options to determine which checks to perform and where to find the related files or data. Let's dig in and see if my assumptions hold. |
| 32/2 | 2026/09/20 10:03 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 8788,
"LineCount": 15
}Results: {
"Contents": "8788:\t\n8789:\tstatic int check_btf_kconfigs(const struct module *module, const char *feature)\n8790:\t{\n8791:\t\tif (!module \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {\n8792:\t\t\tpr_err(\"missing vmlinux BTF, cannot register %s\\n\", feature);\n8793:\t\t\treturn -ENOENT;\n8794:\t\t}\n8795:\t\tif (module \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))\n8796:\t\t\tpr_warn(\"missing module BTF, cannot register %s\\n\", feature);\n8797:\t\treturn 0;\n8798:\t}\n8799:\t\n8800:\tBPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)\n8801:\t{\n8802:\t\tstruct btf *btf = NULL;\n"
} |
| 33/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37738 output: 27 thoughts: 163 Thoughts: **My Analysis of BTF and Kfunc Resolution** Okay, so here's the situation I'm seeing: if `CONFIG_DEBUG_INFO_BTF` isn't enabled, the `check_btf_kconfigs` function returns 0, which seems fine on the surface. However, and this is the critical point, the *kfunc* itself isn't ever registered in any BTF set! The `btf` pointer is null, so the registration process aborts. That's a huge problem. The BPF verifier is only capable of resolving and using these kfuncs if BTF information is present *and* the kfunc is actually included in that registered kfunc set. So, without `CONFIG_DEBUG_INFO_BTF`, it's essentially a dead end. BPF programs won't be able to properly resolve and actually *call* the kfuncs. Therefore, I'm confident that `CONFIG_DEBUG_INFO_BTF` is an absolute requirement for the proper resolution and execution of BPF kfuncs. Alright, let me shift gears and check on `CONFIG_MEMCG`. Looking at `init/Kconfig` now, the definition reads: `config MEMCG`, and it `depends on CGROUPS`. I should take a moment and also look at other dependencies within `init/Kconfig`. |
| 34/2 | 2026/09/20 10:03 | tool | grepper |
0mArgs:{
"Expression": "config MEMCG",
"PathPrefix": "init/Kconfig"
}Results: {
"Output": "init/Kconfig=1075=config CGROUP_FAVOR_DYNMODS\n--\ninit/Kconfig-1084-\ninit/Kconfig:1085:config MEMCG\ninit/Kconfig-1086-\tbool \"Memory controller\"\n--\ninit/Kconfig-1093-\ninit/Kconfig:1094:config MEMCG_NMI_UNSAFE\ninit/Kconfig-1095-\tbool\n--\ninit/Kconfig-1100-\ninit/Kconfig:1101:config MEMCG_NMI_SAFETY_REQUIRES_ATOMIC\ninit/Kconfig-1102-\tbool\n--\ninit/Kconfig-1107-\ninit/Kconfig:1108:config MEMCG_V1\ninit/Kconfig-1109-\tbool \"Legacy cgroup v1 memory controller\"\n"
} |
| 35/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38443 output: 33 thoughts: 22 Thoughts: Here's a summary of my thought process, as if I were reading those lines of `init/Kconfig`: **Analyzing Kconfig: The Crucial `initramfs` Configuration** Okay, let's zero in on lines 1084-1092 of `init/Kconfig`. This is where the magic happens for `initramfs`, a vital component for early boot and system initialization in the Linux kernel. I'm already anticipating some critical configuration options here. I expect to see the core controls for building and selecting the initramfs, probably including whether to build it statically or dynamically. I'm also betting there'll be choices for the method, or the underlying technology used, for loading it into memory. It’s important to see how the code is structured in the Kconfig file because it dictates how these options appear to the user. I'm also looking for any dependencies or interrelationships with other boot options. Any potential conflicts are of immediate interest. This section is key for anyone trying to customize the early boot process, so I need to understand it thoroughly. |
| 36/2 | 2026/09/20 10:03 | tool | read-file |
0mArgs:{
"File": "init/Kconfig",
"FirstLine": 1084,
"LineCount": 10
}Results: {
"Contents": "1084:\t\n1085:\tconfig MEMCG\n1086:\t\tbool \"Memory controller\"\n1087:\t\tselect PAGE_COUNTER\n1088:\t\tselect EVENTFD\n1089:\t\tselect SLAB_OBJ_EXT\n1090:\t\tselect VM_EVENT_COUNTERS\n1091:\t\thelp\n1092:\t\t Provides control over the memory footprint of tasks in a cgroup.\n1093:\t\n"
} |
| 37/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38855 output: 33 thoughts: 33 Thoughts: Here's my take on the thought process: **Diving into the Kernel Configuration for CGROUPS** Okay, so I have a hunch this functionality I'm trying to enable is tied into the `CGROUPS` configuration. Makes sense; they're often the go-to for resource management and isolation. Let's dig in. I'm going to quickly check lines 1050 to 1085 of the `init/Kconfig` file. That's usually where the core feature configurations reside, and if `CGROUPS` is the key, this should be the area to inspect for its dependencies and options. Hopefully, the relevant config option, and how it is enabled, is obvious once I see the section. Let's see what's there... |
| 38/2 | 2026/09/20 10:03 | tool | read-file |
0mArgs:{
"File": "init/Kconfig",
"FirstLine": 1050,
"LineCount": 35
}Results: {
"Contents": "1050:\t\t If set, automatic NUMA balancing will be enabled if running on a NUMA\n1051:\t\t machine.\n1052:\t\n1053:\tconfig SLAB_OBJ_EXT\n1054:\t\tbool\n1055:\t\n1056:\tmenuconfig CGROUPS\n1057:\t\tbool \"Control Group support\"\n1058:\t\tselect KERNFS\n1059:\t\thelp\n1060:\t\t This option adds support for grouping sets of processes together, for\n1061:\t\t use with process control subsystems such as Cpusets, CFS, memory\n1062:\t\t controls or device isolation.\n1063:\t\t See\n1064:\t\t\t- Documentation/scheduler/sched-design-CFS.rst\t(CFS)\n1065:\t\t\t- Documentation/admin-guide/cgroup-v1/ (features for grouping, isolation\n1066:\t\t\t\t\t\t and resource control)\n1067:\t\n1068:\t\t Say N if unsure.\n1069:\t\n1070:\tif CGROUPS\n1071:\t\n1072:\tconfig PAGE_COUNTER\n1073:\t\tbool\n1074:\t\n1075:\tconfig CGROUP_FAVOR_DYNMODS\n1076:\t\tbool \"Favor dynamic modification latency reduction by default\"\n1077:\t\thelp\n1078:\t\t This option enables the \"favordynmods\" mount option by default\n1079:\t\t which reduces the latencies of dynamic cgroup modifications such\n1080:\t\t as task migrations and controller on/offs at the cost of making\n1081:\t\t hot path operations such as forks and exits more expensive.\n1082:\t\n1083:\t\t Say N if unsure.\n1084:\t\n"
} |
| 39/2 | 2026/09/20 10:03 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39566 output: 29 thoughts: 119 Thoughts: **My Configuration Investigation** Alright, so the task at hand is definitely related to `CGROUPS`. I remember that's the place to start within `menuconfig`. So, I'm thinking, specifically, `CGROUPS`, `MEMCG`, `BPF_SYSCALL`, and `DEBUG_INFO_BTF` will be my primary targets. I need to confirm if there are any other crucial configurations intertwined with `BPF_SYSCALL`. Let's dig into `init/Kconfig` to see what we find there. Ah, here it is: `config BPF_SYSCALL`, with the description "Enable bpf() system call". It has a `select BPF` and, likely, a `depends on BPF` (or something similar). Now, to make absolutely sure, let's take a look at `kernel/bpf/Kconfig`. I'll want to get a broader understanding of dependencies and options within that area. This seems like a reasonable and methodical way to approach this. |
| 40/2 | 2026/09/20 10:04 | tool | grepper |
0mError:no matches Args: {
"Expression": "config BPF_SYSCALL",
"PathPrefix": "init/"
}Results: {
"error": "no matches"
} |
| 41/2 | 2026/09/20 10:04 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39949 output: 29 thoughts: 19 Thoughts: Here's my thought process, as if I were considering this query: **Finding the BPF_SYSCALL Configuration** Okay, I need to track down how `CONFIG_BPF_SYSCALL` is defined across the entire kernel's Kconfig structure. It's a critical piece for understanding the BPF subsystem, so I want a comprehensive view. My approach is to start with a broad search. I'll need to hit every Kconfig file to be certain I have a complete picture. This probably means a `grep` or similar command will be the fastest way. Now, I need to formulate the right search terms to catch all the possibilities, taking into account potential variations in syntax. I'll make sure to get all instances of `config BPF_SYSCALL` and see what comes back. Then I'll filter out anything uninteresting. I expect to find dependencies, default values, and maybe some conditional logic. I'm hoping this will illuminate its intended purpose and integration within the broader kernel configuration. |
| 42/2 | 2026/09/20 10:04 | tool | grepper |
0mArgs:{
"Expression": "config BPF_SYSCALL",
"PathPrefix": "kernel/"
}Results: {
"Output": "kernel/bpf/Kconfig=29=menu \"BPF subsystem\"\nkernel/bpf/Kconfig-30-\nkernel/bpf/Kconfig:31:config BPF_SYSCALL\nkernel/bpf/Kconfig-32-\tbool \"Enable bpf() system call\"\n"
} |
| 43/2 | 2026/09/20 10:04 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 40296 output: 34 thoughts: 19 Thoughts: Here's my summary, as though I'm reading and thinking about the Kconfig file: **Navigating the BPF Kernel Configuration** Okay, let's dive into this `kernel/bpf/Kconfig` file. I'm focusing around line 31 – that's usually where the meat of the initial BPF configuration options tend to reside. I'm expecting to see the core enablement flag – the master switch, if you will, that activates BPF functionality within the kernel. I'll be looking for the dependencies, the necessary prerequisites, and perhaps the default setting. It's important to understand the hierarchy and how these options relate to each other. This part is critical for understanding the baseline BPF configuration. This Kconfig file will be the key to understanding how the feature is toggled. |
| 44/2 | 2026/09/20 10:04 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/Kconfig",
"FirstLine": 29,
"LineCount": 25
}Results: {
"Contents": " 29:\tmenu \"BPF subsystem\"\n 30:\t\n 31:\tconfig BPF_SYSCALL\n 32:\t\tbool \"Enable bpf() system call\"\n 33:\t\tselect BPF\n 34:\t\tselect IRQ_WORK\n 35:\t\tselect NEED_TASKS_RCU\n 36:\t\tselect TASKS_TRACE_RCU\n 37:\t\tselect BINARY_PRINTF\n 38:\t\tselect NET_SOCK_MSG if NET\n 39:\t\tselect NET_XGRESS if NET\n 40:\t\tselect PAGE_POOL if NET\n 41:\t\tdefault n\n 42:\t\thelp\n 43:\t\t Enable the bpf() system call that allows to manipulate BPF programs\n 44:\t\t and maps via file descriptors.\n 45:\t\n 46:\tconfig BPF_JIT\n 47:\t\tbool \"Enable BPF Just In Time compiler\"\n 48:\t\tdepends on BPF\n 49:\t\tdepends on HAVE_CBPF_JIT || HAVE_EBPF_JIT\n 50:\t\tselect EXECMEM\n 51:\t\thelp\n 52:\t\t BPF programs are normally handled by a BPF interpreter. This option\n 53:\t\t allows the kernel to generate native code when a program is loaded\n"
} |
| 45/2 | 2026/09/20 10:04 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 40853 output: 160 thoughts: 377 Thoughts: **My Assessment of the Patch's Impact** Okay, so I've just gone over this patch and my initial thought process is focusing on a few key elements: `BPF_SYSCALL`, `MEMCG`, and `DEBUG_INFO_BTF`. I need to ensure a comprehensive understanding before I approve this. First, I need to verify that this patch introduces new executable code. Yes, I see that `bpf_proactive_reclaim` is being added to `mm/bpf_memcontrol.c`. Importantly, it's being registered as a sleepable kfunc specifically for `BPF_PROG_TYPE_SYSCALL`, which is notable. Next, I need to determine if syzkaller can reach it. Given the prevalence of syzkaller in testing BPF syscalls, I'm confident that loading BPF syscall programs and invoking them, either directly or through kfunc testing, will be able to hit this functionality. Now for the critical bit: Does this touch core subsystems? Absolutely. It directly impacts both the memory management subsystem (`mm`) and the BPF subsystem. This connection needs scrutiny. Looking closer, `bpf_proactive_reclaim` is the exact new kfunc added. It's also non-static and `noinline` (via `__bpf_kfunc`), which I should note. The necessary configurations, `MEMCG`, `BPF_SYSCALL`, and `DEBUG_INFO_BTF`, are all present, which is great. Essentially, this patch introduces a new sleepable BPF kfunc, `bpf_proactive_reclaim()`, within `mm/bpf_memcontrol.c`. It's designed for `BPF_PROG_TYPE_SYSCALL` programs, allowing BPF programs to trigger proactive memory reclaim on a memory cgroup. The critical takeaway is that this establishes a direct connection between BPF syscall programs and the core memory management reclaim subsystem through `try_to_free_mem_cgroup_pages()`. This is user-space reachable. Therefore, I need to make sure this is tested thoroughly for reclaim behavior, potential deadlocks, and any invariant violations. With all of this assessed, everything seems clear. Let's call `set-results`. |
| 46/2 | 2026/09/20 10:04 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"MEMCG",
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_proactive_reclaim"
],
"Reasoning": "The patch introduces a new sleepable BPF kfunc, bpf_proactive_reclaim(), which allows BPF programs of type BPF_PROG_TYPE_SYSCALL to trigger proactive memory reclamation on a specified memory cgroup via try_to_free_mem_cgroup_pages(). This modifies reachable core kernel code bridging BPF and the memory management reclaim subsystem, making it worth fuzzing for potential deadlocks, race conditions, or invariant violations.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"MEMCG",
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_proactive_reclaim"
],
"Reasoning": "The patch introduces a new sleepable BPF kfunc, bpf_proactive_reclaim(), which allows BPF programs of type BPF_PROG_TYPE_SYSCALL to trigger proactive memory reclamation on a specified memory cgroup via try_to_free_mem_cgroup_pages(). This modifies reachable core kernel code bridging BPF and the memory management reclaim subsystem, making it worth fuzzing for potential deadlocks, race conditions, or invariant violations.",
"WorthFuzzing": true
} |
| 47/1 | 2026/09/20 10:04 | action | If |
0mArgs:{
"WorthFuzzing": true
}Results: null |
| 48/2 | 2026/09/20 10:04 | agent | kmsan-evaluator |
0mModel:core Args: null Results: {
"KMSANReasoning": "The patch introduces a new BPF kfunc, `bpf_proactive_reclaim()`, in `mm/bpf_memcontrol.c` registered for `BPF_PROG_TYPE_SYSCALL`, and exports swappiness constants as an enum in `mm/internal.h`.\n\nKMSAN is not applicable for the following reasons:\n1. No uninitialized memory or info-leak risks: The kfunc operates entirely on scalar arguments (`size`, `swappiness`) and a verified `struct mem_cgroup` pointer, returning a scalar `long` value representing reclaimed bytes. No kernel structures or buffers are copied to userspace via `copy_to_user`, ioctl, netlink, or BPF buffers.\n2. All local variables (`nr_pages`, `nr_reclaimed`) and parameters are explicitly initialized before use. The pointer passed to `try_to_free_mem_cgroup_pages` (`swappiness == -1 ? NULL : \u0026swappiness`) references the function argument passed by value, which is fully initialized.\n3. No complex data structures are allocated or partially initialized.\n\nAny risks associated with this change relate to memory reclaim concurrency, invalid memcg pointer dereferences, or locking/deadlocks in sleepable context, all of which are caught by KASAN and LOCKDEP in standard debugging builds. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 7f5fe58e78a00d7fe8315e8a4dae89d0a33c5a20
Author: syz-cluster <triage@syzkaller.com>
Date: Sun Sep 20 10:02:46 2026 +0000
syz-cluster: applied patch under review
diff --git a/mm/bpf_memcontrol.c b/mm/bpf_memcontrol.c
index 716df49d76477..c5d7f29ade858 100644
--- a/mm/bpf_memcontrol.c
+++ b/mm/bpf_memcontrol.c
@@ -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;
}
diff --git a/mm/internal.h b/mm/internal.h
index 38b1165212c94..44e95e87e3cd9 100644
--- a/mm/internal.h
+++ b/mm/internal.h
@@ -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,
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2f79688dcf7ce..1edaa752facb2 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -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
diff --git a/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c b/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
new file mode 100644
index 0000000000000..179b64fb6de84
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c
@@ -0,0 +1,890 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Memory controller eBPF async reclaim test
+ *
+ * Setting TEST_MEMCG_ASYNC_RECLAIM_BENCH=1 adds a baseline run of the
+ * workload without the BPF program to memcg_async_reclaim, and prints
+ * the baseline and reclaim timings, plus the speedup of the pressured
+ * cgroup, to stdout. The cgroups are recreated between the two runs so
+ * that both start from the same cold state.
+ */
+
+#include <test_progs.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/vfs.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <time.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <linux/magic.h>
+
+#include "cgroup_helpers.h"
+
+struct bpf_args {
+ u64 high_cgroup_id;
+ u64 low_cgroup_id;
+ u64 event_delta_threshold;
+ u64 check_ns;
+};
+
+/* Reclaim outcomes reported by the BPF program through the ringbuf. */
+enum reclaim_outcome {
+ RECLAIM_OUTCOME_CALLED,
+ RECLAIM_OUTCOME_SKIPPED_DYING,
+ RECLAIM_OUTCOME_TARGET_GONE,
+};
+
+struct reclaim_event {
+ u64 outcome;
+};
+
+#include "memcg_async_reclaim.skel.h"
+
+#define FILE_SIZE (32 * 1024 * 1024ul)
+#define BUFFER_SIZE (4096)
+#define CG_LIMIT (32 * 1024 * 1024ul)
+#define READ_TIMES 50
+
+#define CG_DIR "/memcg_async_reclaim"
+#define CG_HIGH_DIR CG_DIR "/high"
+#define CG_LOW_DIR CG_DIR "/low"
+
+#define CG_DYING_DIR "/memcg_async_reclaim_dying"
+#define CG_DYING_TRIGGER_DIR CG_DYING_DIR "/trigger"
+#define CG_DYING_TARGET_DIR CG_DYING_DIR "/target"
+
+#define CHECK_PERIOD_NS (2 * 1000 * 1000ull)
+#define EVENT_DELTA_THRESHOLD 1
+
+/*
+ * Timing for the dying test: after the target cgroup is removed, give
+ * in-flight reclaim passes time to drain, then wait for a reclaim round
+ * to hit the removed target. The keepalive reader keeps the trigger
+ * cgroup refaulting, and the timer fires every CHECK_PERIOD_NS, so
+ * such a round must show up within a few timer periods. The BPF
+ * program reports every reclaim outcome through the ringbuf, so the
+ * waits just poll it with a timeout.
+ */
+#define DYING_SETTLE_US (200 * 1000)
+#define EVENT_POLL_TIMEOUT_MS (100)
+#define EVENT_POLL_ROUNDS (50)
+
+static bool usable_for_workload_files(const char *dir)
+{
+ struct statfs st;
+
+ if (statfs(dir, &st))
+ return false;
+
+ return st.f_type != TMPFS_MAGIC && st.f_type != RAMFS_MAGIC;
+}
+
+/*
+ * The workload files must sit on a regular filesystem: with swap
+ * disabled for the cgroup, tmpfs/ramfs pages are unevictable and would
+ * OOM the cgroup instead of exercising reclaim; they are also charged
+ * as anonymous memory, so they never raise the WORKINGSET_REFAULT_FILE
+ * events the BPF program monitors.
+ *
+ * /tmp is tmpfs on many systems, so fall back to the current directory.
+ * That fallback needs the very same check: test_progs is routinely run
+ * from a tmpfs working directory, and silently landing there produces an
+ * OOM that looks like a reclaim failure. Returns NULL when neither
+ * directory is usable, in which case the workload cannot run at all.
+ */
+static const char *workload_files_dir(void)
+{
+ if (usable_for_workload_files("/tmp"))
+ return "/tmp";
+ if (usable_for_workload_files("."))
+ return ".";
+
+ return NULL;
+}
+
+/*
+ * Keep the workload from swapping out, so that reclaim has to evict page
+ * cache instead. memory.swap.max only exists when the kernel is built with
+ * CONFIG_SWAP, and /proc/swaps is registered by the same CONFIG_SWAP-gated
+ * code (mm/swapfile.c), so it stands in for the file here. With CONFIG_SWAP=n
+ * no swap can happen anyway, so skipping the write is the correct behaviour.
+ */
+static int disable_swap(const char *cgroup_dir)
+{
+ if (access("/proc/swaps", F_OK))
+ return 0;
+
+ return write_cgroup_file(cgroup_dir, "memory.swap.max", "0");
+}
+
+/*
+ * The forked children run after test_progs hijacked stdio, so anything
+ * they print is lost with their private copy of the hijacked buffer
+ * unless the test runs under -v. The exit status is the one diagnostics
+ * channel that always reaches the parent, so each failing step gets its
+ * own code.
+ */
+enum child_exit_code {
+ CHILD_EXIT_OK = 0,
+ CHILD_EXIT_JOIN_CGROUP,
+ CHILD_EXIT_WRITE_FILE,
+ CHILD_EXIT_READ_FILE,
+ CHILD_EXIT_TIME_FILE,
+};
+
+static const char *child_exit_str(int code)
+{
+ switch (code) {
+ case CHILD_EXIT_OK:
+ return "success";
+ case CHILD_EXIT_JOIN_CGROUP:
+ return "join cgroup";
+ case CHILD_EXIT_WRITE_FILE:
+ return "write data file";
+ case CHILD_EXIT_READ_FILE:
+ return "read data file";
+ case CHILD_EXIT_TIME_FILE:
+ return "write time file";
+ default:
+ return "unknown";
+ }
+}
+
+static int setup_high_low_cgroups(u64 *high_cgroup_id, u64 *low_cgroup_id)
+{
+ int ret;
+ char limit_buf[20];
+
+ ret = setup_cgroup_environment();
+ if (!ASSERT_OK(ret, "setup_cgroup_environment"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DIR))
+ goto cleanup;
+ close(ret);
+
+ ret = enable_controllers(CG_DIR, "memory");
+ if (!ASSERT_OK(ret, "enable_controllers"))
+ goto cleanup;
+
+ snprintf(limit_buf, sizeof(limit_buf), "%lu", CG_LIMIT);
+ ret = write_cgroup_file(CG_DIR, "memory.max", limit_buf);
+ if (!ASSERT_OK(ret, "write_cgroup_file memory.max"))
+ goto cleanup;
+
+ ret = disable_swap(CG_DIR);
+ if (!ASSERT_OK(ret, "disable_swap"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_HIGH_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_HIGH_DIR))
+ goto cleanup;
+ close(ret);
+
+ *high_cgroup_id = get_cgroup_id(CG_HIGH_DIR);
+ if (!ASSERT_GT(*high_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_LOW_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_LOW_DIR))
+ goto cleanup;
+ close(ret);
+
+ *low_cgroup_id = get_cgroup_id(CG_LOW_DIR);
+ if (!ASSERT_GT(*low_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ return 0;
+
+cleanup:
+ cleanup_cgroup_environment();
+ return -1;
+}
+
+/*
+ * The dying test needs an empty reclaim target plus a cgroup that keeps
+ * refaulting while the target is removed, so reclaim rounds keep
+ * starting and run into the removed target. The two have to be separate
+ * cgroups: the target must hold no processes to be removed, and v2's
+ * no-internal-process constraint keeps the refaulting workload out of
+ * any parent that has domain children.
+ */
+static int setup_dying_cgroups(u64 *trigger_cgroup_id, u64 *target_cgroup_id)
+{
+ int ret;
+ char limit_buf[20];
+
+ ret = setup_cgroup_environment();
+ if (!ASSERT_OK(ret, "setup_cgroup_environment"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DYING_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DYING_DIR))
+ goto cleanup;
+ close(ret);
+
+ ret = enable_controllers(CG_DYING_DIR, "memory");
+ if (!ASSERT_OK(ret, "enable_controllers"))
+ goto cleanup;
+
+ snprintf(limit_buf, sizeof(limit_buf), "%lu", CG_LIMIT);
+ ret = write_cgroup_file(CG_DYING_DIR, "memory.max", limit_buf);
+ if (!ASSERT_OK(ret, "write_cgroup_file memory.max"))
+ goto cleanup;
+
+ ret = disable_swap(CG_DYING_DIR);
+ if (!ASSERT_OK(ret, "disable_swap"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DYING_TRIGGER_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DYING_TRIGGER_DIR))
+ goto cleanup;
+ close(ret);
+
+ *trigger_cgroup_id = get_cgroup_id(CG_DYING_TRIGGER_DIR);
+ if (!ASSERT_GT(*trigger_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ ret = create_and_get_cgroup(CG_DYING_TARGET_DIR);
+ if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DYING_TARGET_DIR))
+ goto cleanup;
+ close(ret);
+
+ *target_cgroup_id = get_cgroup_id(CG_DYING_TARGET_DIR);
+ if (!ASSERT_GT(*target_cgroup_id, 0, "get_cgroup_id"))
+ goto cleanup;
+
+ return 0;
+
+cleanup:
+ cleanup_cgroup_environment();
+ return -1;
+}
+
+static int write_file(int fd)
+{
+ int ret = -1;
+ size_t written = 0;
+ char *buffer;
+
+ buffer = malloc(BUFFER_SIZE);
+ if (!buffer)
+ goto out;
+
+ memset(buffer, 'A', BUFFER_SIZE);
+
+ while (written < FILE_SIZE) {
+ size_t to_write = FILE_SIZE - written < BUFFER_SIZE ?
+ FILE_SIZE - written : BUFFER_SIZE;
+ ssize_t n = write(fd, buffer, to_write);
+
+ if (n <= 0)
+ goto cleanup;
+ written += n;
+ }
+
+ ret = 0;
+cleanup:
+ free(buffer);
+out:
+ return ret;
+}
+
+static int read_file(int fd, int iterations)
+{
+ long page_size = sysconf(_SC_PAGESIZE);
+ struct stat sb;
+ char *map;
+ size_t i;
+
+ if (fstat(fd, &sb) == -1)
+ return -1;
+
+ if (sb.st_size != FILE_SIZE) {
+ fprintf(stderr, "File size mismatch: expected %lu, got %lu\n",
+ (unsigned long)FILE_SIZE, (unsigned long)sb.st_size);
+ return -1;
+ }
+
+ map = mmap(NULL, FILE_SIZE, PROT_READ, MAP_PRIVATE, fd, 0);
+ if (map == MAP_FAILED)
+ return -1;
+
+ for (int iter = 0; iter < iterations; iter++) {
+ for (i = 0; i < FILE_SIZE; i += page_size) {
+ /* access a byte to trigger page fault */
+ volatile char v = map[i];
+ (void)v;
+ }
+ }
+
+ if (munmap(map, FILE_SIZE) == -1)
+ return -1;
+
+ return 0;
+}
+
+static int real_test_child_work(const char *cgroup_path, int data_fd,
+ int time_fd, int read_times)
+{
+ struct timespec start, end;
+ double elapsed;
+ char buf[32];
+ int len;
+
+ if (join_parent_cgroup(cgroup_path))
+ return CHILD_EXIT_JOIN_CGROUP;
+
+ clock_gettime(CLOCK_MONOTONIC, &start);
+
+ if (write_file(data_fd))
+ return CHILD_EXIT_WRITE_FILE;
+
+ if (read_file(data_fd, read_times))
+ return CHILD_EXIT_READ_FILE;
+
+ clock_gettime(CLOCK_MONOTONIC, &end);
+
+ elapsed = (end.tv_sec - start.tv_sec) +
+ (end.tv_nsec - start.tv_nsec) / 1000000000.0;
+
+ len = snprintf(buf, sizeof(buf), "%.6f", elapsed);
+ /* snprintf() returns the untruncated length, so bound it before write() */
+ if (len < 0 || len >= (int)sizeof(buf) || write(time_fd, buf, len) != len)
+ return CHILD_EXIT_TIME_FILE;
+
+ return CHILD_EXIT_OK;
+}
+
+static int get_time(int fd, double *time)
+{
+ char buf[64] = {};
+ ssize_t n;
+
+ /* The child wrote through the fork-shared description, so rewind. */
+ if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
+ PRINT_FAIL("lseek time file");
+ return -1;
+ }
+
+ n = read(fd, buf, sizeof(buf) - 1);
+ if (!ASSERT_GT(n, 0, "read time file"))
+ return -1;
+
+ if (sscanf(buf, "%lf", time) != 1) {
+ PRINT_FAIL("sscanf %s", buf);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int
+run_high_low_workload(const char *dir, double *high_elapsed, double *low_elapsed,
+ int read_times)
+{
+ char high_data_file[PATH_MAX];
+ char low_data_file[PATH_MAX];
+ char high_time_file[PATH_MAX];
+ char low_time_file[PATH_MAX];
+ int high_data_fd = -1, low_data_fd = -1;
+ int high_time_fd = -1, low_time_fd = -1;
+ pid_t high_pid = -1, low_pid = -1;
+ pid_t wait_ret;
+ int status;
+ int ret = -1;
+
+ snprintf(high_data_file, sizeof(high_data_file),
+ "%s/memcg_async_high_data_XXXXXX", dir);
+ snprintf(low_data_file, sizeof(low_data_file),
+ "%s/memcg_async_low_data_XXXXXX", dir);
+ snprintf(high_time_file, sizeof(high_time_file),
+ "%s/memcg_async_high_time_XXXXXX", dir);
+ snprintf(low_time_file, sizeof(low_time_file),
+ "%s/memcg_async_low_time_XXXXXX", dir);
+
+ /*
+ * The mkstemp() fds are kept and inherited by the children rather
+ * than reopened by name: reopening would resolve the path again and
+ * follow whatever sits there by then.
+ */
+ high_data_fd = mkstemp(high_data_file);
+ if (!ASSERT_GE(high_data_fd, 0, "mkstemp high data"))
+ goto cleanup;
+
+ low_data_fd = mkstemp(low_data_file);
+ if (!ASSERT_GE(low_data_fd, 0, "mkstemp low data"))
+ goto cleanup;
+
+ high_time_fd = mkstemp(high_time_file);
+ if (!ASSERT_GE(high_time_fd, 0, "mkstemp high time"))
+ goto cleanup;
+
+ low_time_fd = mkstemp(low_time_file);
+ if (!ASSERT_GE(low_time_fd, 0, "mkstemp low time"))
+ goto cleanup;
+
+ low_pid = fork();
+ if (!ASSERT_GE(low_pid, 0, "fork low"))
+ goto cleanup;
+ if (low_pid == 0)
+ _exit(real_test_child_work(CG_LOW_DIR, low_data_fd,
+ low_time_fd, read_times));
+
+ high_pid = fork();
+ if (!ASSERT_GE(high_pid, 0, "fork high"))
+ goto cleanup;
+ if (high_pid == 0)
+ _exit(real_test_child_work(CG_HIGH_DIR, high_data_fd,
+ high_time_fd, read_times));
+
+ wait_ret = waitpid(low_pid, &status, 0);
+ if (!ASSERT_GT(wait_ret, 0, "low waitpid"))
+ goto cleanup;
+ /*
+ * The child has been reaped and its PID can already be reused,
+ * so mark it to keep cleanup from signaling an unrelated process.
+ */
+ low_pid = -1;
+ if (!ASSERT_TRUE(WIFEXITED(status), "low exited"))
+ goto cleanup;
+ if (WEXITSTATUS(status) != CHILD_EXIT_OK) {
+ PRINT_FAIL("low child failed at: %s (exit status %d)",
+ child_exit_str(WEXITSTATUS(status)),
+ WEXITSTATUS(status));
+ goto cleanup;
+ }
+
+ wait_ret = waitpid(high_pid, &status, 0);
+ if (!ASSERT_GT(wait_ret, 0, "high waitpid"))
+ goto cleanup;
+ /* Same as above: the reaped PID must not be signaled again. */
+ high_pid = -1;
+ if (!ASSERT_TRUE(WIFEXITED(status), "high exited"))
+ goto cleanup;
+ if (WEXITSTATUS(status) != CHILD_EXIT_OK) {
+ PRINT_FAIL("high child failed at: %s (exit status %d)",
+ child_exit_str(WEXITSTATUS(status)),
+ WEXITSTATUS(status));
+ goto cleanup;
+ }
+
+ if (get_time(high_time_fd, high_elapsed))
+ goto cleanup;
+ if (get_time(low_time_fd, low_elapsed))
+ goto cleanup;
+
+ ret = 0;
+
+cleanup:
+ /* On failure, make sure no child process is left behind */
+ if (ret) {
+ if (high_pid > 0) {
+ kill(high_pid, SIGKILL);
+ (void)waitpid(high_pid, NULL, 0);
+ }
+ if (low_pid > 0) {
+ kill(low_pid, SIGKILL);
+ (void)waitpid(low_pid, NULL, 0);
+ }
+ }
+ if (high_data_fd >= 0)
+ close(high_data_fd);
+ if (low_data_fd >= 0)
+ close(low_data_fd);
+ if (high_time_fd >= 0)
+ close(high_time_fd);
+ if (low_time_fd >= 0)
+ close(low_time_fd);
+ unlink(low_time_file);
+ unlink(high_time_file);
+ unlink(low_data_file);
+ unlink(high_data_file);
+ return ret;
+}
+
+static int
+setup_bpf(u64 high_cgroup_id, u64 low_cgroup_id,
+ struct memcg_async_reclaim **skel_ptr)
+{
+ struct memcg_async_reclaim *skel;
+ struct bpf_args args = {
+ .high_cgroup_id = high_cgroup_id,
+ .low_cgroup_id = low_cgroup_id,
+ .event_delta_threshold = EVENT_DELTA_THRESHOLD,
+ .check_ns = CHECK_PERIOD_NS,
+ };
+ LIBBPF_OPTS(bpf_test_run_opts, run_opts,
+ .ctx_in = &args,
+ .ctx_size_in = sizeof(args));
+ int prog_init_fd, err;
+
+ skel = memcg_async_reclaim__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "memcg_async_reclaim__open_and_load"))
+ return -1;
+
+ prog_init_fd = bpf_program__fd(skel->progs.wq_prog_init);
+
+ err = bpf_prog_test_run_opts(prog_init_fd, &run_opts);
+ if (!ASSERT_OK(err, "bpf_prog_test_run_opts"))
+ goto error_out;
+ if (!ASSERT_EQ(run_opts.retval, 0, "prog_init retval"))
+ goto error_out;
+
+ *skel_ptr = skel;
+ return 0;
+
+error_out:
+ memcg_async_reclaim__destroy(skel);
+ return -1;
+}
+
+/*
+ * A timer that stopped rearming produces no further reclaim rounds, which
+ * the "no events" failures below would otherwise report as a kernel bug.
+ * Only call this on a path that is already failing.
+ */
+static void report_timer_failures(struct memcg_async_reclaim *skel)
+{
+ u64 failures = skel->bss->timer_failures;
+
+ if (failures)
+ PRINT_FAIL("bpf_timer failed to rearm %llu time(s), so the reclaim loop stopped",
+ (unsigned long long)failures);
+}
+
+/*
+ * A kfunc that fails on every call is indistinguishable from a cgroup with
+ * nothing left to reclaim, which the reclaim_calls and reclaimed_bytes
+ * assertions below cannot tell apart. Only call this on a path that is
+ * already failing.
+ */
+static void report_reclaim_errors(struct memcg_async_reclaim *skel)
+{
+ u64 last_err = skel->bss->last_reclaim_err;
+
+ if (last_err)
+ PRINT_FAIL("bpf_proactive_reclaim() last failed with -%llu, nothing was reclaimed",
+ (unsigned long long)last_err);
+}
+
+/*
+ * The benchmark numbers are only interesting when the test passes, but
+ * dump_test_log() drops the captured log unless the test failed or -v was
+ * given, so they have to bypass the hijack. The ?: stdout fallback is
+ * required, not defensive: stdio_hijack() returns early in verbose mode and
+ * never sets env.stdout_saved.
+ *
+ * This also bypasses the worker-to-dispatcher log protocol, so under -j the
+ * line can interleave with the per-test records. It carries no '#' prefix:
+ * test_progs uses that only for its own result records, and print_test_log()
+ * dumps free-form test output verbatim.
+ */
+static void bench_printf(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprintf(env.stdout_saved ?: stdout, fmt, ap);
+ va_end(ap);
+}
+
+void test_memcg_async_reclaim(void)
+{
+ u64 high_cgroup_id, low_cgroup_id;
+ double high_time = 0.0, low_time = 0.0;
+ double base_high_time = 0.0, base_low_time = 0.0;
+ struct memcg_async_reclaim *skel = NULL;
+ const char *dir;
+ int err, bench;
+
+ dir = workload_files_dir();
+ if (!ASSERT_TRUE(dir != NULL, "workload_files_dir"))
+ return;
+
+ bench = !!getenv("TEST_MEMCG_ASYNC_RECLAIM_BENCH");
+
+ err = setup_high_low_cgroups(&high_cgroup_id, &low_cgroup_id);
+ if (!ASSERT_OK(err, "setup_high_low_cgroups reclaim"))
+ return;
+
+ /*
+ * 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;
+
+ /*
+ * 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();
+ err = setup_high_low_cgroups(&high_cgroup_id, &low_cgroup_id);
+ if (!ASSERT_OK(err, "setup_high_low_cgroups after baseline"))
+ goto out;
+ }
+
+ err = setup_bpf(high_cgroup_id, low_cgroup_id, &skel);
+ if (!ASSERT_OK(err, "setup_bpf"))
+ goto out;
+
+ err = run_high_low_workload(dir, &high_time, &low_time, READ_TIMES);
+ if (!ASSERT_OK(err, "run_high_low_workload reclaim"))
+ goto out;
+
+ /*
+ * Timing alone cannot distinguish a working reclaim from a no-op
+ * one, so require that the BPF program actually reclaimed memory
+ * from the low cgroup.
+ */
+ if (!ASSERT_GT(skel->bss->reclaim_calls, 0, "reclaim_calls")) {
+ report_timer_failures(skel);
+ report_reclaim_errors(skel);
+ goto out;
+ }
+ if (!ASSERT_GT(skel->bss->reclaimed_bytes, 0, "reclaimed_bytes")) {
+ report_reclaim_errors(skel);
+ goto out;
+ }
+
+ /*
+ * The timing comparison is a benchmark and too flaky to fail CI
+ * runs, so it only logs the numbers; the counters above already
+ * proved that the BPF program reclaimed memory.
+ */
+ if (bench && base_high_time > 0.0)
+ bench_printf("memcg_async_reclaim: baseline high=%f low=%f, "
+ "reclaim high=%f low=%f, high speedup=%.1f%%\n",
+ base_high_time, base_low_time, high_time, low_time,
+ 100.0 * (base_high_time - high_time) / base_high_time);
+
+out:
+ if (skel)
+ memcg_async_reclaim__destroy(skel);
+ cleanup_cgroup_environment();
+}
+
+/*
+ * Keep refaults flowing through the trigger cgroup so reclaim rounds
+ * keep being triggered while the target cgroup is being removed. The
+ * child joins the trigger cgroup and writes the data file there, so
+ * that the file pages are charged to the trigger cgroup and actually
+ * come under its memory limit; then it re-reads the file in a loop
+ * until it is killed.
+ */
+static pid_t spawn_keepalive_reader(int data_fd)
+{
+ pid_t pid = fork();
+
+ if (pid != 0)
+ return pid;
+
+ if (join_parent_cgroup(CG_DYING_TRIGGER_DIR))
+ _exit(CHILD_EXIT_JOIN_CGROUP);
+ if (write_file(data_fd))
+ _exit(CHILD_EXIT_WRITE_FILE);
+ for (;;) {
+ if (read_file(data_fd, READ_TIMES))
+ _exit(CHILD_EXIT_READ_FILE);
+ }
+}
+
+/* Reclaim outcomes observed so far, tallied from ringbuf events. */
+struct reclaim_events_seen {
+ int called;
+ int skipped_dying;
+ int target_gone;
+};
+
+static int on_reclaim_event(void *ctx, void *data, size_t sz)
+{
+ struct reclaim_events_seen *seen = ctx;
+ const struct reclaim_event *ev = data;
+
+ if (sz < sizeof(*ev))
+ return 0;
+
+ switch (ev->outcome) {
+ case RECLAIM_OUTCOME_CALLED:
+ seen->called++;
+ break;
+ case RECLAIM_OUTCOME_SKIPPED_DYING:
+ seen->skipped_dying++;
+ break;
+ case RECLAIM_OUTCOME_TARGET_GONE:
+ seen->target_gone++;
+ break;
+ }
+
+ return 0;
+}
+
+/*
+ * Remove the reclaim target while the BPF program keeps running and verify
+ * that reclaim stops instead of reclaiming from the removed cgroup.
+ *
+ * The target stays empty; the workload lives in the trigger cgroup and only
+ * keeps refaults flowing so that reclaim rounds keep starting, both before
+ * and after the target is removed. A CALLED event while the target is alive
+ * proves that rounds really run (the kfunc returns 0 on the empty target, but
+ * the call is still counted).
+ *
+ * Once rmdir has returned, bpf_cgroup_from_id() has already stopped resolving
+ * the target: kernfs deactivates the directory node inside the rmdir syscall,
+ * see cgroup_is_dying() in the BPF program. TARGET_GONE is therefore the
+ * outcome this test can rely on, and the one it asserts. SKIPPED_DYING needs
+ * an attempt to land in the short window between cgroup_destroy_locked()
+ * clearing CSS_ONLINE and kernfs_remove() deactivating the node, so it is
+ * counted and reported on failure but never required.
+ */
+void test_memcg_async_reclaim_dying(void)
+{
+ u64 trigger_cgroup_id, target_cgroup_id;
+ char data_file[PATH_MAX] = "";
+ struct reclaim_events_seen seen = {};
+ struct memcg_async_reclaim *skel = NULL;
+ struct ring_buffer *rb = NULL;
+ u64 calls_before;
+ const char *dir;
+ pid_t reader_pid = -1;
+ int data_fd = -1;
+ int err, status, i, n;
+
+ dir = workload_files_dir();
+ if (!ASSERT_TRUE(dir != NULL, "workload_files_dir"))
+ return;
+
+ err = setup_dying_cgroups(&trigger_cgroup_id, &target_cgroup_id);
+ if (!ASSERT_OK(err, "setup_dying_cgroups"))
+ return;
+
+ err = setup_bpf(trigger_cgroup_id, target_cgroup_id, &skel);
+ if (!ASSERT_OK(err, "setup_bpf"))
+ goto out;
+
+ rb = ring_buffer__new(bpf_map__fd(skel->maps.reclaim_events),
+ on_reclaim_event, &seen, NULL);
+ if (!ASSERT_OK_PTR(rb, "ring_buffer__new"))
+ goto out;
+
+ snprintf(data_file, sizeof(data_file),
+ "%s/memcg_async_dying_XXXXXX", dir);
+ /* Kept open and inherited, see run_high_low_workload(). */
+ data_fd = mkstemp(data_file);
+ if (!ASSERT_GE(data_fd, 0, "mkstemp"))
+ goto out;
+
+ 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;
+
+ /*
+ * 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;
+ }
+
+ /*
+ * 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
+ * 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.
+ */
+ if (!ASSERT_EQ(skel->bss->reclaim_calls, calls_before, "reclaim_calls"))
+ goto out;
+ if (!ASSERT_EQ(skel->bss->reclaimed_bytes, 0ULL, "reclaimed_bytes"))
+ goto out;
+
+out:
+ if (reader_pid > 0) {
+ kill(reader_pid, SIGKILL);
+ (void)waitpid(reader_pid, NULL, 0);
+ }
+ if (data_fd >= 0)
+ close(data_fd);
+ if (data_file[0])
+ unlink(data_file);
+ if (rb)
+ ring_buffer__free(rb);
+ if (skel)
+ memcg_async_reclaim__destroy(skel);
+ cleanup_cgroup_environment();
+}
diff --git a/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c b/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
new file mode 100644
index 0000000000000..d78d547af7bf1
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c
@@ -0,0 +1,327 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include "vmlinux.h"
+#include "bpf_experimental.h"
+
+#define CLOCK_MONOTONIC 1
+/*
+ * One reclaim round targets RECLAIM_MAX_ITER batches of RECLAIM_SIZE
+ * each, i.e. 4 MiB in total. Each bpf_wq callback reclaims a single
+ * batch and requeues the same work item for the next one, so no callback
+ * runs longer than one bounded reclaim pass.
+ *
+ * RECLAIM_SIZE is a byte count, not a page count: bpf_proactive_reclaim()
+ * converts it against the running kernel's PAGE_SIZE and returns bytes, so
+ * this holds on any page size. The kfunc also clamps a batch to the
+ * kernel's MEMCG_CHARGE_BATCH, which is not visible to BPF; a clamped
+ * batch only means a round needs more callbacks, because remaining is
+ * decremented by the bytes actually reclaimed.
+ */
+#define RECLAIM_SIZE (128 * 1024UL)
+#define RECLAIM_MAX_ITER 32
+
+struct bpf_args {
+ u64 high_cgroup_id;
+ u64 low_cgroup_id;
+ u64 event_delta_threshold;
+ u64 check_ns;
+};
+
+struct cgroup_memcg {
+ struct cgroup *cgrp;
+ struct mem_cgroup *memcg;
+};
+
+static u64 wq_high_cgroup_id;
+static u64 wq_low_cgroup_id;
+
+/*
+ * Statistics exposed to userspace through .bss, so the test can verify
+ * that reclaim actually happened instead of relying on timing alone.
+ */
+u64 reclaim_calls;
+u64 reclaimed_bytes;
+
+/*
+ * A timer that fails to rearm stops the whole chain, which from userspace
+ * looks exactly like "the kernel never reclaimed". Count it so the test can
+ * tell the two apart instead of blaming the kernel.
+ */
+u64 timer_failures;
+
+/*
+ * bpf_proactive_reclaim() reports failure as a negative return, which is
+ * otherwise indistinguishable from "this cgroup has nothing left to
+ * reclaim". Keep the last one so a failing kfunc is not mistaken for an
+ * idle cgroup. Stored as a positive errno.
+ */
+u64 last_reclaim_err;
+
+/*
+ * Outcome of a single reclaim attempt, reported to userspace through
+ * the reclaim_events ringbuf so tests can wait for reclaim events with
+ * a timeout instead of polling the counters above.
+ */
+enum reclaim_outcome {
+ RECLAIM_OUTCOME_CALLED,
+ RECLAIM_OUTCOME_SKIPPED_DYING,
+ RECLAIM_OUTCOME_TARGET_GONE,
+};
+
+struct reclaim_event {
+ __u64 outcome;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(max_entries, 1 << 16);
+} reclaim_events SEC(".maps");
+
+/*
+ * Reports are best effort: when the ringbuf is full, for example when
+ * userspace does not consume the events, the report is dropped.
+ */
+static void emit_reclaim_event(enum reclaim_outcome outcome)
+{
+ struct reclaim_event *ev;
+
+ ev = bpf_ringbuf_reserve(&reclaim_events, sizeof(*ev), 0);
+ if (!ev)
+ return;
+
+ ev->outcome = outcome;
+ bpf_ringbuf_submit(ev, 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)
+ return -1;
+
+ cm->memcg = bpf_get_mem_cgroup(&cm->cgrp->self);
+ if (!cm->memcg) {
+ bpf_cgroup_release(cm->cgrp);
+ return -1;
+ }
+
+ return 0;
+}
+
+static void put_cgroup_memcg(struct cgroup_memcg *cm)
+{
+ bpf_put_mem_cgroup(cm->memcg);
+ bpf_cgroup_release(cm->cgrp);
+}
+
+static int get_cgroup_event(u64 cgroup_id, u64 *val)
+{
+ struct cgroup_memcg cm;
+
+ if (get_cgroup_memcg_from_id(cgroup_id, &cm))
+ return -1;
+ bpf_mem_cgroup_flush_stats(cm.memcg);
+ *val = bpf_mem_cgroup_page_state(cm.memcg,
+ bpf_core_enum_value(enum node_stat_item,
+ WORKINGSET_REFAULT_FILE));
+ put_cgroup_memcg(&cm);
+
+ return 0;
+}
+
+static bool
+should_reclaim_cgroup(u64 cgroup_id, u64 *prev_event, u64 event_delta_threshold)
+{
+ u64 cur, delta;
+
+ if (get_cgroup_event(cgroup_id, &cur))
+ return false;
+
+ delta = cur - *prev_event;
+ *prev_event = cur;
+
+ return delta >= event_delta_threshold;
+}
+
+/*
+ * rmdir clears CSS_ONLINE on cgrp->self in cgroup_destroy_locked() and only
+ * then deactivates the cgroup's kernfs node with kernfs_remove().
+ * bpf_cgroup_from_id() resolves an id through
+ * kernfs_find_and_get_node_by_id(), which refuses deactivated nodes, so the
+ * lookup starts failing inside the rmdir syscall -- not, as one might expect,
+ * once the cgroup's last reference has been dropped.
+ *
+ * The window in which the lookup still succeeds while the cgroup is already
+ * dying is therefore just the few statements between those two. An attempt
+ * that lands in it reports RECLAIM_OUTCOME_SKIPPED_DYING; after rmdir has
+ * returned, every attempt reports TARGET_GONE instead. The check is kept
+ * because it is the only thing standing between reclaim and a cgroup that is
+ * mid-teardown, but it cannot be hit reliably from userspace, so the test
+ * does not require SKIPPED_DYING.
+ *
+ * Only CSS_ONLINE is worth testing. CSS_DYING is raised by kill_css_sync(),
+ * which dereferences css->ss and so is never called with cgrp->self; the
+ * cgroup's own css only ever loses CSS_ONLINE. This is therefore
+ * cgroup_is_dead() from include/linux/cgroup.h, not css_is_dying().
+ *
+ * CSS_ONLINE comes from vmlinux.h: the kernel defines it in an anonymous
+ * enum, so bpf_core_enum_value() has no enum type to bind to, and
+ * redeclaring it locally would clash with the vmlinux.h enumerators.
+ * vmlinux.h is generated from the running kernel's BTF, so the value
+ * already matches the target kernel.
+ */
+static bool cgroup_is_dying(struct cgroup *cgrp)
+{
+ return !(cgrp->self.flags & CSS_ONLINE);
+}
+
+/*
+ * Reclaim one batch from the target cgroup. Returns the number of
+ * bytes reclaimed, or 0 if the cgroup is dying or gone, the kfunc
+ * failed, or nothing was reclaimed. Each attempt reports its outcome
+ * through the reclaim_events ringbuf, and a failing kfunc additionally
+ * records its errno in last_reclaim_err.
+ */
+static u64 reclaim_cgroup(u64 cgroup_id, u64 size)
+{
+ struct cgroup_memcg cm;
+ long nr;
+
+ if (get_cgroup_memcg_from_id(cgroup_id, &cm)) {
+ emit_reclaim_event(RECLAIM_OUTCOME_TARGET_GONE);
+ return 0;
+ }
+
+ if (cgroup_is_dying(cm.cgrp)) {
+ emit_reclaim_event(RECLAIM_OUTCOME_SKIPPED_DYING);
+ put_cgroup_memcg(&cm);
+ return 0;
+ }
+
+ reclaim_calls++;
+ nr = bpf_proactive_reclaim(cm.memcg, size, -1);
+ if (nr < 0)
+ last_reclaim_err = -nr;
+ else if (nr > 0)
+ reclaimed_bytes += nr;
+ emit_reclaim_event(RECLAIM_OUTCOME_CALLED);
+
+ put_cgroup_memcg(&cm);
+
+ return nr > 0 ? nr : 0;
+}
+
+struct wq_elem {
+ struct bpf_timer timer;
+ struct bpf_wq work;
+ u64 prev_event;
+ u64 event_delta_threshold;
+ u64 check_ns;
+ /*
+ * Bytes still to reclaim in the current round, carried across
+ * requeues. 0 means no round is in progress; the timer path
+ * starts a new round by resetting it, requeued work only looks
+ * at it.
+ */
+ u64 remaining;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, struct wq_elem);
+} wq_map SEC(".maps");
+
+static int reclaim_work_fn(void *map, int *key, void *value)
+{
+ struct wq_elem *elem = value;
+ u64 nr, size;
+
+ if (!elem->remaining) {
+ /*
+ * Timer-triggered entry: start a new round only when the
+ * high cgroup refaults enough. Requeued entries skip this
+ * check and only look at remaining, so a round consumes the
+ * refault delta only on the tick that starts it; ticks that
+ * find no round in progress consume and discard it.
+ */
+ if (!should_reclaim_cgroup(wq_high_cgroup_id, &elem->prev_event,
+ elem->event_delta_threshold))
+ return 0;
+ elem->remaining = RECLAIM_MAX_ITER * RECLAIM_SIZE;
+ }
+
+ /* One bounded reclaim pass per callback */
+ size = elem->remaining < RECLAIM_SIZE ? elem->remaining : RECLAIM_SIZE;
+ nr = reclaim_cgroup(wq_low_cgroup_id, size);
+ if (!nr) {
+ elem->remaining = 0;
+ return 0;
+ }
+
+ /* try_to_free_mem_cgroup_pages() may reclaim more than requested */
+ if (nr >= elem->remaining)
+ elem->remaining = 0;
+ else
+ elem->remaining -= nr;
+
+ /* Requeue the same work item for the next batch */
+ if (elem->remaining)
+ bpf_wq_start(&elem->work, 0);
+
+ return 0;
+}
+
+static int wq_timer_cb(void *map, int *key, struct wq_elem *elem)
+{
+ /*
+ * A failed bpf_wq_start() self-heals on the next tick; a failed
+ * rearm does not, so only the latter is worth reporting.
+ */
+ bpf_wq_start(&elem->work, 0);
+ if (bpf_timer_start(&elem->timer, elem->check_ns, 0))
+ timer_failures++;
+
+ return 0;
+}
+
+SEC("syscall")
+int wq_prog_init(struct bpf_args *ctx)
+{
+ struct wq_elem *elem;
+ __u32 key = 0;
+ int ret;
+
+ elem = bpf_map_lookup_elem(&wq_map, &key);
+ if (!elem)
+ return -1;
+
+ ret = bpf_wq_init(&elem->work, &wq_map, 0);
+ if (ret)
+ return ret;
+
+ ret = bpf_wq_set_callback(&elem->work, reclaim_work_fn, 0);
+ if (ret)
+ return ret;
+
+ ret = bpf_timer_init(&elem->timer, &wq_map, CLOCK_MONOTONIC);
+ if (ret)
+ return ret;
+
+ ret = bpf_timer_set_callback(&elem->timer, wq_timer_cb);
+ if (ret)
+ return ret;
+
+ elem->prev_event = 0;
+ elem->remaining = 0;
+ elem->event_delta_threshold = ctx->event_delta_threshold;
+ elem->check_ns = ctx->check_ns;
+
+ wq_high_cgroup_id = ctx->high_cgroup_id;
+ wq_low_cgroup_id = ctx->low_cgroup_id;
+
+ return bpf_timer_start(&elem->timer, elem->check_ns, 0);
+}
+
+char _license[] SEC("license") = "GPL";
|
| 49/3 | 2026/09/20 10:04 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 17472 output: 34 thoughts: 1051 Thoughts: **KMSAN Fuzzing Session Assessment** Okay, so I need to decide if this patch series warrants a KMSAN fuzzing session. I need to keep in mind the crucial difference between KASAN and KMSAN. KASAN is already enabled in standard builds and covers things like out-of-bounds accesses, use-after-free, double frees, invalid frees, lockdep issues, and memory corruption. KMSAN, on the other hand, is all about detecting reads of *uninitialized* memory, specifically on the stack, heap, and page allocations, as well as kernel-to-user memory leaks. The rule is simple: if KASAN or other standard detectors can catch it, no need for KMSAN, as that is expensive! The deciding factors are: Does this patch introduce or expose uninitialized memory risks ONLY detected by KMSAN? Specifically, I'm looking for these scenarios: kernel structures sent to userspace with uninitialized fields, logic depending on uninitialized variables, allocation of complex data structures with later uninitialized reads, and bounds checks exposing uninitialized bytes. So, let's break down the patch. It touches `mm/bpf_memcontrol.c`, `mm/internal.h`, and some selftest files. The core of it seems to be adding a new kfunc, `bpf_proactive_reclaim`, and registering it for `BPF_PROG_TYPE_SYSCALL`. The changes in `mm/internal.h` are relatively straightforward, converting a few defines to an enum, probably for BTF generation. The selftests are just for testing, so they aren't where the action is. The real meat is that kfunc. Let's look at `bpf_proactive_reclaim` and, specifically, how the arguments are used. It takes a `struct mem_cgroup *memcg`, an `unsigned long size`, and an `int swappiness`. The code checks the `swappiness` value, checks the `size` is valid, and then calls `try_to_free_mem_cgroup_pages`. This is where I need to focus: does `try_to_free_mem_cgroup_pages` use any of these arguments, or anything they indirectly influence, in a way that could lead to reading uninitialized memory? Does it potentially leak uninitialized data to userspace? I'm going to run `grepper` on `try_to_free_mem_cgroup_pages` to understand the data flow, and identify any potential risks. I want to see how these arguments are used, how they're passed, and if they influence any memory allocations or copies to userspace. If it turns out that the data flow is handled securely with existing checks and zeroing, then this patch does not warrant a KMSAN session. However, if there's any hint of uninitialized data usage, I'll recommend running KMSAN. |
| 50/3 | 2026/09/20 10:04 | tool | grepper |
0mArgs:{
"Expression": "try_to_free_mem_cgroup_pages",
"PathPrefix": "mm/"
}Results: {
"Output": "mm/bpf_memcontrol.c=183=__bpf_kfunc long bpf_proactive_reclaim(struct mem_cgroup *memcg,\n--\nmm/bpf_memcontrol.c-197-\nmm/bpf_memcontrol.c:198:\tnr_reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages, GFP_KERNEL,\nmm/bpf_memcontrol.c-199-\t\t\t\t\t\t MEMCG_RECLAIM_MAY_SWAP |\n--\nmm/internal.h=77=enum {\n--\nmm/internal.h-84-\nmm/internal.h:85:unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\nmm/internal.h-86-\t\t\t\t\t unsigned long nr_pages,\n--\nmm/memcontrol-v1.c=1771=static int mem_cgroup_resize_max(struct mem_cgroup *memcg,\n--\nmm/memcontrol-v1.c-1815-\nmm/memcontrol-v1.c:1816:\t\tif (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,\nmm/memcontrol-v1.c-1817-\t\t\t\tmemsw ? 0 : MEMCG_RECLAIM_MAY_SWAP, NULL)) {\n--\nmm/memcontrol-v1.c=1834=static int mem_cgroup_force_empty(struct mem_cgroup *memcg)\n--\nmm/memcontrol-v1.c-1851-\nmm/memcontrol-v1.c:1852:\t\tif (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,\nmm/memcontrol-v1.c-1853-\t\t\t\t\t\t MEMCG_RECLAIM_MAY_SWAP, NULL))\n--\nmm/memcontrol.c=2378=static unsigned long reclaim_high(struct mem_cgroup *memcg,\n--\nmm/memcontrol.c-2393-\t\tpsi_memstall_enter(\u0026pflags);\nmm/memcontrol.c:2394:\t\tnr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,\nmm/memcontrol.c-2395-\t\t\t\t\t\t\tgfp_mask,\n--\nmm/memcontrol.c=2645=static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,\n--\nmm/memcontrol.c-2717-\tpsi_memstall_enter(\u0026pflags);\nmm/memcontrol.c:2718:\tnr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,\nmm/memcontrol.c-2719-\t\t\t\t\t\t gfp_mask, reclaim_options, NULL);\n--\nmm/memcontrol.c=4838=static ssize_t memory_high_write(struct kernfs_open_file *of,\n--\nmm/memcontrol.c-4879-\nmm/memcontrol.c:4880:\t\treclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,\nmm/memcontrol.c-4881-\t\t\t\t\tGFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);\n--\nmm/memcontrol.c=4897=static ssize_t memory_max_write(struct kernfs_open_file *of,\n--\nmm/memcontrol.c-4938-\t\tif (nr_reclaims) {\nmm/memcontrol.c:4939:\t\t\tif (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,\nmm/memcontrol.c-4940-\t\t\t\t\tGFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))\n--\nmm/vmscan.c=6815=unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,\n--\nmm/vmscan.c-6854-\nmm/vmscan.c:6855:unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\nmm/vmscan.c-6856-\t\t\t\t\t unsigned long nr_pages,\n--\nmm/vmscan.c-6895-#else\nmm/vmscan.c:6896:unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\nmm/vmscan.c-6897-\t\t\t\t\t unsigned long nr_pages,\n--\nmm/vmscan.c=7958=int user_proactive_reclaim(char *buf,\n--\nmm/vmscan.c-8029-\t\t\t\t\t MEMCG_RECLAIM_PROACTIVE;\nmm/vmscan.c:8030:\t\t\treclaimed = try_to_free_mem_cgroup_pages(memcg,\nmm/vmscan.c-8031-\t\t\t\t\t\t batch_size, gfp_mask,\n"
} |
| 51/3 | 2026/09/20 10:04 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 20456 output: 35 thoughts: 28 Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue: **Investigating `try_to_free_mem_cgroup_pages` and Swappiness** Alright, I need to dig into `try_to_free_mem_cgroup_pages` again. It's crucial for understanding how memory pressure is handled within cgroups, and I know I've glanced at it before but I need to refresh my understanding. Specifically, I want to see how it interacts with the system's `swappiness` setting. I need to clearly define where the connection point exists between the two and what the behaviour is. It's probably related to how the kernel decides when and how aggressively to reclaim memory from a cgroup, and whether it's more likely to swap out clean pages or dirty pages under different swappiness configurations. I'm guessing that `swappiness` will ultimately affect the priority or preference given to swapping vs. page reclamation in that function. I should also check if the function directly checks `swappiness` or indirectly via other settings. I'm anticipating some interesting interactions to unpack here. I'm going to start with the source and work from there. |
| 52/3 | 2026/09/20 10:04 | tool | read-file |
0mArgs:{
"File": "mm/vmscan.c",
"FirstLine": 6850,
"LineCount": 40
}Results: {
"Contents": "6850:\t\t*nr_scanned = sc.nr_scanned;\n6851:\t\n6852:\t\treturn sc.nr_reclaimed;\n6853:\t}\n6854:\t\n6855:\tunsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\n6856:\t\t\t\t\t\t unsigned long nr_pages,\n6857:\t\t\t\t\t\t gfp_t gfp_mask,\n6858:\t\t\t\t\t\t unsigned int reclaim_options,\n6859:\t\t\t\t\t\t int *swappiness)\n6860:\t{\n6861:\t\tunsigned long nr_reclaimed;\n6862:\t\tunsigned int noreclaim_flag;\n6863:\t\tstruct scan_control sc = {\n6864:\t\t\t.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),\n6865:\t\t\t.proactive_swappiness = swappiness,\n6866:\t\t\t.gfp_mask = (current_gfp_context(gfp_mask) \u0026 GFP_RECLAIM_MASK) |\n6867:\t\t\t\t\t(GFP_HIGHUSER_MOVABLE \u0026 ~GFP_RECLAIM_MASK),\n6868:\t\t\t.reclaim_idx = MAX_NR_ZONES - 1,\n6869:\t\t\t.target_mem_cgroup = memcg,\n6870:\t\t\t.priority = DEF_PRIORITY,\n6871:\t\t\t.may_writepage = 1,\n6872:\t\t\t.may_unmap = 1,\n6873:\t\t\t.may_swap = !!(reclaim_options \u0026 MEMCG_RECLAIM_MAY_SWAP),\n6874:\t\t\t.proactive = !!(reclaim_options \u0026 MEMCG_RECLAIM_PROACTIVE),\n6875:\t\t};\n6876:\t\t/*\n6877:\t\t * Traverse the ZONELIST_FALLBACK zonelist of the current node to put\n6878:\t\t * equal pressure on all the nodes. This is based on the assumption that\n6879:\t\t * the reclaim does not bail out early.\n6880:\t\t */\n6881:\t\tstruct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);\n6882:\t\n6883:\t\tset_task_reclaim_state(current, \u0026sc.reclaim_state);\n6884:\t\ttrace_mm_vmscan_memcg_reclaim_begin(sc.gfp_mask, 0, memcg);\n6885:\t\tnoreclaim_flag = memalloc_noreclaim_save();\n6886:\t\n6887:\t\tnr_reclaimed = do_try_to_free_pages(zonelist, \u0026sc);\n6888:\t\n6889:\t\tmemalloc_noreclaim_restore(noreclaim_flag);\n"
} |
| 53/3 | 2026/09/20 10:04 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 21507 output: 28 thoughts: 362 Thoughts: **Analyzing the `bpf_proactive_reclaim` Function** Okay, let's break this down. My initial observation is focused on `bpf_proactive_reclaim`, specifically the way it handles `swappiness`. The function itself seems straightforward; it's designed to proactively reclaim memory within a memory cgroup (`memcg`). I see the typical checks for invalid input – ensuring `swappiness` is within the acceptable range and that the requested `size` is at least a page. We determine `nr_pages` and then call `try_to_free_mem_cgroup_pages` with some flags and the `swappiness` value. The crucial part here is the conditional logic around `swappiness`: `if (swappiness == -1)`. If `swappiness` is -1, a `NULL` is passed; otherwise, the *address* of `swappiness` is passed: `&swappiness`. This is where my expert eye focuses. `swappiness` is just a local `int` argument. Since it's passed by value, it *must* be initialized within the function's scope. It's allocated on the stack or in a register, and the value we receive is a copy. So, even though it may look odd, `swappiness` is guaranteed to be fully initialized. When a memory address is given, the value must be available at that address. It looks like it is setting `sc.proactive_swappiness = swappiness`. This means that if it's not -1 it is being passed by address to be used. Now, my next question: How is this `sc.proactive_swappiness` value actually *used* downstream in `vmscan.c`? That's the next critical piece of this puzzle. I need to understand the implications of this value on memory reclaim decisions. |
| 54/3 | 2026/09/20 10:04 | tool | grepper |
0mArgs:{
"Expression": "proactive_swappiness",
"PathPrefix": "mm/"
}Results: {
"Output": "mm/vmscan.c=76=struct scan_control {\n--\nmm/vmscan.c-98-\t/* Swappiness value for proactive reclaim. Always use sc_swappiness()! */\nmm/vmscan.c:99:\tint *proactive_swappiness;\nmm/vmscan.c-100-\n--\nmm/vmscan.c=203=static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)\nmm/vmscan.c-204-{\nmm/vmscan.c:205:\tif (sc-\u003eproactive \u0026\u0026 sc-\u003eproactive_swappiness)\nmm/vmscan.c:206:\t\treturn *sc-\u003eproactive_swappiness;\nmm/vmscan.c-207-\treturn mem_cgroup_swappiness(memcg);\n--\nmm/vmscan.c=6855=unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,\n--\nmm/vmscan.c-6864-\t\t.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),\nmm/vmscan.c:6865:\t\t.proactive_swappiness = swappiness,\nmm/vmscan.c-6866-\t\t.gfp_mask = (current_gfp_context(gfp_mask) \u0026 GFP_RECLAIM_MASK) |\n--\nmm/vmscan.c=7958=int user_proactive_reclaim(char *buf,\n--\nmm/vmscan.c-8037-\t\t\t\t.reclaim_idx = gfp_zone(gfp_mask),\nmm/vmscan.c:8038:\t\t\t\t.proactive_swappiness = swappiness == -1 ? NULL : \u0026swappiness,\nmm/vmscan.c-8039-\t\t\t\t.priority = DEF_PRIORITY,\n"
} |
| 55/3 | 2026/09/20 10:04 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 22790 output: 35 thoughts: 389 Thoughts: **Analyzing the Proactive Swappiness Implementation** Okay, so I'm looking at how `sc.proactive_swappiness` is handled. It looks like it's just read if it's not null, using `*sc->proactive_swappiness`, and the `swappiness` argument itself is an integer. Nothing unusual there, it's just a dereference of the integer. Now, I need to make sure there are no obvious memory safety issues. Let's see... is there any uninitialized memory lurking around? * Are we copying any structs to userspace? No, `bpf_proactive_reclaim` returns a `long`, which is just a scalar (basically, `nr_reclaimed * PAGE_SIZE`). * Does it allocate any kernel memory that then gets copied to userspace, or that's just left uninitialized? Nope. * Does it pass uninitialized stack or heap data? No again. * Is there any conditional logic that might branch based on uninitialized variables? Nope. * Are there any complex data structure allocations that could expose uninitialized memory? No. * Are there any bounds checks or length calculations that might be vulnerable? I don't see any. * What about the BPF verifier's handling of `bpf_proactive_reclaim`? Let me look at the registration in `bpf_memcontrol.c`. Okay, I see the registration: `BTF_KFUNCS_START(bpf_memcontrol_reclaim_kfuncs)`, `BTF_ID_FLAGS(func, bpf_proactive_reclaim, KF_SLEEPABLE)`, and `BTF_KFUNCS_END(bpf_memcontrol_reclaim_kfuncs)`. Finally, `register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &bpf_memcontrol_reclaim_kfunc_set)`. Now, how does the BPF verifier handle the `memcg` pointer validation? From what I can tell, `struct mem_cgroup *memcg` is passed as a trusted / `PTR_TO_BTF_ID` pointer in BPF. That looks sound. I should probably check the other kfuncs in `mm/bpf_memcontrol.c` just to be completely sure, but so far, it all seems pretty clean. |
| 56/3 | 2026/09/20 10:04 | tool | read-file |
0mArgs:{
"File": "mm/bpf_memcontrol.c",
"FirstLine": 1,
"LineCount": 80
}Results: {
"Contents": " 1:\t// SPDX-License-Identifier: GPL-2.0-or-later\n 2:\t/*\n 3:\t * Memory Controller-related BPF kfuncs and auxiliary code\n 4:\t *\n 5:\t * Author: Roman Gushchin \u003croman.gushchin@linux.dev\u003e\n 6:\t */\n 7:\t\n 8:\t#include \u003clinux/memcontrol.h\u003e\n 9:\t#include \u003clinux/bpf.h\u003e\n 10:\t\n 11:\t#include \"internal.h\"\n 12:\t\n 13:\t__bpf_kfunc_start_defs();\n 14:\t\n 15:\t/**\n 16:\t * bpf_get_root_mem_cgroup - Returns a pointer to the root memory cgroup\n 17:\t *\n 18:\t * The function has KF_ACQUIRE semantics, even though the root memory\n 19:\t * cgroup is never destroyed after being created and doesn't require\n 20:\t * reference counting. And it's perfectly safe to pass it to\n 21:\t * bpf_put_mem_cgroup()\n 22:\t *\n 23:\t * Return: A pointer to the root memory cgroup.\n 24:\t */\n 25:\t__bpf_kfunc struct mem_cgroup *bpf_get_root_mem_cgroup(void)\n 26:\t{\n 27:\t\tif (mem_cgroup_disabled())\n 28:\t\t\treturn NULL;\n 29:\t\n 30:\t\t/* css_get() is not needed */\n 31:\t\treturn root_mem_cgroup;\n 32:\t}\n 33:\t\n 34:\t/**\n 35:\t * bpf_get_mem_cgroup - Get a reference to a memory cgroup\n 36:\t * @css: pointer to the css structure\n 37:\t *\n 38:\t * It's fine to pass a css which belongs to any cgroup controller,\n 39:\t * e.g. unified hierarchy's main css.\n 40:\t *\n 41:\t * Implements KF_ACQUIRE semantics.\n 42:\t *\n 43:\t * Return: A pointer to a mem_cgroup structure after bumping\n 44:\t * the corresponding css's reference counter.\n 45:\t */\n 46:\t__bpf_kfunc struct mem_cgroup *\n 47:\tbpf_get_mem_cgroup(struct cgroup_subsys_state *css)\n 48:\t{\n 49:\t\tstruct mem_cgroup *memcg = NULL;\n 50:\t\tbool rcu_unlock = false;\n 51:\t\n 52:\t\tif (mem_cgroup_disabled() || !root_mem_cgroup)\n 53:\t\t\treturn NULL;\n 54:\t\n 55:\t\tif (root_mem_cgroup-\u003ecss.ss != css-\u003ess) {\n 56:\t\t\tstruct cgroup *cgroup = css-\u003ecgroup;\n 57:\t\t\tint ssid = root_mem_cgroup-\u003ecss.ss-\u003eid;\n 58:\t\n 59:\t\t\trcu_read_lock();\n 60:\t\t\trcu_unlock = true;\n 61:\t\t\tcss = rcu_dereference_raw(cgroup-\u003esubsys[ssid]);\n 62:\t\t}\n 63:\t\n 64:\t\tif (css \u0026\u0026 css_tryget(css))\n 65:\t\t\tmemcg = container_of(css, struct mem_cgroup, css);\n 66:\t\n 67:\t\tif (rcu_unlock)\n 68:\t\t\trcu_read_unlock();\n 69:\t\n 70:\t\treturn memcg;\n 71:\t}\n 72:\t\n 73:\t/**\n 74:\t * bpf_put_mem_cgroup - Put a reference to a memory cgroup\n 75:\t * @memcg: memory cgroup to release\n 76:\t *\n 77:\t * Releases a previously acquired memcg reference.\n 78:\t * Implements KF_RELEASE semantics.\n 79:\t */\n 80:\t__bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg)\n"
} |
| 57/3 | 2026/09/20 10:04 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 24835 output: 37 thoughts: 18 Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience and written in the first person: **Diving Deeper into `bpf_memcontrol.c`** Okay, so we've covered the basics, but let's not stop there. I need to get a really comprehensive grasp on how memory control works within the BPF framework. That means we need to drill down further into the code, and a good place to start is, naturally, `bpf_memcontrol.c`. I want to understand *all* aspects. It's not enough to just see the main functions, I need to know how they interconnect, what the edge cases are, and how it handles concurrency and potential resource contention. I'm going to look for any potential bottlenecks or areas where optimizations might be possible. Knowing how this module integrates with the broader memory management subsystem is key. Let's see what secrets this file holds. |
| 58/3 | 2026/09/20 10:04 | tool | read-file |
0mArgs:{
"File": "mm/bpf_memcontrol.c",
"FirstLine": 140,
"LineCount": 40
}Results: {
"Contents": " 140:\t *\n 141:\t * Allows to read memory cgroup statistics. The output is in bytes.\n 142:\t *\n 143:\t * Return: The value of the page state counter in bytes.\n 144:\t */\n 145:\t__bpf_kfunc unsigned long bpf_mem_cgroup_page_state(struct mem_cgroup *memcg, int idx)\n 146:\t{\n 147:\t\tif (unlikely(!memcg_stat_item_valid(idx)))\n 148:\t\t\treturn (unsigned long)-1;\n 149:\t\n 150:\t\treturn memcg_page_state_output(memcg, idx);\n 151:\t}\n 152:\t\n 153:\t/**\n 154:\t * bpf_mem_cgroup_flush_stats - Flush memory cgroup's statistics\n 155:\t * @memcg: memory cgroup\n 156:\t *\n 157:\t * Propagate memory cgroup's statistics up the cgroup tree.\n 158:\t */\n 159:\t__bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem_cgroup *memcg)\n 160:\t{\n 161:\t\tmem_cgroup_flush_stats(memcg);\n 162:\t}\n 163:\t\n 164:\t/**\n 165:\t * bpf_proactive_reclaim - proactively reclaim memory from a memory cgroup\n 166:\t * @memcg: the target memory cgroup to reclaim from.\n 167:\t * @size: the amount of memory to reclaim, in bytes, clamped to\n 168:\t * MEMCG_CHARGE_BATCH.\n 169:\t * @swappiness: the reclaim swappiness, in the range [MIN_SWAPPINESS,\n 170:\t * SWAPPINESS_ANON_ONLY], or -1 to use the memcg's own\n 171:\t * swappiness.\n 172:\t *\n 173:\t * Performs one proactive reclaim pass on @memcg, like a write to\n 174:\t * memory.reclaim but without retrying until @size is reached. Call it\n 175:\t * repeatedly to reclaim more than one batch.\n 176:\t *\n 177:\t * Only available to BPF_PROG_TYPE_SYSCALL, because other sleepable programs\n 178:\t * may run with filesystem locks held, which the reclaim path can deadlock\n 179:\t * on via filesystem shrinkers.\n"
} |
| 59/3 | 2026/09/20 10:04 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25764 output: 328 thoughts: 1043 Thoughts: **KMSAN Assessment of `bpf_proactive_reclaim`** Okay, let's break down this `bpf_proactive_reclaim` kfunc. I see it takes a `mem_cgroup` pointer, a size, and swappiness as inputs. `swappiness` and `size` are basic types, validated at the start, and `memcg` is a pointer, that the BPF verifier already provides type safety on. The core of the function involves calculating the number of pages to reclaim, calling `try_to_free_mem_cgroup_pages`, and returning the reclaimed size. Looking at the code, `nr_pages` is computed from the input `size` and a batch limit, and `nr_reclaimed` gets the result from the `try_to_free_mem_cgroup_pages` call. The return value is straightforward: the number of reclaimed pages, multiplied by `PAGE_SIZE`. No complex structures, no uninitialized variables, no struct copies to user space, no information leaks; it's all very clean. Now, let's analyze this against the KMSAN criteria. First, there are no kernel data structures sent to userspace. The function returns a single scalar integer, so criterion number one is a non-issue. Second, the code doesn't rely on uninitialized values for any conditional branching. All branches are based on validated input parameters. Third, no complex data structures are allocated or initialized, so we don't have to worry about uninitialized fields leaking through. Fourth, there are no checks or manipulations that could lead to reading uninitialized bytes from existing buffers. So, based on all of this, the potential issues here are limited to deadlocks or locking violations in sleepable BPF programs (which is, by design, restricted to BPF_PROG_TYPE_SYSCALL), invalid memcg or NULL pointers (which will be caught by KASAN), and memory reclaim bugs or race conditions, which are covered by KASAN / LOCKDEP. None of these involve the type of memory safety issues that KMSAN is designed to catch. Therefore, this patch doesn't require KMSAN. KASAN and the standard debuggers, especially LOCKDEP for concurrency issues, are sufficient for this case. ```tool_code set_results(NeedsKMSAN=False, KMSANReasoning="The `bpf_proactive_reclaim()` kfunc, introduced in `mm/bpf_memcontrol.c` for `BPF_PROG_TYPE_SYSCALL` programs, enables proactive cgroup memory reclaim passes via `try_to_free_mem_cgroup_pages()`. KMSAN is not applicable because: no kernel data structures or buffers are copied to userspace (it returns a scalar `long` value); all local variables and function arguments are fully initialized before use; the pointer `&swappiness` is dereferenced for reading an initialized integer within `try_to_free_mem_cgroup_pages()`; no new heap/stack allocations with uninitialized fields or padding are introduced. KASAN and LOCKDEP cover potential pointer dereference issues (e.g. invalid `memcg` references), and reclaim concurrency and lock inversion risks, respectively. Standard bug detectors and KASAN sufficiently cover any risks introduced.") ``` |
| 60/3 | 2026/09/20 10:04 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch introduces a new BPF kfunc, `bpf_proactive_reclaim()`, in `mm/bpf_memcontrol.c` registered for `BPF_PROG_TYPE_SYSCALL`, and exports swappiness constants as an enum in `mm/internal.h`.\n\nKMSAN is not applicable for the following reasons:\n1. No uninitialized memory or info-leak risks: The kfunc operates entirely on scalar arguments (`size`, `swappiness`) and a verified `struct mem_cgroup` pointer, returning a scalar `long` value representing reclaimed bytes. No kernel structures or buffers are copied to userspace via `copy_to_user`, ioctl, netlink, or BPF buffers.\n2. All local variables (`nr_pages`, `nr_reclaimed`) and parameters are explicitly initialized before use. The pointer passed to `try_to_free_mem_cgroup_pages` (`swappiness == -1 ? NULL : \u0026swappiness`) references the function argument passed by value, which is fully initialized.\n3. No complex data structures are allocated or partially initialized.\n\nAny risks associated with this change relate to memory reclaim concurrency, invalid memcg pointer dereferences, or locking/deadlocks in sleepable context, all of which are caught by KASAN and LOCKDEP in standard debugging builds. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch introduces a new BPF kfunc, `bpf_proactive_reclaim()`, in `mm/bpf_memcontrol.c` registered for `BPF_PROG_TYPE_SYSCALL`, and exports swappiness constants as an enum in `mm/internal.h`.\n\nKMSAN is not applicable for the following reasons:\n1. No uninitialized memory or info-leak risks: The kfunc operates entirely on scalar arguments (`size`, `swappiness`) and a verified `struct mem_cgroup` pointer, returning a scalar `long` value representing reclaimed bytes. No kernel structures or buffers are copied to userspace via `copy_to_user`, ioctl, netlink, or BPF buffers.\n2. All local variables (`nr_pages`, `nr_reclaimed`) and parameters are explicitly initialized before use. The pointer passed to `try_to_free_mem_cgroup_pages` (`swappiness == -1 ? NULL : \u0026swappiness`) references the function argument passed by value, which is fully initialized.\n3. No complex data structures are allocated or partially initialized.\n\nAny risks associated with this change relate to memory reclaim concurrency, invalid memcg pointer dereferences, or locking/deadlocks in sleepable context, all of which are caught by KASAN and LOCKDEP in standard debugging builds. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|