From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.subspace.kernel.org (Postfix) with ESMTP id 488EE606A68D for ; Wed, 2 Dec 2026 21:04:51 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=U71prdl4 Received: by kanga.kvack.org (Postfix) id 5B64A6B05B6; Wed, 2 Dec 2026 16:04:32 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 5664F6B05B7; Wed, 2 Dec 2026 16:04:32 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 4069A6B05B8; Wed, 2 Dec 2026 16:04:32 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id B5C6E6B05B6 for ; Wed, 2 Dec 2026 16:04:31 -0500 (EST) Received: from smtpin12.hostedemail.com (lb01a-stub [10.200.18.249]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 1201CA7FE3 for ; Wed, 2 Dec 2026 21:04:31 +0000 (UTC) X-FDA: 85500271542.12.0F1A201 Received: from mail-oi1-f197.google.com (mail-oi1-f197.google.com [209.85.167.197]) by imf24.hostedemail.com (Postfix) with ESMTP id 3F7FD180014 for ; Wed, 2 Dec 2026 21:04:29 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=google.com header.s=20260707 header.b=U71prdl4; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf24.hostedemail.com: domain of 324cQawcKCIwrwq7t43w44w1u.s421y3AD-220Bqs0.47w@flex--bgardon.bounces.google.com designates 209.85.167.197 as permitted sender) smtp.mailfrom=324cQawcKCIwrwq7t43w44w1u.s421y3AD-220Bqs0.47w@flex--bgardon.bounces.google.com ARC-Seal: i=1; a=rsa-sha256; d=hostedemail.com; s=arc-20220608; cv=none; t=1796245469; b=O6gxiWP6xArvqRvIrraKhQTpMxhPT/LQRHFGq3vTKo3Q3NC9oqgPGt7WSN69GGUMgEjawX pe3urna3eZPDCqmdu7UJIZCYaCXVMiG73N8629LSqV9CVWNLD1BYA60JqVWnXxaxmCaTG8 v4nWQi5O8cQlxkKqudrxSTAE8d++kgo= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1796245469; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=+ABtbUfwyWryMJDCytDAGqSieAyTXNhJBg+FBk/e/YI=; b=5i5tEgQBIvx0H2StnFHDXePZZ06MZoTeSlpm7eL7NKguSCrHPu/i4Lw7cYiAkKwJbj7w7I VnP3/ofq3a3RjWMhEvlb3CZYYmaIrYqNFxkPwhu96Ke+AmZtrBQCWISXwdCGWSUnErEF1x PqTRwN/19DCf19FF7yFzY55ECZECA74= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=google.com header.s=20260707 header.b=U71prdl4; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf24.hostedemail.com: domain of 324cQawcKCIwrwq7t43w44w1u.s421y3AD-220Bqs0.47w@flex--bgardon.bounces.google.com designates 209.85.167.197 as permitted sender) smtp.mailfrom=324cQawcKCIwrwq7t43w44w1u.s421y3AD-220Bqs0.47w@flex--bgardon.bounces.google.com Received: by mail-oi1-f197.google.com with SMTP id 5614622812f47-4c7f887ac6bso22876989b6e.3 for ; Wed, 02 Dec 2026 13:04:29 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1796245468; x=1796850268; darn=kvack.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=+ABtbUfwyWryMJDCytDAGqSieAyTXNhJBg+FBk/e/YI=; b=U71prdl4ZJkq6uWYxw8C7OPKhImPy17Sk+XUtqwfBfCobmbvH9lhqHlDh6Fi1kAyWV 3fV7THZHjRsnq5wUNA5Knn15zusbfoouGB/yCLpPXIBCPKRENdKnrWPtjc8zZ/Gv3+yN MWyTkubROY1HmzEqiLyN9Rowtv/nAVOQvSX0VPytBqp9UQk/UbEchsLZbf+x4QkpKKYh FijsE4E0HNjy5GYTw69U2tWD6mP91qQxvywzwKuRvbcaNDgN84aV9mkMA93tzqMU77CG FkdLPlsGDmPdc6uQT7lJruZcug1r8NvJ3LNGtAvzgqP6EBKYtVI2UT5ungBOy6Nra4c/ FJiw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796245468; x=1796850268; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=+ABtbUfwyWryMJDCytDAGqSieAyTXNhJBg+FBk/e/YI=; b=BZfsbF0wR1N10YLSXIYeg/9B6ulrSXKFKf/dhbQOPmXfgpl0jQoQkWXF5EgggMRIeo Fw0g5L5zVsCpl2FqMQ9+S6pfRVTrN4tSB62Ivb5nm8YF/PRYseFFWSRslkNBl8dPs+5u 1S7ahjxVMkvQbumx2D21R92xAOLD/E92ImHC6cf2cgmg6urjsl6qeqji9vsQzHqYU9P1 Ko+YWeL14dW1dzwo7fd6Ge1mvc8f2mKngHuykg+XU6tq4pgAJL+MzobFFwyEGh1Mk5sr uc72hmxRVCPrtVkwBzxpKWYumbgg28wtUydNCMx6Tz9oanfe/7ncZM/IDV1zyyntlZBT XIxQ== X-Forwarded-Encrypted: i=1; AL+hErFJC8+TUwLxKaHQsOYXjd72WOyYVW3gZDG73vYGWkwZwq1QUobnPmegkA2aPx0NYFqRymXDk7AvAA==@kvack.org X-Gm-Message-State: APuU4Z8G37dDPXU91QWs6w1pKZ9DuxwBHzPdrIThToU0INXDJaYTWqeW H+Y538Bb49DzVUmy4v2e/dnX7EozEer8ENRWWBrUqnjbJV9W61+t+TxUOjc05PMqPWsrX05StM9 vqidqf0EM2A== X-Received: from iojj12.prod.google.com ([2002:a05:6602:820c:b0:9c7:7732:c3c1]) (user=bgardon job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6808:e90:b0:568:d66f:6327 with SMTP id 5614622812f47-57a0b44ef0bmr40073969b6e.51.1796245467884; Wed, 02 Dec 2026 13:04:27 -0800 (PST) Date: Wed, 2 Dec 2026 13:03:55 -0800 In-Reply-To: <20261202210415.517651-1-bgardon@google.com> X-Archived-By: Mime-Version: 1.0 References: <20261202210415.517651-1-bgardon@google.com> X-Mailer: git-send-email 2.56.1.911.g883d8bcb20-goog Message-ID: <20261202210415.517651-6-bgardon@google.com> Subject: [PATCH bpf-next v4 05/17] selftests/bpf: Add BPF OOM struct ops test From: Ben Gardon To: Alexei Starovoitov , Daniel Borkmann , Andrii Nakryiko , Andrew Morton , Johannes Weiner , Michal Hocko , Shakeel Butt , Roman Gushchin , Tejun Heo Cc: JP Kobryn , Eduard Zingerman , Kumar Kartikeya Dwivedi , Martin KaFai Lau , Song Liu , Yonghong Song , Jiri Olsa , Emil Tsalapatis , Ihor Solodrai , David Rientjes , Suren Baghdasaryan , Josh Don , Sweet Tea Dorminy , Chuyi Zhou , Yafang Shao , benbwgardon@gmail.com, bpf@vger.kernel.org, linux-mm@kvack.org, cgroups@vger.kernel.org, linux-kernel@vger.kernel.org, Ben Gardon , Shuah Khan , linux-kselftest@vger.kernel.org Content-Type: text/plain; charset="UTF-8" X-Stat-Signature: 3x35pjka47qm5asz6zf4mbcady6mn3yd X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 3F7FD180014 X-Rspam-User: X-Spam-Status: No, score=-26.3 required=3.0 tests=BAYES_00,DKIMWL_WL_MED, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,HEADER_FROM_DIFFERENT_DOMAINS, INCLUDES_CR_TRAILER,INCLUDES_PATCH,MAILING_LIST_MULTI,SPF_HELO_PASS, SPF_PASS,USER_AGENT_GIT,USER_IN_DEF_DKIM_WL autolearn=ham autolearn_force=no version=4.0.1 X-HE-Tag: 1796245469-849557 X-HE-Meta: U2FsdGVkX1/cSk88qG3U1Es8v+yr1/p1lOmiWIKuTEqYdGGSqrdpH3lZrrNF185VPxBC+gGCkG/B8OGe8ZuJVJEikc6dySd8E+POiKROmkndCu3MFG4iMzgYuk+P0K2fDzS3khGEZd5ngm6rxP0W7Y2+5IvfxbbPrguIfNZLGBqUSuE0Jqy0WKJCTsEn9xJStqZ4tCJ4lCvbYqcT7p18tIUcqsC/aGj0SpVKRe81fkLRN6XzZQz/xv3lySDIXZuCMzSFdeVAZqjdMO18igEUmvx3Q6XcyTLsAS5nkpv1eaIVSqdnMVVI1HzYSBLSHjljX9fuOiUGK/LQY2BmUzqqPXDrLYTP4MSg9lB7kGKQyp1XiwxtEL0UZwquCssn1XFxMNcQ84YgHKTAJQgFP3pB6hMrk8efrIPZJlQXQOWNlFc6DzcQSatiKkfqIFpnwYq84A3OUgMQsIxfbdkaKTpnadi6WxZxHvSKifvBL1VotoyO7mex0SzBctlt1fgga072Kgkftm6lEp5IbmVEQcQPmH+2HS+pAy25VE3RYxI1hXVv6pyXp9qwLewqQ6rALnG2OTzDHHwp6PodpoOLe9viRBfv5IzmLea2gFPsZGLlwAD059uL+In85OSnybEIdyOoizKEOJdkPxsg2QGM9zSsgdMjjaoXAek02KhWhPTOsUSHCMhcHqwOq8iFmhwB8C3EySMxam1rIFDLM9c1WCXJASMxGkaBfXzAAxflhkax5aDLS6lEdKw9Kd6sliVKiHn7gZjb9BVQ3snSEA1wrsDd3L5FUf6PqExBYeXPO50Ok40zVM+XV4E8vEoWpCx/sXPduqrVLpmPRRaT68rNTtMVCfXz6DDGXKPG2dXVEkefcZAX5hVW3FqDzuEBQy2XMKybnRknM+6LeQxV5ORVmx22+ElapXjSsRGbuC8zihZRFHpSBBy81vywl+Y+UlcKM4jKpo/ThvquAXFRuQwseZ4 wLszEqb7 9zj4DCgYz3LoIj77quY7CAE+vbC6bAQXDNpafn1y8EAkRyEY8zl/kidG1EOjvNDFzMNZsOx6k8YS7KSvMOiWPR0rKYZtKuwB/9RDfwYHwMuBIWY/KKU8jRynkv3G6EjtoPHY9Ioq1/Kjvaf6XRjsPX7bIYtVCC+9S/B5ntKdil4hMIMlCiE4CTDZu/T6VRj4ma3BiDU2xLMrJzWdruvQ+A29t01oBMJ8erg3UonPhnk9hKWVmpEAZpKpCA6iVBkA1dWnDviybxDjID8mDvLuXjCt/3TZ5N30Q+ZqEWcUzlKQ94yjtSZAfqS9yIF/kUplfZp2Zh0uu9zHJn2EwirNQOMMmeOsucGTKtnh3U3etmRV+GRK/UVC7bf4hlMLgNiyKv9XU4ViANlnE+poSAVwRrGRMlFk9pXDvHLn2XLfFKAFL5Hat/8HPBsT3vl4U/3UA73ZqVlPVOw2eWY8FYsl+YubbGS1S13Zv1dUS6E03mfciJUr9tniaIj6Kfo6OODVPhwcR4nE9kvSSYL9SWP3p5M515QLxNYiaFIhoxUEDEDxaFHVlYuj9/2J24pFD/jCx336TMGyN73+XFf6crZbv2BYExMc4rlYhXNUFLXt8OpmgAvbdXJtUntAJT2ftoi/wMpit43+BatHyP6Up2S5JAN234A518JB8bJIfwTh/cD2MCXdAeUgIm9X9zKDDk9LoJEI8/pc8NSwf+cST4yRLaFdZbgowS/2YN8qXvUoeBk524pEKx8AWoHfHo5Tn5wproeUVKbpKyl3DQVzzQRZZ1o8rUtJN3GRpB8KHZnP56Q1SHi3g4di3Bt/aGb2hgt6eXW1Ry/Uk3GHIg7zrixdD0yzvT1j5ZeQnDKZfMs+VBbIIzB1J2DatO47DdtS61TqS87oyeHPyQqY1Z9D/7fAkHBVpvZ2flvnfpb6vwR1WsxZviS0= Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: X-Spam-Checker-Version: SpamAssassin 4.0.1 (2024-03-26) on aws-us-west-2-korg-listserv-alma10-1 From: Roman Gushchin Implement a kselftest for the OOM handling functionality. This BPF OOM policy terminates all tasks belonging to the largest leaf cgroup (excluding page cache) that contains no exempt tasks (oom_score_adj set to -1000). The test: 1. builds a hierarchy of memory cgroups 2. pre-allocates baseline memory, below memory.max 3. triggers an OOM from the largest eligible leaf 4. verifies that the expected process is selected and terminated with SIGKILL 5. checks the chosen memcg's memory.events oom_kill counter to validate Attaching the same policy to both the subtree root (where it returns 0) and the root cgroup verifies hierarchical delegation. Signed-off-by: Roman Gushchin Co-developed-by: Ben Gardon Signed-off-by: Ben Gardon --- v3 -> v4: - Adopted bpf_map__attach_cgroup_opts() and CO-RE task->signal->oom_mm. - Replaced cgroup freezing with pipes to synchronize with workers so multi-CPU runs cannot flake. - Renamed to serial_test_oom() to avoid root-cgroup collisions under test_progs -j. - Scanned the full subtree for in-flight oom_mm, passed acquired task reference to bpf_oom_kill_process(), and checked its return value. v3: https://lore.kernel.org/all/20260127024421.494929-13-roman.gushchin@linux.dev/ .../selftests/bpf/prog_tests/memory_holder.h | 158 +++++++++++++ .../selftests/bpf/prog_tests/test_oom.c | 218 ++++++++++++++++++ tools/testing/selftests/bpf/progs/test_oom.c | 132 +++++++++++ 3 files changed, 508 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/memory_holder.h create mode 100644 tools/testing/selftests/bpf/prog_tests/test_oom.c create mode 100644 tools/testing/selftests/bpf/progs/test_oom.c diff --git a/tools/testing/selftests/bpf/prog_tests/memory_holder.h b/tools/testing/selftests/bpf/prog_tests/memory_holder.h new file mode 100644 index 000000000000..34b408da3958 --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/memory_holder.h @@ -0,0 +1,158 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __MEMORY_HOLDER_H +#define __MEMORY_HOLDER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +struct memory_holder { + pid_t pid; + int start_fd; + int done_fd; +}; + +static inline void memory_holder_init(struct memory_holder *w) +{ + w->pid = -1; + w->start_fd = -1; + w->done_fd = -1; +} + +static inline void memory_holder_cleanup(struct memory_holder *w) +{ + if (w->start_fd >= 0) { + close(w->start_fd); + w->start_fd = -1; + } + if (w->done_fd >= 0) { + close(w->done_fd); + w->done_fd = -1; + } + if (w->pid > 0) { + kill(w->pid, SIGKILL); + waitpid(w->pid, NULL, 0); + w->pid = -1; + } +} + +/* + * Fork a child that sets /proc/self/oom_score_adj, waits for a byte on + * start_fd (after the parent places it into a cgroup), faults in @target + * bytes of anonymous memory (in @chunk-byte chunks if @chunk > 0), writes a + * byte to done_fd, and either exits (if @exit_after_alloc is true) or sleeps + * until killed. + */ +static inline int memory_holder_spawn(struct memory_holder *w, size_t target, + size_t chunk, int oom_score_adj, + bool exit_after_alloc) +{ + int start_pipe[2] = { -1, -1 }; + int done_pipe[2] = { -1, -1 }; + int ret = 0; + pid_t pid; + char c; + + memory_holder_init(w); + + if (pipe(start_pipe) < 0) + return -errno; + if (pipe(done_pipe) < 0) { + ret = -errno; + goto err_pipes; + } + + pid = fork(); + if (pid < 0) { + ret = -errno; + goto err_pipes; + } + + if (pid > 0) { + w->pid = pid; + w->start_fd = start_pipe[1]; + w->done_fd = done_pipe[0]; + close(start_pipe[0]); + close(done_pipe[1]); + return 0; + } + + close(start_pipe[1]); + close(done_pipe[0]); + + { + char buf[8]; + int fd = open("/proc/self/oom_score_adj", O_WRONLY); + + if (fd < 0) + _exit(1); + snprintf(buf, sizeof(buf), "%d", oom_score_adj); + if (write(fd, buf, strlen(buf)) < 0) + _exit(1); + close(fd); + } + + /* Wait for parent to place us in the target cgroup and release us */ + if (read(start_pipe[0], &c, 1) != 1) + _exit(1); + close(start_pipe[0]); + + if (target) { + size_t step = chunk ?: target; + size_t done = 0; + + while (done < target) { + size_t sz = target - done < step ? target - done : step; + char *ptr = malloc(sz); + + if (!ptr) + _exit(ENOMEM); + memset(ptr, 'a', sz); + /* Prevent -O2 dead-store elimination before _exit() */ + asm volatile("" : : "r"(ptr) : "memory"); + done += sz; + } + } + + if (write(done_pipe[1], "d", 1) != 1) + _exit(1); + close(done_pipe[1]); + + if (exit_after_alloc) + _exit(0); + + for (;;) + sleep(1000); + +err_pipes: + if (start_pipe[0] >= 0) + close(start_pipe[0]); + if (start_pipe[1] >= 0) + close(start_pipe[1]); + if (done_pipe[0] >= 0) + close(done_pipe[0]); + if (done_pipe[1] >= 0) + close(done_pipe[1]); + return ret; +} + +static inline int memory_holder_start(struct memory_holder *w) +{ + return write(w->start_fd, "g", 1) == 1 ? 0 : -EIO; +} + +static inline int memory_holder_wait_ready(struct memory_holder *w) +{ + char c; + + return read(w->done_fd, &c, 1) == 1 ? 0 : -EIO; +} + +#endif /* __MEMORY_HOLDER_H */ diff --git a/tools/testing/selftests/bpf/prog_tests/test_oom.c b/tools/testing/selftests/bpf/prog_tests/test_oom.c new file mode 100644 index 000000000000..f17742ace1ce --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/test_oom.c @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include + +#include "cgroup_helpers.h" +#include "memory_holder.h" + +#define MB (1024UL * 1024UL) +#include "test_oom.skel.h" + +#define OOM_SCORE_ADJ_MIN (-1000) +#define OOM_SCORE_ADJ_MAX 1000 + +struct cgroup_desc { + const char *path; + int fd; + struct memory_holder worker; + size_t target; + size_t max; + int oom_score_adj; + bool expect_terminated; +}; + +/* + * Baseline workers (cg1 10 MB + cg2 35 MB + cg5 10 MB = 55 MB) allocate first + * and wait under the 80 MB limit. Then cg4 (35 MB) allocates and crosses 80 MB + * at ~25 MB, triggering a single deterministic OOM where cg2 (35 MB) is exempt + * via OOM_SCORE_ADJ_MIN and cg4 (~25 MB) is the largest eligible leaf. + */ +static struct cgroup_desc cgroups[] = { + { .path = "/oom_test", .max = 80 * MB }, + { .path = "/oom_test/cg1", .target = 10 * MB, + .oom_score_adj = OOM_SCORE_ADJ_MAX }, + { .path = "/oom_test/cg2", .target = 35 * MB, + .oom_score_adj = OOM_SCORE_ADJ_MIN }, + { .path = "/oom_test/cg3" }, + { .path = "/oom_test/cg3/cg4", .target = 35 * MB, + .expect_terminated = true }, + { .path = "/oom_test/cg3/cg5", .target = 10 * MB }, +}; + +static void reset_cgroups(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + cgroups[i].fd = -1; + memory_holder_init(&cgroups[i].worker); + } +} + +static void cleanup_workers(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + memory_holder_cleanup(&cgroups[i].worker); + if (cgroups[i].fd >= 0) { + close(cgroups[i].fd); + cgroups[i].fd = -1; + } + } +} + +static int setup_environment(void) +{ + int i, err; + + reset_cgroups(); + + err = setup_cgroup_environment(); + if (!ASSERT_OK(err, "setup_cgroup_environment")) + return -1; + + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + char buf[64]; + + cgroups[i].fd = create_and_get_cgroup(cgroups[i].path); + if (!ASSERT_GE(cgroups[i].fd, 0, "create_and_get_cgroup")) + return -1; + + if (cgroups[i].target == 0) { + err = write_cgroup_file(cgroups[i].path, + "cgroup.subtree_control", + "+memory"); + if (!ASSERT_OK(err, "enable memory controller")) + return -1; + } + + if (cgroups[i].max) { + snprintf(buf, sizeof(buf), "%zu", cgroups[i].max); + err = write_cgroup_file(cgroups[i].path, "memory.max", + buf); + if (!ASSERT_OK(err, "set memory.max")) + return -1; + write_cgroup_file(cgroups[i].path, "memory.swap.max", + "0"); + } + + if (cgroups[i].target) { + err = memory_holder_spawn(&cgroups[i].worker, + cgroups[i].target, 0, + cgroups[i].oom_score_adj, + cgroups[i].expect_terminated); + if (!ASSERT_OK(err, "spawn worker")) + return -1; + + snprintf(buf, sizeof(buf), "%d", cgroups[i].worker.pid); + err = write_cgroup_file(cgroups[i].path, "cgroup.procs", + buf); + if (!ASSERT_OK(err, "put child into cgroup")) + return -1; + } + } + + /* Pre-allocate all non-trigger baseline workers under memory.max */ + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (!cgroups[i].target || cgroups[i].expect_terminated) + continue; + + if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker), + "start baseline worker")) + return -1; + if (!ASSERT_OK(memory_holder_wait_ready(&cgroups[i].worker), + "wait baseline worker")) + return -1; + } + + return 0; +} + +/* + * Serialized because this test attaches a BPF OOM policy to the root cgroup + * and triggers real memcg OOMs, which would collide with other OOM tests + * running in parallel under test_progs -j. + */ +void serial_test_oom(void) +{ + LIBBPF_OPTS(bpf_cgroup_opts, opts); + struct bpf_link *cgroup_link = NULL, *root_link = NULL; + struct test_oom *skel = NULL; + int root_cg_fd = -1, status = 0, i; + char buf[4096] = {}; + + if (setup_environment()) + goto cleanup; + + skel = test_oom__open_and_load(); + if (!ASSERT_OK_PTR(skel, "open_and_load")) + goto cleanup; + + /* + * Attach to both /oom_test (which returns 0) and root (which handles + * the OOM) to exercise hierarchical delegation. + */ + cgroup_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom, + cgroups[0].fd, &opts); + if (!ASSERT_OK_PTR(cgroup_link, "attach_oom_cgroup")) + goto cleanup; + + root_cg_fd = get_root_cgroup(); + if (!ASSERT_GE(root_cg_fd, 0, "get_root_cgroup")) + goto cleanup; + + root_link = bpf_map__attach_cgroup_opts(skel->maps.test_bpf_oom, + root_cg_fd, &opts); + if (!ASSERT_OK_PTR(root_link, "attach_oom_root")) + goto cleanup; + + /* Release the trigger worker (cg4) to cross memory.max */ + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (!cgroups[i].expect_terminated) + continue; + + if (!ASSERT_OK(memory_holder_start(&cgroups[i].worker), + "start trigger worker")) + goto cleanup; + + if (!ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status, 0), + cgroups[i].worker.pid, "waitpid trigger")) + goto cleanup; + cgroups[i].worker.pid = -1; + + if (!ASSERT_TRUE(WIFSIGNALED(status) && + WTERMSIG(status) == SIGKILL, + "expected process was terminated")) + goto cleanup; + + if (!ASSERT_OK(read_cgroup_file(cgroups[i].path, + "memory.events", + buf, sizeof(buf)), + "read memory.events")) + goto cleanup; + + if (!ASSERT_OK_PTR(strstr(buf, "oom_kill 1"), + "oom_kill count check")) + goto cleanup; + } + + /* Verify all other baseline workers survived */ + for (i = 0; i < ARRAY_SIZE(cgroups); i++) { + if (cgroups[i].worker.pid > 0) + ASSERT_EQ(waitpid(cgroups[i].worker.pid, &status, + WNOHANG), 0, + "non-target worker survived"); + } + +cleanup: + bpf_link__destroy(root_link); + bpf_link__destroy(cgroup_link); + if (root_cg_fd >= 0) + close(root_cg_fd); + cleanup_workers(); + cleanup_cgroup_environment(); + test_oom__destroy(skel); +} diff --git a/tools/testing/selftests/bpf/progs/test_oom.c b/tools/testing/selftests/bpf/progs/test_oom.c new file mode 100644 index 000000000000..a752d332f8b7 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/test_oom.c @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Example BPF OOM policy for selftests (not intended for production use). + * + * Exercises bpf_oom_ops attachment, hierarchical delegation (returning 0 on + * the subtree root and handling on root), and bpf_oom_kill_process() by + * terminating all tasks in the largest eligible leaf cgroup (similar to + * memory.oom.group semantics). + */ +#include "vmlinux.h" +#include +#include +#include + +char _license[] SEC("license") = "GPL"; + +#define OOM_SCORE_ADJ_MIN (-1000) + +static bool mem_cgroup_has_oom_victim(struct mem_cgroup *memcg) +{ + struct task_struct *task; + + bpf_for_each(css_task, task, &memcg->css, CSS_TASK_ITER_PROCS) + if (BPF_CORE_READ(task, signal, oom_mm)) + return true; + + return false; +} + +static bool mem_cgroup_killable(struct mem_cgroup *memcg) +{ + struct task_struct *task; + + bpf_for_each(css_task, task, &memcg->css, CSS_TASK_ITER_PROCS) + if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN) + return false; + + return true; +} + +/* + * Find the largest leaf cgroup (ignoring page cache) without exempt tasks + * and terminate all belonging tasks. + */ +SEC("struct_ops.s/handle_out_of_memory") +int BPF_PROG(test_out_of_memory, struct oom_control *oc, struct cgroup *cgrp) +{ + struct task_struct *task; + struct mem_cgroup *root_memcg = oc->memcg; + struct mem_cgroup *memcg, *chosen = NULL; + struct cgroup_subsys_state *css_pos, *css; + unsigned long usage, max_usage = 0; + unsigned long pagecache = 0; + int ret = 0; + + if (root_memcg) + root_memcg = bpf_get_mem_cgroup(&root_memcg->css); + else + root_memcg = bpf_get_root_mem_cgroup(); + + if (!root_memcg) + return 0; + + css = &root_memcg->css; + if (css && css->cgroup == cgrp) + goto exit; + + bpf_rcu_read_lock(); + bpf_for_each(css, css_pos, &root_memcg->css, BPF_CGROUP_ITER_DESCENDANTS_POST) { + if (css_pos->cgroup->nr_descendants + css_pos->cgroup->nr_dying_descendants) + continue; + + memcg = bpf_get_mem_cgroup(css_pos); + if (!memcg) + continue; + + /* + * If any task in the subtree is already exiting due to OOM, + * back off and let it release memory. + */ + if (mem_cgroup_has_oom_victim(memcg)) { + bpf_put_mem_cgroup(memcg); + ret = 1; + break; + } + + usage = bpf_mem_cgroup_usage(memcg); + pagecache = bpf_mem_cgroup_page_state(memcg, NR_FILE_PAGES); + + if (usage > pagecache) + usage -= pagecache; + else + usage = 0; + + if (usage > max_usage && mem_cgroup_killable(memcg)) { + max_usage = usage; + if (chosen) + bpf_put_mem_cgroup(chosen); + chosen = bpf_get_mem_cgroup(&memcg->css); + } + + bpf_put_mem_cgroup(memcg); + } + bpf_rcu_read_unlock(); + + if (ret || !chosen) + goto put_chosen; + + bpf_for_each(css_task, task, &chosen->css, CSS_TASK_ITER_PROCS) { + struct task_struct *t = bpf_task_acquire(task); + + if (t) { + if (!bpf_oom_kill_process(oc, t, "bpf oom test")) + ret = 1; + bpf_task_release(t); + } + } + +put_chosen: + if (chosen) + bpf_put_mem_cgroup(chosen); +exit: + bpf_put_mem_cgroup(root_memcg); + + return ret; +} + +SEC(".struct_ops.link") +struct bpf_oom_ops test_bpf_oom = { + .name = "bpf_test_policy", + .handle_out_of_memory = (void *)test_out_of_memory, +}; -- 2.56.1.911.g883d8bcb20-goog