* [PATCH bpf-next v5 1/5] bpf: Avoid per-CPU private stack in preemptible tracing progs
2026-12-01 15:32 [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs Mike Bazov via B4 Relay
@ 2026-12-01 15:32 ` Mike Bazov via B4 Relay
2026-12-01 15:32 ` [PATCH bpf-next v5 2/5] bpf: Mark programs that keep per-CPU state Mike Bazov via B4 Relay
` (4 subsequent siblings)
5 siblings, 0 replies; 8+ messages in thread
From: Mike Bazov via B4 Relay @ 2026-12-01 15:32 UTC (permalink / raw)
To: bpf, 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, linux-kernel,
Mike Bazov
From: Mike Bazov <mikeba@sentinelone.com>
A per-CPU private stack is only safe if a program never runs in two
tasks at once on one CPU. Commit a76ab5731e32 ("bpf: Find eligible
subprogs for private stack support") gave one to tracing, raw_tp and
tracepoint programs, but they run preemptibly, and two tasks can
already be inside one of them on a CPU:
- Two raw_tp dispatchers that tail-call the same handler each pass
their own per-CPU recursion check, so both tasks run the handler.
- A tracepoint program attached to a syscall tracepoint and to a
regular tracepoint can be entered by a second task through the
regular one, which only checks bpf_prog_active.
The second task then overwrites the preempted task's stack. Neither case
can be seen when the program is loaded, so never give these program
types a private stack.
check_recursion() told tracing programs apart by whether they can get a
private stack. Make it check the program type instead, so that
recursive subprograms stay rejected in these program types.
Move the selftests that relied on these program types having a private
stack to kprobe.multi and perf_event programs. The stack argument test
keeps a raw_tp copy, which still runs the program.
Trade-offs:
- These programs use the kernel stack again.
- A program with two 2000-byte frames no longer loads: "combined stack
size of 2 calls is 4000. Too large".
- Unwinding on a private stack is no longer tested at run time: raw_tp
was the only such program type that BPF_PROG_TEST_RUN runs.
Signed-off-by: Mike Bazov <mikeba@sentinelone.com>
---
kernel/bpf/verifier.c | 42 +++++++----
.../selftests/bpf/prog_tests/may_goto_priv_stack.c | 6 +-
.../selftests/bpf/prog_tests/timed_may_goto.c | 6 +-
.../selftests/bpf/progs/may_goto_priv_stack.c | 14 +++-
.../selftests/bpf/progs/test_global_func3.c | 9 +++
.../selftests/bpf/progs/timed_may_goto_user.c | 16 ++++-
.../selftests/bpf/progs/verifier_private_stack.c | 81 ++++++++++++----------
.../selftests/bpf/progs/verifier_stack_arg.c | 38 ++++++++--
.../testing/selftests/bpf/progs/verifier_unwind.c | 33 +++++++--
9 files changed, 180 insertions(+), 65 deletions(-)
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 18c59ae784eb..d43b54caa9a1 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -5426,9 +5426,15 @@ static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
if (!bpf_jit_supports_private_stack())
return NO_PRIV_STACK;
- /* bpf_prog_check_recur() checks all prog types that use bpf trampoline
- * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
- * explicitly.
+ /*
+ * A private stack is per CPU, so a program using it must never run in two
+ * tasks at once on one CPU. Tracing, raw_tp and tracepoint programs run
+ * preemptibly, and the same program can be entered by another task on the
+ * same CPU, e.g. through a second tail-call dispatcher, or as a tracepoint
+ * program attached to both a syscall and a regular tracepoint. They always
+ * use the task's kernel stack. Kprobe multi, kprobe session and perf_event
+ * programs are serialized per CPU by bpf_prog_active, and struct_ops
+ * programs that request a private stack keep per-CPU recursion protection.
*/
switch (prog->type) {
case BPF_PROG_TYPE_KPROBE:
@@ -5441,14 +5447,10 @@ static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
prog->expected_attach_type != BPF_TRACE_KPROBE_SESSION)
return NO_PRIV_STACK;
fallthrough;
- case BPF_PROG_TYPE_TRACEPOINT:
case BPF_PROG_TYPE_PERF_EVENT:
- case BPF_PROG_TYPE_RAW_TRACEPOINT:
return PRIV_STACK_ADAPTIVE;
- case BPF_PROG_TYPE_TRACING:
- case BPF_PROG_TYPE_LSM:
case BPF_PROG_TYPE_STRUCT_OPS:
- if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
+ if (prog->aux->priv_stack_requested)
return PRIV_STACK_ADAPTIVE;
fallthrough;
default:
@@ -5458,6 +5460,22 @@ static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
return NO_PRIV_STACK;
}
+/* Progs that run on top of other progs, whose frames are still on the stack */
+static bool bpf_prog_runs_nested(struct bpf_prog *prog)
+{
+ switch (prog->type) {
+ case BPF_PROG_TYPE_KPROBE:
+ case BPF_PROG_TYPE_PERF_EVENT:
+ case BPF_PROG_TYPE_TRACEPOINT:
+ case BPF_PROG_TYPE_RAW_TRACEPOINT:
+ return true;
+ case BPF_PROG_TYPE_TRACING:
+ return bpf_prog_check_recur(prog);
+ default:
+ return false;
+ }
+}
+
static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
{
if (env->prog->jit_requested)
@@ -5594,12 +5612,10 @@ static int check_recursion(struct bpf_verifier_env *env, struct bpf_call_graph *
}
if (env->subprog_info[s].recursive) {
/*
- * These progs run on top of other progs. Their frames belong in the
- * private stack, which has room for one frame of a subprog. A kprobe prog
- * that can be attached to a uprobe has no private stack, and is no better.
+ * These progs run on top of other progs. A private stack has room for one
+ * frame of a subprog, and the kernel stack under them is already in use.
*/
- if ((bpf_enable_priv_stack(env->prog) != NO_PRIV_STACK ||
- env->prog->type == BPF_PROG_TYPE_KPROBE) &&
+ if (bpf_prog_runs_nested(env->prog) &&
!env->prog->aux->priv_stack_requested) {
verbose(env, "recursive %s() in a tracing program\n",
bpf_subprog_name(env, s));
diff --git a/tools/testing/selftests/bpf/prog_tests/may_goto_priv_stack.c b/tools/testing/selftests/bpf/prog_tests/may_goto_priv_stack.c
index 4f8476d36250..b4aab50b8a77 100644
--- a/tools/testing/selftests/bpf/prog_tests/may_goto_priv_stack.c
+++ b/tools/testing/selftests/bpf/prog_tests/may_goto_priv_stack.c
@@ -24,13 +24,17 @@ void test_may_goto_priv_stack(void)
return;
err = may_goto_priv_stack__attach(skel);
+ if (err == -EOPNOTSUPP) {
+ test__skip();
+ goto out;
+ }
if (!ASSERT_OK(err, "attach"))
goto out;
memset(skel->bss->regs_64, 0xff, sizeof(skel->bss->regs_64));
memset(skel->bss->regs_128, 0xff, sizeof(skel->bss->regs_128));
- err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.priv_stack_64), &topts);
+ err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.trigger), &topts);
if (!ASSERT_OK(err, "test_run"))
goto out;
diff --git a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
index 3da3f33a2898..ee7b79ef77e0 100644
--- a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
+++ b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
@@ -131,10 +131,14 @@ static void test_user_ringbuf(struct timed_may_goto_user *skel)
static void test_priv_stack(struct timed_may_goto_user *skel)
{
LIBBPF_OPTS(bpf_test_run_opts, opts);
- int fd = bpf_program__fd(skel->progs.priv_stack);
+ int fd = bpf_program__fd(skel->progs.trigger);
struct bpf_link *link;
link = bpf_program__attach(skel->progs.priv_stack);
+ if (!link && errno == EOPNOTSUPP) {
+ test__skip();
+ return;
+ }
if (!ASSERT_OK_PTR(link, "attach"))
return;
ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), "test_run");
diff --git a/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c b/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c
index 5c2aa0aa5055..e11a7f7493a6 100644
--- a/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c
+++ b/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c
@@ -10,11 +10,11 @@ __u64 regs_64[7];
__u64 regs_128[7];
/*
- * fentry prog with 64 or more bytes of stack uses private stack.
+ * kprobe.multi prog with 64 or more bytes of stack uses private stack.
* Loop until may_goto expires. r0-r5 should stay zero.
*/
#define TIMED_MAY_GOTO_PRIV_STACK(size, func) \
-SEC("fentry/" #func) \
+SEC("kprobe.multi/" #func) \
__naked void priv_stack_##size(void) \
{ \
asm volatile ( \
@@ -49,4 +49,14 @@ __naked void priv_stack_##size(void) \
TIMED_MAY_GOTO_PRIV_STACK(64, bpf_fentry_test1)
TIMED_MAY_GOTO_PRIV_STACK(128, bpf_fentry_test2)
+/*
+ * No tests in here, just to trigger 'bpf_fentry_test*'
+ * through tracing test_run
+ */
+SEC("fentry/bpf_modify_return_test")
+int trigger(void *ctx)
+{
+ return 0;
+}
+
char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/test_global_func3.c b/tools/testing/selftests/bpf/progs/test_global_func3.c
index b916355c5e59..a473bed346d2 100644
--- a/tools/testing/selftests/bpf/progs/test_global_func3.c
+++ b/tools/testing/selftests/bpf/progs/test_global_func3.c
@@ -267,6 +267,15 @@ int global_func3_recursion_in_tracing_prog(void *ctx)
return depth(again + 7);
}
+SEC("raw_tp")
+__arch_x86_64
+__arch_arm64
+__failure __msg("recursive depth() in a tracing program")
+int global_func3_recursion_in_raw_tp(void *ctx)
+{
+ return depth(again + 7);
+}
+
__attribute__ ((noinline))
int redirects(struct __sk_buff *skb, int n)
{
diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
index 8b85815d45d2..ed56b6afb607 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
@@ -277,7 +277,7 @@ int drain(void *ctx)
}
/*
- * A tracing prog with large frames: they are in a private stack.
+ * A kprobe.multi prog with large frames: they are in a private stack.
*/
int priv_stack_spun, priv_stack_cb_spun;
@@ -296,8 +296,8 @@ static int priv_stack_cb(__u64 i, int *spun)
return 0;
}
-SEC("fentry/bpf_fentry_test1")
-int BPF_PROG(priv_stack)
+SEC("kprobe.multi/bpf_fentry_test1")
+int BPF_KPROBE(priv_stack)
{
volatile char buf[128] = {};
int i, n = buf[zero & 127], spun = 0;
@@ -309,3 +309,13 @@ int BPF_PROG(priv_stack)
priv_stack_cb_spun = spun;
return 0;
}
+
+/*
+ * No tests in here, just to trigger 'bpf_fentry_test*'
+ * through tracing test_run
+ */
+SEC("fentry/bpf_modify_return_test")
+int BPF_PROG(trigger)
+{
+ return 0;
+}
diff --git a/tools/testing/selftests/bpf/progs/verifier_private_stack.c b/tools/testing/selftests/bpf/progs/verifier_private_stack.c
index ed2a40475125..a55acdb5cdab 100644
--- a/tools/testing/selftests/bpf/progs/verifier_private_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_private_stack.c
@@ -61,7 +61,7 @@ __naked void private_stack_single_prog(void)
" ::: __clobber_all);
}
-SEC("raw_tp")
+SEC("kprobe.multi")
__description("No private stack")
__success
__arch_x86_64
@@ -95,7 +95,7 @@ __naked static long subprog_6args(long a, long b, long c, long d, long e, long f
}
/* x86-64 has one register for the private stack and for the sixth argument */
-SEC("raw_tp")
+SEC("kprobe.multi")
__description("No private stack, stack arguments")
__success
__load_if_JITed()
@@ -113,7 +113,7 @@ __naked void no_private_stack_stack_args(void)
" ::: __clobber_all);
}
#else
-SEC("raw_tp")
+SEC("kprobe.multi")
__description("No private stack, stack arguments")
__skip("stack_arg is not supported by compiler")
__success
@@ -140,6 +140,23 @@ __naked void no_private_stack_kprobe(void)
" ::: __clobber_all);
}
+SEC("fentry/bpf_fentry_test9")
+__description("No private stack, fentry")
+__success
+__arch_x86_64
+__jited(" subq $0x100, %rsp")
+__arch_arm64
+__jited(" sub sp, sp, #0x100")
+__naked void no_private_stack_fentry(void)
+{
+ asm volatile (" \
+ r1 = 42; \
+ *(u64 *)(r10 - 256) = r1; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
SEC("uprobe")
__description("No private stack, uprobe")
__success
@@ -236,7 +253,7 @@ static unsigned long loop_callback(void)
: __clobber_common);
}
-SEC("raw_tp")
+SEC("kprobe.multi")
__description("Private stack, callback")
__success
__arch_x86_64
@@ -304,9 +321,9 @@ __naked void private_stack_callback(void)
: __clobber_common);
}
-SEC("fentry/bpf_fentry_test9")
+SEC("perf_event")
__description("Private stack, exception in main prog")
-__success __retval(0)
+__success
__arch_x86_64
__jited(" pushq %r9")
__jited("...")
@@ -352,9 +369,9 @@ __used static int subprog_exception(void)
return 0;
}
-SEC("fentry/bpf_fentry_test9")
+SEC("perf_event")
__description("Private stack, exception in subprog")
-__success __retval(0)
+__success
__arch_x86_64
__jited(" movq %rdi, -0x200(%r9)")
__jited(" pushq %r9")
@@ -386,20 +403,16 @@ int private_stack_exception_sub_prog(void)
}
/*
- * Nothing attaches the two fentry progs above, so they are loaded, but never
- * run. BPF_PROG_TEST_RUN does run a raw_tp prog. The default exception callback
- * returns the cookie of bpf_throw().
+ * Nothing attaches the two perf_event progs above, so they are loaded, but
+ * never run. BPF_PROG_TEST_RUN does run a raw_tp prog. The default exception
+ * callback returns the cookie of bpf_throw().
*/
SEC("raw_tp")
-__description("Private stack, run, exception in main prog")
+__description("No private stack, run, exception in main prog")
__success __retval(1)
__arch_x86_64
-__jited(" movq %rdi, -0x200(%r9)")
-__jited(" movl $0x1, %edi")
-__jited(" pushq %r9")
-__jited("...")
-__jited(" callq")
-__naked void private_stack_run_exception_main_prog(void)
+__jited(" subq $0x200, %rsp")
+__naked void big_stack_run_exception_main_prog(void)
{
asm volatile (" \
r1 = 42; \
@@ -427,15 +440,11 @@ __naked static void subprog_throw(void)
}
SEC("raw_tp")
-__description("Private stack, run, exception in subprog")
+__description("No private stack, run, exception in subprog")
__success __retval(2)
__arch_x86_64
-__jited(" movq %rdi, -0x200(%r9)")
-__jited(" pushq %r9")
-__jited("...")
-__jited(" callq")
-__jited(" popq %r9")
-__naked void private_stack_run_exception_sub_prog(void)
+__jited(" subq $0x200, %rsp")
+__naked void big_stack_run_exception_sub_prog(void)
{
asm volatile (" \
r1 = 42; \
@@ -447,7 +456,7 @@ __naked void private_stack_run_exception_sub_prog(void)
}
__used
-__naked static void private_stack_subprog_throw(void)
+__naked static void big_stack_subprog_throw(void)
{
asm volatile (" \
r1 = 42; \
@@ -461,24 +470,22 @@ __naked static void private_stack_subprog_throw(void)
: __clobber_all);
}
-/* Only the frame of the main prog counts, and it has nothing pushed at the call */
+/* The subprog that throws has a large frame, the main prog a small one */
SEC("raw_tp")
-__description("Private stack, run, exception in subprog, no private stack in main prog")
+__description("No private stack, run, exception in subprog with a large stack")
__success __retval(3)
__arch_x86_64
__jited(" subq $0x8, %rsp")
__jited("...")
__jited("func #1")
__jited("...")
-__jited(" movq %rdi, -0x200(%r9)")
-__jited(" movl $0x3, %edi")
-__jited(" pushq %r9")
+__jited(" subq $0x200, %rsp")
__naked void no_private_stack_run_exception_sub_prog(void)
{
asm volatile (" \
r1 = 42; \
*(u64 *)(r10 - 8) = r1; \
- call private_stack_subprog_throw; \
+ call big_stack_subprog_throw; \
r0 = 0; \
exit; \
" ::: __clobber_all);
@@ -509,9 +516,9 @@ __noinline static int timer_cb2(void *map, int *key, struct bpf_timer *timer)
return 0;
}
-SEC("fentry/bpf_fentry_test9")
+SEC("kprobe.multi")
__description("Private stack, async callback, not nested")
-__success __retval(0)
+__success
__arch_x86_64
__jited(" movabsq $0x{{.*}}, %r9")
__arch_arm64
@@ -538,9 +545,9 @@ int private_stack_async_callback_1(void)
return 0;
}
-SEC("fentry/bpf_fentry_test9")
+SEC("kprobe.multi")
__description("Private stack, async callback, potential nesting")
-__success __retval(0)
+__success
__load_if_JITed()
__log_level(4) __msg("stack depth max 272")
__msg("subprog 0 (private_stack_async_callback_2) main {{.*}} stack 8")
@@ -571,7 +578,7 @@ int private_stack_async_callback_2(void)
return 0;
}
-SEC("fentry/bpf_fentry_test9")
+SEC("kprobe.multi")
__description("private stack, max stack depth is private stack")
__success
__log_level(4) __msg("stack depth max 256")
diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
index 16afc69af947..b5746bcb3b3b 100644
--- a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
+++ b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
@@ -1175,13 +1175,43 @@ long priv_stack_10args(long a, long b, long c, long d, long e, long f, long g, l
}
/*
- * A frame of 64 bytes in a raw_tp prog goes to the private stack.
- * arm64 and riscv64 pass args 9 and 10 on the kernel stack. On x86-64
- * both frames stay there as well.
+ * A frame of 64 bytes in a raw_tp prog stays on the kernel stack: raw_tp progs
+ * get no private stack, since two tasks can run one on a CPU at once.
*/
SEC("raw_tp")
-__description("stack_arg: private stack in the caller and in the callee")
+__description("stack_arg: 64-byte frames in the caller and in the callee")
__success __retval(890)
+__naked void stack_arg_big_frames(void)
+{
+ asm volatile (
+ "r1 = 800;"
+ "*(u64 *)(r10 - 64) = r1;"
+ "r1 = r10;"
+ "r1 += -64;"
+ "*(u64 *)(r11 - 40) = r1;"
+ "*(u64 *)(r11 - 32) = 90;"
+ "*(u64 *)(r11 - 24) = 8;"
+ "*(u64 *)(r11 - 16) = 7;"
+ "*(u64 *)(r11 - 8) = 6;"
+ "r1 = 1;"
+ "r2 = 2;"
+ "r3 = 3;"
+ "r4 = 4;"
+ "r5 = 5;"
+ "call priv_stack_10args;"
+ "exit;"
+ ::: __clobber_all
+ );
+}
+
+/*
+ * A frame of 64 bytes in a kprobe.multi prog goes to the private stack.
+ * arm64 and riscv64 pass args 9 and 10 on the kernel stack. On x86-64
+ * both frames stay there as well. kprobe.multi progs can't be test-run.
+ */
+SEC("kprobe.multi")
+__description("stack_arg: private stack in the caller and in the callee")
+__success
__naked void stack_arg_priv_stack(void)
{
asm volatile (
diff --git a/tools/testing/selftests/bpf/progs/verifier_unwind.c b/tools/testing/selftests/bpf/progs/verifier_unwind.c
index 596e5e0301e5..c779b455e1db 100644
--- a/tools/testing/selftests/bpf/progs/verifier_unwind.c
+++ b/tools/testing/selftests/bpf/progs/verifier_unwind.c
@@ -1197,9 +1197,9 @@ static unsigned long may_unwind_big_stack(void)
* x86-64 keeps the pointer to the private stack in r9 and saves it around a call.
* The value that is read back in the pad is there only when r9 is restored.
*/
-SEC("raw_tp")
+SEC("kprobe.multi")
__description("unwind: private stack, the callee unwinds")
-__success __retval(47)
+__success
__load_if_JITed()
__arch_x86_64
__jited(" movl $0x1234, %esi") /* past the load, see above */
@@ -1232,12 +1232,37 @@ __naked int private_stack_unwinds(void)
}
SEC("raw_tp")
-__description("unwind: private stack, the callee returns")
+__description("unwind: big stack, the callee unwinds")
+__success __retval(47)
+__load_if_JITed()
+__arch_x86_64
+__arch_arm64
+__naked int big_stack_unwinds(void)
+{
+ asm volatile (
+ "*(u64 *)(r10 - 200) = 42;"
+ "r1 = %[one] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "call may_unwind_big_stack;"
+ unwind_goto(1)
+ "exit;"
+ "r1 = *(u64 *)(r10 - 200);"
+ "r0 += r1;"
+ "exit;"
+ :
+ : __imm_addr(one),
+ __imm_unwind_goto(1)
+ : __clobber_all
+ );
+}
+
+SEC("raw_tp")
+__description("unwind: big stack, the callee returns")
__success __retval(49)
__load_if_JITed()
__arch_x86_64
__arch_arm64
-__naked int private_stack_returns(void)
+__naked int big_stack_returns(void)
{
asm volatile (
"*(u64 *)(r10 - 200) = 42;"
--
2.43.0
^ permalink raw reply related [flat|nested] 8+ messages in thread* [PATCH bpf-next v5 2/5] bpf: Mark programs that keep per-CPU state
2026-12-01 15:32 [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs Mike Bazov via B4 Relay
2026-12-01 15:32 ` [PATCH bpf-next v5 1/5] bpf: Avoid per-CPU private stack in preemptible tracing progs Mike Bazov via B4 Relay
@ 2026-12-01 15:32 ` Mike Bazov via B4 Relay
2026-12-01 15:32 ` [PATCH bpf-next v5 3/5] bpf: Check program recursion per task via bpf_ctx Mike Bazov via B4 Relay
` (3 subsequent siblings)
5 siblings, 0 replies; 8+ messages in thread
From: Mike Bazov via B4 Relay @ 2026-12-01 15:32 UTC (permalink / raw)
To: bpf, 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, linux-kernel,
Mike Bazov
From: Mike Bazov <mikeba@sentinelone.com>
Once recursion is checked per task, a second task can enter a tracing or
raw tracepoint program while another task is preempted inside it on the
same CPU. Some programs rely on that not happening:
- A per-CPU map value that a program looked up stays its own until the
run ends: programs use these maps as scratch space.
- A private stack is per CPU. Of the programs whose recursion check
becomes per task, only struct_ops programs that request one have it.
Mark them at load time, so that their runs on a CPU can be kept apart.
Set prog->percpu_state when the verifier sees:
- a helper called with a per-CPU map, also through an inner map,
- the address of a per-CPU array value loaded directly,
- bpf_this_cpu_ptr() or bpf_per_cpu_ptr(),
- bpf_get_smp_processor_id(): the CPU id often indexes per-CPU slots
that the program keeps itself, e.g. in a regular array,
- a tail call: the target runs in the caller's run and may use a
per-CPU map,
- a private stack.
Only code the verifier walks counts: a per-CPU map referenced in a
branch that a constant in .rodata disables doesn't mark the program.
Timed may_goto doesn't mark a program: a marked program would run the
loop with preemption disabled, for up to 250 ms. Its budget is per-CPU
memory that the first insns of a run reset, so a run that preempts
another one can renew the other's budget. lsm, cgroup and uprobe progs,
and struct_ops progs without a private stack, already share the budget
this way.
No functional change: nothing reads the flag yet.
Trade-off: every program that calls bpf_get_smp_processor_id() is
marked, also one that only records the CPU id.
Signed-off-by: Mike Bazov <mikeba@sentinelone.com>
---
include/linux/bpf.h | 3 ++-
kernel/bpf/verifier.c | 15 +++++++++++++++
2 files changed, 17 insertions(+), 1 deletion(-)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 4f9c2bf64643..2dfd963a2703 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -2075,7 +2075,8 @@ struct bpf_prog {
call_get_func_ip:1, /* Do we call get_func_ip() */
call_session_cookie:1, /* Do we call bpf_session_cookie() */
tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
- sleepable:1; /* BPF program is sleepable */
+ sleepable:1, /* BPF program is sleepable */
+ percpu_state:1; /* Runs must not overlap on a CPU */
enum bpf_prog_type type; /* Type of BPF program */
enum bpf_attach_type expected_attach_type; /* For some prog types */
u32 len; /* Number of filter blocks */
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index d43b54caa9a1..dd35abb37a23 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -6158,6 +6158,7 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
if (round_up_stack_depth(env, si[s].stack_depth) >= BPF_PRIV_STACK_MIN_SIZE) {
si[s].priv_stack_mode = PRIV_STACK_ADAPTIVE;
env->prog->aux->jits_use_priv_stack = true;
+ env->prog->percpu_state = true;
}
}
@@ -13106,6 +13107,10 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
if (err)
return err;
+ /* A per-CPU value stays the run's own only while no other run starts on the CPU */
+ if (meta.map.ptr && bpf_map_is_percpu_map(meta.map.ptr->map_type))
+ env->prog->percpu_state = true;
+
err = record_func_map(env, &meta, func_id, insn_idx);
if (err)
return err;
@@ -13132,10 +13137,16 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
switch (func_id) {
case BPF_FUNC_tail_call:
+ /* The target runs without a recursion check of its own */
+ env->prog->percpu_state = true;
err = check_resource_leak(env, false, true, "tail_call");
if (err)
return err;
break;
+ case BPF_FUNC_get_smp_processor_id:
+ /* The CPU id often indexes per-CPU slots that the program keeps itself */
+ env->prog->percpu_state = true;
+ break;
case BPF_FUNC_get_local_storage:
/* check that flags argument in get_local_storage(map, flags) is 0,
* this is required because get_local_storage() can't return an error.
@@ -13247,6 +13258,8 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
struct bpf_reg_state *reg = ®s[BPF_REG_1];
const struct btf_type *type;
+ env->prog->percpu_state = true;
+
if (reg->type & MEM_RCU) {
type = btf_type_by_id(reg->btf, reg->btf_id);
if (!type || !btf_type_is_struct(type)) {
@@ -19638,6 +19651,8 @@ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
__mark_reg_known(dst_reg, aux->map_off);
dst_reg->type = PTR_TO_MAP_VALUE;
dst_reg->map_ptr = map;
+ if (bpf_map_is_percpu_map(map->map_type))
+ env->prog->percpu_state = true;
WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
map->max_entries != 1);
/* We want reg->id to be same (0) as map_value is not distinct */
--
2.43.0
^ permalink raw reply related [flat|nested] 8+ messages in thread* [PATCH bpf-next v5 3/5] bpf: Check program recursion per task via bpf_ctx
2026-12-01 15:32 [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs Mike Bazov via B4 Relay
2026-12-01 15:32 ` [PATCH bpf-next v5 1/5] bpf: Avoid per-CPU private stack in preemptible tracing progs Mike Bazov via B4 Relay
2026-12-01 15:32 ` [PATCH bpf-next v5 2/5] bpf: Mark programs that keep per-CPU state Mike Bazov via B4 Relay
@ 2026-12-01 15:32 ` Mike Bazov via B4 Relay
2026-12-01 21:12 ` Alexei Starovoitov
2026-12-01 15:32 ` [PATCH bpf-next v5 4/5] bpf: Remove the per-CPU recursion counter of programs Mike Bazov via B4 Relay
` (2 subsequent siblings)
5 siblings, 1 reply; 8+ messages in thread
From: Mike Bazov via B4 Relay @ 2026-12-01 15:32 UTC (permalink / raw)
To: bpf, 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, linux-kernel,
Mike Bazov
From: Mike Bazov <mikeba@sentinelone.com>
Trampoline programs, raw tracepoint programs and tracepoint programs on
syscall tracepoints run preemptibly, but their recursion check is a
per-CPU, per-program counter. When a task is preempted inside a program,
the counter stays raised, and every other task that enters the program
on that CPU is dropped and counted as a recursion miss, although nothing
recursed.
Since commit 7dadeaa6e851 ("sched: Further restrict the preemption
modes") x86 and arm64 have only lazy and full preemption, so this
happens in normal operation, and every drop is a lost event.
Check recursion per task instead. The runners already link a
stack-allocated bpf_run_ctx into current->bpf_ctx with
bpf_set_run_ctx(). Move saved_run_ctx into struct bpf_run_ctx, so every
frame links to the outer one, and record in the frame the program that
runs in it. bpf_prog_enter_run_ctx() fills in the frame, refuses a
program that a frame in the chain already runs, and links the frame only
if the program may run; bpf_prog_exit_run_ctx() unlinks it. Interrupts
and NMIs run on top of the chain of the task they interrupt, so
recursion through them is still caught. The syscall tracepoint runner
links a frame per program.
An async callback doesn't run in a hook, and current may be any task.
Its runner now links a frame of its own on the stack, with
BPF_PROG_ASYNC_CB as the program, so that bpf_in_async_cb() still
recognizes it and a program that the callback runs into is still checked
against the frames below. This replaces bpf_async_run_ctx, which all
CPUs shared.
The frame of a marked program is unlinked before preemption is enabled:
enabling preemption can switch tasks, and a program that runs in the
scheduler would otherwise be dropped as recursion.
A program with prog->percpu_state set runs with preemption disabled
instead, so that no other task starts a run of it on the CPU before it
exits. Its per-CPU data stays its own, and the runs of other tasks wait
instead of being dropped. Two marked programs that share a per-CPU map
are also kept apart: no other task runs on the CPU while one of them
runs. The per-program counter never did that. A sleepable program can't
disable preemption: it has to use bpf_preempt_disable() itself, and a
sleepable struct_ops program no longer gets a private stack.
An extension (freplace) runs in the run of its target, so a marked
extension can only be attached to a raw tracepoint or tracepoint program
that runs with preemption disabled: marked and not sleepable.
Trade-offs:
- A marked program can't be preempted until it exits. A program that
tail-calls is marked, so its targets run that way too.
- A sleepable program with per-CPU state gets no protection.
- On PREEMPT_RT a marked program runs non-preemptibly too, as kprobe
programs do.
- An unmarked program that keeps per-CPU state the verifier doesn't
see can have two runs share it, and nothing counts that.
- A run that preempts another one inside a timed may_goto loop can
renew the other's 250 ms budget, as it already can for lsm programs.
- Attaching a marked extension to a raw tracepoint or tracepoint
program that is unmarked or sleepable now fails with -EINVAL.
Signed-off-by: Mike Bazov <mikeba@sentinelone.com>
---
include/linux/bpf.h | 120 ++++++++++++++++++++++++++++++++++++++++-------
kernel/bpf/helpers.c | 5 +-
kernel/bpf/syscall.c | 15 ++++++
kernel/bpf/trampoline.c | 29 +++++-------
kernel/bpf/verifier.c | 5 +-
kernel/trace/bpf_trace.c | 11 ++---
net/bpf/test_run.c | 9 +---
net/ipv4/bpf_tcp_ops.c | 6 +--
8 files changed, 141 insertions(+), 59 deletions(-)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 2dfd963a2703..2172e732ccc2 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -2801,7 +2801,22 @@ int bpf_prog_array_copy(struct bpf_prog_array *old_array,
struct bpf_prog_array **new_array);
struct bpf_prog *bpf_prog_dummy(void);
-struct bpf_run_ctx {};
+/*
+ * A frame in the chain of the programs that a task is running, from
+ * current->bpf_ctx to the outermost one.
+ */
+struct bpf_run_ctx {
+ /* The next outer frame, NULL in the outermost one */
+ struct bpf_run_ctx *saved_run_ctx;
+ /*
+ * The program that runs in the frame, see bpf_prog_enter_run_ctx().
+ * NULL if the runner records none, BPF_PROG_ASYNC_CB in an async callback.
+ */
+ const struct bpf_prog *prog;
+};
+
+/* ->prog of the frame of an async callback, see bpf_in_async_cb() */
+#define BPF_PROG_ASYNC_CB ((const struct bpf_prog *)1)
struct bpf_cg_run_ctx {
struct bpf_run_ctx run_ctx;
@@ -2819,25 +2834,98 @@ struct bpf_tramp_run_ctx {
struct bpf_run_ctx run_ctx;
u64 bpf_cookie;
int retval;
- struct bpf_run_ctx *saved_run_ctx;
};
-static inline struct bpf_run_ctx *bpf_set_run_ctx(struct bpf_run_ctx *new_ctx)
+/*
+ * Link @new_ctx into the chain of the current task, with @prog as the program
+ * that runs in it. Returns the frame it pointed to before.
+ */
+static __always_inline struct bpf_run_ctx *bpf_set_run_ctx_prog(struct bpf_run_ctx *new_ctx,
+ const struct bpf_prog *prog)
{
struct bpf_run_ctx *old_ctx = NULL;
#ifdef CONFIG_BPF_SYSCALL
- old_ctx = current->bpf_ctx;
- current->bpf_ctx = new_ctx;
+ old_ctx = READ_ONCE(current->bpf_ctx);
+ if (new_ctx) {
+ new_ctx->saved_run_ctx = old_ctx;
+ new_ctx->prog = prog;
+ }
+ /* Initialize the frame before interrupts and NMIs on this CPU see it. */
+ barrier();
+ WRITE_ONCE(current->bpf_ctx, new_ctx);
+#else
+ if (new_ctx)
+ new_ctx->saved_run_ctx = NULL;
#endif
return old_ctx;
}
-static inline void bpf_reset_run_ctx(struct bpf_run_ctx *old_ctx)
+static __always_inline struct bpf_run_ctx *bpf_set_run_ctx(struct bpf_run_ctx *new_ctx)
+{
+ return bpf_set_run_ctx_prog(new_ctx, NULL);
+}
+
+static __always_inline void bpf_reset_run_ctx(struct bpf_run_ctx *old_ctx)
+{
+#ifdef CONFIG_BPF_SYSCALL
+ WRITE_ONCE(current->bpf_ctx, old_ctx);
+ /* Unlink the frame before its stack storage can be reused. */
+ barrier();
+#endif
+}
+
+/*
+ * Run @prog in @run_ctx: link the frame into the chain of the current task,
+ * unless a frame in the chain runs @prog already. That would be recursion, and
+ * the frame is not linked. Interrupts and NMIs run on top of the chain of the
+ * task they interrupt, so recursion through them is caught too.
+ *
+ * A program with per-CPU state (prog->percpu_state) runs with preemption
+ * disabled, so that no other run of it starts on this CPU before it exits. A
+ * sleepable one has to use bpf_preempt_disable() itself. The frame of a
+ * non-sleepable one is linked only while preemption is disabled: a task switch
+ * runs the scheduler, and a program there must not find @prog in the chain.
+ *
+ * Returns false if @prog must not run. Call bpf_prog_exit_run_ctx() either way.
+ * Always inline: the callers are notrace.
+ */
+static __always_inline bool bpf_prog_enter_run_ctx(struct bpf_prog *prog,
+ struct bpf_run_ctx *run_ctx)
{
+ struct bpf_run_ctx *ctx, *old_ctx = NULL;
+
#ifdef CONFIG_BPF_SYSCALL
- current->bpf_ctx = old_ctx;
+ old_ctx = READ_ONCE(current->bpf_ctx);
#endif
+ run_ctx->saved_run_ctx = old_ctx;
+ run_ctx->prog = prog;
+ if (prog->percpu_state) {
+ if (!prog->sleepable)
+ preempt_disable_notrace();
+ /* sleepable prog should be using explicit bpf_preempt_disable() */
+ }
+ for (ctx = old_ctx; ctx; ctx = ctx->saved_run_ctx) {
+ if (ctx->prog == prog)
+ return false;
+ }
+#ifdef CONFIG_BPF_SYSCALL
+ /* Initialize the frame before interrupts and NMIs on this CPU see it. */
+ barrier();
+ WRITE_ONCE(current->bpf_ctx, run_ctx);
+#endif
+ return true;
+}
+
+/* After an enter that returned false the frame is not linked, and the reset changes nothing */
+static __always_inline void bpf_prog_exit_run_ctx(struct bpf_prog *prog,
+ struct bpf_run_ctx *run_ctx)
+{
+ bpf_reset_run_ctx(run_ctx->saved_run_ctx);
+ if (!prog->percpu_state)
+ return;
+ if (!prog->sleepable)
+ preempt_enable_notrace();
}
/* BPF program asks to bypass CAP_NET_BIND_SERVICE in bind. */
@@ -3498,11 +3586,11 @@ static inline bool has_current_bpf_ctx(void)
}
/* An async callback runs in no hook, and current is not the task that has armed it */
-extern struct bpf_run_ctx bpf_async_run_ctx;
-
static inline bool bpf_in_async_cb(void)
{
- return current->bpf_ctx == &bpf_async_run_ctx;
+ struct bpf_run_ctx *ctx = current->bpf_ctx;
+
+ return ctx && ctx->prog == BPF_PROG_ASYNC_CB;
}
void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog);
@@ -3519,7 +3607,6 @@ bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
{
const struct bpf_prog_array_item *item;
struct bpf_prog *prog;
- struct bpf_run_ctx *old_run_ctx;
struct bpf_trace_run_ctx run_ctx;
u32 ret = 1;
@@ -3530,7 +3617,6 @@ bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
run_ctx.is_uprobe = false;
- old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
item = &array->items[0];
while ((prog = READ_ONCE(item->prog))) {
/* Skip dummy_bpf_prog placeholder (len == 0) */
@@ -3539,15 +3625,14 @@ bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
continue;
}
- if (unlikely(!bpf_prog_get_recursion_context(prog))) {
+ run_ctx.bpf_cookie = item->bpf_cookie;
+ if (unlikely(!bpf_prog_enter_run_ctx(prog, &run_ctx.run_ctx))) {
bpf_prog_inc_misses_counter(prog);
- bpf_prog_put_recursion_context(prog);
+ bpf_prog_exit_run_ctx(prog, &run_ctx.run_ctx);
item++;
continue;
}
- run_ctx.bpf_cookie = item->bpf_cookie;
-
if (!prog->sleepable) {
guard(rcu)();
ret &= run_prog(prog, ctx);
@@ -3555,10 +3640,9 @@ bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
ret &= run_prog(prog, ctx);
}
- bpf_prog_put_recursion_context(prog);
+ bpf_prog_exit_run_ctx(prog, &run_ctx.run_ctx);
item++;
}
- bpf_reset_run_ctx(old_run_ctx);
migrate_enable();
return ret;
}
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 7b3e10a4a97e..aea624c85445 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -1235,14 +1235,13 @@ static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
static void bpf_async_refcount_put(struct bpf_async_cb *cb);
-struct bpf_run_ctx bpf_async_run_ctx;
-
static void bpf_run_async_cb(struct bpf_prog *prog, bpf_callback_t callback_fn,
struct bpf_map *map, void *key, void *value)
{
- struct bpf_run_ctx *old_ctx = bpf_set_run_ctx(&bpf_async_run_ctx);
+ struct bpf_run_ctx run_ctx, *old_ctx;
struct bpf_timed_may_goto saved;
+ old_ctx = bpf_set_run_ctx_prog(&run_ctx, BPF_PROG_ASYNC_CB);
bpf_timed_may_goto_save(prog, &saved);
callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
bpf_timed_may_goto_restore(prog, &saved);
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 0bdb4288beb2..0525dc376c9a 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -3878,6 +3878,21 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog,
err = -EINVAL;
goto out_unlock;
}
+ /*
+ * An extension runs in the run of its target. One that keeps per-CPU
+ * state relies on its runs not overlapping on a CPU, so a target that
+ * is checked per task must run with preemption disabled: marked and
+ * not sleepable.
+ */
+ if (prog->type == BPF_PROG_TYPE_EXT && prog->percpu_state &&
+ (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
+ tgt_prog->type == BPF_PROG_TYPE_TRACEPOINT) &&
+ (!tgt_prog->percpu_state || tgt_prog->sleepable)) {
+ bpf_log(log,
+ "Freplace prog with per-CPU state needs a target that runs with preemption disabled.\n");
+ err = -EINVAL;
+ goto out_unlock;
+ }
/*
* The size of these contexts depends on what the program is attached
* to, or run with. That is compared with max_ctx_offset of the program,
diff --git a/kernel/bpf/trampoline.c b/kernel/bpf/trampoline.c
index 96454443441b..619297eae8c1 100644
--- a/kernel/bpf/trampoline.c
+++ b/kernel/bpf/trampoline.c
@@ -1341,9 +1341,7 @@ static u64 notrace __bpf_prog_enter_recur(struct bpf_prog *prog, struct bpf_tram
{
rcu_read_lock_dont_migrate();
- run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
-
- if (unlikely(!bpf_prog_get_recursion_context(prog))) {
+ if (unlikely(!bpf_prog_enter_run_ctx(prog, &run_ctx->run_ctx))) {
bpf_prog_inc_misses_counter(prog);
if (prog->aux->recursion_detected)
prog->aux->recursion_detected(prog);
@@ -1384,10 +1382,9 @@ static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start,
struct bpf_tramp_run_ctx *run_ctx)
__releases(RCU)
{
- bpf_reset_run_ctx(run_ctx->saved_run_ctx);
-
+ /* Before the exit, which can enable preemption: time off the CPU is not run time */
update_prog_stats(prog, start);
- bpf_prog_put_recursion_context(prog);
+ bpf_prog_exit_run_ctx(prog, &run_ctx->run_ctx);
rcu_read_unlock_migrate();
}
@@ -1400,7 +1397,7 @@ static u64 notrace __bpf_prog_enter_lsm_cgroup(struct bpf_prog *prog,
*/
rcu_read_lock_dont_migrate();
- run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
+ bpf_set_run_ctx(&run_ctx->run_ctx);
return NO_START_TIME;
}
@@ -1409,7 +1406,7 @@ static void notrace __bpf_prog_exit_lsm_cgroup(struct bpf_prog *prog, u64 start,
struct bpf_tramp_run_ctx *run_ctx)
__releases(RCU)
{
- bpf_reset_run_ctx(run_ctx->saved_run_ctx);
+ bpf_reset_run_ctx(run_ctx->run_ctx.saved_run_ctx);
rcu_read_unlock_migrate();
}
@@ -1421,9 +1418,7 @@ u64 notrace __bpf_prog_enter_sleepable_recur(struct bpf_prog *prog,
migrate_disable();
might_fault();
- run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
-
- if (unlikely(!bpf_prog_get_recursion_context(prog))) {
+ if (unlikely(!bpf_prog_enter_run_ctx(prog, &run_ctx->run_ctx))) {
bpf_prog_inc_misses_counter(prog);
if (prog->aux->recursion_detected)
prog->aux->recursion_detected(prog);
@@ -1435,10 +1430,8 @@ u64 notrace __bpf_prog_enter_sleepable_recur(struct bpf_prog *prog,
void notrace __bpf_prog_exit_sleepable_recur(struct bpf_prog *prog, u64 start,
struct bpf_tramp_run_ctx *run_ctx)
{
- bpf_reset_run_ctx(run_ctx->saved_run_ctx);
-
update_prog_stats(prog, start);
- bpf_prog_put_recursion_context(prog);
+ bpf_prog_exit_run_ctx(prog, &run_ctx->run_ctx);
migrate_enable();
rcu_read_unlock_trace();
}
@@ -1450,7 +1443,7 @@ static u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog,
migrate_disable();
might_fault();
- run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
+ bpf_set_run_ctx(&run_ctx->run_ctx);
return bpf_prog_start_time();
}
@@ -1458,7 +1451,7 @@ static u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog,
static void notrace __bpf_prog_exit_sleepable(struct bpf_prog *prog, u64 start,
struct bpf_tramp_run_ctx *run_ctx)
{
- bpf_reset_run_ctx(run_ctx->saved_run_ctx);
+ bpf_reset_run_ctx(run_ctx->run_ctx.saved_run_ctx);
update_prog_stats(prog, start);
migrate_enable();
@@ -1471,7 +1464,7 @@ static u64 notrace __bpf_prog_enter(struct bpf_prog *prog,
{
rcu_read_lock_dont_migrate();
- run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
+ bpf_set_run_ctx(&run_ctx->run_ctx);
return bpf_prog_start_time();
}
@@ -1480,7 +1473,7 @@ static void notrace __bpf_prog_exit(struct bpf_prog *prog, u64 start,
struct bpf_tramp_run_ctx *run_ctx)
__releases(RCU)
{
- bpf_reset_run_ctx(run_ctx->saved_run_ctx);
+ bpf_reset_run_ctx(run_ctx->run_ctx.saved_run_ctx);
update_prog_stats(prog, start);
rcu_read_unlock_migrate();
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index dd35abb37a23..2e3be7c11221 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -5434,7 +5434,8 @@ static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
* program attached to both a syscall and a regular tracepoint. They always
* use the task's kernel stack. Kprobe multi, kprobe session and perf_event
* programs are serialized per CPU by bpf_prog_active, and struct_ops
- * programs that request a private stack keep per-CPU recursion protection.
+ * programs that get a private stack run with preemption disabled, see
+ * bpf_prog_enter_run_ctx(). A sleepable one can't, so it gets none.
*/
switch (prog->type) {
case BPF_PROG_TYPE_KPROBE:
@@ -5450,7 +5451,7 @@ static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
case BPF_PROG_TYPE_PERF_EVENT:
return PRIV_STACK_ADAPTIVE;
case BPF_PROG_TYPE_STRUCT_OPS:
- if (prog->aux->priv_stack_requested)
+ if (prog->aux->priv_stack_requested && !prog->sleepable)
return PRIV_STACK_ADAPTIVE;
fallthrough;
default:
diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c
index 7b9bd6f560a5..2031c3727320 100644
--- a/kernel/trace/bpf_trace.c
+++ b/kernel/trace/bpf_trace.c
@@ -2125,7 +2125,6 @@ void __bpf_trace_run(struct bpf_raw_tp_link *link, u64 *args)
struct srcu_ctr __percpu *scp = NULL;
struct bpf_prog *prog = link->link.prog;
bool sleepable = prog->sleepable;
- struct bpf_run_ctx *old_run_ctx;
struct bpf_trace_run_ctx run_ctx;
if (sleepable) {
@@ -2135,19 +2134,15 @@ void __bpf_trace_run(struct bpf_raw_tp_link *link, u64 *args)
rcu_read_lock_dont_migrate();
}
- if (unlikely(!bpf_prog_get_recursion_context(prog))) {
+ run_ctx.bpf_cookie = link->cookie;
+ if (unlikely(!bpf_prog_enter_run_ctx(prog, &run_ctx.run_ctx))) {
bpf_prog_inc_misses_counter(prog);
goto out;
}
- run_ctx.bpf_cookie = link->cookie;
- old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
-
(void)bpf_prog_run(prog, args);
-
- bpf_reset_run_ctx(old_run_ctx);
out:
- bpf_prog_put_recursion_context(prog);
+ bpf_prog_exit_run_ctx(prog, &run_ctx.run_ctx);
if (sleepable) {
migrate_enable();
diff --git a/net/bpf/test_run.c b/net/bpf/test_run.c
index cc3236e3c0c4..8b8c4e9ded9d 100644
--- a/net/bpf/test_run.c
+++ b/net/bpf/test_run.c
@@ -748,9 +748,6 @@ __bpf_prog_test_run_raw_tp(void *data)
struct bpf_raw_tp_test_run_info *info = data;
struct srcu_ctr __percpu *scp = NULL;
struct bpf_trace_run_ctx run_ctx = {};
- struct bpf_run_ctx *old_run_ctx;
-
- old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
if (info->prog->sleepable) {
scp = rcu_read_lock_tasks_trace();
@@ -759,7 +756,7 @@ __bpf_prog_test_run_raw_tp(void *data)
rcu_read_lock();
}
- if (unlikely(!bpf_prog_get_recursion_context(info->prog))) {
+ if (unlikely(!bpf_prog_enter_run_ctx(info->prog, &run_ctx.run_ctx))) {
bpf_prog_inc_misses_counter(info->prog);
goto out;
}
@@ -767,7 +764,7 @@ __bpf_prog_test_run_raw_tp(void *data)
info->retval = bpf_prog_run(info->prog, info->ctx);
out:
- bpf_prog_put_recursion_context(info->prog);
+ bpf_prog_exit_run_ctx(info->prog, &run_ctx.run_ctx);
if (info->prog->sleepable) {
migrate_enable();
@@ -775,8 +772,6 @@ __bpf_prog_test_run_raw_tp(void *data)
} else {
rcu_read_unlock();
}
-
- bpf_reset_run_ctx(old_run_ctx);
}
int bpf_prog_test_run_raw_tp(struct bpf_prog *prog,
diff --git a/net/ipv4/bpf_tcp_ops.c b/net/ipv4/bpf_tcp_ops.c
index 926b29d36883..6b8ad08fa54d 100644
--- a/net/ipv4/bpf_tcp_ops.c
+++ b/net/ipv4/bpf_tcp_ops.c
@@ -207,11 +207,11 @@ BPF_CALL_0(bpf_tcp_ops_get_retval)
* return value chained across the bpf_tcp_ops attached to the cgroup
* and is this program's saved_run_ctx.
*/
- if (bpf_in_async_cb() || WARN_ON_ONCE(!ctx->saved_run_ctx))
+ if (bpf_in_async_cb() || WARN_ON_ONCE(!ctx->run_ctx.saved_run_ctx))
return 0;
- return container_of(ctx->saved_run_ctx, struct bpf_tramp_run_ctx,
- run_ctx)->retval;
+ return container_of(ctx->run_ctx.saved_run_ctx,
+ struct bpf_tramp_run_ctx, run_ctx)->retval;
}
const struct bpf_func_proto bpf_tcp_ops_get_retval_proto = {
--
2.43.0
^ permalink raw reply related [flat|nested] 8+ messages in thread* Re: [PATCH bpf-next v5 3/5] bpf: Check program recursion per task via bpf_ctx
2026-12-01 15:32 ` [PATCH bpf-next v5 3/5] bpf: Check program recursion per task via bpf_ctx Mike Bazov via B4 Relay
@ 2026-12-01 21:12 ` Alexei Starovoitov
0 siblings, 0 replies; 8+ messages in thread
From: Alexei Starovoitov @ 2026-12-01 21:12 UTC (permalink / raw)
To: mikeba, Mike Bazov via B4 Relay, bpf, 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, linux-kernel
On Tue, Dec 01, 2026 at 07:32 AM Mike Bazov via B4 Relay <devnull+mikeba.sentinelone.com@kernel.org> wrote:
> - On PREEMPT_RT a marked program runs non-preemptibly too, as kprobe
> programs do.
Applied, but let's keep a per-cpu counter for marked progs on RT.
Pls send a followup with something like:
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 648a8b9..0f9398e 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -37,6 +37,7 @@
#include <linux/xattr.h>
#include <linux/key.h>
#include <linux/ftrace.h>
+#include <linux/u64_stats_sync.h>
#include <asm/rqspinlock.h>
struct bpf_verifier_env;
@@ -2055,6 +2056,14 @@ struct bpf_prog_aux {
struct bpf_map __rcu *st_ops_assoc;
};
+struct bpf_prog_stats {
+ u64_stats_t cnt;
+ u64_stats_t nsecs;
+ u64_stats_t misses;
+ struct u64_stats_sync syncp;
+ int active; /* PREEMPT_RT only, see bpf_prog_enter_run_ctx() */
+} __aligned(2 * sizeof(u64));
+
struct bpf_prog {
u16 pages; /* Number of allocated pages */
u32 jited:1, /* Is our filter JIT'ed? */
@@ -2863,10 +2872,13 @@ static __always_inline bool bpf_prog_enter_run_ctx(struct bpf_prog *prog,
#endif
run_ctx->saved_run_ctx = old_ctx;
run_ctx->prog = prog;
- if (prog->percpu_state) {
- if (!prog->sleepable)
+ /* sleepable prog should be using explicit bpf_preempt_disable() */
+ if (prog->percpu_state && !prog->sleepable) {
+ if (!IS_ENABLED(CONFIG_PREEMPT_RT))
preempt_disable_notrace();
- /* sleepable prog should be using explicit bpf_preempt_disable() */
+ else if (this_cpu_inc_return(prog->stats->active) != 1)
+ return false;
}
for (ctx = old_ctx; ctx; ctx = ctx->saved_run_ctx) {
if (ctx->prog == prog)
@@ -2885,10 +2897,12 @@ static __always_inline void bpf_prog_exit_run_ctx(struct bpf_prog *prog,
struct bpf_run_ctx *run_ctx)
{
bpf_reset_run_ctx(run_ctx->saved_run_ctx);
- if (!prog->percpu_state)
+ if (!prog->percpu_state || prog->sleepable)
return;
- if (!prog->sleepable)
+ if (!IS_ENABLED(CONFIG_PREEMPT_RT))
preempt_enable_notrace();
+ else
+ this_cpu_dec(prog->stats->active);
}
/* BPF program asks to bypass CAP_NET_BIND_SERVICE in bind. */
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 06f1286..20e7c52 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -807,13 +807,6 @@ struct bpf_binary_header {
u8 image[] __aligned(BPF_IMAGE_ALIGNMENT);
};
-struct bpf_prog_stats {
- u64_stats_t cnt;
- u64_stats_t nsecs;
- u64_stats_t misses;
- struct u64_stats_sync syncp;
-} __aligned(2 * sizeof(u64));
-
/*
* Per-cpu memory of a prog. All may_goto of one invocation of the prog use it. An invocation is
* one call from the kernel into the main prog, with the subprogs and sync callbacks it reaches.
> + * programs that get a private stack run with preemption disabled, see
> + * bpf_prog_enter_run_ctx(). A sleepable one can't, so it gets none.
There is an existing bug here,
when the struct_ops prog is the target of a tail call.
Pls follow up with a fix like:
diff --git a/kernel/bpf/arraymap.c b/kernel/bpf/arraymap.c
index 508706d..7b294c8 100644
--- a/kernel/bpf/arraymap.c
+++ b/kernel/bpf/arraymap.c
@@ -1043,7 +1043,9 @@ static void *prog_fd_array_get_ptr(struct bpf_map *map,
if (IS_ERR(prog))
return prog;
if (prog->type == BPF_PROG_TYPE_EXT ||
+ (prog->type == BPF_PROG_TYPE_STRUCT_OPS && prog->aux->jits_use_priv_stack) ||
!bpf_prog_map_compatible(map, prog)) {
bpf_prog_put(prog);
return ERR_PTR(-EINVAL);
^ permalink raw reply related [flat|nested] 8+ messages in thread
* [PATCH bpf-next v5 4/5] bpf: Remove the per-CPU recursion counter of programs
2026-12-01 15:32 [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs Mike Bazov via B4 Relay
` (2 preceding siblings ...)
2026-12-01 15:32 ` [PATCH bpf-next v5 3/5] bpf: Check program recursion per task via bpf_ctx Mike Bazov via B4 Relay
@ 2026-12-01 15:32 ` Mike Bazov via B4 Relay
2026-12-01 15:32 ` [PATCH bpf-next v5 5/5] selftests/bpf: Add preemption recursion test for tracing programs Mike Bazov via B4 Relay
2026-12-01 21:10 ` [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs patchwork-bot+netdevbpf
5 siblings, 0 replies; 8+ messages in thread
From: Mike Bazov via B4 Relay @ 2026-12-01 15:32 UTC (permalink / raw)
To: bpf, 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, linux-kernel,
Mike Bazov
From: Mike Bazov <mikeba@sentinelone.com>
Recursion of every program that used prog->active is checked per task
now. Remove the counter, the bpf_prog_get_recursion_context() and
bpf_prog_put_recursion_context() helpers, BPF_NR_CONTEXTS, and the
per-CPU memory that each program allocated for it.
Signed-off-by: Mike Bazov <mikeba@sentinelone.com>
---
include/linux/bpf.h | 37 -------------------------------------
kernel/bpf/core.c | 12 ------------
2 files changed, 49 deletions(-)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 2172e732ccc2..648a8b9be47b 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -2055,8 +2055,6 @@ struct bpf_prog_aux {
struct bpf_map __rcu *st_ops_assoc;
};
-#define BPF_NR_CONTEXTS 4 /* normal, softirq, hardirq, NMI */
-
struct bpf_prog {
u16 pages; /* Number of allocated pages */
u32 jited:1, /* Is our filter JIT'ed? */
@@ -2086,7 +2084,6 @@ struct bpf_prog {
u8 tag[BPF_TAG_SIZE];
};
struct bpf_prog_stats __percpu *stats;
- u8 __percpu *active; /* u8[BPF_NR_CONTEXTS] for recursion protection */
unsigned int (*bpf_func)(const void *ctx,
const struct bpf_insn *insn);
struct bpf_prog_aux *aux; /* Auxiliary fields */
@@ -2379,40 +2376,6 @@ struct bpf_struct_ops_common_value {
enum bpf_struct_ops_state state;
};
-static inline bool bpf_prog_get_recursion_context(struct bpf_prog *prog)
-{
-#ifdef CONFIG_ARM64
- u8 rctx = interrupt_context_level();
- u8 *active = this_cpu_ptr(prog->active);
- u32 val;
-
- preempt_disable();
- active[rctx]++;
- val = le32_to_cpu(*(__le32 *)active);
- preempt_enable();
- if (val != BIT(rctx * 8))
- return false;
-
- return true;
-#else
- return this_cpu_inc_return(*(int __percpu *)(prog->active)) == 1;
-#endif
-}
-
-static inline void bpf_prog_put_recursion_context(struct bpf_prog *prog)
-{
-#ifdef CONFIG_ARM64
- u8 rctx = interrupt_context_level();
- u8 *active = this_cpu_ptr(prog->active);
-
- preempt_disable();
- active[rctx]--;
- preempt_enable();
-#else
- this_cpu_dec(*(int __percpu *)(prog->active));
-#endif
-}
-
static inline bool is_tracing_multi(enum bpf_attach_type type)
{
return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index facb0d6d2e8d..32a267656c0e 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -118,14 +118,6 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
vfree(fp);
return NULL;
}
- fp->active = __alloc_percpu_gfp(sizeof(u8[BPF_NR_CONTEXTS]), 4,
- bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
- if (!fp->active) {
- vfree(fp);
- kfree(aux);
- return NULL;
- }
-
fp->pages = size / PAGE_SIZE;
fp->aux = aux;
fp->aux->main_prog_aux = aux;
@@ -161,7 +153,6 @@ struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
prog->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags);
if (!prog->stats) {
- free_percpu(prog->active);
kfree(prog->aux);
vfree(prog);
return NULL;
@@ -282,7 +273,6 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
*/
fp_old->aux = NULL;
fp_old->stats = NULL;
- fp_old->active = NULL;
__bpf_prog_free(fp_old);
}
@@ -302,7 +292,6 @@ void __bpf_prog_free(struct bpf_prog *fp)
kfree(fp->aux);
}
free_percpu(fp->stats);
- free_percpu(fp->active);
vfree(fp);
}
@@ -1816,7 +1805,6 @@ static void bpf_prog_clone_free(struct bpf_prog *fp)
*/
fp->aux = NULL;
fp->stats = NULL;
- fp->active = NULL;
__bpf_prog_free(fp);
}
--
2.43.0
^ permalink raw reply related [flat|nested] 8+ messages in thread* [PATCH bpf-next v5 5/5] selftests/bpf: Add preemption recursion test for tracing programs
2026-12-01 15:32 [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs Mike Bazov via B4 Relay
` (3 preceding siblings ...)
2026-12-01 15:32 ` [PATCH bpf-next v5 4/5] bpf: Remove the per-CPU recursion counter of programs Mike Bazov via B4 Relay
@ 2026-12-01 15:32 ` Mike Bazov via B4 Relay
2026-12-01 21:10 ` [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs patchwork-bot+netdevbpf
5 siblings, 0 replies; 8+ messages in thread
From: Mike Bazov via B4 Relay @ 2026-12-01 15:32 UTC (permalink / raw)
To: bpf, 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, linux-kernel,
Mike Bazov
From: Mike Bazov <mikeba@sentinelone.com>
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 <mikeba@sentinelone.com>
---
.../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 <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#include <test_progs.h>
+#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 <asm/unistd.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_misc.h"
+#include "bpf_compiler.h"
+#include <bpf_may_goto.h>
+
+/* 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
^ permalink raw reply related [flat|nested] 8+ messages in thread* Re: [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs
2026-12-01 15:32 [PATCH bpf-next v5 0/5] bpf: Check recursion per task for preemptible programs Mike Bazov via B4 Relay
` (4 preceding siblings ...)
2026-12-01 15:32 ` [PATCH bpf-next v5 5/5] selftests/bpf: Add preemption recursion test for tracing programs Mike Bazov via B4 Relay
@ 2026-12-01 21:10 ` patchwork-bot+netdevbpf
5 siblings, 0 replies; 8+ messages in thread
From: patchwork-bot+netdevbpf @ 2026-12-01 21:10 UTC (permalink / raw)
To: Mike Bazov
Cc: bpf, ast, daniel, andrii, martin.lau, eddyz87, memxor, song,
yonghong.song, jolsa, john.fastabend, emil, ihor.solodrai,
rostedt, mhiramat, mathieu.desnoyers, jp.kobryn,
linux-trace-kernel, linux-kernel
Hello:
This series was applied to bpf/bpf-next.git (master)
by Alexei Starovoitov <ast@kernel.org>:
On Tue, 01 Dec 2026 17:32:11 +0200 you wrote:
> fentry, fexit, raw_tp and syscall tracepoint programs can be preempted
> while they run, but their recursion check is a per-CPU counter:
>
> task A enters prog on CPU 0 prog->active = 1
> task A is preempted inside prog
> task B enters prog on CPU 0 dropped, counted as recursion miss
>
> [...]
Here is the summary with links:
- [bpf-next,v5,1/5] bpf: Avoid per-CPU private stack in preemptible tracing progs
https://git.kernel.org/bpf/bpf-next/c/2a16d9e22383
- [bpf-next,v5,2/5] bpf: Mark programs that keep per-CPU state
https://git.kernel.org/bpf/bpf-next/c/9e38f12ae067
- [bpf-next,v5,3/5] bpf: Check program recursion per task via bpf_ctx
https://git.kernel.org/bpf/bpf-next/c/2f381c8fd2ff
- [bpf-next,v5,4/5] bpf: Remove the per-CPU recursion counter of programs
https://git.kernel.org/bpf/bpf-next/c/a424697a9e2d
- [bpf-next,v5,5/5] selftests/bpf: Add preemption recursion test for tracing programs
https://git.kernel.org/bpf/bpf-next/c/095b368b4b47
You are awesome, thank you!
--
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html
^ permalink raw reply [flat|nested] 8+ messages in thread