From nobody Mon Sep 28 03:41:41 2026 Received: from mta1.migadu.com (out-193.mta1.migadu.com [95.215.58.193]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 448584078CE for ; Thu, 27 Aug 2026 10:37:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=95.215.58.193 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787827027; cv=none; b=aGu5exvsol5X8vjr1vQSbstZSeIQhsJqG1a/t8frrllq3r7EDOcihKBBhjIQGYipZQQSx4mQygBMbq/I3+gKLZzOM6q3G/NUnVkQ5HfbTxeKKRBekp/aEl3p3wFGR0yTLWWGe7VOh6GDxlrHZlz5b+3VetlhyFQ6Yy+8g6C7GJ8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787827027; c=relaxed/simple; bh=1ZjfrCA2Bn7B9nyXIM3hZk40HAEkBRrlXow1cP7e6/M=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=p2KXDTMPMHn7MhVFuMpbs+MmK52K3jxuy97wf9qhWl4rMzhRPK6pY/mAlPd+0GFhvnx2DNBCxWbmNihpwVcgz+ea8Oto23ifaJcftNuht2/zqLOzEmynyf47Kko2RD0A+T47Cy+CWxU6s5WSnHs5Ob5CNH5mZlVhEPu/bbWhU8Y= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.dev; spf=pass smtp.mailfrom=linux.dev; dkim=pass (1024-bit key) header.d=linux.dev header.i=@linux.dev header.b=ca+KZQEo; arc=none smtp.client-ip=95.215.58.193 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.dev Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=linux.dev header.i=@linux.dev header.b="ca+KZQEo" X-Envelope-To: linux-kernel@vger.kernel.org DKIM-Signature: a=rsa-sha256; bh=1ZjfrCA2Bn7B9nyXIM3hZk40HAEkBRrlXow1cP7e6/M=; c=simple/simple; d=linux.dev; h=from:to:subject:date:message-id:mime-version:content-type; s=key1; t=1787827023; v=1; x=1788431823; b=ca+KZQEo6ekqcYHvyNX/+cb7LDUPX3D5a4xOlwQPLXgEINXu3faC4ajBI9mgMMdY/0Wg/1sX mAxg9w0Y4BsiWZ5+uJ0Df7EF1fyO5xMOZ8Gr5FMwh4KSbIAqzHHxu6+hCR795qPiO8bQBbJ7NuA 4S04s2Hwl3fjab9UfaqY49YY= X-Envelope-To: linux-kernel@vger.kernel.org Received: by smtp.migadu.com with ESMTPS id db1b73aa76be19cb; Thu, 27 Aug 2026 10:37:02 +0000 X-Mizu-Trace-ID: db1b73aa76be19cb X-Migadu-Flow: FLOW_OUT From: "Hui Zhu" To: Roman Gushchin , JP Kobryn , Shakeel Butt , Andrew Morton , Andrii Nakryiko , Eduard Zingerman , Ihor Solodrai , Alexei Starovoitov , Daniel Borkmann , Kumar Kartikeya Dwivedi , Martin KaFai Lau , Song Liu , Yonghong Song , Jiri Olsa , Emil Tsalapatis , Shuah Khan , Barry Song , Geliang Tang , linux-kernel@vger.kernel.org, bpf@vger.kernel.org, linux-mm@kvack.org, linux-kselftest@vger.kernel.org Cc: Hui Zhu Subject: [PATCH bpf-next v5 1/2] mm/bpf: Add bpf_proactive_reclaim kfunc Date: Thu, 27 Aug 2026 18:36:29 +0800 Message-ID: <5dfdc7800469eac4e9a240f2422ba65d4ef4c4ba.1787826402.git.zhuhui@kylinos.cn> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Hui Zhu Add bpf_proactive_reclaim(), a sleepable kfunc which performs one proactive reclaim pass on a given memory cgroup, similar to a write to memory.reclaim but without retrying until the target is reached. The kfunc refuses to reclaim if the calling task is already in a reclaim context, as a nested reclaim would corrupt the outer reclaim state. Signed-off-by: Hui Zhu --- mm/bpf_memcontrol.c | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/mm/bpf_memcontrol.c b/mm/bpf_memcontrol.c index 716df49d7647..297ff7f05042 100644 --- a/mm/bpf_memcontrol.c +++ b/mm/bpf_memcontrol.c @@ -6,6 +6,7 @@ */ =20 #include +#include #include =20 __bpf_kfunc_start_defs(); @@ -159,6 +160,49 @@ __bpf_kfunc void bpf_mem_cgroup_flush_stats(struct mem= _cgroup *memcg) mem_cgroup_flush_stats(memcg); } =20 +/* + * Reclaim must not recurse: try_to_free_mem_cgroup_pages() overwrites + * current->reclaim_state, so a nested call would corrupt the outer + * reclaim state. Reclaim windows are marked with PF_MEMALLOC; + * reclaim_state is also checked because it is installed slightly + * before PF_MEMALLOC. + */ +static bool bpf_in_reclaim_context(void) +{ + return (current->flags & PF_MEMALLOC) || current->reclaim_state; +} + +/** + * 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 + * + * Trigger one proactive reclaim pass on @memcg, similar to a write to + * memory.reclaim, but without retrying until @size is reached. + * Must not be called with a filesystem lock held: the reclaim path + * may deadlock on it via filesystem shrinkers. + * + * Return: The amount of memory reclaimed, in bytes, or 0 if @size is + * smaller than a page or the task is already in a reclaim context. + */ +__bpf_kfunc unsigned long bpf_proactive_reclaim(struct mem_cgroup *memcg, + unsigned long size) +{ + unsigned long nr_reclaimed; + + if (size < PAGE_SIZE || unlikely(bpf_in_reclaim_context())) + return 0; + + nr_reclaimed =3D try_to_free_mem_cgroup_pages(memcg, size / PAGE_SIZE, + GFP_KERNEL, + MEMCG_RECLAIM_MAY_SWAP | + MEMCG_RECLAIM_PROACTIVE, + NULL); + + return nr_reclaimed * PAGE_SIZE; +} + __bpf_kfunc_end_defs(); =20 BTF_KFUNCS_START(bpf_memcontrol_kfuncs) @@ -172,6 +216,8 @@ BTF_ID_FLAGS(func, bpf_mem_cgroup_usage) BTF_ID_FLAGS(func, bpf_mem_cgroup_page_state) BTF_ID_FLAGS(func, bpf_mem_cgroup_flush_stats, KF_SLEEPABLE) =20 +BTF_ID_FLAGS(func, bpf_proactive_reclaim, KF_SLEEPABLE) + BTF_KFUNCS_END(bpf_memcontrol_kfuncs) =20 static const struct btf_kfunc_id_set bpf_memcontrol_kfunc_set =3D { --=20 2.53.0 From nobody Mon Sep 28 03:41:41 2026 Received: from mta0.migadu.com (out-40.mta0.migadu.com [91.218.175.40]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C97A942587F for ; Thu, 27 Aug 2026 10:37:09 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=91.218.175.40 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787827033; cv=none; b=gOs2pUKuHRfJd7Axlk1X07I0PoK4/2vut0SanwKqki2xfFZ7q6ZCE5UipmFoze3O5e3rfc/MZoKKps+unZL/AtG7JBpbBxB0nKBzdbfRf8+Mb4y2SuwtnNZg+XKrl1gAmxZww4K70LE/eihxst3q01ZoMfUNX2kPmOkAL59Z2pY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787827033; c=relaxed/simple; bh=1XtC/dLTi1RO1xLUeELKwYr73zXU50mDq2Ac8mtDvNw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=P87hMG1vxQuzfXb06jjDJzFNIObV85sFiGIpiejICg0MzVG4BYMnNdQSkzdh+vom76+SpRG3GpKJCbR1tdSawMyduKgrCsBT3wfDbAyS9bwYwOOCBevACOz/Mk6aLLNtzxbIyWSWrlHwsDk0tS5pHvOgH0x0FBUpdbfu+1xJTCI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.dev; spf=pass smtp.mailfrom=linux.dev; dkim=pass (1024-bit key) header.d=linux.dev header.i=@linux.dev header.b=tTnGAzxJ; arc=none smtp.client-ip=91.218.175.40 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.dev Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=linux.dev header.i=@linux.dev header.b="tTnGAzxJ" X-Envelope-To: linux-kernel@vger.kernel.org DKIM-Signature: a=rsa-sha256; bh=1XtC/dLTi1RO1xLUeELKwYr73zXU50mDq2Ac8mtDvNw=; c=simple/simple; d=linux.dev; h=from:to:subject:date:message-id:mime-version:content-type; s=key1; t=1787827027; v=1; x=1788431827; b=tTnGAzxJvZ2h7vU/sBxmr83Qnp0TY+KDO4xHll1dAcemTBeFjAA+nL+X4HwoCgCd+S9H64EV H3bYszbUvQGoklG50C78kEi0GonuaNgMH11962nyVdZD4OgWoGJ39rCKSML1xl4xxB1Mv+8ho8D po1GhEDsskOI1SdYImsb3qJM= X-Envelope-To: linux-kernel@vger.kernel.org Received: by smtp.migadu.com with ESMTPS id 958f4337405634ea; Thu, 27 Aug 2026 10:37:07 +0000 X-Mizu-Trace-ID: 958f4337405634ea X-Migadu-Flow: FLOW_OUT From: "Hui Zhu" To: Roman Gushchin , JP Kobryn , Shakeel Butt , Andrew Morton , Andrii Nakryiko , Eduard Zingerman , Ihor Solodrai , Alexei Starovoitov , Daniel Borkmann , Kumar Kartikeya Dwivedi , Martin KaFai Lau , Song Liu , Yonghong Song , Jiri Olsa , Emil Tsalapatis , Shuah Khan , Barry Song , Geliang Tang , linux-kernel@vger.kernel.org, bpf@vger.kernel.org, linux-mm@kvack.org, linux-kselftest@vger.kernel.org Cc: Hui Zhu Subject: [PATCH bpf-next v5 2/2] selftests/bpf: Add memcg async reclaim test Date: Thu, 27 Aug 2026 18:36:30 +0800 Message-ID: X-Mailer: git-send-email 2.53.0 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Hui Zhu Add the memcg_async_reclaim selftest, which verifies that BPF-driven async proactive reclaim mitigates refault-induced slowdown under memory pressure: a BPF program monitors the refault stats of a memory-pressured cgroup and, once they grow, asynchronously reclaims another cgroup via bpf_wq and bpf_proactive_reclaim(), letting the pressured workload finish faster. Signed-off-by: Hui Zhu --- .../bpf/prog_tests/memcg_async_reclaim.c | 480 ++++++++++++++++++ .../selftests/bpf/progs/memcg_async_reclaim.c | 181 +++++++ 2 files changed, 661 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/memcg_async_recl= aim.c create mode 100644 tools/testing/selftests/bpf/progs/memcg_async_reclaim.c 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 000000000000..1270d73c9116 --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/memcg_async_reclaim.c @@ -0,0 +1,480 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Memory controller eBPF async reclaim test + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cgroup_helpers.h" + +struct bpf_args { + u64 high_cgroup_id; + u64 low_cgroup_id; + u64 event_delta_threshold; + u64 check_ns; +}; + +#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 CHECK_PERIOD_NS (2 * 1000 * 1000ull) +#define EVENT_DELTA_THRESHOLD 1 + +/* + * 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. Fall back to the current directory + * when /tmp is backed by such a filesystem. + */ +static const char *workload_files_dir(void) +{ + struct statfs st; + + if (!statfs("/tmp", &st) && + (st.f_type =3D=3D TMPFS_MAGIC || st.f_type =3D=3D RAMFS_MAGIC)) + return "."; + return "/tmp"; +} + +/* + * The workload children run after test_progs hijacked stdio, so + * anything they print is lost with their private copy of the hijacked + * buffer. The exit status is the only diagnostics channel that reaches + * the parent, so each failing step gets its own code. + */ +enum child_exit_code { + CHILD_EXIT_OK =3D 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 =3D setup_cgroup_environment(); + if (!ASSERT_OK(ret, "setup_cgroup_environment")) + goto cleanup; + + ret =3D create_and_get_cgroup(CG_DIR); + if (!ASSERT_GE(ret, 0, "create_and_get_cgroup " CG_DIR)) + goto cleanup; + close(ret); + + ret =3D enable_controllers(CG_DIR, "memory"); + if (!ASSERT_OK(ret, "enable_controllers")) + goto cleanup; + + snprintf(limit_buf, sizeof(limit_buf), "%lu", CG_LIMIT); + ret =3D write_cgroup_file(CG_DIR, "memory.max", limit_buf); + if (!ASSERT_OK(ret, "write_cgroup_file memory.max")) + goto cleanup; + + /* + * Keep the workloads from swapping out. With CONFIG_SWAP=3Dn the + * memory.swap.max file does not exist, and no swap can happen + * anyway, so skip the write. + */ + if (!access("/proc/swaps", F_OK)) { + ret =3D write_cgroup_file(CG_DIR, "memory.swap.max", "0"); + if (!ASSERT_OK(ret, "write_cgroup_file memory.swap.max")) + goto cleanup; + } + + ret =3D 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 =3D get_cgroup_id(CG_HIGH_DIR); + if (!ASSERT_GT(*high_cgroup_id, 0, "get_cgroup_id")) + goto cleanup; + + ret =3D 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 =3D 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; +} + +static int write_file(const char *filename) +{ + int ret =3D -1; + size_t written =3D 0; + char *buffer; + FILE *fp; + + fp =3D fopen(filename, "wb"); + if (!fp) + goto out; + + buffer =3D malloc(BUFFER_SIZE); + if (!buffer) + goto cleanup_fp; + + memset(buffer, 'A', BUFFER_SIZE); + + while (written < FILE_SIZE) { + size_t to_write =3D FILE_SIZE - written < BUFFER_SIZE ? + FILE_SIZE - written : BUFFER_SIZE; + + if (fwrite(buffer, 1, to_write, fp) !=3D to_write) + goto cleanup; + written +=3D to_write; + } + + ret =3D 0; +cleanup: + free(buffer); +cleanup_fp: + fclose(fp); +out: + return ret; +} + +static int read_file(const char *filename, int iterations) +{ + int ret =3D -1; + long page_size =3D sysconf(_SC_PAGESIZE); + char *map; + size_t i; + int fd; + struct stat sb; + + fd =3D open(filename, O_RDONLY); + if (fd =3D=3D -1) + goto out; + + if (fstat(fd, &sb) =3D=3D -1) + goto cleanup_fd; + + if (sb.st_size !=3D FILE_SIZE) { + fprintf(stderr, "File size mismatch: expected %lu, got %lu\n", + (unsigned long)FILE_SIZE, (unsigned long)sb.st_size); + goto cleanup_fd; + } + + map =3D mmap(NULL, FILE_SIZE, PROT_READ, MAP_PRIVATE, fd, 0); + if (map =3D=3D MAP_FAILED) + goto cleanup_fd; + + for (int iter =3D 0; iter < iterations; iter++) { + for (i =3D 0; i < FILE_SIZE; i +=3D page_size) { + /* access a byte to trigger page fault */ + volatile char v =3D map[i]; + (void)v; + } + } + + if (munmap(map, FILE_SIZE) =3D=3D -1) + goto cleanup_fd; + + ret =3D 0; + +cleanup_fd: + close(fd); +out: + return ret; +} + +static int real_test_child_work(const char *cgroup_path, char *data_filena= me, + char *time_filename, int read_times) +{ + struct timespec start, end; + double elapsed; + FILE *fp; + + if (join_parent_cgroup(cgroup_path)) + return CHILD_EXIT_JOIN_CGROUP; + + clock_gettime(CLOCK_MONOTONIC, &start); + + if (write_file(data_filename)) + return CHILD_EXIT_WRITE_FILE; + + if (read_file(data_filename, read_times)) + return CHILD_EXIT_READ_FILE; + + clock_gettime(CLOCK_MONOTONIC, &end); + + if (!time_filename) + return CHILD_EXIT_OK; + + elapsed =3D (end.tv_sec - start.tv_sec) + + (end.tv_nsec - start.tv_nsec) / 1000000000.0; + printf("%.6f\n", elapsed); + + fp =3D fopen(time_filename, "w"); + if (!fp) + return CHILD_EXIT_TIME_FILE; + fprintf(fp, "%.6f", elapsed); + fclose(fp); + + return CHILD_EXIT_OK; +} + +static int get_time(char *time_filename, double *time) +{ + int ret =3D -1; + FILE *fp; + char buf[64]; + + fp =3D fopen(time_filename, "r"); + if (!ASSERT_OK_PTR(fp, "fopen")) + goto out; + + if (!ASSERT_OK_PTR(fgets(buf, sizeof(buf), fp), "fgets")) + goto cleanup; + + if (sscanf(buf, "%lf", time) !=3D 1) { + PRINT_FAIL("sscanf %s", buf); + goto cleanup; + } + + ret =3D 0; +cleanup: + fclose(fp); +out: + return ret; +} + +static int +run_high_low_workload(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]; + const char *dir =3D workload_files_dir(); + pid_t high_pid =3D -1, low_pid =3D -1; + pid_t wait_ret; + int fd, status; + int ret =3D -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); + + fd =3D mkstemp(high_data_file); + if (!ASSERT_GE(fd, 0, "mkstemp")) + goto cleanup; + close(fd); + + fd =3D mkstemp(low_data_file); + if (!ASSERT_GE(fd, 0, "mkstemp")) + goto cleanup; + close(fd); + + fd =3D mkstemp(high_time_file); + if (!ASSERT_GE(fd, 0, "mkstemp")) + goto cleanup; + close(fd); + + fd =3D mkstemp(low_time_file); + if (!ASSERT_GE(fd, 0, "mkstemp")) + goto cleanup; + close(fd); + + low_pid =3D fork(); + if (!ASSERT_GE(low_pid, 0, "fork low")) + goto cleanup; + if (low_pid =3D=3D 0) + _exit(real_test_child_work(CG_LOW_DIR, low_data_file, + low_time_file, read_times)); + + high_pid =3D fork(); + if (!ASSERT_GE(high_pid, 0, "fork high")) + goto cleanup; + if (high_pid =3D=3D 0) + _exit(real_test_child_work(CG_HIGH_DIR, high_data_file, + high_time_file, read_times)); + + wait_ret =3D 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 =3D -1; + if (!ASSERT_TRUE(WIFEXITED(status), "low exited")) + goto cleanup; + if (WEXITSTATUS(status) !=3D CHILD_EXIT_OK) { + PRINT_FAIL("low child failed at: %s (exit status %d)", + child_exit_str(WEXITSTATUS(status)), + WEXITSTATUS(status)); + goto cleanup; + } + + wait_ret =3D 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 =3D -1; + if (!ASSERT_TRUE(WIFEXITED(status), "high exited")) + goto cleanup; + if (WEXITSTATUS(status) !=3D 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_file, high_elapsed)) + goto cleanup; + if (get_time(low_time_file, low_elapsed)) + goto cleanup; + + ret =3D 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); + } + } + 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 =3D { + .high_cgroup_id =3D high_cgroup_id, + .low_cgroup_id =3D low_cgroup_id, + .event_delta_threshold =3D EVENT_DELTA_THRESHOLD, + .check_ns =3D CHECK_PERIOD_NS, + }; + LIBBPF_OPTS(bpf_test_run_opts, run_opts, + .ctx_in =3D &args, + .ctx_size_in =3D sizeof(args)); + int prog_init_fd, err; + + skel =3D memcg_async_reclaim__open_and_load(); + if (!ASSERT_OK_PTR(skel, "memcg_async_reclaim__open_and_load")) + return -1; + + prog_init_fd =3D bpf_program__fd(skel->progs.wq_prog_init); + + err =3D 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 =3D skel; + return 0; + +error_out: + memcg_async_reclaim__destroy(skel); + return -1; +} + +void test_memcg_async_reclaim(void) +{ + u64 high_cgroup_id, low_cgroup_id; + int err; + double high_time =3D 0.0, low_time =3D 0.0; + struct memcg_async_reclaim *skel =3D NULL; + + err =3D setup_high_low_cgroups(&high_cgroup_id, &low_cgroup_id); + if (!ASSERT_OK(err, "setup_high_low_cgroups reclaim")) + return; + + err =3D setup_bpf(high_cgroup_id, low_cgroup_id, &skel); + if (!ASSERT_OK(err, "setup_bpf")) + goto out; + + err =3D run_high_low_workload(&high_time, &low_time, READ_TIMES); + if (!ASSERT_OK(err, "run_high_low_workload reclaim")) + goto out; + + /* + * The timing comparison below 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")) + goto out; + if (!ASSERT_GT(skel->bss->reclaimed_bytes, 0, "reclaimed_bytes")) + goto out; + + if (high_time >=3D low_time) + PRINT_FAIL("high cgroup not improved: high=3D%f low=3D%f", + high_time, low_time); + +out: + if (skel) + memcg_async_reclaim__destroy(skel); + cleanup_cgroup_environment(); +} diff --git a/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c b/tool= s/testing/selftests/bpf/progs/memcg_async_reclaim.c new file mode 100644 index 000000000000..b2ca5185150f --- /dev/null +++ b/tools/testing/selftests/bpf/progs/memcg_async_reclaim.c @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" +#include "bpf_experimental.h" +#include +#include +#include + +#define CLOCK_MONOTONIC_ID 1 +#define PAGE_SIZE 4096UL +#define RECLAIM_SIZE (32 * PAGE_SIZE) +#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; + +static int get_cgroup_memcg_from_id(u64 cgroup_id, struct cgroup_memcg *cm) +{ + cm->cgrp =3D bpf_cgroup_from_id(cgroup_id); + if (!cm->cgrp) + return -1; + + cm->memcg =3D 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 =3D 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_thre= shold) +{ + u64 cur, delta; + + if (get_cgroup_event(cgroup_id, &cur)) + return false; + + delta =3D cur - *prev_event; + *prev_event =3D cur; + + return delta >=3D event_delta_threshold; +} + +static int reclaim_cgroup(u64 cgroup_id) +{ + struct cgroup_memcg cm; + int i; + + if (get_cgroup_memcg_from_id(cgroup_id, &cm)) + return 0; + + reclaim_calls++; + for (i =3D 0; i < RECLAIM_MAX_ITER; i++) { + u64 nr =3D bpf_proactive_reclaim(cm.memcg, RECLAIM_SIZE); + + if (!nr) + break; + reclaimed_bytes +=3D nr; + } + + put_cgroup_memcg(&cm); + + return 0; +} + +struct wq_elem { + struct bpf_timer timer; + struct bpf_wq work; + u64 prev_event; + u64 event_delta_threshold; + u64 check_ns; +}; + +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 =3D value; + + if (should_reclaim_cgroup(wq_high_cgroup_id, &elem->prev_event, + elem->event_delta_threshold)) { + reclaim_cgroup(wq_low_cgroup_id); + bpf_wq_start(&elem->work, 0); + } + + return 0; +} + +static int wq_timer_cb(void *map, int *key, struct wq_elem *elem) +{ + bpf_wq_start(&elem->work, 0); + bpf_timer_start(&elem->timer, elem->check_ns, 0); + + return 0; +} + +SEC("syscall") +int wq_prog_init(struct bpf_args *ctx) +{ + struct wq_elem *elem; + __u32 key =3D 0; + int ret; + + elem =3D bpf_map_lookup_elem(&wq_map, &key); + if (!elem) + return -1; + + ret =3D bpf_wq_init(&elem->work, &wq_map, 0); + if (ret) + return ret; + + ret =3D bpf_wq_set_callback(&elem->work, reclaim_work_fn, 0); + if (ret) + return ret; + + ret =3D bpf_timer_init(&elem->timer, &wq_map, CLOCK_MONOTONIC_ID); + if (ret) + return ret; + + ret =3D bpf_timer_set_callback(&elem->timer, wq_timer_cb); + if (ret) + return ret; + + elem->prev_event =3D 0; + elem->event_delta_threshold =3D ctx->event_delta_threshold; + elem->check_ns =3D ctx->check_ns; + + wq_high_cgroup_id =3D ctx->high_cgroup_id; + wq_low_cgroup_id =3D ctx->low_cgroup_id; + + return bpf_timer_start(&elem->timer, elem->check_ns, 0); +} + +char _license[] SEC("license") =3D "GPL"; --=20 2.53.0