From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=pass header.oldest-pass=0 smtp.remote-ip=100.103.45.18 ARC-Seal: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=pass; t=1796139208; b=EEHP76ixdoOIZLRkZnhVZ4bh23lQS6jCM2PqUVd7g0Vqf/xecps4qofU2viiznfxriuY J8iQeHSaDqTVzZwBQ2tXgYRJ621M9WMpnaVwvD3MgN2Ox7a/x4eaSbvHLLPejCgMxuOs+ 9O4WCh1R3u0hokxg0Fq6yo5YWDC7GScxxeJKvHKF+78h65C78s+SvLbMXSzV2J4nTMylA fl98TVerm1oBU3fOPcgGuM9an2JTIohe7i0msHJwxjd7paP8iI0+bzldWSvTDN41pYk9I D3ZojSXhN3Fn/DtSXusA6ZMdi4756qvz+TZlniBMLMXTrPvUkbPm/QWASDnvxePUYcw== ARC-Message-Signature: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796139208; h=Received:DKIM-Signature:Received:From:Date:Subject:MIME-Version: Content-Type:Message-Id:References:In-Reply-To:To:Cc:X-Mailer: X-Developer-Signature:X-Developer-Key:X-Endpoint-Received: X-Original-From:Reply-To:Content-Transfer-Encoding; bh=EtugsUOwhNJfR86XFuupcOV3ntxBQ3/elkLwmQpEOa8=; b=aAi0gNNeQYC0YbfoUID/eDOk82TbOxyFubZYeB+RR4+nTC3wdJJltnqL8lGXoTEAEa9K PBbs7/2eEo+ZTMcKx6XkyptdADGoOFUqtZc/cViOKaUPaIVyykg/kuqLqRcCGOg3Pp9dp 9hoat0Yc7umL+BxVESrPdBC/XiaxbHcu1dJKjSBoANuy7AqXg3N5iEvfsBl7Bm6nybGFG MvynfxlvcdDYqy0Dq+PqqjCOwk3bIHqDGqzmGkZnzL6g2X1o9IDBM6JsLOipwP4wJ9KA+ oemyOt3qS1KUTBAyHk+PuLGJMkJhNFqXdY39mgWKo697C5H3t+UpzuyYxULbJiv6pZA== ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=lFjgOvQ0; arc=pass header.oldest-pass=0 smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1CE77606A327; Tue, 1 Dec 2026 15:33:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=lFjgOvQ0 Authentication-Results: smtp.kernel.org; arc=none smtp.remote-ip=100.80.115.77 ARC-Seal: i=1; d=kernel.org; s=arc20260519; a=rsa-sha256; cv=none; t=1796139207; b=WwmIJeV1nt2I3FxE4CtS4CKF56TUtxciBxg2weFMjxxz2NNMRVPp92bFDeCvrjl6taLA s0irsIl/pPpg9z4yDb/NGeScfWtPVv+Bh22gw2LaPGXsC8CXfKjFSUOewNnXoee0o1bUZ Y4C8HSiOqz+R+UpUrPoBNOt42oeFVizzJsJJYqNUyi9SVEoLNqA/R9LRQAWOWnX5xHVuS vsgCEyo94RkcB0TkdqVgM5DlD4DDhIKt4JID7K6IO2WlzdmYLb5nqZNv77CeQPK7bSPdB 9lsOz4DZU8kR6htFOpJx1p4ydaIQPH2P0+2KhaI9BjgLkLi5KUW3kbqQjOrD6i1FZBA== ARC-Message-Signature: i=1; d=kernel.org; s=arc20260519; a=rsa-sha256; c=relaxed/relaxed; t=1796139207; h=DKIM-Signature:Received:From:Date:Subject:MIME-Version:Content-Type: Message-Id:References:In-Reply-To:To:Cc:X-Mailer: X-Developer-Signature:X-Developer-Key:X-Endpoint-Received: X-Original-From:Reply-To:Content-Transfer-Encoding; bh=EtugsUOwhNJfR86XFuupcOV3ntxBQ3/elkLwmQpEOa8=; b=0OlUWGANYA5hCgcmgrdtlbL3sUn4UqPAm650rnUn93RmfqR1JrVpWGNc5KX4gwpu/OmQ EgIfnn6VOxl40deU8za4IPlIFmF0Uc5dKnmaW9OEd740in9bUwxxethLkH8eq4RcZUfjI oveJeuIklJVY9xoEMxcsGAyiru2yeRm+SpfaucwKOdYZjoAMBGXCaGbqnzL6KhkVA7pLq Eu/n8/HWcsHRf1v+d6dp/IciPOfVA48i7eU5C+7wQ+oBnRfEEzWgpEcpD1uWMhiiHouFK 1uK5J7E8Vd349OXLIeWK7ie6k8b1yt85CHAHQy7XBPRPOf6jnwH0o7nCd9K61mLz0ww== ARC-Authentication-Results: i=1; smtp.kernel.org; arc=none smtp.remote-ip=100.80.115.77 Received: from lkml.kernel.org (nexus.subspace.kernel.org [100.80.115.77]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.kernel.org (Postfix) with ESMTPS id AFF6A1F02832; Tue, 1 Dec 2026 15:33:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1796139207; bh=EtugsUOwhNJfR86XFuupcOV3ntxBQ3/elkLwmQpEOa8=; h=From:Date:Subject:References:In-Reply-To:To:Cc:Reply-To; b=lFjgOvQ0qIoKjm/9Fqzty5nF9aTM+V9L9ncV55dMrC9DN2QqeGGabtKn9mLIpFbwR hHm7+vPMy7pQ4IMeE1NOo97wW6KEBZrtZjvFepnFZr5h6E+nQXxVckPO+VOEvnlfR4 /Ilito2jek+cuU/P1oopguru+s1HeRXmiZPAhH3C19blxHS38s3aaxzUpXaT9HP/Rj stv7c+1feoptEl7AL+GYChy6pE/763b75og/OfyUfHwTKDl3W/JeiQ0/hbxJw66/7B dja220RmI1dkKt9QbRwahCPrMnp941oGJjatMLI/Mr/dANEOlmPphwc4MUxbyeY0VK JTNB9y4E8Yg9w== Received: from nexus.subspace.kernel.org (localhost [IPv6:::1]) by lkml.kernel.org (Postfix) with ESMTP id 373CA4EE84; Tue, 1 Dec 2026 15:32:34 +0000 (UTC) From: Mike Bazov via B4 Relay Date: Tue, 01 Dec 2026 17:32:16 +0200 Subject: [PATCH bpf-next v5 5/5] selftests/bpf: Add preemption recursion test for tracing programs X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Message-Id: <20261201-bpf-preempt-v2-r2-v5-5-a6bb30daae35@sentinelone.com> References: <20261201-bpf-preempt-v2-r2-v5-0-a6bb30daae35@sentinelone.com> In-Reply-To: <20261201-bpf-preempt-v2-r2-v5-0-a6bb30daae35@sentinelone.com> To: bpf@vger.kernel.org, Alexei Starovoitov , Daniel Borkmann , Andrii Nakryiko Cc: Martin KaFai Lau , Eduard Zingerman , Kumar Kartikeya Dwivedi , Song Liu , Yonghong Song , Jiri Olsa , John Fastabend , Emil Tsalapatis , Ihor Solodrai , Steven Rostedt , Masami Hiramatsu , Mathieu Desnoyers , JP Kobryn , linux-trace-kernel@vger.kernel.org, linux-kernel@vger.kernel.org, Mike Bazov X-Mailer: b4 0.13.0 X-Developer-Signature: v=1; a=ed25519-sha256; t=1796139152; l=26570; i=mikeba@sentinelone.com; s=20261022; h=from:subject:message-id; bh=lnLQZnDhqUMpX4mHUXXYWI+MBuIVyWg7xyLIbI6nO5c=; b=tIGfFQXnfeEXvT71wNgF5jazHWhmI7qMx5SOrtKkmzUt2RcMuHkmPSZdhwBxXSezT68p0WCB9 byojcmFusAwCiROltYt/7NkoQVqTWwg8m2+qfo7mj4SUD7eY2CPdcZU X-Developer-Key: i=mikeba@sentinelone.com; a=ed25519; pk=DBXcQ0qoCkgacRsRwT1JU7oOWpWSYuTyLiXMfNLcP+A= X-Endpoint-Received: by B4 Relay for mikeba@sentinelone.com/20261022 with auth_id=1284 X-Original-From: Mike Bazov Reply-To: mikeba@sentinelone.com Content-Transfer-Encoding: 7bit From: Mike Bazov Pin two threads to one CPU. Thread B is SCHED_FIFO and waits for a signal that thread A sends from inside the program under test, so B wakes up while A is inside the program and enters it on the same CPU. The subtests below that use the two threads run 20 rounds each. - fentry, fexit, fmod_ret, fentry_s, raw_tp, raw_tp_s, tp_syscall, may_goto: a program without per-CPU state. B preempts A inside it and runs it too, in every round, without recursion misses. - *_percpu, percpu_var, this_cpu_ptr, smp_processor_id, tail_call: a program with a per-CPU map, a per-CPU variable, bpf_this_cpu_ptr(), bpf_get_smp_processor_id() or a tail call. It runs with preemption disabled: B runs it after A has left, in every round, without recursion misses. The sleepable variants have no protection, so B runs inside them. A constant selects the per-CPU state; with none selected, the same code doesn't mark the program. - two_dispatchers: two raw tracepoint programs tail-call one handler. B runs it after A, and A's stack buffer stays intact. - recursion_raw_tp, recursion_two_hops, recursion_test_run: true recursion is still dropped and counted: directly, through a second program, and from BPF_PROG_TEST_RUN. - timer_cb: a marked program arms a timer on its CPU and stays inside while it fires. The callback hits the program's hook again: that run is dropped and counted instead of starting inside the first one. - ext_attach: an extension that uses a per-CPU map can't be attached to a raw tracepoint program that doesn't, nor to a sleepable one that does, while one without can. Signed-off-by: Mike Bazov --- .../selftests/bpf/prog_tests/trampoline_preempt.c | 383 +++++++++++++++++++++ .../selftests/bpf/progs/trampoline_preempt.c | 382 ++++++++++++++++++++ 2 files changed, 765 insertions(+) diff --git a/tools/testing/selftests/bpf/prog_tests/trampoline_preempt.c b/tools/testing/selftests/bpf/prog_tests/trampoline_preempt.c new file mode 100644 index 000000000000..8708239fed5e --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/trampoline_preempt.c @@ -0,0 +1,383 @@ +// SPDX-License-Identifier: GPL-2.0 +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include "trampoline_preempt.skel.h" + +#define NR_ROUNDS 20 + +/* + * Threads A and B are pinned to one CPU. B is SCHED_FIFO and waits for a signal: + * + * A: prctl() -> enters the program under test + * the program sends B the signal + * B: wakes up and preempts A, which is still inside the program + * prctl() -> enters the same program on the same CPU + * + * A program without per-CPU state runs for B too, while A is preempted inside + * it. A program with per-CPU state runs with preemption disabled: B runs only + * when A has left the program. A sleepable program has to disable preemption + * itself, so B runs inside it too. + */ + +/* The per-CPU state that a program touches, see progs/trampoline_preempt.c */ +enum { NO_PERCPU, PERCPU_MAP, PERCPU_VAR, THIS_CPU_PTR, CPU_ID }; + +enum expect { + B_RUNS, /* B runs the program while A is preempted inside it */ + B_AFTER, /* B runs the program after A has left it */ +}; + +/* What threads A and B share */ +struct ctx { + struct trampoline_preempt *skel; + sigset_t sigset; + int cpu, err_a, err_b; + int overlaps; /* rounds in which B found A still inside the program */ +}; + +static int pin_to_cpu(int cpu) +{ + cpu_set_t set; + + CPU_ZERO(&set); + CPU_SET(cpu, &set); + return sched_setaffinity(0, sizeof(set), &set) ? -errno : 0; +} + +/* A enters the program under test, which wakes B from inside it */ +static void *worker_a(void *arg) +{ + struct ctx *c = arg; + int i; + + c->err_a = pin_to_cpu(c->cpu); + c->skel->bss->tid_a = syscall(SYS_gettid); + for (i = 0; i < NR_ROUNDS && !c->err_a; i++) { + /* Passes every hook that the programs under test are attached to */ + if (prctl(PR_SET_NAME, "worker_a")) + c->err_a = -errno; + } + return NULL; +} + +/* B is SCHED_FIFO on A's CPU: A runs only while B waits, and B preempts A as soon as A wakes it */ +static void *worker_b(void *arg) +{ + struct sched_param sp = { .sched_priority = 1 }; + struct timespec ts = { .tv_sec = 5 }; /* give up if the signal never comes */ + struct ctx *c = arg; + int i; + + c->err_b = pin_to_cpu(c->cpu); + if (!c->err_b && sched_setscheduler(0, SCHED_FIFO, &sp)) + c->err_b = -errno; + c->skel->bss->tid_b = syscall(SYS_gettid); + for (i = 0; i < NR_ROUNDS && !c->err_b; i++) { + while (sigtimedwait(&c->sigset, NULL, &ts) < 0) { + if (errno != EINTR) { + c->err_b = -errno; + return NULL; + } + } + /* B preempted A only if A is still inside the program */ + if (*(volatile int *)&c->skel->bss->a_inside) + c->overlaps++; + /* B's own run of the program */ + if (prctl(PR_SET_NAME, "worker_b")) + c->err_b = -errno; + } + return NULL; +} + +/* Load and attach only programs @a, @b and @c. NULL after a failure or a skip. */ +static struct trampoline_preempt *load_progs(const char *a, const char *b, const char *c, + int percpu) +{ + struct trampoline_preempt *skel = trampoline_preempt__open(); + struct bpf_program *p; + const char *name; + int err; + + if (!ASSERT_OK_PTR(skel, "open")) + return NULL; + bpf_object__for_each_program(p, skel->obj) { + name = bpf_program__name(p); + bpf_program__set_autoload(p, !strcmp(name, a) || (b && !strcmp(name, b)) || + (c && !strcmp(name, c))); + } + skel->bss->sig = SIGUSR1; + skel->rodata->percpu = percpu; + err = trampoline_preempt__load(skel); + /* The kernel or its JIT doesn't support one of the programs */ + if (err == -EOPNOTSUPP || err == -ENOTSUPP) + test__skip(); + else if (ASSERT_OK(err, "load") && ASSERT_OK(trampoline_preempt__attach(skel), "attach")) + return skel; + trampoline_preempt__destroy(skel); + return NULL; +} + +static const struct subtest { + const char *name; + const char *prog; /* A enters it; its recursion misses are checked */ + int percpu; /* the per-CPU state that the program touches */ + enum expect expect; + const char *prog_b; /* two_dispatchers: B reaches the handler through this one */ + const char *handler; /* two_dispatchers: the target of both tail calls */ +} subtests[] = { + /* Each kind of program, without per-CPU state and with a per-CPU map lookup */ + { "fentry", "on_fentry", NO_PERCPU, B_RUNS }, + { "fentry_percpu", "on_fentry", PERCPU_MAP, B_AFTER }, + { "fexit", "on_fexit", NO_PERCPU, B_RUNS }, + { "fexit_percpu", "on_fexit", PERCPU_MAP, B_AFTER }, + { "fmod_ret", "on_fmod_ret", NO_PERCPU, B_RUNS }, + { "fmod_ret_percpu", "on_fmod_ret", PERCPU_MAP, B_AFTER }, + { "fentry_s", "on_fentry_s", NO_PERCPU, B_RUNS }, + { "fentry_s_percpu", "on_fentry_s", PERCPU_MAP, B_RUNS }, + { "raw_tp", "on_raw_tp", NO_PERCPU, B_RUNS }, + { "raw_tp_percpu", "on_raw_tp", PERCPU_MAP, B_AFTER }, + { "raw_tp_s", "on_raw_tp_s", NO_PERCPU, B_RUNS }, + { "raw_tp_s_percpu", "on_raw_tp_s", PERCPU_MAP, B_RUNS }, + { "tp_syscall", "on_tp_syscall", NO_PERCPU, B_RUNS }, + { "tp_syscall_percpu", "on_tp_syscall", PERCPU_MAP, B_AFTER }, + /* The other things that mark a program */ + { "percpu_var", "on_raw_tp", PERCPU_VAR, B_AFTER }, + { "this_cpu_ptr", "on_raw_tp", THIS_CPU_PTR, B_AFTER }, + { "smp_processor_id", "on_raw_tp", CPU_ID, B_AFTER }, + { "tail_call", "on_tail_call", NO_PERCPU, B_AFTER }, + /* Timed may_goto doesn't mark a program: B runs it while A is inside it */ + { "may_goto", "on_may_goto", NO_PERCPU, B_RUNS }, + /* B runs the handler through the other dispatcher after A; A's stack stays intact */ + { "two_dispatchers", "dispatcher_a", NO_PERCPU, B_AFTER, + "dispatcher_b", "handler" }, +}; + +static void run_subtest(const struct subtest *t) +{ + struct bpf_prog_info info = {}; + __u32 info_len = sizeof(info), zero = 0; + struct ctx c = {}; + sigset_t oldset; + pthread_t ta, tb; + int err, fd; + + c.skel = load_progs(t->prog, t->prog_b, t->handler, t->percpu); + if (!c.skel) + return; + if (t->handler) { + /* Both dispatchers tail-call the handler through the prog array */ + fd = bpf_program__fd(bpf_object__find_program_by_name(c.skel->obj, t->handler)); + err = bpf_map_update_elem(bpf_map__fd(c.skel->maps.prog_array), &zero, &fd, + BPF_ANY); + if (!ASSERT_OK(err, "prog_array_update")) + goto out; + } + + /* Both threads go on this CPU. B takes the signal with sigtimedwait(), so block it. */ + c.cpu = sched_getcpu(); + sigemptyset(&c.sigset); + sigaddset(&c.sigset, SIGUSR1); + if (!ASSERT_OK(pthread_sigmask(SIG_BLOCK, &c.sigset, &oldset), "sigmask")) + goto out; + if (ASSERT_OK(pthread_create(&tb, NULL, worker_b, &c), "pthread_b")) { + /* A's program needs tid_b to wake B */ + while (!c.skel->bss->tid_b) + usleep(1000); + if (ASSERT_OK(pthread_create(&ta, NULL, worker_a, &c), "pthread_a")) + pthread_join(ta, NULL); + pthread_join(tb, NULL); + } + pthread_sigmask(SIG_SETMASK, &oldset, NULL); + + /* B may not be allowed to become SCHED_FIFO */ + if (c.err_b == -EPERM || c.err_b == -EACCES) { + test__skip(); + goto out; + } + ASSERT_OK(c.err_a, "worker_a"); + ASSERT_OK(c.err_b, "worker_b"); + ASSERT_EQ(c.skel->bss->sig_err, 0, "sig_err"); + if (t->expect == B_RUNS && !c.overlaps) { + /* B never preempted A inside the program, so nothing was tested */ + test__skip(); + goto out; + } + ASSERT_EQ(c.overlaps, t->expect == B_RUNS ? NR_ROUNDS : 0, "overlaps"); + ASSERT_EQ(c.skel->bss->runs_a, NR_ROUNDS, "runs_a"); + ASSERT_EQ(c.skel->bss->runs_b, NR_ROUNDS, "runs_b"); + if (t->handler) + ASSERT_EQ(c.skel->bss->stack_corrupt, 0, "stack_corrupt"); + fd = bpf_program__fd(bpf_object__find_program_by_name(c.skel->obj, t->prog)); + err = bpf_prog_get_info_by_fd(fd, &info, &info_len); + if (!ASSERT_OK(err, "prog_info")) + goto out; + ASSERT_EQ(info.recursion_misses, 0, "recursion_misses"); +out: + trampoline_preempt__destroy(c.skel); +} + +/* + * The program calls bpf_printk(), which fires the bpf_trace_printk tracepoint + * that it is attached to: the nested run must be rejected as recursion. With a + * hop, a second program runs in between, so the check has to look past the + * frame right below. + */ +static const struct recursion { + const char *name, *prog, *hop; + bool test_run; /* Start the outer run with BPF_PROG_TEST_RUN of @prog */ +} recursions[] = { + { "recursion_raw_tp", "recur_raw_tp" }, + { "recursion_two_hops", "recur_two_hops", "recur_hop" }, + { "recursion_test_run", "recur_raw_tp", .test_run = true }, +}; + +static void run_recursion(const struct recursion *t) +{ + LIBBPF_OPTS(bpf_test_run_opts, opts); + struct trampoline_preempt *skel = load_progs(t->prog, t->hop, "recur_trigger", NO_PERCPU); + struct bpf_prog_info info = {}; + __u32 info_len = sizeof(info); + int err, fd, run_fd; + + if (!skel) + return; + fd = bpf_program__fd(bpf_object__find_program_by_name(skel->obj, t->prog)); + /* The outer run: of @prog itself, or of a program that fires its tracepoint */ + run_fd = t->test_run ? fd : bpf_program__fd(skel->progs.recur_trigger); + skel->bss->recur_tid = syscall(SYS_gettid); + err = bpf_prog_test_run_opts(run_fd, &opts); + skel->bss->recur_tid = 0; + /* The outer run got in; the nested one was dropped and counted */ + if (ASSERT_OK(err, "test_run")) { + ASSERT_EQ(skel->bss->recur_runs, 1, "recur_runs"); + ASSERT_EQ(skel->bss->hop_runs, t->hop ? 1 : 0, "hop_runs"); + err = bpf_prog_get_info_by_fd(fd, &info, &info_len); + if (ASSERT_OK(err, "prog_info")) + ASSERT_EQ(info.recursion_misses, 1, "recursion_misses"); + } + trampoline_preempt__destroy(skel); +} + +/* + * A marked program runs with preemption disabled, but softirqs still run on + * top of it. The program arms a timer on its CPU and stays inside while the + * timer fires. The callback hits the program's hook: that run must be + * rejected as recursion, not start inside the first one. + */ +static void run_timer_subtest(void) +{ + struct trampoline_preempt *skel = load_progs("timer_marked", "recur_trigger", NULL, + NO_PERCPU); + LIBBPF_OPTS(bpf_test_run_opts, opts); + struct bpf_prog_info info = {}; + __u32 info_len = sizeof(info); + int err; + + if (!skel) + return; + /* recur_trigger fires bpf_trace_printk once */ + skel->bss->timer_tid = syscall(SYS_gettid); + err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.recur_trigger), &opts); + skel->bss->timer_tid = 0; + if (!ASSERT_OK(err, "test_run")) + goto out; + /* The callback has to run on top of the program, not in a thread of its own */ + if (!skel->bss->timer_fired_inside) { + test__skip(); + goto out; + } + ASSERT_EQ(skel->bss->timer_overlaps, 0, "timer_overlaps"); + err = bpf_prog_get_info_by_fd(bpf_program__fd(skel->progs.timer_marked), &info, &info_len); + if (ASSERT_OK(err, "prog_info")) + ASSERT_EQ(info.recursion_misses, 1, "recursion_misses"); +out: + trampoline_preempt__destroy(skel); +} + +/* + * An extension runs under the recursion check of its target. A target that + * keeps no per-CPU state is checked per task, and a sleepable one runs + * preemptibly even if it does, so an extension that keeps such state can't be + * attached to either. + */ +static void run_ext_subtest(void) +{ + static const struct { + const char *prog, *tgt, *func; + int err; + } exts[] = { + /* no per-CPU state: attaches */ + { "ext_plain", "ext_target", "ext_target", 0 }, + /* a per-CPU map lookup: rejected */ + { "ext_percpu", "ext_target", "ext_target", -EINVAL }, + /* a marked target runs with preemption disabled: attaches */ + { "ext_percpu", "ext_target_percpu", "ext_target_percpu", 0 }, + /* a sleepable target runs preemptibly: only one without per-CPU state */ + { "ext_plain_sub", "ext_target_s_percpu", "ext_target_sub", 0 }, + { "ext_percpu_sub", "ext_target_s_percpu", "ext_target_sub", -EINVAL }, + }; + struct trampoline_preempt *tgt_skel = NULL, *skel = NULL; + struct bpf_program *ext, *tgt, *p; + struct bpf_link *link; + int i, err, tgt_fd; + + for (i = 0; i < ARRAY_SIZE(exts); i++) { + tgt_skel = trampoline_preempt__open(); + if (!ASSERT_OK_PTR(tgt_skel, "open_tgt")) + goto out; + tgt = bpf_object__find_program_by_name(tgt_skel->obj, exts[i].tgt); + bpf_object__for_each_program(p, tgt_skel->obj) + bpf_program__set_autoload(p, p == tgt); + if (!ASSERT_OK(trampoline_preempt__load(tgt_skel), "load_tgt")) + goto out; + tgt_fd = bpf_program__fd(tgt); + + skel = trampoline_preempt__open(); + if (!ASSERT_OK_PTR(skel, "open_ext")) + goto out; + ext = bpf_object__find_program_by_name(skel->obj, exts[i].prog); + bpf_object__for_each_program(p, skel->obj) + bpf_program__set_autoload(p, p == ext); + err = bpf_program__set_attach_target(ext, tgt_fd, exts[i].func); + if (!ASSERT_OK(err, "set_attach_target")) + goto out; + if (!ASSERT_OK(trampoline_preempt__load(skel), "load_ext")) + goto out; + + link = bpf_program__attach_freplace(ext, tgt_fd, exts[i].func); + ASSERT_EQ(libbpf_get_error(link), exts[i].err, exts[i].prog); + bpf_link__destroy(link); + trampoline_preempt__destroy(skel); + trampoline_preempt__destroy(tgt_skel); + skel = NULL; + tgt_skel = NULL; + } +out: + trampoline_preempt__destroy(skel); + trampoline_preempt__destroy(tgt_skel); +} + +/* Serial: pins threads to one CPU, and a timer callback must find nothing else there */ +void serial_test_trampoline_preempt(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(subtests); i++) { + if (test__start_subtest(subtests[i].name)) + run_subtest(&subtests[i]); + } + for (i = 0; i < ARRAY_SIZE(recursions); i++) { + if (test__start_subtest(recursions[i].name)) + run_recursion(&recursions[i]); + } + if (test__start_subtest("timer_cb")) + run_timer_subtest(); + if (test__start_subtest("ext_attach")) + run_ext_subtest(); +} diff --git a/tools/testing/selftests/bpf/progs/trampoline_preempt.c b/tools/testing/selftests/bpf/progs/trampoline_preempt.c new file mode 100644 index 000000000000..3b34641229c9 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/trampoline_preempt.c @@ -0,0 +1,382 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "vmlinux.h" +#include +#include +#include +#include "bpf_misc.h" +#include "bpf_compiler.h" +#include + +/* The programs of prog_tests/trampoline_preempt.c. The comment there describes the test. */ + +char _license[] SEC("license") = "GPL"; + +struct task_struct *bpf_task_from_pid(s32 pid) __ksym; +void bpf_task_release(struct task_struct *p) __ksym; +int bpf_send_signal_task(struct task_struct *task, int sig, enum pid_type type, u64 value) __ksym; + +/* The target of the tail calls: empty for tail_call, the handler for two_dispatchers */ +struct { + __uint(type, BPF_MAP_TYPE_PROG_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, __u32); +} prog_array SEC(".maps"); + +/* recur_two_hops deletes from it, which runs recur_hop */ +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 1); + __type(key, int); + __type(value, int); +} recur_map SEC(".maps"); + +/* The per-CPU state: a map, a variable, a kernel variable for the helper, and the CPU id */ +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, 1); + __type(key, int); + __type(value, __u64); +} percpu_map SEC(".maps"); + +__u64 percpu_var SEC(".percpu"); +__u32 cpu_id; +extern const struct rq runqueues __ksym; + +/* The per-CPU state that a program touches. The test picks one before the load. */ +enum { NO_PERCPU, PERCPU_MAP, PERCPU_VAR, THIS_CPU_PTR, CPU_ID }; +const volatile int percpu; + +/* Set by the test */ +int tid_a, tid_b, sig, recur_tid; +int loops; /* 0, read at run time so that the may_goto loop is not optimized away */ + +/* Read by the test */ +int runs_a, runs_b, sig_err, stack_corrupt, recur_runs, hop_runs; +int a_inside; /* A is inside the program: B reads it to see that it preempted A there */ + +static void signal_worker_b(void) +{ + struct task_struct *task = bpf_task_from_pid(tid_b); + + if (!task || bpf_send_signal_task(task, sig, PIDTYPE_PID, 0)) + sig_err = 1; + if (task) + bpf_task_release(task); +} + +/* + * The body of every program under test: count the run of A or of B. A also + * wakes B from here, so B preempts A inside the program and enters it too. + */ +static __always_inline int record_run(void) +{ + __u32 tid = (__u32)bpf_get_current_pid_tgid(); + int zero = 0; + + /* The verifier walks only the selected branch, so only that one marks the program */ + switch (percpu) { + case PERCPU_MAP: + bpf_map_lookup_elem(&percpu_map, &zero); + break; + case PERCPU_VAR: + percpu_var++; + break; + case THIS_CPU_PTR: + bpf_this_cpu_ptr(&runqueues); + break; + case CPU_ID: + cpu_id = bpf_get_smp_processor_id(); + break; + } + + if (tid == tid_a) { + runs_a++; + /* volatile: both stores must stay, B reads a_inside between them */ + *(volatile int *)&a_inside = 1; + signal_worker_b(); + *(volatile int *)&a_inside = 0; + } else if (tid == tid_b) { + runs_b++; + } + return 0; +} + +/* Both threads call prctl(PR_SET_NAME), which passes each of the hooks below */ + +SEC("fentry/__set_task_comm") +int BPF_PROG(on_fentry) +{ + return record_run(); +} + +SEC("fexit/__set_task_comm") +int BPF_PROG(on_fexit) +{ + return record_run(); +} + +/* Returns 0: prctl() runs as usual */ +SEC("fmod_ret/" SYS_PREFIX "sys_prctl") +int BPF_PROG(on_fmod_ret) +{ + return record_run(); +} + +SEC("fentry.s/" SYS_PREFIX "sys_prctl") +int BPF_PROG(on_fentry_s) +{ + return record_run(); +} + +SEC("raw_tp/task_rename") +int BPF_PROG(on_raw_tp) +{ + return record_run(); +} + +SEC("raw_tp.s/sys_enter") +int BPF_PROG(on_raw_tp_s, struct pt_regs *regs, long id) +{ + return id == __NR_prctl ? record_run() : 0; +} + +SEC("tp/syscalls/sys_enter_prctl") +int on_tp_syscall(void *ctx) +{ + return record_run(); +} + +/* The prog array is empty, so the tail call does nothing */ +SEC("raw_tp/task_rename") +int on_tail_call(void *ctx) +{ + bpf_tail_call(ctx, &prog_array, 0); + return record_run(); +} + +/* can_loop is a may_goto. With timed may_goto its time budget is per CPU. */ +SEC("raw_tp/task_rename") +int on_may_goto(void *ctx) +{ + int i; + + for (i = loops; i < 1 && can_loop; i++) + ; + return record_run(); +} + +/* Two dispatchers tail-call one handler: A enters through dispatcher_a, B through dispatcher_b */ +SEC("raw_tp/task_rename") +int dispatcher_a(void *ctx) +{ + if ((__u32)bpf_get_current_pid_tgid() == tid_a) + bpf_tail_call(ctx, &prog_array, 0); + return 0; +} + +SEC("raw_tp/sys_enter") +int BPF_PROG(dispatcher_b, struct pt_regs *regs, long id) +{ + if (id == __NR_prctl && (__u32)bpf_get_current_pid_tgid() == tid_b) + bpf_tail_call(ctx, &prog_array, 0); + return 0; +} + +/* The handler keeps 64 bytes of stack across the point where B runs it too */ +SEC("raw_tp") +int handler(void *ctx) +{ + __u32 tid = (__u32)bpf_get_current_pid_tgid(); + volatile __u64 buf[8]; + + __pragma_loop_unroll + for (int i = 0; i < 8; i++) + buf[i] = ((__u64)tid << 32) | i; + + record_run(); + + /* Don't trust a copy of tid that may have been spilled to the stack under test */ + tid = (__u32)bpf_get_current_pid_tgid(); + __pragma_loop_unroll + for (int i = 0; i < 8; i++) + if (buf[i] != (((__u64)tid << 32) | i)) + stack_corrupt = 1; + return 0; +} + +/* bpf_printk() fires the bpf_trace_printk tracepoint that the program is attached to */ +SEC("raw_tp/bpf_trace_printk") +int recur_raw_tp(void *ctx) +{ + /* Other tasks print too: only the runs of the test's thread count */ + if ((__u32)bpf_get_current_pid_tgid() != recur_tid) + return 0; + recur_runs++; + bpf_printk("recur"); + return 0; +} + +/* The test runs it with BPF_PROG_TEST_RUN to fire the tracepoint once */ +SEC("syscall") +int recur_trigger(void *ctx) +{ + bpf_printk("trigger"); + return 0; +} + +/* The same through a second program: recur_two_hops -> recur_hop -> recur_two_hops */ +SEC("raw_tp/bpf_trace_printk") +int recur_two_hops(void *ctx) +{ + int zero = 0; + + if ((__u32)bpf_get_current_pid_tgid() != recur_tid) + return 0; + recur_runs++; + bpf_map_delete_elem(&recur_map, &zero); + return 0; +} + +SEC("fentry/htab_map_delete_elem") +int BPF_PROG(recur_hop, struct bpf_map *map) +{ + if (map != (struct bpf_map *)&recur_map || (__u32)bpf_get_current_pid_tgid() != recur_tid) + return 0; + hop_runs++; + bpf_printk("hop"); + return 0; +} + +/* For ext_attach: targets without and with per-CPU state, and extensions without and with it */ +SEC("raw_tp/task_rename") +int ext_target(struct bpf_raw_tracepoint_args *ctx) +{ + return 0; +} + +SEC("raw_tp/task_rename") +int ext_target_percpu(struct bpf_raw_tracepoint_args *ctx) +{ + int zero = 0; + + bpf_map_lookup_elem(&percpu_map, &zero); + return 0; +} + +SEC("freplace") +int ext_plain(struct bpf_raw_tracepoint_args *ctx) +{ + return 0; +} + +SEC("freplace") +int ext_percpu(struct bpf_raw_tracepoint_args *ctx) +{ + int zero = 0; + + bpf_map_lookup_elem(&percpu_map, &zero); + return 0; +} + +/* + * For ext_attach: a marked sleepable target. It runs preemptibly anyway, and + * an extension can only replace a global subprogram that runs under + * bpf_rcu_read_lock() there. + */ +void bpf_rcu_read_lock(void) __ksym; +void bpf_rcu_read_unlock(void) __ksym; + +__noinline int ext_target_sub(int x) +{ + /* Without a side effect clang drops the call, and the subprogram with it */ + asm volatile(""); + return x; +} + +SEC("raw_tp.s/sys_enter") +int ext_target_s_percpu(void *ctx) +{ + int zero = 0; + + bpf_map_lookup_elem(&percpu_map, &zero); + bpf_rcu_read_lock(); + ext_target_sub(0); + bpf_rcu_read_unlock(); + return 0; +} + +SEC("freplace") +int ext_plain_sub(int x) +{ + return 0; +} + +SEC("freplace") +int ext_percpu_sub(int x) +{ + int zero = 0; + + bpf_map_lookup_elem(&percpu_map, &zero); + return 0; +} + +/* For timer_cb */ +#define CLOCK_MONOTONIC 1 + +struct timer_elem { + struct bpf_timer t; +}; + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, int); + __type(value, struct timer_elem); +} timer_map SEC(".maps"); + +int timer_tid, timer_inside, timer_overlaps, timer_fired, timer_fired_inside; + +/* Runs in a softirq on top of timer_marked and fires bpf_trace_printk */ +static int timer_cb(void *map, int *key, struct timer_elem *val) +{ + timer_fired_inside = *(volatile int *)&timer_inside; + bpf_printk("timer_cb"); + *(volatile int *)&timer_fired = 1; + return 0; +} + +/* + * Marked by the per-CPU map lookup, as in the case this covers, although + * bpf_trace_printk() runs the tracepoint with preemption disabled anyway. Its + * first run arms a timer on this CPU and waits for it. The callback runs in a + * softirq on top of that run and hits this program's hook again: its frame + * has to be linked on top of the first run for the check to see it. + */ +SEC("raw_tp/bpf_trace_printk") +int timer_marked(void *ctx) +{ + struct timer_elem *e; + int zero = 0; + + /* Other tasks print too: only the test's thread counts */ + if ((__u32)bpf_get_current_pid_tgid() != timer_tid) + return 0; + bpf_map_lookup_elem(&percpu_map, &zero); + if (*(volatile int *)&timer_inside) { + timer_overlaps++; + return 0; + } + e = bpf_map_lookup_elem(&timer_map, &zero); + if (!e) + return 0; + *(volatile int *)&timer_inside = 1; + bpf_timer_init(&e->t, &timer_map, CLOCK_MONOTONIC); + bpf_timer_set_callback(&e->t, timer_cb); + bpf_timer_start(&e->t, 0, BPF_F_TIMER_CPU_PIN); + /* Wait for the callback; can_loop ends the wait if it never comes */ + while (!*(volatile int *)&timer_fired && can_loop) + ; + *(volatile int *)&timer_inside = 0; + return 0; +} -- 2.43.0