BPF List
 help / color / mirror / Atom feed
* [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register
@ 2026-12-05  3:37 Alexei Starovoitov
  2026-12-05  3:37 ` [PATCH bpf-next 1/7] selftests/bpf: Don't depend on the expansion of may_goto Alexei Starovoitov
                   ` (7 more replies)
  0 siblings, 8 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:37 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

may_goto cancels a prog that loops for too long. It counts iterations in
per-cpu memory that all invocations of the prog share. When one preempts
another, a loop can run forever or get cancelled too early.

Give each invocation its own state and keep it in %r11 on x86-64, in x24
on arm64 and in current on other archs. It also makes may_goto faster: two
insns on x86-64 and arm64.

  ns per iteration                        Ice Lake       Neoverse V2
                                       before   after  before   after
  empty loop                             1.81    0.29    2.15    0.48
  load and store in arena                1.44    1.15    2.15    1.21
  call of bpf_get_numa_node_id()         2.01    1.81    2.15    0.95
  may_goto in callback of bpf_loop()     2.61    2.02    2.74    2.17
  call of a subprog with may_goto        3.49    1.99    4.30    2.15
  the same in a prog with a tail call    2.99    4.28    4.30    4.40

Progs with tail calls pass the state to subprogs through current, which is
slower. freplace of a subprog of a prog with may_goto is now refused.

Alexei Starovoitov (7):
  selftests/bpf: Don't depend on the expansion of may_goto
  selftests/bpf: Wait longer in parallel tests of libarena
  bpf: Keep the state of may_goto per invocation
  bpf, x86: Keep the state of may_goto in %r11
  bpf, arm64: Keep the state of may_goto in x24
  bpf: Keep the state of may_goto in the task on other archs
  selftests/bpf: Test may_goto state across calls and clobbers of %r11

 arch/arm64/net/bpf_jit_comp.c                 | 203 ++++++--
 arch/arm64/net/bpf_timed_may_goto.S           |  20 +-
 arch/loongarch/net/bpf_timed_may_goto.S       |   9 +-
 arch/powerpc/net/bpf_timed_may_goto.S         |  10 +-
 arch/riscv/net/bpf_timed_may_goto.S           |   8 +-
 arch/s390/net/bpf_timed_may_goto.S            |   2 +-
 arch/x86/net/bpf_jit_comp.c                   | 362 ++++++++++++---
 arch/x86/net/bpf_timed_may_goto.S             |  17 +-
 include/linux/bpf.h                           |   6 +-
 include/linux/bpf_verifier.h                  |   9 +
 include/linux/filter.h                        |  74 ++-
 include/linux/sched.h                         |   2 +
 kernel/bpf/arena.c                            |   1 +
 kernel/bpf/core.c                             |  78 +---
 kernel/bpf/disasm.c                           |  15 +
 kernel/bpf/fixups.c                           | 432 +++++++++++++-----
 kernel/bpf/helpers.c                          |  18 +-
 kernel/bpf/rqspinlock.c                       |   2 +
 kernel/bpf/stream.c                           |   5 +-
 kernel/bpf/verifier.c                         |  19 +
 .../selftests/test_parallel_bitmap.bpf.c      |   2 +-
 .../selftests/test_parallel_spmc.bpf.c        |   2 +-
 .../selftests/bpf/prog_tests/patch_list.c     |   9 +-
 .../selftests/bpf/prog_tests/share_subprogs.c |   9 +-
 .../selftests/bpf/prog_tests/timed_may_goto.c |  71 ++-
 .../selftests/bpf/progs/timed_may_goto.c      |  96 +++-
 .../selftests/bpf/progs/timed_may_goto_ext.c  |  18 +
 .../selftests/bpf/progs/timed_may_goto_user.c |  53 ++-
 .../bpf/progs/verifier_arena_stack.c          |   6 +-
 .../bpf/progs/verifier_bpf_fastcall.c         |  70 +--
 .../selftests/bpf/progs/verifier_budget.c     |  18 +-
 .../selftests/bpf/progs/verifier_loop_walk.c  |   2 +-
 .../selftests/bpf/progs/verifier_may_goto_1.c |  83 +++-
 .../selftests/bpf/progs/verifier_passes.c     |   2 +-
 .../selftests/bpf/progs/verifier_patch_list.c | 117 +++--
 .../selftests/bpf/progs/verifier_trip_count.c |   2 +
 36 files changed, 1340 insertions(+), 512 deletions(-)

-- 
2.55.0


^ permalink raw reply	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 1/7] selftests/bpf: Don't depend on the expansion of may_goto
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
@ 2026-12-05  3:37 ` Alexei Starovoitov
  2026-12-05  3:37 ` [PATCH bpf-next 2/7] selftests/bpf: Wait longer in parallel tests of libarena Alexei Starovoitov
                   ` (6 subsequent siblings)
  7 siblings, 0 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:37 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

may_goto is about to become one BPF insn on x86-64 and arm64. These tests
check other things, so let them match any form of it.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
 tools/testing/selftests/bpf/prog_tests/patch_list.c |  9 ++++++++-
 .../selftests/bpf/prog_tests/share_subprogs.c       |  9 ++++++---
 tools/testing/selftests/bpf/progs/verifier_budget.c | 13 ++-----------
 .../selftests/bpf/progs/verifier_loop_walk.c        |  2 +-
 tools/testing/selftests/bpf/progs/verifier_passes.c |  2 +-
 .../selftests/bpf/progs/verifier_trip_count.c       |  2 ++
 6 files changed, 20 insertions(+), 17 deletions(-)

diff --git a/tools/testing/selftests/bpf/prog_tests/patch_list.c b/tools/testing/selftests/bpf/prog_tests/patch_list.c
index 68d22cac6937..230ffa539532 100644
--- a/tools/testing/selftests/bpf/prog_tests/patch_list.c
+++ b/tools/testing/selftests/bpf/prog_tests/patch_list.c
@@ -45,7 +45,7 @@ static int run(struct bpf_program *prog)
 }
 #endif
 
-/* One of the insns that set the may_goto count, in the stack or in per-cpu memory. */
+/* One of the insns that set up may_goto at the start of a function. */
 static bool is_may_goto_setup(const struct bpf_insn *insn)
 {
 	switch (insn->code) {
@@ -53,7 +53,14 @@ static bool is_may_goto_setup(const struct bpf_insn *insn)
 	case BPF_LD | BPF_IMM | BPF_DW:
 	case 0: /* the second half of ld_imm64 */
 	case BPF_ALU64 | BPF_MOV | BPF_X:
+	case BPF_JMP | BPF_CALL:
+	case BPF_ALU64 | BPF_ADD | BPF_K:
+	case BPF_ALU64 | BPF_LSH | BPF_K:
+	case BPF_LDX | BPF_MEM | BPF_DW:
+	case BPF_STX | BPF_MEM | BPF_DW:
 		return true;
+	case BPF_ALU64 | BPF_MOV | BPF_K:
+		return insn->dst_reg != BPF_REG_0;
 	}
 	return false;
 }
diff --git a/tools/testing/selftests/bpf/prog_tests/share_subprogs.c b/tools/testing/selftests/bpf/prog_tests/share_subprogs.c
index 607af342aede..45e7f70b6477 100644
--- a/tools/testing/selftests/bpf/prog_tests/share_subprogs.c
+++ b/tools/testing/selftests/bpf/prog_tests/share_subprogs.c
@@ -98,9 +98,12 @@ static void test_value(void)
 	ASSERT_EQ(owner_of(bpf_program__fd(skel->progs.thrown_1)), 0, "copies");
 	fd = bpf_program__fd(skel->progs.value_2);
 	ASSERT_NEQ(owner_of(fd), 0, "shared");
-	/* the landing pad is 'r0 = 1; exit' */
-	if (ASSERT_OK(get_xlated_program(fd, &insns, &cnt), "xlated"))
-		ASSERT_EQ(insns[cnt - 2].imm, 1, "value");
+	/* the landing pad is the last 'r0 = 1' */
+	if (ASSERT_OK(get_xlated_program(fd, &insns, &cnt), "xlated")) {
+		while (--cnt && insns[cnt].code != (BPF_ALU64 | BPF_MOV | BPF_K))
+			;
+		ASSERT_EQ(insns[cnt].imm, 1, "value");
+	}
 	free(insns);
 out:
 	share_subprogs__destroy(skel);
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index 8fac2763239e..7e17decbf5b5 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -1189,21 +1189,12 @@ __naked void guard_keeps_r0(void)
 		: __imm_addr(var)			\
 		: __clobber_all
 
-/* No register is dead: R0 waits in the stack */
+/* No register is dead */
 SEC("socket")
 __description("budget: may_goto where all registers are live")
 __arch_x86_64
 __arch_arm64
 __success __retval(36)
-__xlated("...")
-__xlated("*(u64 *)(r10 -8) = r0")
-__xlated("r0 = 0x{{.*}}")
-__xlated("r0 = &(void __percpu *)(r0)")
-__xlated("r13 = *(u64 *)(r0 +0)")
-__xlated("...")
-__xlated("*(u64 *)(r0 +0) = r13")
-__xlated("r0 = *(u64 *)(r10 -8)")
-__xlated("if r1 != 0x0 goto pc-{{[0-9]+}}")
 __naked void guard_all_regs_live(void)
 {
 	asm volatile (
@@ -1397,7 +1388,7 @@ __msg("processed {{[0-9][0-9]}} insns")
 __xlated("r8 += 1")
 __xlated("r7 <<= 1")
 __xlated("...")
-__xlated("if r13 == 0x0 goto")
+__xlated("{{(if r13 == 0x0 goto|if r13 s< 0x0 goto|may_goto) pc}}")
 __xlated("...")
 __xlated("if r7 != 0x400 goto pc-{{[0-9]+}}")
 __naked void ten_trips_that_differ(void)
diff --git a/tools/testing/selftests/bpf/progs/verifier_loop_walk.c b/tools/testing/selftests/bpf/progs/verifier_loop_walk.c
index 0327597a902d..b19c3cd584cc 100644
--- a/tools/testing/selftests/bpf/progs/verifier_loop_walk.c
+++ b/tools/testing/selftests/bpf/progs/verifier_loop_walk.c
@@ -73,7 +73,7 @@ __description("walk: a loop with two entries")
 __success __retval(0)
 __arch_x86_64
 __arch_arm64
-__xlated("if r13 == 0x0 goto")
+__xlated("{{(if r13 == 0x0 goto|may_goto) pc}}")
 __xlated("...")
 __xlated("w3 += -1")
 __xlated("if w3 s< 0x0 goto pc+2")
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index 48c59e7935e2..bd3c40e8657c 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -713,7 +713,7 @@ SEC("tc")
 __description("peel: the state that continues is from an earlier trip of the outer loop")
 __arch_x86_64 __arch_arm64
 __success
-__xlated("call unknown")
+__xlated("{{(call unknown|may_goto pc)}}")
 __naked void prune_by_outer_loop(void)
 {
 	ASM(VALUE_IN_R9
diff --git a/tools/testing/selftests/bpf/progs/verifier_trip_count.c b/tools/testing/selftests/bpf/progs/verifier_trip_count.c
index 23253770be58..ec9be17700e1 100644
--- a/tools/testing/selftests/bpf/progs/verifier_trip_count.c
+++ b/tools/testing/selftests/bpf/progs/verifier_trip_count.c
@@ -4610,8 +4610,10 @@ __xlated("r8 += 1")
 __xlated("if r8 < 0x3 goto pc-2")
 __xlated("goto pc-{{[0-9]+}}")
 __xlated("r0 = 0")
+__xlated("...")
 __xlated("exit")
 __xlated("r0 = 0")
+__xlated("...")
 __xlated("exit")
 __naked void nested_terminating_prune(void)
 {
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 2/7] selftests/bpf: Wait longer in parallel tests of libarena
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
  2026-12-05  3:37 ` [PATCH bpf-next 1/7] selftests/bpf: Don't depend on the expansion of may_goto Alexei Starovoitov
@ 2026-12-05  3:37 ` Alexei Starovoitov
  2026-12-05  3:37 ` [PATCH bpf-next 3/7] bpf: Keep the state of may_goto per invocation Alexei Starovoitov
                   ` (5 subsequent siblings)
  7 siblings, 0 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:37 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

The threads of these tests spin in a loop with may_goto until the other
thread starts, and give up after BPF_MAX_LOOPS iterations. may_goto is
about to get faster, so that's too early. Spin 8 times longer.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
 .../selftests/bpf/libarena/selftests/test_parallel_bitmap.bpf.c | 2 +-
 .../selftests/bpf/libarena/selftests/test_parallel_spmc.bpf.c   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/tools/testing/selftests/bpf/libarena/selftests/test_parallel_bitmap.bpf.c b/tools/testing/selftests/bpf/libarena/selftests/test_parallel_bitmap.bpf.c
index 017add229bef..a0fba6994a19 100644
--- a/tools/testing/selftests/bpf/libarena/selftests/test_parallel_bitmap.bpf.c
+++ b/tools/testing/selftests/bpf/libarena/selftests/test_parallel_bitmap.bpf.c
@@ -9,7 +9,7 @@
 
 #define TEST_BITMAP_THREADS	2
 #define TEST_BITMAP_BITS	(2 * BITS_PER_LONG_LONG)
-#define TEST_BITMAP_SYNC_SPINS	BPF_MAX_LOOPS
+#define TEST_BITMAP_SYNC_SPINS	(8 * BPF_MAX_LOOPS)
 #define TEST_BITMAP_ITERS	10 * 1000 * 1000
 #define TEST_BITMAP_NSEC	(50 * 1000 * 1000)
 
diff --git a/tools/testing/selftests/bpf/libarena/selftests/test_parallel_spmc.bpf.c b/tools/testing/selftests/bpf/libarena/selftests/test_parallel_spmc.bpf.c
index 5fa96eb74095..e04920738121 100644
--- a/tools/testing/selftests/bpf/libarena/selftests/test_parallel_spmc.bpf.c
+++ b/tools/testing/selftests/bpf/libarena/selftests/test_parallel_spmc.bpf.c
@@ -17,7 +17,7 @@
  * and operations are wait-free we just spin around the quiescence
  * point instead. If we time out, we just fail the benchmark.
  */
-#define TEST_SPMC_SYNC_SPINS BPF_MAX_LOOPS
+#define TEST_SPMC_SYNC_SPINS (8 * BPF_MAX_LOOPS)
 
 /*
  * We track all the values we retrieve from the queue
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 3/7] bpf: Keep the state of may_goto per invocation
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
  2026-12-05  3:37 ` [PATCH bpf-next 1/7] selftests/bpf: Don't depend on the expansion of may_goto Alexei Starovoitov
  2026-12-05  3:37 ` [PATCH bpf-next 2/7] selftests/bpf: Wait longer in parallel tests of libarena Alexei Starovoitov
@ 2026-12-05  3:37 ` Alexei Starovoitov
  2026-12-05  3:37 ` [PATCH bpf-next 4/7] bpf, x86: Keep the state of may_goto in %r11 Alexei Starovoitov
                   ` (4 subsequent siblings)
  7 siblings, 0 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:37 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

may_goto keeps the count of iterations and the start time in per-cpu
memory of the prog. Each invocation resets them at entry, also when it
preempts another one:

  task A                          task B
  reset count and time
  while (can_loop) ...
          preempted       ->      reset count and time
                                  while (can_loop) ...
          runs again      <-      preempted

A goes on with the count and time of B. It gets more time than it should,
or it is cancelled because B ran out of time. If A is preempted often
enough it is never cancelled.

Keep the count, the time and the 'time is up' bit in one u64 in a cpu
register. The kernel preserves it over preemption and interrupts.

BPF functions pass the register to each other. Helpers don't pass it to
callbacks, so spill it to current before the call and fill it in the
callback. Otherwise each call of the callback gets a new time slice. Do
the same for subprogs of progs with tail calls, since the target of a tail
call doesn't preserve the register. An extension doesn't either, so refuse
freplace of a subprog when the prog has may_goto.

The time slice becomes 256 ms instead of 250, since the time is in units
of 4 ms. No JIT supports the new form of may_goto yet.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
 include/linux/bpf.h          |   4 +
 include/linux/bpf_verifier.h |   9 ++
 include/linux/filter.h       |  59 +++++++++
 include/linux/sched.h        |   2 +
 kernel/bpf/arena.c           |   1 +
 kernel/bpf/core.c            |  29 +++++
 kernel/bpf/disasm.c          |  15 +++
 kernel/bpf/fixups.c          | 223 ++++++++++++++++++++++++++++++++++-
 kernel/bpf/helpers.c         |   3 +
 kernel/bpf/rqspinlock.c      |   2 +
 kernel/bpf/stream.c          |   1 +
 kernel/bpf/verifier.c        |  19 +++
 12 files changed, 363 insertions(+), 4 deletions(-)

diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index a1bd30e6511b..40e42e8caa92 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -2002,6 +2002,10 @@ struct bpf_prog_aux {
 	struct bpf_prog_aux *main_prog_aux;
 	/* main prog: there when the prog has timed may_goto */
 	struct bpf_timed_may_goto __percpu *timed_may_goto;
+	/* main prog: the JIT gets may_goto as an insn */
+	bool has_may_goto;
+	/* the function keeps the state of may_goto in the cpu register */
+	bool may_goto_in_reg;
 	void *jit_data; /* JIT specific data. arch dependent */
 	struct bpf_jit_poke_descriptor *poke_tab;
 	struct bpf_kfunc_desc_tab *kfunc_tab;
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 39a0868c66be..afb6fb2ba7ef 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -1374,6 +1374,10 @@ struct bpf_insn_aux_data {
 	 * accepts callback function as a parameter.
 	 */
 	u32 calls_callback:1;
+	/* the helper or kfunc calls its callback before it returns */
+	u32 calls_sync_cb:1;
+	/* the callee can call bpf_may_goto_clear_cnt() */
+	u32 may_dump_stack:1;
 	/* true if some jump or call instruction targets this instruction */
 	u32 jump_target:1;
 	/* it can read or write the frame of a caller, in a call with a known callee */
@@ -1574,6 +1578,10 @@ struct bpf_subprog_info {
 	bool is_loop_cb: 1;
 	/* another helper or a kfunc calls it */
 	bool is_other_cb: 1;
+	/* a helper or a kfunc calls it, not counting a bpf_loop() that was inlined */
+	bool called_by_kernel: 1;
+	/* it keeps the state of may_goto in the cpu register */
+	bool may_goto_in_reg: 1;
 	/* a call insn or callx calls it */
 	bool is_called: 1;
 	bool args_cached: 1;
@@ -3089,6 +3097,7 @@ struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem);
 int bpf_copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off);
 bool bpf_insn_is_cond_jump(u8 code);
 bool bpf_is_may_goto_insn(struct bpf_insn *insn);
+bool bpf_kfunc_may_dump_stack(const struct bpf_insn *insn);
 
 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn);
 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 275c89ed7574..6fe38197cbbc 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -311,6 +311,62 @@ static inline bool insn_is_mov_percpu_addr(const struct bpf_insn *insn)
 static_assert(BPF_CANCEL_GOTO > BPF_UNWIND_GOTO);
 static_assert(BPF_CANCEL_EXIT > BPF_UNWIND_EXIT);
 
+/*
+ * An invocation is one call from the kernel into the main prog or an async callback, with the
+ * subprogs and sync callbacks it reaches. All its may_goto share 64 bits of state: a 16-bit count
+ * of trips at bit BPF_MAY_GOTO_CNT_SHIFT, below it the time when the clock was read first, and
+ * BPF_MAY_GOTO_EXPIRED. The bits above the count are 0, so the state is never negative.
+ *
+ * A JIT that has bpf_jit_supports_may_goto_insn() keeps the state in a cpu register, which calls
+ * of BPF functions pass and return.
+ *
+ * may_goto: BPF_JMP32 | BPF_JCOND, the target in imm.
+ *	if the subtraction of BPF_MAY_GOTO_CNT_ONE from the state borrows:
+ *		old = state; state = bpf_may_goto_slowpath(state);
+ *		if (old & BPF_MAY_GOTO_EXPIRED) goto target;
+ *
+ * Moves of the state. BPF_REG_AX as dst_reg names the cpu register. They may clobber AX.
+ *	READ		dst_reg = the cpu register
+ *	INIT		dst_reg = BPF_MAY_GOTO_INIT_STATE
+ *	FILL		dst_reg = current->bpf_may_goto_state
+ *	SPILL		current->bpf_may_goto_state = dst_reg
+ *	SPILL_CALL	SPILL, and FILL after the call that follows and at its landing pads.
+ *			The JIT emits the FILL, since unwind_goto has to follow the call.
+ *	SAVE		*(u64 *)(r10 + imm) = current->bpf_may_goto_state
+ *	RESTORE		current->bpf_may_goto_state = *(u64 *)(r10 + imm)
+ */
+#define BPF_MAY_GOTO_CNT_SHIFT	23
+#define BPF_MAY_GOTO_CNT_ONE	BIT_ULL(BPF_MAY_GOTO_CNT_SHIFT)
+#define BPF_MAY_GOTO_EXPIRED	1
+#define BPF_MAY_GOTO_INIT_STATE	((BPF_MAX_TIMED_LOOPS - 1) * BPF_MAY_GOTO_CNT_ONE)
+
+enum {
+	BPF_MAY_GOTO_READ = -8,
+	BPF_MAY_GOTO_INIT,
+	BPF_MAY_GOTO_FILL,
+	BPF_MAY_GOTO_SPILL,
+	BPF_MAY_GOTO_SPILL_CALL,
+	BPF_MAY_GOTO_SAVE,
+	BPF_MAY_GOTO_RESTORE,
+};
+
+#define __BPF_MAY_GOTO_MOV(OP, REG, IMM)	\
+	BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, REG, REG, OP, IMM)
+#define BPF_MAY_GOTO_MOV(OP, REG)	__BPF_MAY_GOTO_MOV(BPF_MAY_GOTO_##OP, REG, 0)
+#define BPF_MAY_GOTO_SAVE_INSN(OFF)	__BPF_MAY_GOTO_MOV(BPF_MAY_GOTO_SAVE, BPF_REG_FP, OFF)
+#define BPF_MAY_GOTO_RESTORE_INSN(OFF)	__BPF_MAY_GOTO_MOV(BPF_MAY_GOTO_RESTORE, BPF_REG_FP, OFF)
+
+static inline bool insn_is_may_goto_mov(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) &&
+	       insn->off >= BPF_MAY_GOTO_READ && insn->off <= BPF_MAY_GOTO_RESTORE;
+}
+
+static inline bool insn_is_jit_may_goto(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_JMP32 | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
+}
+
 /* gotol, cancel_goto and an unwind_goto that the verifier adds have a 32 bit offset, in imm */
 static inline bool bpf_jmp_offset_is_imm(const struct bpf_insn *insn)
 {
@@ -1444,6 +1500,7 @@ bool bpf_jit_supports_arena_stack(void);
 bool bpf_jit_supports_local_atomics(void);
 bool bpf_jit_supports_large_stack(void);
 bool bpf_jit_supports_timed_may_goto(void);
+bool bpf_jit_supports_may_goto_insn(void);
 bool bpf_jit_supports_fsession(void);
 
 /*
@@ -1494,6 +1551,8 @@ u64 bpf_arch_uaddress_limit(void);
 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie);
 u64 arch_bpf_timed_may_goto(void);
 u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *);
+u64 bpf_may_goto_slowpath(u64 state);
+void bpf_may_goto_clear_cnt(const struct bpf_prog *prog);
 void bpf_timed_may_goto_check_time(const struct bpf_prog *prog);
 void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved);
 void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved);
diff --git a/include/linux/sched.h b/include/linux/sched.h
index e4f6323d7855..691a1e322985 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -1633,6 +1633,8 @@ struct task_struct {
 	/* Used for BPF run context */
 	struct bpf_run_ctx		*bpf_ctx;
 #endif
+	/* The state of BPF may_goto when it is not in a cpu register */
+	u64				bpf_may_goto_state;
 	/* Used by BPF for per-TASK xdp storage */
 	struct bpf_net_context		*bpf_net_context;
 
diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c
index c0c431124a13..8d6e067aee89 100644
--- a/kernel/bpf/arena.c
+++ b/kernel/bpf/arena.c
@@ -1221,6 +1221,7 @@ u64 bpf_arena_stack_get(struct bpf_prog_aux *aux, u64 busy)
 	bpf_stream_stage(ss, aux->prog, BPF_STDERR, ({
 		bpf_stream_printk(ss, "ERROR: No memory for the stack in arena. The program didn't run\n");
 	}));
+	bpf_may_goto_clear_cnt(aux->prog);
 	return 0;
 }
 
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 143fa134fea5..933c19556725 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -4117,6 +4117,11 @@ bool __weak bpf_jit_supports_timed_may_goto(void)
 	return false;
 }
 
+bool __weak bpf_jit_supports_may_goto_insn(void)
+{
+	return false;
+}
+
 u64 __weak arch_bpf_timed_may_goto(void)
 {
 	return 0;
@@ -4260,6 +4265,30 @@ void bpf_timed_may_goto_check_time(const struct bpf_prog *prog)
 		this_cpu_write(tmg->count, 1);
 }
 
+/* The count in @state ran out. Bit 1 of the state is 2^22 ns. The time slice is 256 ms. */
+u64 bpf_may_goto_slowpath(u64 state)
+{
+	u32 mask = BPF_MAY_GOTO_CNT_ONE - 1, start = state & mask, now;
+
+	if (state & BPF_MAY_GOTO_EXPIRED)
+		return BPF_MAY_GOTO_EXPIRED;
+	now = (ktime_get_mono_fast_ns() >> 22 << 1) & mask;
+	if (!start)
+		return BPF_MAY_GOTO_INIT_STATE | now;
+	/* Both times are rounded down. The clock of another cpu can be one step behind. */
+	if (((now - start + 2) & mask) < (((NSEC_PER_SEC / 4) >> 22) + 3) << 1)
+		return BPF_MAY_GOTO_INIT_STATE | start;
+	bpf_prog_report_may_goto_violation();
+	return BPF_MAY_GOTO_EXPIRED;
+}
+
+/* A report is too slow for BPF_MAX_TIMED_LOOPS trips. The next may_goto reads the clock. */
+void bpf_may_goto_clear_cnt(const struct bpf_prog *prog)
+{
+	if (prog->aux->main_prog_aux->has_may_goto)
+		current->bpf_may_goto_state &= BPF_MAY_GOTO_CNT_ONE - 1;
+}
+
 /* for configs without MMU or 32-bit */
 __weak const struct bpf_map_ops arena_map_ops;
 __weak u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena)
diff --git a/kernel/bpf/disasm.c b/kernel/bpf/disasm.c
index 8426c6c04610..ffde0a46841d 100644
--- a/kernel/bpf/disasm.c
+++ b/kernel/bpf/disasm.c
@@ -12,6 +12,8 @@
 #define BPF_ATOMIC_LOCAL 0x1000
 #define BPF_CANCEL_GOTO 2
 #define BPF_CANCEL_EXIT 2
+#define BPF_MAY_GOTO_READ (-8)
+#define BPF_MAY_GOTO_RESTORE (-2)
 
 #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
 static const char * const func_id_str[] = {
@@ -230,6 +232,15 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		} else if (is_mov_percpu_addr(insn)) {
 			verbose(cbs->private_data, "(%02x) r%d = &(void __percpu *)(r%d)",
 				insn->code, insn->dst_reg, insn->src_reg);
+		} else if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) &&
+			   insn->off >= BPF_MAY_GOTO_READ && insn->off <= BPF_MAY_GOTO_RESTORE) {
+			static const char * const op[] = {
+				"read", "init", "fill", "spill", "spill_call", "save", "restore"
+			};
+
+			verbose(cbs->private_data, "(%02x) may_goto_%s r%d%+d",
+				insn->code, op[insn->off - BPF_MAY_GOTO_READ], insn->dst_reg,
+				insn->imm);
 		} else if (BPF_SRC(insn->code) == BPF_X) {
 			verbose(cbs->private_data, "(%02x) %c%d %s %s%c%d",
 				insn->code, class == BPF_ALU ? 'w' : 'r',
@@ -402,6 +413,10 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 			   insn->src_reg == BPF_MAY_GOTO) {
 			verbose(cbs->private_data, "(%02x) may_goto pc%+d",
 				insn->code, insn->off);
+		} else if (insn->code == (BPF_JMP32 | BPF_JCOND) &&
+			   insn->src_reg == BPF_MAY_GOTO) {
+			verbose(cbs->private_data, "(%02x) may_goto pc%+d",
+				insn->code, insn->imm);
 		} else if (insn->code == (BPF_JMP | BPF_JCOND) &&
 			   insn->src_reg == BPF_UNWIND_GOTO) {
 			verbose(cbs->private_data, "(%02x) unwind_goto pc%+d",
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index f8c70dd90bfb..f60a300c6a9b 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -2309,6 +2309,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 
 		func[i]->aux->name[0] = 'F';
 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
+		func[i]->aux->may_goto_in_reg = env->subprog_info[i].may_goto_in_reg;
 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
 			func[i]->aux->jits_use_priv_stack = true;
 
@@ -2725,6 +2726,203 @@ static int may_goto_expand_timed(struct bpf_insn *insn_buf, int *jmp,
 	return cnt;
 }
 
+/* Only bpf_loop() or bpf_for_each_map_elem() call it. Their loop ends when it returns 1. */
+static bool is_loop_cb_only(const struct bpf_subprog_info *sub)
+{
+	return !sub->main && sub->is_loop_cb && !sub->is_called && !sub->is_other_cb &&
+	       !sub->is_async_cb;
+}
+
+/* Each bpf_loop() that calls it was inlined, so the calls are direct */
+static bool is_inlined_loop_cb(const struct bpf_subprog_info *sub)
+{
+	return sub->is_loop_cb && !sub->called_by_kernel && !sub->is_async_cb;
+}
+
+/* callx or a helper can call it. A call of an async callback is an invocation of its own. */
+static bool is_indirect_callee(const struct bpf_subprog_info *sub)
+{
+	return sub->addr_taken && (!is_inlined_loop_cb(sub) || sub->via_callx) &&
+	       (!sub->is_async_cb || sub->via_callx || sub->is_loop_cb || sub->is_other_cb);
+}
+
+/* Marks of the call graph of bpf_insert_may_goto_spills() */
+enum {
+	MAY_GOTO_MOD		= BIT(0), /* it or a callee writes the state */
+	MAY_GOTO_REF		= BIT(1), /* it or a callee tests BPF_MAY_GOTO_EXPIRED at entry */
+	MAY_GOTO_MOD_REF	= MAY_GOTO_MOD | MAY_GOTO_REF,
+	MAY_GOTO_SPILLS		= BIT(2), /* it or a callee spills the state to the task */
+	MAY_GOTO_ARG_IN_TASK	= BIT(3), /* the state is passed and returned in the task */
+};
+
+/* What the callee of insn @i does to the state in current->bpf_may_goto_state */
+static u16 task_slot_mod_ref(struct bpf_verifier_env *env, struct bpf_call_graph *cg, int i)
+{
+	const struct bpf_insn_aux_data *aux = &env->insn_aux_data[i];
+	struct bpf_insn *insn = &env->prog->insnsi[i];
+	u16 callee = 0;
+
+	if (aux->may_dump_stack)
+		return MAY_GOTO_MOD;
+	if (bpf_pseudo_call(insn))
+		callee = cg->marks[insn_callee(env, i)];
+	else if (bpf_is_callx(insn) || aux->calls_sync_cb)
+		callee = cg->marks[env->subprog_cnt];
+	return callee & MAY_GOTO_ARG_IN_TASK ? callee & MAY_GOTO_MOD_REF : 0;
+}
+
+/*
+ * Build the call graph and find the functions that modify or read the state. The last node stands
+ * for indirect calls: callx and helpers call it, it calls each subprog whose address is taken.
+ */
+static int mark_may_goto_mod_ref(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+{
+	struct bpf_subprog_info *si = env->subprog_info;
+	int i, s, indirect = env->subprog_cnt, err = 0;
+
+	for (s = 0; s < env->subprog_cnt; s++) {
+		cg->marks[s] = is_loop_cb_only(&si[s]) ? MAY_GOTO_REF : 0;
+		/* a direct call passes the state in the register: MOD keeps it there */
+		if (cg->marks[s] && is_inlined_loop_cb(&si[s]))
+			cg->marks[s] |= MAY_GOTO_MOD;
+		for (i = si[s].start; i < si[s + 1].start; i++) {
+			const struct bpf_insn_aux_data *aux = &env->insn_aux_data[i];
+			struct bpf_insn *insn = &env->prog->insnsi[i];
+
+			if (verifier_bug_if((aux->calls_sync_cb || aux->may_dump_stack) &&
+					    !is_call(insn), env, "insn %d is no call", i))
+				return -EFAULT;
+			if (bpf_pseudo_call(insn))
+				err = bpf_call_graph_add(cg, s, insn_callee(env, i));
+			else if (bpf_is_callx(insn) || aux->calls_sync_cb)
+				err = bpf_call_graph_add(cg, s, indirect);
+			if (err)
+				return err;
+			/* A report clears the count. So does a fault in arena that is skipped. */
+			if (insn_is_jit_may_goto(insn) || aux->may_dump_stack ||
+			    (is_arena_access(insn) && !aux->fault_unwinds &&
+			     !bpf_is_unwind_goto(insn + 1)))
+				cg->marks[s] |= MAY_GOTO_MOD;
+		}
+	}
+	for (s = 0; s < env->subprog_cnt && !err; s++)
+		if (is_indirect_callee(&si[s]))
+			err = bpf_call_graph_add(cg, indirect, s);
+	if (err)
+		return err;
+	bpf_call_graph_sort(cg, 0);
+	bpf_call_graph_mark_callers(cg, MAY_GOTO_MOD_REF, 0);
+	return 0;
+}
+
+/* Pick the calling convention of each function, and find the callers that have to spill for it */
+static void mark_may_goto_call_conv(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+{
+	struct bpf_subprog_info *si = env->subprog_info;
+	int i, s, indirect = env->subprog_cnt;
+	bool tail_call_reachable = false;
+
+	/* The target of a tail call need not preserve the register */
+	for (s = 0; s < env->subprog_cnt; s++)
+		tail_call_reachable |= si[s].tail_call_reachable;
+	/* All targets of indirect calls have one convention */
+	for (s = 0; s < env->subprog_cnt; s++)
+		if (tail_call_reachable ||
+		    (is_indirect_callee(&si[s]) && si[s].is_cb && !is_inlined_loop_cb(&si[s]) &&
+		     cg->marks[s] & MAY_GOTO_MOD_REF))
+			cg->marks[indirect] |= MAY_GOTO_ARG_IN_TASK;
+	for (s = 0; s < env->subprog_cnt; s++)
+		if (tail_call_reachable || (si[s].is_cb && !is_inlined_loop_cb(&si[s])) ||
+		    (is_indirect_callee(&si[s]) && cg->marks[indirect] & MAY_GOTO_ARG_IN_TASK))
+			cg->marks[s] |= MAY_GOTO_ARG_IN_TASK;
+	for (s = 0; s < env->subprog_cnt; s++)
+		for (i = si[s].start; i < si[s + 1].start; i++)
+			if (task_slot_mod_ref(env, cg, i))
+				cg->marks[s] |= MAY_GOTO_SPILLS;
+	bpf_call_graph_mark_callers(cg, MAY_GOTO_SPILLS, 0);
+}
+
+static int insert_subprog_may_goto_spills(struct bpf_verifier_env *env,
+					  struct bpf_call_graph *cg, int s)
+{
+	struct bpf_subprog_info *sub = &env->subprog_info[s];
+	struct bpf_insn prologue[6], epilogue = {}, patch[2];
+	u16 marks = cg->marks[s], callee;
+	int i, cnt = 0, err;
+
+	/* a callback that only tests BPF_MAY_GOTO_EXPIRED reads it from the task */
+	sub->may_goto_in_reg = sub->main || marks & (MAY_GOTO_MOD | MAY_GOTO_SPILLS);
+
+	if (sub->main && marks & MAY_GOTO_SPILLS) {
+		sub->stack_depth = round_up(sub->stack_depth, 8) + 8;
+		prologue[cnt++] = BPF_MAY_GOTO_SAVE_INSN(-sub->stack_depth);
+		epilogue = BPF_MAY_GOTO_RESTORE_INSN(-sub->stack_depth);
+	}
+	if (sub->main) {
+		prologue[cnt++] = BPF_MAY_GOTO_MOV(INIT, BPF_REG_AX);
+	} else if (sub->may_goto_in_reg && marks & MAY_GOTO_ARG_IN_TASK) {
+		prologue[cnt++] = BPF_MAY_GOTO_MOV(FILL, BPF_REG_AX);
+		epilogue = BPF_MAY_GOTO_MOV(SPILL, BPF_REG_AX);
+	}
+	/* The time is up: return 1, see the same check in bpf_do_misc_fixups() */
+	if (is_loop_cb_only(sub)) {
+		prologue[cnt++] = sub->may_goto_in_reg ? BPF_MAY_GOTO_MOV(READ, BPF_REG_0) :
+							 BPF_MAY_GOTO_MOV(FILL, BPF_REG_0);
+		prologue[cnt++] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, BPF_MAY_GOTO_EXPIRED);
+		prologue[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 1);
+		prologue[cnt++] = BPF_EXIT_INSN();
+	}
+	/* jumps to the first insn of the subprog skip the prologue */
+	err = cnt ? bpf_patch_list_insert(env, sub->start, prologue, cnt) : 0;
+
+	for (i = sub->start; i < sub[1].start && !err; i++) {
+		patch[1] = env->prog->insnsi[i];
+		callee = sub->may_goto_in_reg ? task_slot_mod_ref(env, cg, i) : 0;
+		if (callee & MAY_GOTO_MOD)
+			patch[0] = BPF_MAY_GOTO_MOV(SPILL_CALL, BPF_REG_AX);
+		else if (callee)
+			patch[0] = BPF_MAY_GOTO_MOV(SPILL, BPF_REG_AX);
+		else if (epilogue.code && (patch[1].code == (BPF_JMP | BPF_EXIT) ||
+					   patch[1].code == (BPF_JMP | BPF_TAIL_CALL)))
+			patch[0] = epilogue;
+		else
+			continue;
+		err = PTR_ERR_OR_ZERO(bpf_patch_list_add(env, i, patch, 2));
+	}
+	return err;
+}
+
+/*
+ * The state of may_goto is a hidden argument and return value of BPF functions, in a cpu register.
+ * Helpers and kfuncs don't pass it to their callbacks, so it goes through a slot in the task:
+ *
+ *   main: save; init                          cb: fill
+ *         spill                                   may_goto
+ *         call bpf_for_each_map_elem(cb)          spill
+ *         fill                                    exit
+ *         restore; exit
+ *
+ * The main prog saves and restores the slot, so invocations nest. A call gets no spill when the
+ * callee doesn't touch the state, and no fill when the callee doesn't modify it.
+ */
+static int bpf_insert_may_goto_spills(struct bpf_verifier_env *env)
+{
+	struct bpf_call_graph cg;
+	int s, err;
+
+	err = bpf_call_graph_init(&cg, env->subprog_cnt + 1) ?: mark_may_goto_mod_ref(env, &cg);
+	if (err)
+		goto out;
+	mark_may_goto_call_conv(env, &cg);
+	for (s = 0; s < env->subprog_cnt && !err; s++)
+		if (cg.marks[s] & MAY_GOTO_MOD_REF)
+			err = insert_subprog_may_goto_spills(env, &cg, s);
+	env->prog->aux->may_goto_in_reg = env->subprog_info[0].may_goto_in_reg;
+out:
+	bpf_call_graph_free(&cg);
+	return err;
+}
+
 #ifdef CONFIG_64BIT
 struct bpf_div_magic {
 	u64 m;		/* multiplier, sign extended for signed division */
@@ -2931,9 +3129,13 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 	u16 stack_depth_extra = 0;
 	/* arch_bpf_timed_may_goto() takes and returns AX in a cpu register: for JITs only */
 	bool timed_may_goto = prog->jit_requested && bpf_jit_supports_timed_may_goto();
+	bool may_goto_insn = timed_may_goto && bpf_jit_supports_may_goto_insn();
 	struct bpf_timed_may_goto __percpu *tmg = NULL;
 
 	for (i = 0; i < insn_cnt;) {
+		env->insn_aux_data[i].calls_sync_cb = bpf_is_sync_callback_calling_insn(insn);
+		env->insn_aux_data[i].may_dump_stack = bpf_kfunc_may_dump_stack(insn);
+
 		if (is_addr_space_cast32(env->prog, insn)) {
 			/* convert to 32-bit mov that clears upper 32-bit */
 			insn->code = BPF_ALU | BPF_MOV | BPF_X;
@@ -3164,7 +3366,12 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 			goto next_insn;
 		}
 
-		if (bpf_is_may_goto_insn(insn) && timed_may_goto) {
+		if (bpf_is_may_goto_insn(insn) && may_goto_insn) {
+			*insn = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_MAY_GOTO, 0, insn->off);
+			prog->jit_required = 1;
+			prog->aux->has_may_goto = true;
+			goto next_insn;
+		} else if (bpf_is_may_goto_insn(insn) && timed_may_goto) {
 			u16 live = env->insn_aux_data[i].live_regs_before;
 			int reg, jmp, save_off = 0, to = i + insn->off + 1;
 
@@ -3247,6 +3454,9 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 			goto next_insn;
 		/* imm is not the id of a helper */
 		if (!insn->src_reg && insn->off == BPF_KERNEL_CALL) {
+			/* a main prog exits when it gets no stack, a callback returns to its loop */
+			env->insn_aux_data[i].may_dump_stack = !subprogs[cur_subprog].main &&
+				insn->imm == BPF_CALL_IMM(bpf_arena_stack_get);
 			insn->off = 0;
 			goto next_insn;
 		}
@@ -3738,14 +3948,16 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 		return ret;
 	prog = env->prog;
 
+	ret = prog->aux->has_may_goto ? bpf_insert_may_goto_spills(env) : 0;
+	if (ret)
+		return ret;
+
 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
 	for (i = 0; i < env->subprog_cnt; i++) {
 		int stack_slots = subprogs[i].stack_extra / 8;
 		/* an invocation begins, see bpf_timed_may_goto_save() for async callbacks */
 		bool main_prog = tmg && subprogs[i].main;
-		/* only a helper calls it, in a loop that ends when it returns 1 */
-		bool loop_cb = tmg && i && subprogs[i].is_loop_cb && !subprogs[i].is_called &&
-			       !subprogs[i].is_other_cb && !subprogs[i].is_async_cb;
+		bool loop_cb = tmg && is_loop_cb_only(&subprogs[i]);
 
 		if (timed_may_goto ? !main_prog && !loop_cb : !stack_slots)
 			continue;
@@ -4003,6 +4215,9 @@ int bpf_optimize_bpf_loop(struct bpf_verifier_env *env)
 					      inline_state->callback_subprogno);
 			if (err)
 				return err;
+		} else if (is_bpf_loop_call(insn)) {
+			/* push_callback_call() skips a call while it is fit for inlining */
+			subprogs[inline_state->callback_subprogno].called_by_kernel = true;
 		}
 
 		if (subprogs[cur_subprog + 1].start == i + 1) {
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 5054fbf25e6b..dc99c35a3eb4 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -1241,10 +1241,13 @@ static void bpf_run_async_cb(struct bpf_prog *prog, bpf_callback_t callback_fn,
 {
 	struct bpf_run_ctx run_ctx, *old_ctx;
 	struct bpf_timed_may_goto saved;
+	u64 old_state = READ_ONCE(current->bpf_may_goto_state);
 
 	old_ctx = bpf_set_run_ctx_prog(&run_ctx, BPF_PROG_ASYNC_CB);
 	bpf_timed_may_goto_save(prog, &saved);
+	WRITE_ONCE(current->bpf_may_goto_state, BPF_MAY_GOTO_INIT_STATE);
 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
+	WRITE_ONCE(current->bpf_may_goto_state, old_state);
 	bpf_timed_may_goto_restore(prog, &saved);
 	bpf_reset_run_ctx(old_ctx);
 }
diff --git a/kernel/bpf/rqspinlock.c b/kernel/bpf/rqspinlock.c
index 14d379833589..4f23f0ded7b4 100644
--- a/kernel/bpf/rqspinlock.c
+++ b/kernel/bpf/rqspinlock.c
@@ -16,6 +16,7 @@
 #include <linux/smp.h>
 #include <linux/bug.h>
 #include <linux/bpf.h>
+#include <linux/filter.h>
 #include <linux/err.h>
 #include <linux/cpumask.h>
 #include <linux/percpu.h>
@@ -680,6 +681,7 @@ static void bpf_prog_report_rqspinlock_violation(const char *str, void *lock, bo
 			bpf_stream_printk(ss, "Held lock[%2d] = 0x%px\n", i, rqh->locks[i]);
 		bpf_stream_dump_stack(ss);
 	}));
+	bpf_may_goto_clear_cnt(prog);
 }
 
 #define REPORT_STR(ret) ({ (ret) == -ETIMEDOUT ? "Timeout detected" : "AA or ABBA deadlock detected"; })
diff --git a/kernel/bpf/stream.c b/kernel/bpf/stream.c
index c726e54a63c0..c312e74ebd57 100644
--- a/kernel/bpf/stream.c
+++ b/kernel/bpf/stream.c
@@ -444,6 +444,7 @@ __bpf_kfunc int bpf_stream_print_stack(int stream_id, struct bpf_prog_aux *aux)
 	bpf_stream_stage(ss, prog, stream_id, ({
 		bpf_stream_dump_stack(ss);
 	}));
+	bpf_may_goto_clear_cnt(prog);
 
 	return 0;
 }
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 832f2efcbce4..e49382e654e0 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -12068,6 +12068,9 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	 * callbacks
 	 */
 	env->subprog_info[subprog].is_cb = true;
+	if (bpf_pseudo_kfunc_call(insn) || insn->imm != BPF_FUNC_loop ||
+	    !env->insn_aux_data[insn_idx].loop_inline_state.fit_for_inline)
+		env->subprog_info[subprog].called_by_kernel = true;
 	enter_empty_handed(env, subprog);
 	if (bpf_pseudo_kfunc_call(insn) &&
 	    !is_callback_calling_kfunc(insn->imm)) {
@@ -14890,6 +14893,7 @@ enum special_kfunc_type {
 	KF_bpf_arena_alloc_pages,
 	KF_bpf_arena_free_pages,
 	KF_bpf_session_is_return,
+	KF_bpf_stream_print_stack,
 };
 
 BTF_ID_LIST(special_kfunc_list)
@@ -14991,6 +14995,16 @@ BTF_ID(func, bpf_session_is_return)
 #else
 BTF_ID_UNUSED
 #endif
+BTF_ID(func, bpf_stream_print_stack)
+
+/* The kfunc can call bpf_may_goto_clear_cnt() */
+bool bpf_kfunc_may_dump_stack(const struct bpf_insn *insn)
+{
+	return bpf_pseudo_kfunc_call(insn) && !insn->off &&
+	       (insn->imm == special_kfunc_list[KF_bpf_stream_print_stack] ||
+		insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
+		insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]);
+}
 
 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta)
 {
@@ -26243,6 +26257,11 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
 				BPF_REG_ARENA_SP);
 			return -EOPNOTSUPP;
 		}
+		/* x86: the extension doesn't preserve the register with the state of may_goto */
+		if (subprog && aux->has_may_goto && prog_extension) {
+			bpf_log(log, "Cannot replace a subprog of a program with may_goto\n");
+			return -EOPNOTSUPP;
+		}
 		if (aux->entry_cnt && (!subprog || aux->func[subprog]->aux->is_entry)) {
 			bpf_log(log, "%s is a program of its own\n", tname);
 			return -EINVAL;
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 4/7] bpf, x86: Keep the state of may_goto in %r11
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
                   ` (2 preceding siblings ...)
  2026-12-05  3:37 ` [PATCH bpf-next 3/7] bpf: Keep the state of may_goto per invocation Alexei Starovoitov
@ 2026-12-05  3:37 ` Alexei Starovoitov
  2026-12-05  4:29   ` bot+bpf-ci
  2026-12-05  3:37 ` [PATCH bpf-next 5/7] bpf, arm64: Keep the state of may_goto in x24 Alexei Starovoitov
                   ` (3 subsequent siblings)
  7 siblings, 1 reply; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:37 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

may_goto takes 10 insns with a load and a store of the count. Turn it
into:

  sub r11, 0x800000
  jl  slow

There is no free callee saved register, so use %r11. Spill it around
helpers, kfuncs and the few insns that need it, like division by a
constant. Other users of %r11 switch to %r10 in progs with may_goto.
Trampolines preserve %r11 when they are attached to BPF functions.
Trampolines on kernel functions and progs without may_goto don't change.

Ice Lake:

  ns per iteration                     before   after
  empty loop                             1.81    0.29
  load and store in arena                1.44    1.15
  call of bpf_get_numa_node_id()         2.01    1.81
  may_goto in callback of bpf_loop()     2.61    2.02
  call of a subprog with may_goto        3.49    1.99
  the same in a prog with a tail call    2.99    4.28

The last row is slower, since such progs pass the state through current.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
 arch/x86/net/bpf_jit_comp.c                   | 362 +++++++++++++++---
 arch/x86/net/bpf_timed_may_goto.S             |  17 +-
 kernel/bpf/fixups.c                           |   2 +-
 .../bpf/progs/verifier_arena_stack.c          |   7 +-
 .../bpf/progs/verifier_bpf_fastcall.c         |  29 +-
 .../selftests/bpf/progs/verifier_may_goto_1.c |  29 +-
 .../selftests/bpf/progs/verifier_patch_list.c |  96 ++---
 7 files changed, 394 insertions(+), 148 deletions(-)

diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index c3edda0392fd..34d6fe93d78d 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -134,7 +134,7 @@ static int bpf_size_to_x86_bytes(int bpf_size)
 #define X86_JG  0x7F
 
 /* Pick a register outside of BPF range for JIT internal work */
-#define AUX_REG (MAX_BPF_JIT_REG + 1)
+#define X86_REG_R11 (MAX_BPF_JIT_REG + 1)
 #define X86_REG_R9 (MAX_BPF_JIT_REG + 2)
 #define X86_REG_R12 (MAX_BPF_JIT_REG + 3)
 
@@ -163,7 +163,7 @@ static const int reg2hex[] = {
 	[BPF_REG_FP] = 5, /* RBP readonly */
 	[BPF_REG_ARENA_SP] = 1, /* R9 */
 	[BPF_REG_AX] = 2, /* R10 temp register */
-	[AUX_REG] = 3,    /* R11 temp register */
+	[X86_REG_R11] = 3, /* R11 state of may_goto, or AUX_REG */
 	[X86_REG_R9] = 1, /* R9 register, 6th function argument */
 	[X86_REG_R12] = 4, /* R12 callee saved */
 };
@@ -198,7 +198,7 @@ static bool is_atomic_fetch_op(const struct bpf_insn *insn)
 static bool is_ereg(u32 reg)
 {
 	return (1 << reg) & (BIT(BPF_REG_5) |
-			     BIT(AUX_REG) |
+			     BIT(X86_REG_R11) |
 			     BIT(BPF_REG_7) |
 			     BIT(BPF_REG_8) |
 			     BIT(BPF_REG_9) |
@@ -292,9 +292,10 @@ int bpf_arch_text_invalidate(void *dst, size_t len)
 /*
  * The landing of an unwind_goto or cancel_goto, see BPF_JCOND in do_jit(): the
  * @len bytes of @code that follow the native call, and a jump to insn @to.
+ * Also the slow path of may_goto.
  */
 struct jit_landing {
-	u8 code[16];
+	u8 code[64];
 	u8 len;
 	int to;
 };
@@ -1347,7 +1348,7 @@ static int emit_kasan_check(struct bpf_verifier_env *env, u8 **pprog,
 /*
  * The one-operand x86 mul/imul forms use RAX as the implicit first
  * operand and store the 128-bit product in RDX:RAX.
- * The JIT uses AUX_REG as the explicit second operand.
+ * The JIT uses R11 as the explicit second operand.
  */
 static void emit_hmul_aux(u8 **pprog, u32 dst_reg, bool is_signed)
 {
@@ -1363,8 +1364,8 @@ static void emit_hmul_aux(u8 **pprog, u32 dst_reg, bool is_signed)
 
 	if (save_rax)
 		emit_mov_reg(&prog, true, BPF_REG_0, dst_reg);
-	maybe_emit_1mod(&prog, AUX_REG, true);
-	EMIT2(0xF7, add_1reg(mul_modrm_base, AUX_REG));
+	maybe_emit_1mod(&prog, X86_REG_R11, true);
+	EMIT2(0xF7, add_1reg(mul_modrm_base, X86_REG_R11));
 	if (save_rdx)
 		emit_mov_reg(&prog, true, dst_reg, BPF_REG_3);
 
@@ -1733,19 +1734,19 @@ static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size,
 }
 
 /*
- * AUX_REG = dst_reg, with the low bits of dst_reg + off in the top bits. r12 + AUX_REG + off
+ * tmp = dst_reg, with the low bits of dst_reg + off in the top bits. r12 + tmp + off
  * is not canonical when it's not aligned: the access faults, no split lock is taken.
  */
-static void emit_arena_align_check(u8 **pprog, const struct bpf_insn *insn, u32 dst_reg)
+static void emit_arena_align_check(u8 **pprog, const struct bpf_insn *insn, u32 dst_reg, u32 tmp)
 {
 	int size = BPF_LDST_BYTES(insn);
 	u8 *prog = *pprog;
 
-	/* lea r11, [dst_reg + off % size] */
-	EMIT2(add_2mod(0x48, dst_reg, AUX_REG), 0x8D);
-	emit_insn_suffix(&prog, dst_reg, AUX_REG, insn->off & (size - 1));
-	emit_shift_imm(&prog, BPF_LSH, AUX_REG, 64 - ilog2(size), true);
-	emit_alu_reg(&prog, BPF_OR, AUX_REG, dst_reg, true);
+	/* lea tmp, [dst_reg + off % size] */
+	EMIT2(add_2mod(0x48, dst_reg, tmp), 0x8D);
+	emit_insn_suffix(&prog, dst_reg, tmp, insn->off & (size - 1));
+	emit_shift_imm(&prog, BPF_LSH, tmp, 64 - ilog2(size), true);
+	emit_alu_reg(&prog, BPF_OR, tmp, dst_reg, true);
 	*pprog = prog;
 }
 
@@ -1822,7 +1823,7 @@ static int emit_atomic_ld_st_index(u8 **pprog, u32 atomic_op, u32 size,
  * rest of the sequence and restores R0 itself, see FIXUP_ARENA_R0_IN_AX.
  */
 static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
-				 u32 src_reg, int index_reg, u8 **fault)
+				 u32 src_reg, u32 aux, int index_reg, u8 **fault)
 {
 	bool is64 = BPF_SIZE(insn->code) == BPF_DW;
 	u8 *branch_target, *prog = *pprog;
@@ -1832,33 +1833,33 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
 
 	/* Load old value */
 	if (index_reg >= 0)
-		emit_arena_align_check(&prog, insn, dst_reg);
+		emit_arena_align_check(&prog, insn, dst_reg, aux);
 	if (fault)
 		fault[0] = prog;
 	if (index_reg < 0)
 		emit_ldx(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg, insn->off);
 	else
-		emit_ldx_index(&prog, BPF_SIZE(insn->code), BPF_REG_0, AUX_REG,
+		emit_ldx_index(&prog, BPF_SIZE(insn->code), BPF_REG_0, aux,
 			       index_reg, insn->off);
 
 	/*
 	 * Perform the (commutative) operation locally, put the result in
-	 * the AUX_REG.
+	 * @aux.
 	 */
-	emit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0);
-	maybe_emit_mod(&prog, AUX_REG, src_reg, is64);
+	emit_mov_reg(&prog, is64, aux, BPF_REG_0);
+	maybe_emit_mod(&prog, aux, src_reg, is64);
 	EMIT2(simple_alu_opcodes[BPF_OP(insn->imm)],
-	      add_2reg(0xC0, AUX_REG, src_reg));
+	      add_2reg(0xC0, aux, src_reg));
 
 	/* Attempt to swap in new value */
 	if (fault)
 		fault[1] = prog;
 	if (index_reg < 0)
-		err = emit_atomic_rmw(&prog, BPF_CMPXCHG, dst_reg, AUX_REG,
+		err = emit_atomic_rmw(&prog, BPF_CMPXCHG, dst_reg, aux,
 				      insn->off, BPF_SIZE(insn->code));
 	else
 		err = emit_atomic_rmw_index(&prog, BPF_CMPXCHG, BPF_SIZE(insn->code),
-					    dst_reg, AUX_REG, index_reg, insn->off);
+					    dst_reg, aux, index_reg, insn->off);
 	if (WARN_ON(err))
 		return err;
 
@@ -1881,11 +1882,13 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
  *
  * Bit layout of `fixup` (32-bit):
  *
- * +-----------+-------------+----------+---------+--------+-----------+---------+----------+
- * | 31        | 30          | 29       | 28      | 27-24  |   23-16   |   15-8  |    7-0   |
- * |           |             |          |         |        |           |         |          |
- * | ARENA_ACC | ARENA_WRITE | R0_IN_AX | UNWINDS | Unused | ARENA_REG | DST_REG | INSN_LEN |
- * +-----------+-------------+----------+---------+--------+-----------+---------+----------+
+ * +-----------+-------------+----------+---------+------------+-----------+---------+----------+
+ * | 31        | 30          | 29       | 28      | 27         |   23-16   |   15-8  |    7-0   |
+ * |           |             |          |         |            |           |         |          |
+ * | ARENA_ACC | ARENA_WRITE | R0_IN_AX | UNWINDS | R11_PUSHED | ARENA_REG | DST_REG | INSN_LEN |
+ * +-----------+-------------+----------+---------+------------+-----------+---------+----------+
+ *
+ * Bits 26-24 are unused.
  *
  * - INSN_LEN (8 bits): How far past the faulting insn the BPF insn ends. That is its own length
  *                      for a single-insn access, but the distance to the end of the whole
@@ -1907,6 +1910,7 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
  * - UNWINDS (1 bit): The frame holds nothing at the insn, and no unwind_goto follows it. The
  *                    handler goes to prog->aux->fault_pad, the landing pad that all such
  *                    accesses of the function share.
+ * - R11_PUSHED (1 bit): The CMPXCHG loop pushed R11, the state of may_goto. The handler pops it.
  *
  * Bit layout of `data` (32-bit):
  *
@@ -1924,12 +1928,24 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
 #define FIXUP_INSN_LEN_MASK	GENMASK(7, 0)
 #define FIXUP_REG_MASK		GENMASK(15, 8)
 #define FIXUP_ARENA_REG_MASK	GENMASK(23, 16)
+#define FIXUP_ARENA_R11_PUSHED	BIT(27)
 #define FIXUP_ARENA_UNWINDS	BIT(28)
 #define FIXUP_ARENA_R0_IN_AX	BIT(29)
 #define FIXUP_ARENA_WRITE	BIT(30)
 #define FIXUP_ARENA_ACCESS	BIT(31)
 #define DATA_ARENA_OFFSET_MASK	GENMASK(31, 16)
 
+/* The access was skipped. The next may_goto reads the clock. */
+static void may_goto_clear_cnt(struct pt_regs *regs)
+{
+	struct bpf_prog *prog;
+
+	guard(rcu)();
+	prog = bpf_prog_ksym_find(regs->ip);
+	if (prog && prog->aux->may_goto_in_reg)
+		regs->r11 &= BPF_MAY_GOTO_CNT_ONE - 1;
+}
+
 bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
 {
 	u32 reg = FIELD_GET(FIXUP_REG_MASK, x->fixup);
@@ -1947,6 +1963,12 @@ bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
 		addr = *(unsigned long *)((void *)regs + arena_reg) + off;
 		pad = bpf_arena_fault(is_write, addr, regs->ip, end,
 				      x->fixup & FIXUP_ARENA_UNWINDS);
+		if (x->fixup & FIXUP_ARENA_R11_PUSHED) {
+			regs->r11 = *(unsigned long *)regs->sp;
+			regs->sp += sizeof(long);
+		}
+		if (pad == end)
+			may_goto_clear_cnt(regs);
 	}
 
 	/*
@@ -2233,9 +2255,9 @@ static int emit_kfunc_arg_moves(const struct btf_func_model *fm, s32 stack_base,
 		 * BPF_REG_AX only to pass one stack slot to another.
 		 */
 		if (src == BPF_JIT_ARG_TMP) {
-			reg = AUX_REG;
+			reg = X86_REG_R11;
 		} else if (src_mem) {
-			reg = dst == BPF_JIT_ARG_TMP ? AUX_REG :
+			reg = dst == BPF_JIT_ARG_TMP ? X86_REG_R11 :
 			      dst_mem ? BPF_REG_AX : x86_arg_reg[dst];
 			emit_ldx(&prog, BPF_DW, reg, BPF_REG_FP,
 				 stack_base + (src - nreg) * 8);
@@ -2245,7 +2267,7 @@ static int emit_kfunc_arg_moves(const struct btf_func_model *fm, s32 stack_base,
 
 		/* And leave it where the argument belongs. */
 		if (dst == BPF_JIT_ARG_TMP)
-			emit_mov_reg(&prog, true, AUX_REG, reg);
+			emit_mov_reg(&prog, true, X86_REG_R11, reg);
 		else if (dst_mem)
 			emit_stx(&prog, BPF_DW, BPF_REG_FP, reg,
 				 stack_base + (dst - nreg) * 8);
@@ -2503,19 +2525,25 @@ static bool call_has_cancel_goto(const struct bpf_insn *call, int cnt)
  * unwind_exit, cancel_exit: replace the return address of this frame with what
  * @target returns for it, bpf_unwind_target() or bpf_cancel_target(). The
  * epilogue then returns there. r0 and r2 are returned, so they are saved
- * around the call. So is BPF_REG_ARENA_SP, when it's used.
+ * around the call. So are BPF_REG_ARENA_SP and the state of may_goto, when they're used.
  */
-static int emit_unwind_ret_addr(u8 **pprog, u8 *ip, bool arena_sp, void *target)
+static int emit_unwind_ret_addr(u8 **pprog, u8 *ip, const struct bpf_prog_aux *aux, void *target)
 {
+	bool has_may_goto = aux->main_prog_aux->has_may_goto;
+	bool arena_sp = aux->arena_stack_size;
 	u8 *prog = *pprog, *start = prog;
 
 	EMIT2(0x50, 0x56);			/* push rax; push rsi */
 	if (arena_sp)
 		push_r9(&prog);
+	if (has_may_goto)
+		EMIT2(0x41, 0x53);		/* push r11 */
 	EMIT4(0x48, 0x8B, 0x7D, 0x08);		/* mov rdi, [rbp + 8] */
 	if (emit_rsb_call(&prog, target, ip + (prog - start)))
 		return -EINVAL;
 	EMIT4(0x48, 0x89, 0x45, 0x08);		/* mov [rbp + 8], rax */
+	if (has_may_goto)
+		EMIT2(0x41, 0x5B);		/* pop r11 */
 	if (arena_sp)
 		pop_r9(&prog);
 	EMIT2(0x5E, 0x58);			/* pop rsi; pop rax */
@@ -2523,6 +2551,133 @@ static int emit_unwind_ret_addr(u8 **pprog, u8 *ip, bool arena_sp, void *target)
 	return 0;
 }
 
+/* BPF_MAY_GOTO_MOV(). @reg is dst_reg of @insn, with FP mapped to R9 on a private stack. */
+static void emit_may_goto_mov(u8 **pprog, int op, const struct bpf_insn *insn, u32 reg)
+{
+	int task_off = offsetof(struct task_struct, bpf_may_goto_state);
+	u8 *prog = *pprog;
+
+	if (reg == BPF_REG_AX)
+		reg = X86_REG_R11;
+	if (op != BPF_MAY_GOTO_READ && op != BPF_MAY_GOTO_INIT) {
+		/* mov r10, gs:[current_task] */
+		if (IS_ENABLED(CONFIG_SMP))
+			EMIT1(0x65);
+		EMIT4_off32(0x4C, 0x8B, 0x14, 0x25, (u32)(unsigned long)&current_task);
+	}
+	switch (op) {
+	case BPF_MAY_GOTO_READ:
+		emit_mov_reg(&prog, true, reg, X86_REG_R11);
+		break;
+	case BPF_MAY_GOTO_INIT:
+		emit_mov_imm64(&prog, reg, BPF_MAY_GOTO_INIT_STATE >> 32,
+			       (u32)BPF_MAY_GOTO_INIT_STATE);
+		break;
+	case BPF_MAY_GOTO_FILL:
+		emit_ldx(&prog, BPF_DW, reg, BPF_REG_AX, task_off);
+		break;
+	case BPF_MAY_GOTO_SPILL:
+	case BPF_MAY_GOTO_SPILL_CALL:
+		emit_stx(&prog, BPF_DW, BPF_REG_AX, reg, task_off);
+		break;
+	case BPF_MAY_GOTO_SAVE:
+		emit_ldx(&prog, BPF_DW, BPF_REG_AX, BPF_REG_AX, task_off);
+		emit_stx(&prog, BPF_DW, reg, BPF_REG_AX, insn->imm);
+		break;
+	case BPF_MAY_GOTO_RESTORE:
+		/* push qword ptr [reg + imm]; pop qword ptr [r10 + task_off] */
+		EMIT2(add_1mod(0x40, reg), 0xFF);
+		emit_insn_suffix(&prog, reg, BPF_REG_2 /* FF /6 is push */, insn->imm);
+		EMIT3_off32(0x41, 0x8F, 0x82, task_off);
+		break;
+	}
+	*pprog = prog;
+}
+
+static bool call_needs_may_goto_fill(const struct bpf_prog *prog, const struct bpf_insn *call)
+{
+	return call > prog->insnsi && insn_is_may_goto_mov(call - 1) &&
+	       call[-1].off == BPF_MAY_GOTO_SPILL_CALL;
+}
+
+/* After a call the state is in the task, in the frame at @off, or the callee returned it in R11 */
+static void emit_fill_after_call(u8 **pprog, const struct bpf_prog *bpf_prog,
+				 const struct bpf_insn *call, int off)
+{
+	if (call_needs_may_goto_fill(bpf_prog, call))
+		emit_may_goto_mov(pprog, BPF_MAY_GOTO_FILL, call - 1, BPF_REG_AX);
+	else if (off)
+		emit_ldx(pprog, BPF_DW, X86_REG_R11, BPF_REG_FP, off);
+}
+
+/* In a prog with may_goto the code of @insn leaves R11 alone, or restores it itself */
+static bool insn_preserves_r11(const struct bpf_prog *prog, const struct bpf_insn *insn)
+{
+	u8 mode = BPF_MODE(insn->code);
+
+	switch (BPF_CLASS(insn->code)) {
+	case BPF_ALU:
+	case BPF_ALU64:
+		switch (BPF_OP(insn->code)) {
+		case BPF_ADD:
+		case BPF_SUB:
+		case BPF_AND:
+		case BPF_OR:
+		case BPF_XOR:
+		case BPF_NEG:
+		case BPF_MOV:
+		case BPF_END:
+			return true;
+		case BPF_MUL:
+			return !bpf_insn_is_hmul(insn);
+		case BPF_DIV:
+		case BPF_MOD:
+			return BPF_SRC(insn->code) == BPF_X &&
+			       insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_REG_3;
+		case BPF_LSH:
+		case BPF_RSH:
+		case BPF_ARSH:
+			return BPF_SRC(insn->code) == BPF_K || boot_cpu_has(X86_FEATURE_BMI2);
+		}
+		return false;
+	case BPF_LD:
+		return mode == BPF_IMM;
+	case BPF_LDX:
+		return mode == BPF_MEM || mode == BPF_PROBE_MEM || mode == BPF_PROBE_MEM32 ||
+		       mode == BPF_MEMSX || mode == BPF_PROBE_MEMSX || mode == BPF_PROBE_MEM32SX;
+	case BPF_ST:
+		return mode == BPF_MEM || mode == BPF_PROBE_MEM32 || mode == BPF_NOSPEC;
+	case BPF_STX:
+		return mode == BPF_MEM || mode == BPF_PROBE_MEM32 || mode == BPF_PROBE_ATOMIC ||
+		       (mode == BPF_ATOMIC && !is_atomic_fetch_op(insn));
+	}
+	if (insn->code != (BPF_JMP | BPF_CALL) || call_needs_may_goto_fill(prog, insn))
+		return true;
+	/* The target of a tail call returns for the subprog. It is a prog of its own. */
+	return insn->src_reg == BPF_PSEUDO_CALL && !prog->aux->tail_call_reachable;
+}
+
+/*
+ * Emit the slow path of may_goto into @code, which runs at @ip. @next_ip is the insn after
+ * may_goto. The caller adds the jump to the target of may_goto.
+ */
+static int emit_may_goto_slowpath(u8 *code, u8 *ip, u8 *next_ip)
+{
+	u8 *prog = code;
+
+	EMIT3(0x4C, 0x8D, 0x15);			/* lea r10, [next_ip] */
+	EMIT(next_ip - (ip + (prog - code) + 4), 4);
+	if (emit_rsb_call(&prog, arch_bpf_timed_may_goto, ip + (prog - code)))
+		return -EINVAL;
+	EMIT4(0x41, 0xF6, 0xC2, BPF_MAY_GOTO_EXPIRED);	/* test r10b, 1 */
+	EMIT2(0x0F, X86_JE + 0x10);			/* je next_ip */
+	EMIT(next_ip - (ip + (prog - code) + 4), 4);
+	return prog - code;
+}
+
+/* R11 as a temporary. The JIT fails if insn_preserves_r11() is true for the insn. */
+#define AUX_REG ({ r11_used = true; X86_REG_R11; })
+
 static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *addrs, u8 *image,
 		  u8 *rw_image, int oldproglen, struct jit_context *ctx, bool jmp_padding)
 {
@@ -2540,6 +2695,11 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 	int ilen, moved, proglen = 0;
 	u8 *ip, *prog = temp;
 	u32 stack_depth;
+	/* R11 has the state of may_goto, so R10 is the temporary where one is enough */
+	bool has_may_goto = bpf_prog->aux->main_prog_aux->has_may_goto, r11_used;
+	u32 tmp = has_may_goto ? BPF_REG_AX : X86_REG_R11;
+	/* the spill slot of R11. spill_off is 0 when the insn needs no spill. */
+	int r11_off = 0, spill_off;
 	int callee_saved_size;
 	s32 outgoing_arg_base;
 	/* the program uses BPF_REG_ARENA_SP, which is R9 */
@@ -2548,7 +2708,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 	bool arena_sp_save = arena_sp && calls_clobber_arena_sp(bpf_prog);
 	s32 arena_sp_off = 0;
 	/* the bytes emitted after the native call of the last call insn */
-	u8 after_call[16], *ret_addr;
+	u8 after_call[sizeof_field(struct jit_landing, code)], *ret_addr;
 	/* how many of them the landing of unwind_goto repeats, and that of cancel_goto */
 	int after_call_len = 0, after_call_cancel_len = 0;
 	/* the number of landings in this pass, and their size in bytes so far */
@@ -2563,6 +2723,19 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		stack_depth = 0;
 	}
 
+	/*
+	 * A function with the state in R11 spills it around the insns that clobber it.
+	 * Other subprogs save it once, for their callers. A main prog need not preserve it.
+	 */
+	if (bpf_prog->aux->may_goto_in_reg || (has_may_goto && bpf_is_subprog(bpf_prog))) {
+		for (i = 0; i < insn_cnt && insn_preserves_r11(bpf_prog, insn + i); i++)
+			;
+		if (i < insn_cnt) {
+			stack_depth = round_up(stack_depth, 8) + 8;
+			r11_off = -stack_depth;
+		}
+	}
+
 	/*
 	 * Follow x86-64 calling convention for both BPF-to-BPF and
 	 * kfunc calls:
@@ -2656,6 +2829,9 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 	if (priv_frame_ptr)
 		emit_priv_frame_ptr(&prog, priv_frame_ptr);
 
+	if (r11_off && !bpf_prog->aux->may_goto_in_reg)
+		emit_stx(&prog, BPF_DW, BPF_REG_FP, X86_REG_R11, r11_off);
+
 	ilen = prog - temp;
 	if (rw_image)
 		memcpy(rw_image + proglen, temp, ilen);
@@ -2678,7 +2854,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		u8 *func;
 		int nops;
 		u32 jmp_op = BPF_OP(insn->code);
-		u32 fault_unwinds;
+		u32 fixup_flags;
 		s32 cmp_imm;
 
 		if (priv_frame_ptr) {
@@ -2692,13 +2868,20 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		if (bpf_insn_is_indirect_target(env, bpf_prog, i - 1))
 			EMIT_ENDBR();
 
+		r11_used = false;
+		spill_off = 0;
+		if (bpf_prog->aux->may_goto_in_reg && !insn_preserves_r11(bpf_prog, insn))
+			spill_off = r11_off;
+		if (spill_off)
+			emit_stx(&prog, BPF_DW, BPF_REG_FP, X86_REG_R11, spill_off);
+
 		ip = image + addrs[i - 1] + (prog - temp);
 		insn_idx = i - 1 + bpf_prog->aux->subprog_start;
 		accesses_stack_only =
 			env ? !env->insn_aux_data[insn_idx].non_stack_access :
 			      false;
-		fault_unwinds = bpf_insn_fault_unwinds(env, bpf_prog, i - 1) ?
-				FIXUP_ARENA_UNWINDS : 0;
+		fixup_flags = bpf_insn_fault_unwinds(env, bpf_prog, i - 1) ?
+			      FIXUP_ARENA_UNWINDS : 0;
 
 		switch (insn->code) {
 			/* ALU */
@@ -2720,16 +2903,16 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			if (insn_is_cast_user(insn)) {
 				/* mov dst_reg32, src_reg32 to zero extend the low half */
 				emit_mov_reg(&prog, false, dst_reg, src_reg);
-				/* mov r11, the high half of user_vm_start; or r11, dst_reg */
-				emit_mov_imm64(&prog, AUX_REG, user_vm_start >> 32, 0);
-				emit_alu_reg(&prog, BPF_OR, AUX_REG, dst_reg, true);
+				/* mov tmp, the high half of user_vm_start; or tmp, dst_reg */
+				emit_mov_imm64(&prog, tmp, user_vm_start >> 32, 0);
+				emit_alu_reg(&prog, BPF_OR, tmp, dst_reg, true);
 				/* test dst_reg32, dst_reg32; a NULL pointer stays NULL */
 				maybe_emit_mod(&prog, dst_reg, dst_reg, false);
 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
-				/* cmovne dst_reg, r11 */
+				/* cmovne dst_reg, tmp */
 				/* WARNING: Intel swapped src/dst register encoding in CMOVcc !!! */
-				maybe_emit_mod(&prog, AUX_REG, dst_reg, true);
-				EMIT3(0x0F, 0x45, add_2reg(0xC0, AUX_REG, dst_reg));
+				maybe_emit_mod(&prog, tmp, dst_reg, true);
+				EMIT3(0x0F, 0x45, add_2reg(0xC0, tmp, dst_reg));
 				break;
 			} else if (insn_is_mov_percpu_addr(insn)) {
 				/* mov <dst>, <src> (if necessary) */
@@ -2741,6 +2924,9 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				EMIT((u32)(unsigned long)&this_cpu_off, 4);
 #endif
 				break;
+			} else if (insn_is_may_goto_mov(insn)) {
+				emit_may_goto_mov(&prog, insn->off, insn, dst_reg);
+				break;
 			}
 			fallthrough;
 		case BPF_ALU | BPF_MOV | BPF_X:
@@ -3194,7 +3380,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 							 image + proglen + (start_of_ldx - temp),
 							 prog - start_of_ldx, fixup_reg, arena_reg,
 							 (is_write ? FIXUP_ARENA_WRITE : 0) |
-							 fault_unwinds, insn->off);
+							 fixup_flags, insn->off);
 				if (err)
 					return err;
 			}
@@ -3250,18 +3436,18 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				u8 *end_of_jmp;
 
 				/*
-				 * lea r11, [src_reg + insn->off - VSYSCALL_ADDR]
+				 * lea tmp, [src_reg + insn->off - VSYSCALL_ADDR]
 				 *
 				 * VSYSCALL_ADDR is a small negative number, so the
 				 * whole offset fits into the 32-bit displacement.
 				 */
 				BUILD_BUG_ON((long)(s32)VSYSCALL_ADDR != (long)VSYSCALL_ADDR);
-				EMIT2(add_2mod(0x48, src_reg, AUX_REG), 0x8D);
-				emit_insn_suffix(&prog, src_reg, AUX_REG,
+				EMIT2(add_2mod(0x48, src_reg, tmp), 0x8D);
+				emit_insn_suffix(&prog, src_reg, tmp,
 						 insn->off - (s32)VSYSCALL_ADDR);
 
-				/* shr r11, fls64(limit) */
-				emit_shift_imm(&prog, BPF_RSH, AUX_REG, fls64(limit), true);
+				/* shr tmp, fls64(limit) */
+				emit_shift_imm(&prog, BPF_RSH, tmp, fls64(limit), true);
 
 				/* if not zero, goto load */
 				EMIT2(X86_JNE, 0);
@@ -3371,7 +3557,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			}
 			if (is_atomic_fetch) {
 				err = emit_atomic_fetch_rmw(&prog, insn, real_dst_reg,
-							    real_src_reg, -1, NULL);
+							    real_src_reg, AUX_REG, -1, NULL);
 				if (err)
 					return err;
 				break;
@@ -3409,10 +3595,17 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				if (dst_reg == BPF_REG_0)
 					real_dst_reg = BPF_REG_AX;
 
+				if (has_may_goto) {
+					EMIT2(0x41, 0x53); /* push r11 */
+					fixup_flags |= FIXUP_ARENA_R11_PUSHED;
+				}
 				err = emit_atomic_fetch_rmw(&prog, insn, real_dst_reg,
-							    real_src_reg, X86_REG_R12, fault);
+							    real_src_reg, X86_REG_R11,
+							    X86_REG_R12, fault);
 				if (err)
 					return err;
+				if (has_may_goto)
+					EMIT2(0x41, 0x5B); /* pop r11 */
 
 				/*
 				 * The page may be unmapped between the load and the
@@ -3428,7 +3621,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 								 prog - fault[j],
 								 reg2pt_regs[real_src_reg],
 								 reg2pt_regs[real_dst_reg],
-								 FIXUP_ARENA_WRITE | fault_unwinds |
+								 FIXUP_ARENA_WRITE | fixup_flags |
 								 FIXUP_ARENA_R0_IN_AX, insn->off);
 					if (err)
 						return err;
@@ -3436,7 +3629,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				break;
 			}
 			if (!bpf_atomic_is_load_store(insn))
-				emit_arena_align_check(&prog, insn, dst_reg);
+				emit_arena_align_check(&prog, insn, dst_reg, tmp);
 			start_of_ldx = prog;
 
 			if (bpf_atomic_is_load_store(insn))
@@ -3445,7 +3638,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 							      src_reg, X86_REG_R12, insn->off);
 			else
 				err = emit_atomic_rmw_index(&prog, insn->imm, BPF_SIZE(insn->code),
-							    AUX_REG, src_reg, X86_REG_R12,
+							    tmp, src_reg, X86_REG_R12,
 							    insn->off);
 			if (err)
 				return err;
@@ -3522,6 +3715,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				emit_sub_rsp(&prog, 8);
 			if (arena_sp && call_clobbers_arena_sp(insn))
 				emit_ldx(&prog, BPF_DW, BPF_REG_ARENA_SP, BPF_REG_FP, arena_sp_off);
+			emit_fill_after_call(&prog, bpf_prog, insn, spill_off);
 			/*
 			 * The landing of cancel_goto ends here: after cancel_exit RDX
 			 * is not the second half of what the kfunc returned.
@@ -3560,11 +3754,12 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			ret_addr = prog;
 			if (priv_frame_ptr)
 				pop_r9(&prog);
+			emit_fill_after_call(&prog, bpf_prog, insn, spill_off);
 			after_call_len = after_call_cancel_len = prog - ret_addr;
 			memcpy(after_call, ret_addr, after_call_len);
 			break;
 
-			/* unwind_goto, cancel_goto. The verifier expanded may_goto. */
+			/* may_goto, unwind_goto, cancel_goto */
 		case BPF_JMP | BPF_JCOND:
 		case BPF_JMP32 | BPF_JCOND: {
 			bool cancel_goto = bpf_is_cancel_goto(insn);
@@ -3577,6 +3772,25 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			int len = cancel_goto ? after_call_cancel_len : after_call_len;
 			struct jit_landing *landing;
 
+			if (insn_is_jit_may_goto(insn)) {
+				if (nr_landings >= ctx->max_landings)
+					return -EFAULT;
+				/* sub r11, BPF_MAY_GOTO_CNT_ONE; jl slow. No state is negative. */
+				EMIT3_off32(0x49, 0x81, 0xEB, BPF_MAY_GOTO_CNT_ONE);
+				target = addrs[insn_cnt] + tail;
+				EMIT2_off32(0x0F, X86_JL + 0x10, target - addrs[i]);
+				landing = &ctx->landings[nr_landings++];
+				/* target is an estimate until there is an image */
+				len = emit_may_goto_slowpath(landing->code,
+							     image ? image + target : NULL,
+							     image + addrs[i]);
+				if (len < 0)
+					return len;
+				landing->len = len;
+				landing->to = to;
+				tail += len + 5;
+				break;
+			}
 			if (BPF_CLASS(insn[-1 - after_unwind].code) != BPF_JMP) {
 				if (cancel_goto) {
 					pr_err("bpf_jit: cancel_goto follows no call\n");
@@ -3897,10 +4111,10 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 		case BPF_JMP | BPF_EXIT:
 			if (src_reg == BPF_UNWIND_EXIT && bpf_prog_can_unwind(bpf_prog) &&
-			    emit_unwind_ret_addr(&prog, ip, arena_sp, bpf_unwind_target))
+			    emit_unwind_ret_addr(&prog, ip, bpf_prog->aux, bpf_unwind_target))
 				return -EINVAL;
 			if (src_reg == BPF_CANCEL_EXIT && bpf_prog_can_unwind(bpf_prog) &&
-			    emit_unwind_ret_addr(&prog, ip, arena_sp, bpf_cancel_target))
+			    emit_unwind_ret_addr(&prog, ip, bpf_prog->aux, bpf_cancel_target))
 				return -EINVAL;
 			if (seen_exit) {
 				jmp_offset = ctx->cleanup_addr - addrs[i] + moved;
@@ -3914,6 +4128,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				if (emit_spectre_bhb_barrier(&prog, ip, bpf_prog))
 					return -EINVAL;
 			}
+			if (r11_off && !bpf_prog->aux->may_goto_in_reg)
+				emit_ldx(&prog, BPF_DW, X86_REG_R11, BPF_REG_FP, r11_off);
 			/* Deallocate outgoing args 7+ area and the slot of BPF_REG_ARENA_SP. */
 			emit_add_rsp(&prog, outgoing_rsp + (arena_sp_save ? 8 : 0));
 			pop_callee_regs(&prog, callee_regs_used);
@@ -3936,6 +4152,12 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			return -EINVAL;
 		}
 
+		if (WARN_ON_ONCE(has_may_goto && r11_used &&
+				 insn_preserves_r11(bpf_prog, insn)))
+			return -EFAULT;
+		if (spill_off && BPF_CLASS(insn->code) != BPF_JMP)
+			emit_ldx(&prog, BPF_DW, X86_REG_R11, BPF_REG_FP, spill_off);
+
 		ilen = prog - temp;
 		if (ilen > BPF_MAX_INSN_SIZE) {
 			pr_err("bpf_jit: fatal insn size error\n");
@@ -4488,7 +4710,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 	int i, ret, nr_regs, stack_size = 0;
 	u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS];
 	int regs_off, func_meta_off, ip_off, run_ctx_off, arg_stack_off, rbx_off;
-	int tcc_off = 0;
+	int tcc_off = 0, r11_off = 0;
 	struct bpf_tramp_nodes *fentry = &tnodes[BPF_TRAMP_FENTRY];
 	struct bpf_tramp_nodes *fexit = &tnodes[BPF_TRAMP_FEXIT];
 	struct bpf_tramp_nodes *fmod_ret = &tnodes[BPF_TRAMP_MODIFY_RETURN];
@@ -4541,6 +4763,8 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 	 *
 	 * RBP - tcc_off   [ tail_call_cnt_ptr ]  BPF_TRAMP_F_TAIL_CALL_CTX
 	 *
+	 * RBP - r11_off   [ r11 value       ]  the target is a BPF function
+	 *
 	 *                     [ stack slotN ]  BPF_TRAMP_F_CALL_ORIG,
 	 *                     [ ...         ]  the incoming stack
 	 *                     [ stack slot2 ]  arguments, alignment
@@ -4580,6 +4804,12 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 		tcc_off = stack_size;
 	}
 
+	/* BPF functions take and return the state of may_goto in R11 */
+	if (is_bpf_text_address((long)func_addr)) {
+		stack_size += 8;
+		r11_off = stack_size;
+	}
+
 	if (nr_regs > 6 && (flags & BPF_TRAMP_F_CALL_ORIG)) {
 		/* the space that used to pass arguments on-stack */
 		stack_size += get_nr_stack_slots(pos_of_slot, nr_regs) * 8;
@@ -4633,6 +4863,8 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 	if (flags & BPF_TRAMP_F_TAIL_CALL_CTX)
 		/* mov QWORD PTR [rbp - tcc_off], rax */
 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -tcc_off);
+	if (r11_off)
+		emit_stx(&prog, BPF_DW, BPF_REG_FP, X86_REG_R11, -r11_off);
 	/* mov QWORD PTR [rbp - rbx_off], rbx */
 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_6, -rbx_off);
 
@@ -4695,6 +4927,8 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 			 */
 			LOAD_TRAMP_TAIL_CALL_CNT_PTR(tcc_off);
 		}
+		if (r11_off)
+			emit_ldx(&prog, BPF_DW, X86_REG_R11, BPF_REG_FP, -r11_off);
 
 		if (flags & BPF_TRAMP_F_ORIG_STACK) {
 			emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, 8);
@@ -4708,6 +4942,8 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 		}
 		/* remember return value in a stack for bpf prog to access */
 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
+		if (r11_off)
+			emit_stx(&prog, BPF_DW, BPF_REG_FP, X86_REG_R11, -r11_off);
 	}
 
 	if (fmod_ret->nr_nodes) {
@@ -4765,6 +5001,8 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 		emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, -8);
 
 	emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, -rbx_off);
+	if (r11_off)
+		emit_ldx(&prog, BPF_DW, X86_REG_R11, BPF_REG_FP, -r11_off);
 
 	EMIT1(0xC9); /* leave */
 	im->ksym.fp_end = prog - (u8 *)rw_image;
@@ -5051,7 +5289,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	if (!addrs)
 		goto out_addrs;
 	for (i = 0; i < prog->len; i++)
-		ctx.max_landings += bpf_is_pad_goto(&prog->insnsi[i]);
+		ctx.max_landings += bpf_is_pad_goto(&prog->insnsi[i]) ||
+				    insn_is_jit_may_goto(&prog->insnsi[i]);
 	if (ctx.max_landings) {
 		ctx.landings = kvmalloc_objs(*ctx.landings, ctx.max_landings);
 		if (!ctx.landings)
@@ -5417,6 +5656,11 @@ bool bpf_jit_supports_timed_may_goto(void)
 	return true;
 }
 
+bool bpf_jit_supports_may_goto_insn(void)
+{
+	return true;
+}
+
 bool bpf_jit_supports_fsession(void)
 {
 	return true;
diff --git a/arch/x86/net/bpf_timed_may_goto.S b/arch/x86/net/bpf_timed_may_goto.S
index da42de7cca98..a4e254314857 100644
--- a/arch/x86/net/bpf_timed_may_goto.S
+++ b/arch/x86/net/bpf_timed_may_goto.S
@@ -15,6 +15,10 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	pushq %rbp
 	movq %rsp, %rbp
 
+	/* r10 is the address after may_goto. A dump of the stack takes it as the return address. */
+	pushq 8(%rbp)
+	movq %r10, 8(%rbp)
+
 	/* Save r0-r5. */
 	pushq %rax
 	pushq %rdi
@@ -25,15 +29,17 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	/* Save stack argument 6. */
 	pushq %r9
 
-	/* r10 has the pointer to count and timestamp. Pass it as first argument. */
-	movq %r10, %rdi
+	/* r11 has the state. Pass it as first argument. */
+	pushq %r11
+	movq %r11, %rdi
 
 	/* Emit call depth accounting for call below. */
 	CALL_DEPTH_ACCOUNT
-	call bpf_check_timed_may_goto
+	call bpf_may_goto_slowpath
 
-	/* BPF_REG_AX=r10 will be stored into count, so move return value to it. */
-	movq %rax, %r10
+	/* The old state goes back in r10. */
+	popq %r10
+	movq %rax, %r11
 
 	popq %r9
 	/* Restore r5-r0. */
@@ -43,6 +49,7 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	popq %rsi
 	popq %rdi
 	popq %rax
+	popq 8(%rbp)
 
 	leave
 	RET
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index f60a300c6a9b..9d4f89269711 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -3127,7 +3127,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 	struct bpf_subprog_info *subprogs = env->subprog_info;
 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
 	u16 stack_depth_extra = 0;
-	/* arch_bpf_timed_may_goto() takes and returns AX in a cpu register: for JITs only */
+	/* arch_bpf_timed_may_goto() has a calling convention of its own: for JITs only */
 	bool timed_may_goto = prog->jit_requested && bpf_jit_supports_timed_may_goto();
 	bool may_goto_insn = timed_may_goto && bpf_jit_supports_may_goto_insn();
 	struct bpf_timed_may_goto __percpu *tmg = NULL;
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index 2a3210a50678..afe6dc7958b8 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -1002,7 +1002,7 @@ __naked void callback_of_drain(void)
 	: __clobber_all);
 }
 
-/* 200000 iterations: may_goto calls arch_bpf_timed_may_goto() three times */
+/* 200000 iterations: may_goto takes its slow path three times */
 SEC("syscall")
 __description("arena stack: may_goto doesn't change r12")
 __success __retval(42)
@@ -1069,10 +1069,11 @@ static __naked __noinline __used long spin_cb(void)
  */
 SEC("syscall")
 __description("arena stack: bpf_loop() ends when the time of may_goto is up")
+__arch_x86_64
 __success __retval(121)
 /* a call of the callback when the time is up returns 1 before it takes a stack */
-__xlated("if r0 != 0x0 goto pc+2")
-__xlated("r0 = 1")
+__xlated("r0 &= 1")
+__xlated("if r0 == 0x0 goto pc+1")
 __xlated("exit")
 __xlated("r6 = ")
 __xlated("r6 = &(void __percpu *)(r6)")
diff --git a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
index 8a69d6b7874f..5b3d760bd160 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
@@ -937,31 +937,16 @@ SEC("raw_tp")
 __arch_x86_64
 __log_level(4)
 __msg("subprog 0 (may_goto_interaction_x86_64) main {{.*}} stack 8")
-/* may_goto counter and timestamp */
-__xlated("0: r0 = ")
-__xlated("2: r0 = &(void __percpu *)(r0)")
+__xlated("0: may_goto_init")
+__xlated("1: r1 = 1")
 __xlated("...")
-__xlated("6: r1 = 1")
-__xlated("...")
-__xlated("8: r0 = &(void __percpu *)(r0)")
-__xlated("...")
-/* may_goto expansion starts, r0 and r1 are live */
-__xlated("10: r2 = ")
-__xlated("12: r2 = &(void __percpu *)(r2)")
-__xlated("13: r13 = *(u64 *)(r2 +0)")
 /* when the time is up may_goto goes to the landing pad of the prog */
-__xlated("14: if r13 == 0x0 goto pc+7")
-__xlated("15: r13 -= 1")
-__xlated("16: if r13 != 0x0 goto pc+2")
-__xlated("17: r13 = r2")
-__xlated("18: call unknown")
-__xlated("19: *(u64 *)(r2 +0) = r13")
-/* may_goto expansion ends */
-__xlated("20: *(u64 *)(r10 -8) = r1")
-__xlated("21: exit")
+__xlated("may_goto pc+2")
+__xlated("*(u64 *)(r10 -8) = r1")
+__xlated("exit")
 /* the landing pad */
-__xlated("22: r0 = 0")
-__xlated("23: exit")
+__xlated("r0 = 0")
+__xlated("exit")
 __success
 __naked void may_goto_interaction_x86_64(void)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
index f8861ad046ce..aeff39968a4d 100644
--- a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
+++ b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
@@ -83,7 +83,6 @@ __naked void may_goto_batch_1(void)
 SEC("raw_tp")
 __description("may_goto batch with offsets 2/0")
 __load_if_JITed()
-__arch_x86_64
 __arch_s390x
 __arch_arm64
 __arch_riscv64
@@ -125,6 +124,34 @@ __naked void may_goto_batch_2(void)
 	: __clobber_all);
 }
 
+SEC("raw_tp")
+__description("may_goto batch with offsets 2/0, JIT of may_goto")
+__load_if_JITed()
+__arch_x86_64
+__xlated("0: may_goto_init")
+/* when the time is up may_goto goes to the landing pad of the prog */
+__xlated("1: may_goto pc+3")
+__xlated("2: r0 = 1")
+__xlated("3: r0 = 2")
+__xlated("4: exit")
+/* the landing pad */
+__xlated("5: r0 = 0")
+__xlated("6: exit")
+__success
+__naked void may_goto_batch_2_insn(void)
+{
+	asm volatile (
+	".8byte %[may_goto1];"
+	".8byte %[may_goto3];"
+	"r0 = 1;"
+	"r0 = 2;"
+	"exit;"
+	:
+	: __imm_insn(may_goto1, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 2 /* offset */, 0)),
+	  __imm_insn(may_goto3, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0 /* offset */, 0))
+	: __clobber_all);
+}
+
 /*
  * Use bpf_get_prandom_u32() to prevent DCE from removing the checks.
  * retval: 0=all ok, 1-6=R0-R5 clobbered.
diff --git a/tools/testing/selftests/bpf/progs/verifier_patch_list.c b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
index da5542bcb6e7..2a18f182c0db 100644
--- a/tools/testing/selftests/bpf/progs/verifier_patch_list.c
+++ b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
@@ -86,36 +86,27 @@ __naked void patch_list_backward(void)
 }
 
 /*
- * The jump of may_goto leaves its own patch and crosses another one, on the way to the landing pad
- * that follows the prog.
+ * The jump of may_goto crosses a patch on the way to the landing pad that follows the prog.
  */
 SEC("raw_tp")
 __description("patch list: may_goto between patched insns")
 __arch_x86_64
-__arch_arm64
 __success
-__xlated("0: r0 = ")
-__xlated("2: r0 = &(void __percpu *)(r0)")
-__xlated("3: *(u64 *)(r0 +0) = 65535")
-__xlated("...")
-__xlated("6: call")
-__xlated("7: r1 = r0")
+__xlated("0: may_goto_init")
+__xlated("1: call")
+__xlated("2: r1 = r0")
+__xlated("3: if r1 != 0x0 goto pc+2")
+__xlated("4: w0 ^= w0")
+__xlated("5: goto pc+1")
+__xlated("6: r0 /= r1")
+__xlated("7: may_goto pc+5")
 __xlated("8: if r1 != 0x0 goto pc+2")
 __xlated("9: w0 ^= w0")
 __xlated("10: goto pc+1")
 __xlated("11: r0 /= r1")
-__xlated("12: r2 = ")
-__xlated("14: r2 = &(void __percpu *)(r2)")
-__xlated("15: r13 = *(u64 *)(r2 +0)")
-__xlated("16: if r13 == 0x0 goto pc+10")
-__xlated("...")
-__xlated("22: if r1 != 0x0 goto pc+2")
-__xlated("23: w0 ^= w0")
-__xlated("24: goto pc+1")
-__xlated("25: r0 /= r1")
-__xlated("26: exit")
-__xlated("27: r0 = 0")
-__xlated("28: exit")
+__xlated("12: exit")
+__xlated("13: r0 = 0")
+__xlated("14: exit")
 __naked void patch_list_may_goto(void)
 {
 	asm volatile (
@@ -316,38 +307,34 @@ int patch_list_indirect(void)
 #endif
 
 /*
- * When the time is up may_goto goes to the landing pad, which follows the prog: over 8191
- * divisions, 32764 insns once each of them is guarded by a patch of 4 insns. That does not fit
- * the 16 bits of the jump that may_goto expands to, which has to become gotol.
+ * When the time is up may_goto goes to the landing pad, which follows the prog: over 8192
+ * divisions, 32768 insns once each of them is guarded by a patch of 4 insns. That does not fit
+ * 16 bits.
  */
 SEC("raw_tp")
-__description("patch list: far may_goto expanded to gotol")
+__description("patch list: far may_goto")
 __arch_x86_64
-__arch_arm64
 __success
-__xlated("12: r13 = *(u64 *)(r2 +0)")
-__xlated("13: if r13 == 0x0 goto pc+1")
-__xlated("14: goto pc+1")
-__xlated("15: gotol pc+32771")
+__xlated("4: may_goto pc+32770")
 __xlated("...")
-__xlated("32786: exit")
-__xlated("32787: r0 = 0")
-__xlated("32788: exit")
-__naked void patch_list_may_goto_gotol(void)
+__xlated("32774: exit")
+__xlated("32775: r0 = 0")
+__xlated("32776: exit")
+__naked void patch_list_may_goto_far(void)
 {
 	asm volatile ("					\
 	call %[bpf_get_prandom_u32];			\
 	r1 = r0;					\
 	r6 = 0;						\
 	.8byte %[may_goto];				\
-	.rept 8191;					\
+	.rept 8192;					\
 	r0 /= r1;					\
 	.endr;						\
 	r0 = 0;						\
 	exit;						\
 "	:
 	: __imm(bpf_get_prandom_u32),
-	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 8191 /* offset */, 0))
+	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 8192 /* offset */, 0))
 	: __clobber_all);
 }
 
@@ -403,7 +390,7 @@ static unsigned long patch_list_loop_at_start(void)
 	: __clobber_all)
 
 /*
- * The check of the may_goto count goes in front of the callback of bpf_loop().
+ * The check of the time of may_goto goes in front of the callback of bpf_loop().
  * The call of the inlined bpf_loop() lands on the check, the jump to the first
  * insn of the callback behind it.
  * This is the code for the JITs that support the timed may_goto and unwind programs: the callback
@@ -413,28 +400,23 @@ static unsigned long patch_list_loop_at_start(void)
 SEC("raw_tp")
 __description("patch list: call of and jump to an insn with insns inserted in front")
 __arch_x86_64
-__arch_arm64
 __success
-__xlated("27: call pc+10")
-__xlated("28: cancel_goto pc-15")
-__xlated("...")
-__xlated("37: exit")
-__xlated("38: r0 = ")
-__xlated("40: r0 = &(void __percpu *)(r0)")
-__xlated("41: r0 = *(u64 *)(r0 +0)")
-__xlated("42: if r0 != 0x0 goto pc+2")
-__xlated("43: r0 = 1")
-__xlated("44: exit")
-__xlated("45: r1 += -1")
-__xlated("...")
-__xlated("50: if r13 == 0x0 goto pc+8")
+__xlated("22: call pc+10")
+__xlated("23: cancel_goto pc-15")
 __xlated("...")
-__xlated("56: if r1 != 0x0 goto pc-12")
-__xlated("57: r0 = 0")
-__xlated("58: exit")
-__xlated("59: r0 = 0")
-__xlated("60: r2 = 0")
-__xlated("61: cancel_exit")
+__xlated("32: exit")
+__xlated("33: may_goto_read r0")
+__xlated("34: r0 &= 1")
+__xlated("35: if r0 == 0x0 goto pc+1")
+__xlated("36: exit")
+__xlated("37: r1 += -1")
+__xlated("38: may_goto pc+3")
+__xlated("39: if r1 != 0x0 goto pc-3")
+__xlated("40: r0 = 0")
+__xlated("41: exit")
+__xlated("42: r0 = 0")
+__xlated("43: r2 = 0")
+__xlated("44: cancel_exit")
 __naked void patch_list_insert_in_front(void)
 {
 	INSERT_IN_FRONT;
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 5/7] bpf, arm64: Keep the state of may_goto in x24
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
                   ` (3 preceding siblings ...)
  2026-12-05  3:37 ` [PATCH bpf-next 4/7] bpf, x86: Keep the state of may_goto in %r11 Alexei Starovoitov
@ 2026-12-05  3:37 ` Alexei Starovoitov
  2026-12-05  4:18   ` bot+bpf-ci
  2026-12-05  3:38 ` [PATCH bpf-next 6/7] bpf: Keep the state of may_goto in the task on other archs Alexei Starovoitov
                   ` (2 subsequent siblings)
  7 siblings, 1 reply; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:37 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

may_goto loads and stores the count on each iteration, and each load waits
for the previous store. Keep the state in x24, which the JIT doesn't use:

  subs x24, x24, #0x800, lsl #12
  b.lo slow

x24 is callee saved, so helpers and kfuncs preserve it.

Neoverse V2:

  ns per iteration                     before   after
  empty loop                             2.15    0.48
  load and store in arena                2.15    1.21
  call of bpf_get_numa_node_id()         2.15    0.95
  may_goto in callback of bpf_loop()     2.74    2.17
  call of a subprog with may_goto        4.30    2.15
  the same in a prog with a tail call    4.30    4.40

The last row is slower, since such progs pass the state through current.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
 arch/arm64/net/bpf_jit_comp.c                 | 203 +++++++++++++++---
 arch/arm64/net/bpf_timed_may_goto.S           |  20 +-
 .../bpf/progs/verifier_arena_stack.c          |   1 -
 .../bpf/progs/verifier_bpf_fastcall.c         |   6 +-
 .../selftests/bpf/progs/verifier_may_goto_1.c |   2 +-
 .../selftests/bpf/progs/verifier_patch_list.c |   3 +
 6 files changed, 187 insertions(+), 48 deletions(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index c3547c7e4c55..3ac287580d22 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -33,6 +33,7 @@
 #define TMP_REG_3 (MAX_BPF_JIT_REG + 3)
 #define PRIVATE_SP (MAX_BPF_JIT_REG + 4)
 #define ARENA_VM_START (MAX_BPF_JIT_REG + 5)
+#define MAY_GOTO_STATE (MAX_BPF_JIT_REG + 6)
 
 #define check_imm(bits, imm) do {				\
 	if ((((imm) > 0) && ((imm) >> ((bits) - 1))) ||		\
@@ -76,6 +77,8 @@ static const int bpf2a64[] = {
 	[PRIVATE_SP] = A64_R(27),
 	/* callee saved register for kern_vm_start address */
 	[ARENA_VM_START] = A64_R(28),
+	/* callee saved register for the state of may_goto */
+	[MAY_GOTO_STATE] = A64_R(24),
 };
 
 struct jit_ctx {
@@ -87,7 +90,7 @@ struct jit_ctx {
 	int *landing_ex;	/* the extable entry of each landing, see build_landings() */
 	int landing_idx;
 	int nr_used_callee_reg;
-	u8 used_callee_reg[8]; /* r6~r9, fp, arena_vm_start */
+	u8 used_callee_reg[9]; /* see find_used_callee_regs() */
 	__le32 *image;
 	__le32 *ro_image;
 	u32 stack_size;
@@ -825,6 +828,11 @@ static void find_used_callee_regs(struct jit_ctx *ctx)
 			ctx->fp_used = true;
 			reg_used |= 16;
 		}
+
+		/* other functions take the state from the caller and return it */
+		if (insn_is_may_goto_mov(insn) && insn->dst_reg == BPF_REG_AX &&
+		    (insn->off == BPF_MAY_GOTO_INIT || insn->off == BPF_MAY_GOTO_FILL))
+			reg_used |= 32;
 	}
 
 	i = 0;
@@ -846,6 +854,9 @@ static void find_used_callee_regs(struct jit_ctx *ctx)
 			ctx->used_callee_reg[i++] = bpf2a64[PRIVATE_SP];
 	}
 
+	if (reg_used & 32)
+		ctx->used_callee_reg[i++] = bpf2a64[MAY_GOTO_STATE];
+
 	if (ctx->arena_vm_start)
 		ctx->used_callee_reg[i++] = bpf2a64[ARENA_VM_START];
 
@@ -1506,11 +1517,11 @@ static void build_epilogue(struct jit_ctx *ctx, bool was_classic, bool unwind)
  *
  * Bit layout of `fixup` (32-bit):
  *
- * +-----------+--------+---------+-------------+-----------+-----------+----------+
- * |   31-27   | 26-24  |    23   |      22     |     21    |   20-16   |   15-0   |
- * |           |        |         |             |           |           |          |
- * | FIXUP_REG | Unused | UNWINDS | ARENA_WRITE | ARENA_ACC | ARENA_REG |  OFFSET  |
- * +-----------+--------+---------+-------------+-----------+-----------+----------+
+ * +-----------+--------+----------+---------+-------------+-----------+-----------+----------+
+ * |   31-27   | 26-25  |    24    |    23   |      22     |     21    |   20-16   |   15-0   |
+ * |           |        |          |         |             |           |           |          |
+ * | FIXUP_REG | Unused | MAY_GOTO | UNWINDS | ARENA_WRITE | ARENA_ACC | ARENA_REG |  OFFSET  |
+ * +-----------+--------+----------+---------+-------------+-----------+-----------+----------+
  *
  * - OFFSET (16 bits): Offset used to compute address for Load/Store instruction.
  * - ARENA_REG (5 bits): Register that is used to calculate the address for load/store when
@@ -1522,6 +1533,7 @@ static void build_epilogue(struct jit_ctx *ctx, bool was_classic, bool unwind)
  * - UNWINDS (1 bit): The frame holds nothing at the insn, and no unwind_goto follows it. The
  *                    handler goes to prog->aux->fault_pad, the landing pad that all such
  *                    accesses of the function share.
+ * - MAY_GOTO (1 bit): The state of may_goto is in its register.
  * - FIXUP_REG (5 bits): Destination register for the load instruction (cleared on fault) or set to
  *                       DONT_CLEAR if the instruction does not read into a register.
  */
@@ -1531,6 +1543,7 @@ static void build_epilogue(struct jit_ctx *ctx, bool was_classic, bool unwind)
 #define BPF_ARENA_ACCESS           BIT(21)
 #define BPF_ARENA_WRITE            BIT(22)
 #define BPF_ARENA_UNWINDS          BIT(23)
+#define BPF_ARENA_MAY_GOTO         BIT(24)
 #define BPF_FIXUP_REG_MASK	GENMASK(31, 27)
 #define DONT_CLEAR 5 /* Unused ARM64 register from BPF's POV */
 
@@ -1549,6 +1562,9 @@ bool ex_handler_bpf(const struct exception_table_entry *ex,
 		addr = regs->regs[arena_reg] + off;
 		pad = bpf_arena_fault(is_write, addr, regs->pc, end,
 				      ex->fixup & BPF_ARENA_UNWINDS);
+		/* The access is skipped. The next may_goto reads the clock. */
+		if (pad == end && ex->fixup & BPF_ARENA_MAY_GOTO)
+			regs->regs[bpf2a64[MAY_GOTO_STATE]] &= BPF_MAY_GOTO_CNT_ONE - 1;
 	}
 
 	/*
@@ -1633,6 +1649,8 @@ static int add_exception_handler(const struct bpf_verifier_env *env,
 			ex->fixup |= BPF_ARENA_WRITE;
 		if (bpf_insn_fault_unwinds(env, ctx->prog, insn - ctx->prog->insnsi))
 			ex->fixup |= BPF_ARENA_UNWINDS;
+		if (ctx->prog->aux->may_goto_in_reg)
+			ex->fixup |= BPF_ARENA_MAY_GOTO;
 		/*
 		 * insn->src_reg/dst_reg holds the address in the arena region with upper 32-bits
 		 * being zero because of a preceding addr_space_cast(r<n>, 0x0, 0x1) instruction.
@@ -1656,15 +1674,125 @@ static int add_exception_handler(const struct bpf_verifier_env *env,
 	return 0;
 }
 
-/* Whether @insn, unwind_goto or cancel_goto, follows the call of a helper or a kfunc */
-static bool goto_after_helper(const struct bpf_insn *insn)
+/* BPF_MAY_GOTO_MOV() */
+static void emit_may_goto_mov(int op, const struct bpf_insn *insn, struct jit_ctx *ctx)
+{
+	const int task_off = offsetof(struct task_struct, bpf_may_goto_state);
+	const u8 fp = bpf2a64[BPF_REG_FP], state = bpf2a64[MAY_GOTO_STATE];
+	const u8 task = bpf2a64[TMP_REG_1], tmp = bpf2a64[TMP_REG_2];
+	const u8 reg = insn->dst_reg == BPF_REG_AX ? state : bpf2a64[insn->dst_reg];
+
+	BUILD_BUG_ON(task_off % 8 || task_off > 0xfff * 8);
+
+	if (op != BPF_MAY_GOTO_READ && op != BPF_MAY_GOTO_INIT)
+		emit(A64_MRS_SP_EL0(task), ctx);
+	switch (op) {
+	case BPF_MAY_GOTO_READ:
+		emit(A64_MOV(1, reg, state), ctx);
+		break;
+	case BPF_MAY_GOTO_INIT:
+		emit_a64_mov_i64(reg, BPF_MAY_GOTO_INIT_STATE, ctx);
+		break;
+	case BPF_MAY_GOTO_FILL:
+		emit(A64_LDR64I(reg, task, task_off), ctx);
+		break;
+	case BPF_MAY_GOTO_SPILL:
+	case BPF_MAY_GOTO_SPILL_CALL:
+		emit(A64_STR64I(reg, task, task_off), ctx);
+		break;
+	case BPF_MAY_GOTO_SAVE:
+		emit(A64_LDR64I(tmp, task, task_off), ctx);
+		emit_ldst(BPF_STX | BPF_MEM | BPF_DW, tmp, fp, insn->imm, bpf2a64[TMP_REG_3], ctx);
+		break;
+	case BPF_MAY_GOTO_RESTORE:
+		emit_ldst(BPF_LDX | BPF_MEM | BPF_DW, tmp, fp, insn->imm, bpf2a64[TMP_REG_3], ctx);
+		emit(A64_STR64I(tmp, task, task_off), ctx);
+		break;
+	}
+}
+
+static bool call_needs_may_goto_fill(const struct bpf_prog *prog, const struct bpf_insn *call)
 {
-	const struct bpf_insn *call = insn - 1;
+	return call > prog->insnsi && insn_is_may_goto_mov(call - 1) &&
+	       call[-1].off == BPF_MAY_GOTO_SPILL_CALL;
+}
 
+/* The code at the return address of @call */
+static void emit_after_call(const struct bpf_insn *call, struct jit_ctx *ctx)
+{
+	emit(A64_MOV(1, bpf2a64[BPF_REG_0], A64_R(0)), ctx);
+	if (call_needs_may_goto_fill(ctx->prog, call))
+		emit_may_goto_mov(BPF_MAY_GOTO_FILL, call - 1, ctx);
+}
+
+static int after_call_len(const struct bpf_prog *prog, const struct bpf_insn *call)
+{
+	return call_needs_may_goto_fill(prog, call) ? 3 : 1;
+}
+
+/*
+ * The slow path of may_goto, insn @i. It is among the landings.
+ *
+ *   near:                        far:
+ *   subs x24, x24, CNT_ONE       subs x24, x24, CNT_ONE
+ *   b.lo slow                    b.hs end
+ *                                bl slow
+ *   end:
+ *   ...
+ *   slow: tbz x24, 0, 1f
+ *         mov x24, EXPIRED
+ *         b target
+ *   1:    adr lr, end            <- near form only
+ *         b arch_bpf_timed_may_goto, which returns to end
+ *
+ * Pass 1 takes the far form, no later layout is longer, see find_tb(). ctx->tb marks the near form.
+ */
+static int build_may_goto_slowpath(int i, struct jit_ctx *ctx)
+{
+	const u8 state = bpf2a64[MAY_GOTO_STATE];
+	long func_addr = (long)arch_bpf_timed_may_goto;
+	int end = ctx->offset[i + 1], jmp_offset = ctx->idx - (end - 1);
+	bool near;
+
+	if (!ctx->image && jmp_offset + 3 < SZ_256K)
+		__set_bit(i, ctx->tb);
+	near = test_bit(i, ctx->tb);
+	check_imm26(jmp_offset);
+	if (ctx->image)
+		ctx->image[end - 1] = cpu_to_le32(near ? A64_B_(A64_COND_CC, jmp_offset) :
+						  A64_BRANCH(A64_BR_OFF(jmp_offset), LINK));
+
+	emit(A64_TBZ(state, 0, 3), ctx);
+	emit(A64_MOVZ(1, state, BPF_MAY_GOTO_EXPIRED, 0), ctx);
+	jmp_offset = ctx->offset[i + 1 + ctx->prog->insnsi[i].imm] - ctx->idx;
+	check_imm26(jmp_offset);
+	emit(A64_B(jmp_offset), ctx);
+	if (near)
+		emit(A64_ADR(A64_LR, A64_BR_OFF(end - ctx->idx)), ctx);
+	if (should_emit_indirect_call(func_addr, ctx)) {
+		/* BTI C at the target takes BR of x16 */
+		emit_addr_mov_i64(A64_R(16), func_addr, ctx);
+		emit(A64_BR(A64_R(16)), ctx);
+	} else {
+		emit(A64_BRANCH(func_addr - (long)&ctx->ro_image[ctx->idx], NOLINK), ctx);
+	}
+	return 0;
+}
+
+/* The insn that @insn, unwind_goto or cancel_goto, belongs to */
+static const struct bpf_insn *pad_goto_call(const struct bpf_insn *insn)
+{
 	/* 'call; unwind_goto; cancel_goto' */
-	if (bpf_is_cancel_goto(insn) && bpf_is_unwind_goto(call))
-		call--;
-	return call->code == (BPF_JMP | BPF_CALL) && call->src_reg != BPF_PSEUDO_CALL;
+	return insn - 1 - (bpf_is_cancel_goto(insn) && bpf_is_unwind_goto(insn - 1));
+}
+
+/* Whether @insn, unwind_goto or cancel_goto, needs the code after its call */
+static bool goto_has_landing(const struct bpf_prog *prog, const struct bpf_insn *insn)
+{
+	const struct bpf_insn *call = pad_goto_call(insn);
+
+	return (call->code == (BPF_JMP | BPF_CALL) && call->src_reg != BPF_PSEUDO_CALL) ||
+	       call_needs_may_goto_fill(prog, call);
 }
 
 /*
@@ -1725,7 +1853,7 @@ static int add_goto_exentry(struct jit_ctx *ctx, const struct bpf_insn *insn, in
 	int i = insn - ctx->prog->insnsi;
 	int target = ctx->offset[i + 1 + bpf_jmp_offset(insn)];
 
-	if (goto_after_helper(insn)) {
+	if (goto_has_landing(ctx->prog, insn)) {
 		*landing = ctx->exentry_idx;
 		target = ret_addr;
 	}
@@ -1747,21 +1875,23 @@ static int add_goto_exentry(struct jit_ctx *ctx, const struct bpf_insn *insn, in
  *   mov x8, x0; b cancel_pad   <- cancel_exit returns here, key ret_addr - 2
  *
  * build_insn() has added the entries. Each landing fills in the fixup of its
- * entry.
+ * entry. The fill of the state of may_goto after a call is repeated like the mov.
  */
 static int build_landings(struct jit_ctx *ctx)
 {
 	const struct bpf_prog *prog = ctx->prog;
 	int i, k = 0;
 
-	for (i = 1; i < prog->len; i++) {
+	for (i = 0; i < prog->len; i++) {
 		const struct bpf_insn *insn = &prog->insnsi[i];
 		int ret_addr, jmp_offset;
 
-		if (!bpf_is_pad_goto(insn) || !goto_after_helper(insn))
+		if (insn_is_jit_may_goto(insn) && build_may_goto_slowpath(i, ctx))
+			return -EINVAL;
+		if (!bpf_is_pad_goto(insn) || !goto_has_landing(prog, insn))
 			continue;
 		/* unwind_goto emits no code, so this also holds for the cancel_goto after it */
-		ret_addr = ctx->offset[i] - 1;
+		ret_addr = ctx->offset[i] - after_call_len(prog, pad_goto_call(insn));
 		if (ctx->image) {
 			struct exception_table_entry *ex;
 
@@ -1770,7 +1900,7 @@ static int build_landings(struct jit_ctx *ctx)
 			ex->fixup = (ctx->idx - ret_addr) * AARCH64_INSN_SIZE;
 		}
 		k++;
-		emit(A64_MOV(1, bpf2a64[BPF_REG_0], A64_R(0)), ctx);
+		emit_after_call(pad_goto_call(insn), ctx);
 		jmp_offset = ctx->offset[i + 1 + bpf_jmp_offset(insn)] - ctx->idx;
 		check_imm26(jmp_offset);
 		emit(A64_B(jmp_offset), ctx);
@@ -2078,6 +2208,9 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 					emit(A64_MOVK(1, dst, upper_high, 48), ctx);
 			}
 			break;
+		} else if (insn_is_may_goto_mov(insn)) {
+			emit_may_goto_mov(off, insn, ctx);
+			break;
 		} else if (insn_is_mov_percpu_addr(insn)) {
 			if (dst != src)
 				emit(A64_MOV(1, dst, src), ctx);
@@ -2485,13 +2618,7 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 			emit_kfunc_arg_moves(ctx, fm);
 		}
 		emit_call(func_addr, ctx);
-		/*
-		 * Call to arch_bpf_timed_may_goto() is emitted by the
-		 * verifier and called with custom calling convention with
-		 * first argument and return value in BPF_REG_AX (x9).
-		 */
-		if (func_addr != (u64)arch_bpf_timed_may_goto)
-			emit(A64_MOV(1, r0, A64_R(0)), ctx);
+		emit_after_call(insn, ctx);
 		break;
 	}
 	/* indirect call of a bpf subprog, dst holds its address */
@@ -2503,14 +2630,14 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		 * counter and the private stack are callee saved.
 		 */
 		emit(A64_BLR(dst), ctx);
-		emit(A64_MOV(1, bpf2a64[BPF_REG_0], A64_R(0)), ctx);
+		emit_after_call(insn, ctx);
 		break;
 	/* tail call */
 	case BPF_JMP | BPF_TAIL_CALL:
 		if (emit_bpf_tail_call(ctx))
 			return -EFAULT;
 		break;
-	/* unwind_goto, cancel_goto. The verifier expanded may_goto. */
+	/* may_goto, unwind_goto, cancel_goto */
 	case BPF_JMP | BPF_JCOND:
 	case BPF_JMP32 | BPF_JCOND:
 	{
@@ -2518,9 +2645,18 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		/* 'call; unwind_goto; cancel_goto', and this is the second one */
 		bool after_unwind = cancel_goto && bpf_is_unwind_goto(insn - 1);
 		int landing[2] = { -1, -1 };
-		int ret_addr = ctx->idx - 1;
-		int j;
-
+		int ret_addr, j;
+
+		if (insn_is_jit_may_goto(insn)) {
+			emit(A64_SUBS_I(1, bpf2a64[MAY_GOTO_STATE], bpf2a64[MAY_GOTO_STATE],
+					BPF_MAY_GOTO_CNT_ONE), ctx);
+			if (!test_bit(i, ctx->tb))
+				emit(A64_B_(A64_COND_CS, 2), ctx);
+			/* build_may_goto_slowpath() writes the branch */
+			emit(A64_NOP, ctx);
+			break;
+		}
+		ret_addr = ctx->idx - after_call_len(ctx->prog, pad_goto_call(insn));
 		/*
 		 * The extable is sorted by address, and the entry of cancel_goto has
 		 * the lower one. So unwind_goto adds no entry when cancel_goto follows
@@ -2916,7 +3052,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 
 	for (i = 1; i < prog->len; i++)
 		if (bpf_is_pad_goto(&prog->insnsi[i]) &&
-		    goto_after_helper(&prog->insnsi[i]))
+		    goto_has_landing(prog, &prog->insnsi[i]))
 			nr_landings++;
 	if (nr_landings) {
 		ctx.landing_ex = kvzalloc_objs(int, nr_landings);
@@ -4145,6 +4281,11 @@ bool bpf_jit_supports_timed_may_goto(void)
 	return true;
 }
 
+bool bpf_jit_supports_may_goto_insn(void)
+{
+	return true;
+}
+
 bool bpf_jit_inlines_helper_call(s32 imm)
 {
 	switch (imm) {
diff --git a/arch/arm64/net/bpf_timed_may_goto.S b/arch/arm64/net/bpf_timed_may_goto.S
index f8732b13bb1e..15f8452c4973 100644
--- a/arch/arm64/net/bpf_timed_may_goto.S
+++ b/arch/arm64/net/bpf_timed_may_goto.S
@@ -12,26 +12,22 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	stp	x8, x0, [sp, #16]
 	stp	x1, x2, [sp, #32]
 	stp	x3, x4, [sp, #48]
-	/* Save stack arguments 6 - 8 (x5-x7) */
+	/* Save stack arguments 6 - 8 (x5-x7) and BPF_REG_AX (x9) */
 	stp	x5, x6, [sp, #64]
-	str	x7, [sp, #80]
+	stp	x7, x9, [sp, #80]
 
-	/*
-	 * The pointer to count and timestamp was passed in BPF_REG_AX (x9),
-	 * pass it as the first argument in x0.
-	 */
-	mov	x0, x9
-	bl	bpf_check_timed_may_goto
-	/* BPF_REG_AX(x9) will be stored into count, so move return value to it. */
-	mov	x9, x0
+	/* The state is in x24, LR is the address after may_goto */
+	mov	x0, x24
+	bl	bpf_may_goto_slowpath
+	mov	x24, x0
 
 	/* Restore BPF registers R0 - R5 (x8, x0-x4) */
 	ldp	x8, x0, [sp, #16]
 	ldp	x1, x2, [sp, #32]
 	ldp	x3, x4, [sp, #48]
-	/* Restore stack arguments 6 - 8 (x5-x7) */
+	/* Restore stack arguments 6 - 8 (x5-x7) and BPF_REG_AX (x9) */
 	ldp	x5, x6, [sp, #64]
-	ldr	x7, [sp, #80]
+	ldp	x7, x9, [sp, #80]
 
 	/* Restore FP and LR */
 	ldp     x29, x30, [sp], #96
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index afe6dc7958b8..ce140f0cc8a2 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -1069,7 +1069,6 @@ static __naked __noinline __used long spin_cb(void)
  */
 SEC("syscall")
 __description("arena stack: bpf_loop() ends when the time of may_goto is up")
-__arch_x86_64
 __success __retval(121)
 /* a call of the callback when the time is up returns 1 before it takes a stack */
 __xlated("r0 &= 1")
diff --git a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
index 5b3d760bd160..bdd462f2f039 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
@@ -935,8 +935,9 @@ __naked void unconditional_jump_to_fill(void)
 
 SEC("raw_tp")
 __arch_x86_64
+__arch_arm64
 __log_level(4)
-__msg("subprog 0 (may_goto_interaction_x86_64) main {{.*}} stack 8")
+__msg("subprog 0 (may_goto_interaction_insn) main {{.*}} stack 8")
 __xlated("0: may_goto_init")
 __xlated("1: r1 = 1")
 __xlated("...")
@@ -948,7 +949,7 @@ __xlated("exit")
 __xlated("r0 = 0")
 __xlated("exit")
 __success
-__naked void may_goto_interaction_x86_64(void)
+__naked void may_goto_interaction_insn(void)
 {
 	asm volatile (
 	"r1 = 1;"
@@ -966,7 +967,6 @@ __naked void may_goto_interaction_x86_64(void)
 }
 
 SEC("raw_tp")
-__arch_arm64
 __arch_riscv64
 __arch_loongarch
 __log_level(4)
diff --git a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
index aeff39968a4d..53dd54ad2762 100644
--- a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
+++ b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
@@ -84,7 +84,6 @@ SEC("raw_tp")
 __description("may_goto batch with offsets 2/0")
 __load_if_JITed()
 __arch_s390x
-__arch_arm64
 __arch_riscv64
 __arch_loongarch
 /* the main prog sets count, timestamp, owner */
@@ -128,6 +127,7 @@ SEC("raw_tp")
 __description("may_goto batch with offsets 2/0, JIT of may_goto")
 __load_if_JITed()
 __arch_x86_64
+__arch_arm64
 __xlated("0: may_goto_init")
 /* when the time is up may_goto goes to the landing pad of the prog */
 __xlated("1: may_goto pc+3")
diff --git a/tools/testing/selftests/bpf/progs/verifier_patch_list.c b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
index 2a18f182c0db..75da37f72721 100644
--- a/tools/testing/selftests/bpf/progs/verifier_patch_list.c
+++ b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
@@ -91,6 +91,7 @@ __naked void patch_list_backward(void)
 SEC("raw_tp")
 __description("patch list: may_goto between patched insns")
 __arch_x86_64
+__arch_arm64
 __success
 __xlated("0: may_goto_init")
 __xlated("1: call")
@@ -314,6 +315,7 @@ int patch_list_indirect(void)
 SEC("raw_tp")
 __description("patch list: far may_goto")
 __arch_x86_64
+__arch_arm64
 __success
 __xlated("4: may_goto pc+32770")
 __xlated("...")
@@ -400,6 +402,7 @@ static unsigned long patch_list_loop_at_start(void)
 SEC("raw_tp")
 __description("patch list: call of and jump to an insn with insns inserted in front")
 __arch_x86_64
+__arch_arm64
 __success
 __xlated("22: call pc+10")
 __xlated("23: cancel_goto pc-15")
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 6/7] bpf: Keep the state of may_goto in the task on other archs
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
                   ` (4 preceding siblings ...)
  2026-12-05  3:37 ` [PATCH bpf-next 5/7] bpf, arm64: Keep the state of may_goto in x24 Alexei Starovoitov
@ 2026-12-05  3:38 ` Alexei Starovoitov
  2026-12-05  4:18   ` bot+bpf-ci
  2026-12-05  3:38 ` [PATCH bpf-next 7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11 Alexei Starovoitov
  2026-12-05  6:40 ` [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register patchwork-bot+netdevbpf
  7 siblings, 1 reply; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:38 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

riscv, powerpc, loongarch and s390 still count in per-cpu memory that
invocations of the prog share. Count in current->bpf_may_goto_state
instead. The main prog saves it at entry and restores it at exit, so
invocations can nest.

Remove the per-cpu memory and the code that saved and restored it.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
 arch/loongarch/net/bpf_timed_may_goto.S       |   9 +-
 arch/powerpc/net/bpf_timed_may_goto.S         |  10 +-
 arch/riscv/net/bpf_timed_may_goto.S           |   8 +-
 arch/s390/net/bpf_timed_may_goto.S            |   2 +-
 include/linux/bpf.h                           |   4 +-
 include/linux/filter.h                        |  15 --
 kernel/bpf/core.c                             |  63 ------
 kernel/bpf/fixups.c                           | 209 +++++++++---------
 kernel/bpf/helpers.c                          |  15 +-
 kernel/bpf/stream.c                           |   4 +-
 .../selftests/bpf/prog_tests/timed_may_goto.c |   2 +-
 .../selftests/bpf/progs/timed_may_goto.c      |  14 +-
 .../bpf/progs/verifier_bpf_fastcall.c         |  35 ++-
 .../selftests/bpf/progs/verifier_budget.c     |   5 +-
 .../selftests/bpf/progs/verifier_may_goto_1.c |  52 +++--
 .../selftests/bpf/progs/verifier_patch_list.c |  24 +-
 16 files changed, 192 insertions(+), 279 deletions(-)

diff --git a/arch/loongarch/net/bpf_timed_may_goto.S b/arch/loongarch/net/bpf_timed_may_goto.S
index 4aaca029404b..91bec021f141 100644
--- a/arch/loongarch/net/bpf_timed_may_goto.S
+++ b/arch/loongarch/net/bpf_timed_may_goto.S
@@ -21,13 +21,10 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	st.d		a3, sp, 40
 	st.d		a4, sp, 48
 
-	/*
-	 * BPF_REG_AX (t0) holds the pointer to the count and timestamp;
-	 * pass it as the first argument in a0.
-	 */
+	/* BPF_REG_AX (t0) holds the state of may_goto; pass it as the first argument in a0. */
 	move		a0, t0
-	bl		bpf_check_timed_may_goto
-	/* BPF_REG_AX (t0) will be stored into count, so move the return value to it. */
+	bl		bpf_may_goto_slowpath
+	/* BPF_REG_AX (t0) will be stored into the state, so move the return value to it. */
 	move		t0, a0
 
 	ld.d		ra, sp, 56
diff --git a/arch/powerpc/net/bpf_timed_may_goto.S b/arch/powerpc/net/bpf_timed_may_goto.S
index b8ae9885eb31..1d9dbc6abdd1 100644
--- a/arch/powerpc/net/bpf_timed_may_goto.S
+++ b/arch/powerpc/net/bpf_timed_may_goto.S
@@ -8,11 +8,11 @@
  * arch_bpf_timed_may_goto() trampoline for powerpc64
  *
  * Custom BPF convention (verifier/JIT):
- *	- input:  pointer to count and timestamp in BPF_REG_AX (r12)
- *	- output: updated count in BPF_REG_AX (r12)
+ *	- input:  state of may_goto in BPF_REG_AX (r12)
+ *	- output: updated state in BPF_REG_AX (r12)
  *
- * Call bpf_check_timed_may_goto(ptr) with normal powerpc64 ABI:
- * 	- r3 = ptr, return in r3
+ * Call bpf_may_goto_slowpath(state) with normal powerpc64 ABI:
+ * 	- r3 = state, return in r3
  *
  * Preserve BPF regs R0-R5 (mapping: r8, r3-r7).
  */
@@ -33,7 +33,7 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 
 	/* r3 = BPF_REG_AX (r12) */
 	mr      r3, r12
-	bl      CFUNC(bpf_check_timed_may_goto)
+	bl      CFUNC(bpf_may_goto_slowpath)
 
 	/* Put return value back into AX */
 	mr      r12, r3
diff --git a/arch/riscv/net/bpf_timed_may_goto.S b/arch/riscv/net/bpf_timed_may_goto.S
index 2ce1c89c913e..61af456151a1 100644
--- a/arch/riscv/net/bpf_timed_may_goto.S
+++ b/arch/riscv/net/bpf_timed_may_goto.S
@@ -6,10 +6,10 @@
 
 /*
  * Trampoline for the BPF timed may_goto loop bound. Custom calling convention:
- *	- input:  pointer to count and timestamp in BPF_REG_AX (t0)
- *	- output: updated count in BPF_REG_AX (t0)
+ *	- input:  state of may_goto in BPF_REG_AX (t0)
+ *	- output: updated state in BPF_REG_AX (t0)
  *
- * Calls bpf_check_timed_may_goto(ptr) with the standard RISC-V ABI. BPF R0-R5
+ * Calls bpf_may_goto_slowpath(state) with the standard RISC-V ABI. BPF R0-R5
  * (t6, a0-a4) and stack arguments 6-8 (a5-a7) are saved across the call.
  */
 
@@ -32,7 +32,7 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	REG_S	a7, 8*SZREG(sp)
 
 	mv	a0, t0
-	call	bpf_check_timed_may_goto
+	call	bpf_may_goto_slowpath
 	mv	t0, a0
 
 	/* Restore BPF registers R0-R5 */
diff --git a/arch/s390/net/bpf_timed_may_goto.S b/arch/s390/net/bpf_timed_may_goto.S
index 05f532f8c639..e910209e0047 100644
--- a/arch/s390/net/bpf_timed_may_goto.S
+++ b/arch/s390/net/bpf_timed_may_goto.S
@@ -34,7 +34,7 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	stg %r1,__SF_BACKCHAIN(%r15)
 
 	lgr %r2,%r12
-	brasl %r14,bpf_check_timed_may_goto
+	brasl %r14,bpf_may_goto_slowpath
 	lgr %r12,%r2
 
 	lg %r15,FRAME_SIZE+FRAME_OFF+R15_OFF(%r15)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 40e42e8caa92..4f8d419fd824 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -2000,9 +2000,7 @@ struct bpf_prog_aux {
 	bool arena_stack_entry;
 	struct bpf_prog **func;
 	struct bpf_prog_aux *main_prog_aux;
-	/* main prog: there when the prog has timed may_goto */
-	struct bpf_timed_may_goto __percpu *timed_may_goto;
-	/* main prog: the JIT gets may_goto as an insn */
+	/* main prog: the prog has timed may_goto */
 	bool has_may_goto;
 	/* the function keeps the state of may_goto in the cpu register */
 	bool may_goto_in_reg;
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 6fe38197cbbc..66dcdc86240f 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -900,17 +900,6 @@ struct bpf_binary_header {
 	u8 image[] __aligned(BPF_IMAGE_ALIGNMENT);
 };
 
-/*
- * 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.
- */
-struct bpf_timed_may_goto {
-	u64 count;
-	u64 timestamp;
-	/* the async callback that has set count and timestamp, see bpf_timed_may_goto_save() */
-	void *owner;
-};
-
 struct sk_filter {
 	refcount_t	refcnt;
 	struct rcu_head	rcu;
@@ -1550,12 +1539,8 @@ u32 bpf_jit_plan_arg_moves(const struct bpf_jit_arg_abi *abi,
 u64 bpf_arch_uaddress_limit(void);
 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie);
 u64 arch_bpf_timed_may_goto(void);
-u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *);
 u64 bpf_may_goto_slowpath(u64 state);
 void bpf_may_goto_clear_cnt(const struct bpf_prog *prog);
-void bpf_timed_may_goto_check_time(const struct bpf_prog *prog);
-void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved);
-void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved);
 u64 bpf_prog_report_recursion(void);
 u64 bpf_prog_report_cancelled(struct bpf_prog_aux *aux);
 void bpf_prog_cancelled_to_kernel(unsigned long ip);
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 933c19556725..4249abbf6ae4 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -294,7 +294,6 @@ void __bpf_prog_free(struct bpf_prog *fp)
 		mutex_destroy(&fp->aux->used_maps_mutex);
 		mutex_destroy(&fp->aux->dst_mutex);
 		kfree(fp->aux->poke_tab);
-		free_percpu(fp->aux->timed_may_goto);
 		kfree(fp->aux);
 	}
 	free_percpu(fp->stats);
@@ -4203,68 +4202,6 @@ void bpf_prog_cancelled_to_kernel(unsigned long ip)
 		st_ops->cancelled(prog);
 }
 
-u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *p)
-{
-	u64 time = ktime_get_mono_fast_ns();
-
-	/* Populate the timestamp for this stack frame, and refresh count. */
-	if (!p->timestamp) {
-		p->timestamp = time;
-		return BPF_MAX_TIMED_LOOPS;
-	}
-	/*
-	 * Check if we've exhausted our time slice, and zero count. An invocation that preempted
-	 * this one after the clock was read could have stored a later timestamp.
-	 */
-	if (unlikely((s64)(time - p->timestamp) >= (s64)(NSEC_PER_SEC / 4))) {
-		bpf_prog_report_may_goto_violation();
-		return 0;
-	}
-	/* Refresh the count for the stack frame. */
-	return BPF_MAX_TIMED_LOOPS;
-}
-
-/*
- * The main prog sets count and timestamp in its first insns. A call of an async callback is an
- * invocation of its own too, but it can interrupt an invocation of the prog on this cpu, or go on
- * next to one that is preempted. So its caller sets count and timestamp, and puts the old ones
- * back at the end. Not when another invocation has set them in the meantime: they are for that
- * one now.
- * The caller has disabled migration.
- */
-void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved)
-{
-	struct bpf_timed_may_goto *cur;
-
-	if (!prog->aux->timed_may_goto)
-		return;
-	cur = this_cpu_ptr(prog->aux->timed_may_goto);
-	*saved = *cur;
-	cur->count = BPF_MAX_TIMED_LOOPS;
-	cur->timestamp = 0;
-	cur->owner = saved;
-}
-
-void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved)
-{
-	struct bpf_timed_may_goto *cur;
-
-	if (!prog->aux->timed_may_goto)
-		return;
-	cur = this_cpu_ptr(prog->aux->timed_may_goto);
-	if (cur->owner == saved)
-		*cur = *saved;
-}
-
-/* A walk of the stack is too long for BPF_MAX_TIMED_LOOPS trips. The next one looks at the time. */
-void bpf_timed_may_goto_check_time(const struct bpf_prog *prog)
-{
-	struct bpf_timed_may_goto __percpu *tmg = prog->aux->main_prog_aux->timed_may_goto;
-
-	if (tmg && this_cpu_read(tmg->count))
-		this_cpu_write(tmg->count, 1);
-}
-
 /* The count in @state ran out. Bit 1 of the state is 2^22 ns. The time slice is 256 ms. */
 u64 bpf_may_goto_slowpath(u64 state)
 {
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 9d4f89269711..58238249fce4 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -281,8 +281,6 @@ static void patch_list_adj_aux(struct bpf_prog *prog, struct bpf_insn_patch *p,
 		slot[i].seen = last->seen ?: i > p->self;
 		/* messages name the insn of the original program */
 		slot[i].orig_idx = last->orig_idx;
-		/* for may_goto before the insn, see bpf_insert_sites() */
-		slot[i].live_regs_before = last->live_regs_before;
 		slot[i].zext_dst = bpf_insn_def32(prog, &patch[i]) >= 0;
 		/*
 		 * A copy of the patched insn keeps its marking. Any other
@@ -1016,10 +1014,6 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
  * pad:	the releases		each site has its own pad, see collect_pads()
  *	r0 = bpf_cancelled_retval()
  *	cancel_exit		or exit, see unwind_exit_insn()
- *
- * bpf_do_misc_fixups() keeps the address of the count of may_goto in a register that is
- * dead at the may_goto. What is live in front of the insn is live in front of its guard.
- * Nothing else is: a landing pad reads only locations that are live before the insn.
  */
 int bpf_insert_sites(struct bpf_verifier_env *env)
 {
@@ -1218,17 +1212,7 @@ int bpf_insert_recursion_checks(struct bpf_verifier_env *env)
 		if (err)
 			return err;
 	}
-	err = bpf_patch_list_commit(env);
-	if (err)
-		return err;
-	/* may_goto keeps the address of its count in a register that is dead: R0 */
-	for (s = 1; s < env->subprog_cnt; s++) {
-		if (!si[s].recursive)
-			continue;
-		n = si[s].start + is_arena_sp_adj(&env->prog->insnsi[si[s].start]);
-		env->insn_aux_data[n].live_regs_before = (u16)~BIT(BPF_REG_0);
-	}
-	return 0;
+	return bpf_patch_list_commit(env);
 }
 
 static void free_loop(struct bpf_loop *loop)
@@ -2692,38 +2676,61 @@ int bpf_fixup_call_args(struct bpf_verifier_env *env)
 }
 
 /*
- * Timed may_goto. All may_goto of a prog use one count and one timestamp: per-cpu memory of the
- * prog, set in the first insns of the main prog, and by the callers of async callbacks.
- * @reg holds the address. It is a register that is dead at the may_goto, or R0 that is saved at
- * @save_off in the stack. @jmp is the insn that goes where may_goto goes.
+ * Timed may_goto for a JIT without bpf_jit_supports_may_goto_insn(). The state of the invocation
+ * is in current->bpf_may_goto_state all the time. The JIT inlines the call that gets the task,
+ * which writes R0 only. Constant blinding of 'r0 += imm' uses AX, so the address of the state is
+ * computed before the state is loaded into AX.
  */
-static int may_goto_expand_timed(struct bpf_insn *insn_buf, int *jmp,
-				 struct bpf_timed_may_goto __percpu *tmg, int reg, int save_off)
+#define CALL_GET_CURRENT_TASK	\
+	BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_current_task)
+#define ADD_MAY_GOTO_STATE_OFF	\
+	BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, offsetof(struct task_struct, bpf_may_goto_state))
+
+/*
+ * Main prog @sub saves the state that it finds in the task, inits its own and restores the saved
+ * one at each exit. A tail call can fall through: swap the two before it and after it.
+ */
+static int insert_may_goto_save_restore(struct bpf_verifier_env *env,
+					struct bpf_subprog_info *sub)
 {
-	struct bpf_insn ld_tmg[] = { BPF_LD_IMM64(reg, (__force unsigned long)tmg) };
-	int cnt = 0;
+	int i, err, off = -(round_up(sub->stack_depth, 8) + 8);
+	/* R0 is dead at the entry */
+	const struct bpf_insn prologue[] = {
+		CALL_GET_CURRENT_TASK,
+		ADD_MAY_GOTO_STATE_OFF,
+		BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_0, 0),
+		BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_AX, off),
+		BPF_MOV64_IMM(BPF_REG_AX, BPF_MAY_GOTO_INIT_STATE >> BPF_MAY_GOTO_CNT_SHIFT),
+		BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, BPF_MAY_GOTO_CNT_SHIFT),
+		BPF_STX_MEM(BPF_DW, BPF_REG_0, BPF_REG_AX, 0),
+	};
+	/* R4 and R5 are dead at exit and around a tail call */
+	struct bpf_insn swap[] = {
+		BPF_MOV64_REG(BPF_REG_4, BPF_REG_0),
+		CALL_GET_CURRENT_TASK,
+		ADD_MAY_GOTO_STATE_OFF,
+		BPF_LDX_MEM(BPF_DW, BPF_REG_5, BPF_REG_0, 0),
+		BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_FP, off),
+		BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_5, off),
+		BPF_STX_MEM(BPF_DW, BPF_REG_0, BPF_REG_AX, 0),
+		BPF_MOV64_REG(BPF_REG_0, BPF_REG_4),
+		{},
+	};
+	const int n = ARRAY_SIZE(swap) - 1;
 
-	if (save_off)
-		insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, reg, save_off);
-	insn_buf[cnt++] = ld_tmg[0];
-	insn_buf[cnt++] = ld_tmg[1];
-	insn_buf[cnt++] = BPF_MOV64_PERCPU_REG(reg, reg);
-	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, reg, 0);
-	if (save_off) {
-		insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
-		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_10, save_off);
+	sub->stack_depth = -off;
+	/* jumps to the first insn of the subprog skip the prologue */
+	err = bpf_patch_list_insert(env, sub->start, prologue, ARRAY_SIZE(prologue));
+	for (i = sub->start; i < sub[1].start && !err; i++) {
+		swap[n] = env->prog->insnsi[i];
+		if (swap[n].code != (BPF_JMP | BPF_EXIT) &&
+		    swap[n].code != (BPF_JMP | BPF_TAIL_CALL))
+			continue;
+		err = PTR_ERR_OR_ZERO(bpf_patch_list_add(env, i, swap, n + 1));
+		if (!err && swap[n].code == (BPF_JMP | BPF_TAIL_CALL))
+			err = bpf_patch_list_append(env, i, swap, n);
 	}
-	*jmp = cnt;
-	insn_buf[cnt++] = save_off ? BPF_JMP32_A(0) : BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 0);
-	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
-	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
-	/* AX is the argument and the return value */
-	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_AX, reg);
-	insn_buf[cnt++] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
-	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, reg, BPF_REG_AX, 0);
-	if (save_off)
-		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_10, save_off);
-	return cnt;
+	return err;
 }
 
 /* Only bpf_loop() or bpf_for_each_map_elem() call it. Their loop ends when it returns 1. */
@@ -3130,7 +3137,6 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 	/* arch_bpf_timed_may_goto() has a calling convention of its own: for JITs only */
 	bool timed_may_goto = prog->jit_requested && bpf_jit_supports_timed_may_goto();
 	bool may_goto_insn = timed_may_goto && bpf_jit_supports_may_goto_insn();
-	struct bpf_timed_may_goto __percpu *tmg = NULL;
 
 	for (i = 0; i < insn_cnt;) {
 		env->insn_aux_data[i].calls_sync_cb = bpf_is_sync_callback_calling_insn(insn);
@@ -3372,32 +3378,32 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 			prog->aux->has_may_goto = true;
 			goto next_insn;
 		} else if (bpf_is_may_goto_insn(insn) && timed_may_goto) {
-			u16 live = env->insn_aux_data[i].live_regs_before;
-			int reg, jmp, save_off = 0, to = i + insn->off + 1;
+			int stack_off = -stack_depth - 8, to = i + insn->off + 1;
 
-			/* a register that is dead here holds the address of the count */
-			for (reg = BPF_REG_0; reg <= BPF_REG_9; reg++)
-				if (!(live & BIT(reg)))
-					break;
-			if (reg > BPF_REG_9) {
-				reg = BPF_REG_0;
-				save_off = -stack_depth - 8;
-				stack_depth_extra = 8;
-			}
-			if (!tmg) {
-				tmg = alloc_percpu_gfp(struct bpf_timed_may_goto,
-						       BPF_VERIFIER_GFP);
-				if (!tmg)
-					return -ENOMEM;
-				prog->aux->timed_may_goto = tmg;
-			}
+			if (verifier_bug_if(!bpf_jit_inlines_helper_call(BPF_FUNC_get_current_task),
+					    env, "JIT does not inline current"))
+				return -EFAULT;
+			stack_depth_extra = 8;
+			insn_buf[0] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_0, stack_off);
+			insn_buf[1] = CALL_GET_CURRENT_TASK;
+			insn_buf[2] = ADD_MAY_GOTO_STATE_OFF;
+			insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_0, 0);
+			insn_buf[4] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, BPF_MAY_GOTO_CNT_ONE);
+			insn_buf[5] = BPF_JMP_IMM(BPF_JSGE, BPF_REG_AX, 0, 2);
+			/* Expired: skip the store. AX stays negative on this path only. */
+			insn_buf[6] = BPF_JMP_IMM(BPF_JSET, BPF_REG_AX, BPF_MAY_GOTO_EXPIRED, 2);
+			/* AX is the argument and the return value */
+			insn_buf[7] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
+			insn_buf[8] = BPF_STX_MEM(BPF_DW, BPF_REG_0, BPF_REG_AX, 0);
+			insn_buf[9] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_10, stack_off);
+			insn_buf[10] = BPF_JMP_IMM(BPF_JSLT, BPF_REG_AX, 0, 0);
 			prog->jit_required = 1;
-			cnt = may_goto_expand_timed(insn_buf, &jmp, tmg, reg, save_off);
+			prog->aux->has_may_goto = true;
 
-			insn = bpf_patch_list_add(env, i, insn_buf, cnt);
+			insn = bpf_patch_list_add(env, i, insn_buf, 11);
 			if (IS_ERR(insn))
 				return PTR_ERR(insn);
-			bpf_patch_list_jump(&env->patch_list, insn - (cnt - 1 - jmp), to, 0);
+			bpf_patch_list_jump(&env->patch_list, insn, to, 0);
 			goto next_insn;
 		} else if (bpf_is_may_goto_insn(insn)) {
 			int stack_off = -stack_depth - 8, to = i + insn->off + 1;
@@ -3948,18 +3954,20 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 		return ret;
 	prog = env->prog;
 
-	ret = prog->aux->has_may_goto ? bpf_insert_may_goto_spills(env) : 0;
+	ret = prog->aux->has_may_goto && may_goto_insn ? bpf_insert_may_goto_spills(env) : 0;
 	if (ret)
 		return ret;
 
-	env->prog->aux->stack_depth = subprogs[0].stack_depth;
 	for (i = 0; i < env->subprog_cnt; i++) {
 		int stack_slots = subprogs[i].stack_extra / 8;
-		/* an invocation begins, see bpf_timed_may_goto_save() for async callbacks */
-		bool main_prog = tmg && subprogs[i].main;
-		bool loop_cb = tmg && is_loop_cb_only(&subprogs[i]);
+		bool in_task = prog->aux->has_may_goto && !may_goto_insn;
 
-		if (timed_may_goto ? !main_prog && !loop_cb : !stack_slots)
+		/* an invocation begins, see bpf_run_async_cb() for async callbacks */
+		ret = in_task && subprogs[i].main ?
+		      insert_may_goto_save_restore(env, &subprogs[i]) : 0;
+		if (ret)
+			return ret;
+		if (timed_may_goto ? !in_task || !is_loop_cb_only(&subprogs[i]) : !stack_slots)
 			continue;
 		if (stack_slots > 1) {
 			verifier_bug(env, "stack_slots supports may_goto only");
@@ -3969,42 +3977,24 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 		cnt = 0;
 		stack_depth = subprogs[i].stack_depth;
 		if (timed_may_goto) {
-			struct bpf_insn ld_tmg[] = {
-				BPF_LD_IMM64(BPF_REG_0, (__force unsigned long)tmg)
-			};
-			int count_off = offsetof(struct bpf_timed_may_goto, count);
-			int timestamp_off = offsetof(struct bpf_timed_may_goto, timestamp);
-			int owner_off = offsetof(struct bpf_timed_may_goto, owner);
-
-			/* R0 has nothing at the entry */
-			insn_buf[cnt++] = ld_tmg[0];
-			insn_buf[cnt++] = ld_tmg[1];
-			insn_buf[cnt++] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
-			if (main_prog) {
-				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, count_off,
-							     BPF_MAX_TIMED_LOOPS);
-				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, timestamp_off, 0);
-				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, owner_off, 0);
-			} else {
-				/*
-				 * The time is up, but the helper would call the function again and
-				 * again. End its loop. The verifier has seen that: the loop can end
-				 * after each call.
-				 *
-				 * This check is not a site, unlike a may_goto of the program, see
-				 * check_may_goto_site(). When it ends the loop, the helper returns
-				 * the number of calls that it made, and the program continues
-				 * until its next may_goto. The main pass cannot make the check a
-				 * site: no insn of the program stands for it, and only after the
-				 * pass is it known that only loop helpers call the function and
-				 * that the program has a timed may_goto.
-				 */
-				insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0,
-							      count_off);
-				insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 2);
-				insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, 1);
-				insn_buf[cnt++] = BPF_EXIT_INSN();
-			}
+			/*
+			 * The time is up, but the helper would call the function again and again.
+			 * End its loop. The verifier has seen that: the loop can end after each
+			 * call.
+			 *
+			 * This check is not a site, unlike a may_goto of the program, see
+			 * check_may_goto_site(). When it ends the loop, the helper returns the
+			 * number of calls that it made, and the program continues until its next
+			 * may_goto. The main pass cannot make the check a site: no insn of the
+			 * program stands for it, and only after the pass is it known that only loop
+			 * helpers call the function and that the program has a timed may_goto.
+			 */
+			insn_buf[cnt++] = CALL_GET_CURRENT_TASK;
+			insn_buf[cnt++] = ADD_MAY_GOTO_STATE_OFF;
+			insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0);
+			insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, BPF_MAY_GOTO_EXPIRED);
+			insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 1);
+			insn_buf[cnt++] = BPF_EXIT_INSN();
 		} else {
 			/* Add ST insn to subprog prologue to init extra stack */
 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
@@ -4020,6 +4010,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 	if (ret)
 		return ret;
 	prog = env->prog;
+	prog->aux->stack_depth = subprogs[0].stack_depth;
 
 	/* Since poke tab is now finalized, publish aux to tracker. */
 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index dc99c35a3eb4..f8c13f75faa4 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -1236,19 +1236,16 @@ static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
 
 static void bpf_async_refcount_put(struct bpf_async_cb *cb);
 
-static void bpf_run_async_cb(struct bpf_prog *prog, bpf_callback_t callback_fn,
-			     struct bpf_map *map, void *key, void *value)
+static void bpf_run_async_cb(bpf_callback_t callback_fn, struct bpf_map *map, void *key,
+			     void *value)
 {
 	struct bpf_run_ctx run_ctx, *old_ctx;
-	struct bpf_timed_may_goto saved;
 	u64 old_state = READ_ONCE(current->bpf_may_goto_state);
 
 	old_ctx = bpf_set_run_ctx_prog(&run_ctx, BPF_PROG_ASYNC_CB);
-	bpf_timed_may_goto_save(prog, &saved);
 	WRITE_ONCE(current->bpf_may_goto_state, BPF_MAY_GOTO_INIT_STATE);
 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
 	WRITE_ONCE(current->bpf_may_goto_state, old_state);
-	bpf_timed_may_goto_restore(prog, &saved);
 	bpf_reset_run_ctx(old_ctx);
 }
 
@@ -1278,7 +1275,7 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
 	key = map_key_from_value(map, value, &idx);
 
 	/* The return value is ignored. It need not be 0 after unwind_exit or a cancellation. */
-	bpf_run_async_cb(prog, callback_fn, map, key, value);
+	bpf_run_async_cb(callback_fn, map, key, value);
 
 	this_cpu_write(hrtimer_running, NULL);
 out:
@@ -1311,7 +1308,7 @@ static void bpf_wq_work(struct work_struct *work)
 
 	migrate_disable();
 
-	bpf_run_async_cb(prog, callback_fn, map, key, value);
+	bpf_run_async_cb(callback_fn, map, key, value);
 
 	migrate_enable();
 out:
@@ -4776,7 +4773,7 @@ static void bpf_task_work_callback(struct callback_head *cb)
 	key = (void *)map_key_from_value(ctx->map, ctx->map_val, &idx);
 
 	migrate_disable();
-	bpf_run_async_cb(ctx->prog, ctx->callback_fn, ctx->map, key, ctx->map_val);
+	bpf_run_async_cb(ctx->callback_fn, ctx->map, key, ctx->map_val);
 	migrate_enable();
 
 	bpf_task_work_ctx_reset(ctx);
@@ -5049,7 +5046,7 @@ static void bpf_rcu_run_callback(struct rcu_head *rcu)
 	smp_store_release(&rh->armed, 0);
 
 	rcu_read_lock_dont_migrate();
-	bpf_run_async_cb(prog, callback_fn, map, key, value);
+	bpf_run_async_cb(callback_fn, map, key, value);
 	rcu_read_unlock_migrate();
 
 	bpf_prog_put(prog);
diff --git a/kernel/bpf/stream.c b/kernel/bpf/stream.c
index c312e74ebd57..2352ad896073 100644
--- a/kernel/bpf/stream.c
+++ b/kernel/bpf/stream.c
@@ -562,7 +562,9 @@ int bpf_stream_stage_commit(struct bpf_stream_stage *ss, struct bpf_prog *prog,
 	struct bpf_stream *stream;
 	int ret;
 
-	bpf_timed_may_goto_check_time(prog);
+	/* without the cpu register the state is always in the task */
+	if (!bpf_jit_supports_may_goto_insn())
+		bpf_may_goto_clear_cnt(prog);
 
 	stream = bpf_stream_get(stream_id, prog->aux);
 	if (!stream)
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 cdba18a92d4b..82f5874ea4b6 100644
--- a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
+++ b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
@@ -225,7 +225,7 @@ void serial_test_timed_may_goto(void)
 	if (!ASSERT_OK_PTR(skel, "open_and_load"))
 		return;
 
-	/* Count and timestamp are per-cpu: all progs of a subtest run on one cpu. */
+	/* All progs of a subtest run on one cpu. */
 	if (!ASSERT_OK(sched_getaffinity(0, sizeof(old), &old), "getaffinity"))
 		goto out;
 	CPU_ZERO(&new);
diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto.c b/tools/testing/selftests/bpf/progs/timed_may_goto.c
index e01b7e727707..250ea6ca4d9e 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto.c
@@ -546,8 +546,8 @@ int rbtree_add(void *ctx)
 }
 
 /*
- * All registers are live at the may_goto, so it saves one of them in the stack. They are the same
- * after 70000 iterations: the loop reads the clock.
+ * All registers are live at the may_goto. They are the same after 70000 iterations: the loop
+ * reads the clock.
  */
 __naked __noinline __used
 static long regs_across_may_goto(void)
@@ -593,7 +593,7 @@ __naked void regs_across_may_goto_main(void)
 }
 
 /*
- * may_goto uses a register that is dead. In live_r0_rN() R0 - RN are live at the may_goto and the
+ * may_goto keeps live registers. In live_r0_rN() R0 - RN are live at the may_goto and the
  * next one is not. The values come from memory, so the verifier doesn't know them. Return their sum
  * and the number of iterations.
  */
@@ -746,9 +746,9 @@ static long live_fall_through(void)
  * and 6. 12 * 70000 iterations: each function reads the clock.
  */
 SEC("tc")
-__description("timed may_goto: may_goto takes a register that is dead")
+__description("timed may_goto: live registers across may_goto")
 __success __retval(840180)
-__naked void dead_reg(void)
+__naked void live_regs(void)
 {
 	asm volatile (
 		"r6 = 0;"
@@ -796,9 +796,9 @@ static bool less_all_live(struct bpf_rb_node *a, const struct bpf_rb_node *b)
  * may_goto jumps) and 4 (R2 isn't stored).
  */
 SEC("tc")
-__description("timed may_goto: may_goto takes a register that is dead, the time is up")
+__description("timed may_goto: live registers across may_goto, the time is up")
 __success __retval(181)
-int dead_reg_time_is_up(void *ctx)
+int live_regs_time_is_up(void *ctx)
 {
 	return run_stuck(less_all_live) ?: stuck_ret;
 }
diff --git a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
index bdd462f2f039..c48b612a1b70 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
@@ -970,30 +970,25 @@ SEC("raw_tp")
 __arch_riscv64
 __arch_loongarch
 __log_level(4)
-__msg("subprog 0 (may_goto_interaction) main {{.*}} stack 8")
-/* may_goto counter and timestamp */
-__xlated("0: r0 = ")
-__xlated("2: r0 = &(void __percpu *)(r0)")
+__msg("subprog 0 (may_goto_interaction) main {{.*}} stack 24")
+__xlated("0: call bpf_get_current_task")
 __xlated("...")
-__xlated("6: r1 = 1")
-__xlated("7: call bpf_get_smp_processor_id")
-/* may_goto expansion starts, r0 and r1 are live */
-__xlated("8: r2 = ")
-__xlated("10: r2 = &(void __percpu *)(r2)")
-__xlated("11: r13 = *(u64 *)(r2 +0)")
+__xlated("7: r1 = 1")
+__xlated("8: call bpf_get_smp_processor_id")
+/* may_goto expansion starts */
+__xlated("9: *(u64 *)(r10 -16) = r0")
+__xlated("...")
+__xlated("18: r0 = *(u64 *)(r10 -16)")
 /* when the time is up may_goto goes to the landing pad of the prog */
-__xlated("12: if r13 == 0x0 goto pc+7")
-__xlated("13: r13 -= 1")
-__xlated("14: if r13 != 0x0 goto pc+2")
-__xlated("15: r13 = r2")
-__xlated("16: call unknown")
-__xlated("17: *(u64 *)(r2 +0) = r13")
+__xlated("19: if r13 s< 0x0 goto pc+10")
 /* may_goto expansion ends */
-__xlated("18: *(u64 *)(r10 -8) = r1")
-__xlated("19: exit")
+__xlated("20: *(u64 *)(r10 -8) = r1")
+__xlated("...")
+__xlated("29: exit")
 /* the landing pad */
-__xlated("20: r0 = 0")
-__xlated("21: exit")
+__xlated("30: r0 = 0")
+__xlated("...")
+__xlated("39: exit")
 __success
 __naked void may_goto_interaction(void)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index 7e17decbf5b5..daeb3996c038 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -1137,10 +1137,7 @@ __naked void loop_without_exit(void)
 	);
 }
 
-/*
- * may_goto keeps the address of its count in a register that is dead. What is live in front
- * of the insn that gets may_goto is live in front of may_goto.
- */
+/* What is live in front of the insn that gets may_goto is live in front of may_goto. */
 SEC("socket")
 __description("budget: may_goto in front of a jump keeps R0")
 __arch_x86_64
diff --git a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
index 53dd54ad2762..a2e4731c2753 100644
--- a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
+++ b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
@@ -86,28 +86,42 @@ __load_if_JITed()
 __arch_s390x
 __arch_riscv64
 __arch_loongarch
-/* the main prog sets count, timestamp, owner */
-__xlated("0: r0 = ")
-__xlated("2: r0 = &(void __percpu *)(r0)")
-__xlated("3: *(u64 *)(r0 +0) = 65535")
-__xlated("4: *(u64 *)(r0 +8) = 0")
-__xlated("5: *(u64 *)(r0 +16) = 0")
-/* may_goto, r0 is dead. When the time is up it goes to the landing pad of the prog. */
-__xlated("6: r0 = ")
-__xlated("8: r0 = &(void __percpu *)(r0)")
-__xlated("9: r13 = *(u64 *)(r0 +0)")
-__xlated("10: if r13 == 0x0 goto pc+8")
-__xlated("11: r13 -= 1")
-__xlated("12: if r13 != 0x0 goto pc+2")
-__xlated("13: r13 = r0")
+/* the main prog saves the state in the task and inits its own */
+__xlated("0: call bpf_get_current_task")
+__xlated("1: r0 += ")
+__xlated("2: r13 = *(u64 *)(r0 +0)")
+__xlated("3: *(u64 *)(r10 -16) = r13")
+__xlated("4: r13 = 65534")
+__xlated("5: r13 <<= 23")
+__xlated("6: *(u64 *)(r0 +0) = r13")
+/* may_goto. When the time is up it goes to the landing pad of the prog. */
+__xlated("7: *(u64 *)(r10 -8) = r0")
+__xlated("8: call bpf_get_current_task")
+__xlated("9: r0 += ")
+__xlated("10: r13 = *(u64 *)(r0 +0)")
+__xlated("11: r13 -= 8388608")
+__xlated("12: if r13 s>= 0x0 goto pc+2")
+__xlated("13: if r13 & 0x1 goto pc+2")
 __xlated("14: call unknown")
 __xlated("15: *(u64 *)(r0 +0) = r13")
-__xlated("16: r0 = 1")
-__xlated("17: r0 = 2")
-__xlated("18: exit")
+__xlated("16: r0 = *(u64 *)(r10 -8)")
+__xlated("17: if r13 s< 0x0 goto pc+11")
+__xlated("18: r0 = 1")
+__xlated("19: r0 = 2")
+/* the saved state is restored */
+__xlated("20: r4 = r0")
+__xlated("21: call bpf_get_current_task")
+__xlated("22: r0 += ")
+__xlated("23: r5 = *(u64 *)(r0 +0)")
+__xlated("24: r13 = *(u64 *)(r10 -16)")
+__xlated("25: *(u64 *)(r10 -16) = r5")
+__xlated("26: *(u64 *)(r0 +0) = r13")
+__xlated("27: r0 = r4")
+__xlated("28: exit")
 /* the landing pad */
-__xlated("19: r0 = 0")
-__xlated("20: exit")
+__xlated("29: r0 = 0")
+__xlated("...")
+__xlated("38: exit")
 __success
 __naked void may_goto_batch_2(void)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_patch_list.c b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
index 75da37f72721..0d6228a997da 100644
--- a/tools/testing/selftests/bpf/progs/verifier_patch_list.c
+++ b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
@@ -432,20 +432,20 @@ __arch_s390x
 __arch_riscv64
 __arch_loongarch
 __success
-__xlated("23: call pc+7")
+__xlated("24: call pc+15")
 __xlated("...")
-__xlated("30: exit")
-__xlated("31: r0 = ")
-__xlated("33: r0 = &(void __percpu *)(r0)")
-__xlated("34: r0 = *(u64 *)(r0 +0)")
-__xlated("35: if r0 != 0x0 goto pc+2")
-__xlated("36: r0 = 1")
-__xlated("37: exit")
-__xlated("38: r1 += -1")
+__xlated("39: exit")
+__xlated("40: call bpf_get_current_task")
+__xlated("41: r0 += ")
+__xlated("42: r0 = *(u64 *)(r0 +0)")
+__xlated("43: r0 &= 1")
+__xlated("44: if r0 == 0x0 goto pc+1")
+__xlated("45: exit")
+__xlated("46: r1 += -1")
 __xlated("...")
-__xlated("49: if r1 != 0x0 goto pc-12")
-__xlated("50: r0 = 0")
-__xlated("51: exit")
+__xlated("58: if r1 != 0x0 goto pc-13")
+__xlated("59: r0 = 0")
+__xlated("60: exit")
 __naked void patch_list_insert_in_front_no_pads(void)
 {
 	INSERT_IN_FRONT;
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
                   ` (5 preceding siblings ...)
  2026-12-05  3:38 ` [PATCH bpf-next 6/7] bpf: Keep the state of may_goto in the task on other archs Alexei Starovoitov
@ 2026-12-05  3:38 ` Alexei Starovoitov
  2026-12-05  4:51   ` sashiko-bot
  2026-12-05  6:40 ` [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register patchwork-bot+netdevbpf
  7 siblings, 1 reply; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-05  3:38 UTC (permalink / raw)
  To: bpf; +Cc: daniel, andrii, eddyz87, memxor

From: Alexei Starovoitov <ast@kernel.org>

Check that a loop is cancelled in time when it calls helpers with
callbacks, calls functions that are traced, runs insns that clobber %r11,
or runs the same prog again. Check that freplace is refused.

The refusal comes before the check for a function that can unwind. Drop
the test of the latter here, unwind_attach has it.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
 .../selftests/bpf/prog_tests/timed_may_goto.c | 69 +++++++++++++---
 .../selftests/bpf/progs/timed_may_goto.c      | 82 +++++++++++++++++++
 .../selftests/bpf/progs/timed_may_goto_ext.c  | 18 ++++
 .../selftests/bpf/progs/timed_may_goto_user.c | 53 ++++++++----
 4 files changed, 195 insertions(+), 27 deletions(-)

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 82f5874ea4b6..79a39ec7d0e4 100644
--- a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
+++ b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
@@ -77,22 +77,25 @@ static void test_timer_on_top(struct timed_may_goto_user *skel)
 	ASSERT_LT(ticks, 100, "ticks");
 }
 
-static void test_freplace(struct timed_may_goto_user *skel)
+static void test_nested(struct timed_may_goto_user *skel)
 {
-	struct timed_may_goto_ext *ext;
-
-	/* replaced_global() is unwound, and the prog with it */
-	ASSERT_EQ(run_tc(skel->progs.freplace_target), 2, "not replaced");
+	struct netns_obj *ns = netns_new("timed_may_goto", true);
+	struct bpf_link *link;
 
-	/* so it cannot be replaced */
-	ext = timed_may_goto_ext__open();
-	if (!ASSERT_OK_PTR(ext, "ext_open"))
+	if (!ASSERT_OK_PTR(ns, "netns_new"))
 		return;
-	bpf_program__set_attach_target(ext->progs.replacement,
-				       bpf_program__fd(skel->progs.freplace_target),
-				       "replaced_global");
-	ASSERT_ERR(timed_may_goto_ext__load(ext), "ext_load of what can unwind");
-	timed_may_goto_ext__destroy(ext);
+	link = bpf_program__attach_tcx(skel->progs.nests, 1, NULL);
+	if (ASSERT_OK_PTR(link, "attach_tcx")) {
+		ASSERT_EQ(run_tc(skel->progs.nests), 2, "nests");
+		ASSERT_EQ(skel->bss->nested_cnt, 1000, "nested_cnt");
+	}
+	bpf_link__destroy(link);
+	netns_free(ns);
+}
+
+static void test_freplace(struct timed_may_goto_user *skel)
+{
+	struct timed_may_goto_ext *ext;
 
 	ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10, "not replaced");
 	ext = timed_may_goto_ext__open();
@@ -114,6 +117,38 @@ static void test_freplace(struct timed_may_goto_user *skel)
 	ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10, "not replaced");
 }
 
+static void test_freplace_refused(struct timed_may_goto_user *skel)
+{
+	struct timed_may_goto_ext *ext = timed_may_goto_ext__open();
+
+	if (!ASSERT_OK_PTR(ext, "ext_open"))
+		return;
+	bpf_program__set_attach_target(ext->progs.replacement,
+				       bpf_program__fd(skel->progs.calls_in_loop), "traced_global");
+	ASSERT_EQ(timed_may_goto_ext__load(ext), -EOPNOTSUPP, "ext_load");
+	timed_may_goto_ext__destroy(ext);
+}
+
+static void test_tracer(struct timed_may_goto_user *skel, int target_fd, const char *func)
+{
+	struct timed_may_goto_ext *ext = timed_may_goto_ext__open();
+
+	if (!ASSERT_OK_PTR(ext, "ext_open"))
+		return;
+	bpf_program__set_autoload(ext->progs.replacement, false);
+	bpf_program__set_autoload(ext->progs.tracer, true);
+	bpf_program__set_attach_target(ext->progs.tracer, target_fd, func);
+	if (!ASSERT_OK(timed_may_goto_ext__load(ext), "ext_load") ||
+	    !ASSERT_OK(timed_may_goto_ext__attach(ext), "ext_attach"))
+		goto out;
+	skel->bss->trips = 100000;
+	ASSERT_EQ(run_tc(skel->progs.calls_in_loop), 10, "short loop");
+	skel->bss->trips = 1 << 27;
+	ASSERT_EQ(run_tc(skel->progs.calls_in_loop), 2, "long loop");
+out:
+	timed_may_goto_ext__destroy(ext);
+}
+
 /* What a prog leaves behind when its time is up doesn't matter for the next one on the cpu. */
 static void test_tail_call_and_throw(struct timed_may_goto_user *skel)
 {
@@ -237,8 +272,16 @@ void serial_test_timed_may_goto(void)
 		test_async(skel);
 	if (test__start_subtest("timer_on_top"))
 		test_timer_on_top(skel);
+	if (test__start_subtest("nested"))
+		test_nested(skel);
 	if (test__start_subtest("freplace"))
 		test_freplace(skel);
+	if (test__start_subtest("freplace_refused"))
+		test_freplace_refused(skel);
+	if (test__start_subtest("fentry_helper"))
+		test_tracer(skel, 0, "bpf_user_rnd_u32");
+	if (test__start_subtest("fentry_subprog"))
+		test_tracer(skel, bpf_program__fd(skel->progs.calls_in_loop), "traced_global");
 	if (test__start_subtest("tail_call_and_throw"))
 		test_tail_call_and_throw(skel);
 	if (test__start_subtest("user_ringbuf"))
diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto.c b/tools/testing/selftests/bpf/progs/timed_may_goto.c
index 250ea6ca4d9e..037ddb81d38f 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto.c
@@ -256,6 +256,88 @@ int loop_not_inlined(void *ctx)
 	return spun;
 }
 
+static int one_trip_cb(__u64 i, void *ctx)
+{
+	return !can_loop;
+}
+
+SEC("tc")
+__description("timed may_goto: the trips of a callback and of its caller add up")
+__success __retval(2)
+int count_over_callback(void *ctx)
+{
+	__u64 i;
+
+	for (i = zero; i < 1 << 29 && can_loop; i++)
+		bpf_loop(1, one_trip_cb, NULL, zero);
+	return 10;
+}
+
+/* x86 divides by R0 with a temporary register. Returns 1. */
+__u64 big = 1ULL << 62;
+
+static __always_inline __u64 divides(void)
+{
+	__u64 a = big;
+
+	asm volatile ("r0 = %[a]; %[a] /= r0" : [a]"+r"(a) :: "r0");
+	return a;
+}
+
+SEC("tc")
+__description("timed may_goto: division in a loop")
+__success __retval(2)
+int div_in_loop(void *ctx)
+{
+	__u64 i;
+
+	for (i = zero; i < 1ULL << 32 && can_loop;)
+		i += divides();
+	return 10;
+}
+
+/* The division by a constant becomes a high multiply, which x86 does with a temporary register */
+SEC("tc")
+__description("timed may_goto: high multiply in a loop")
+__success __retval(2)
+int hmul_in_loop(void *ctx)
+{
+	__u64 i, a;
+
+	for (i = zero; i < 1ULL << 32 && can_loop; i++) {
+		a = big;
+		asm volatile ("%[a] /= 7" : [a]"+r"(a));
+	}
+	return 10;
+}
+
+struct {
+	__uint(type, BPF_MAP_TYPE_ARENA);
+	__uint(map_flags, BPF_F_MMAPABLE);
+	__uint(max_entries, 2);
+} arena SEC(".maps");
+
+/* The arena has no pages. The access is skipped and fetches 0. */
+static bool less_faults(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+	__u64 *p = (void *)__PAGE_SIZE, n = zero;
+
+	asm volatile ("r0 = %[arena] ll" :: __imm_addr(arena) : "r0");
+	bpf_addr_space_cast(p, 0, 1);
+	while (n < 1 << 24 && can_loop)
+		n += 1 + __sync_fetch_and_or(p, 1);
+	stuck_ret = n > 100 && n < 1 << 24;
+	return false;
+}
+
+SEC("tc")
+__description("timed may_goto: fault of a fetching atomic in a loop")
+__success __retval(1)
+int fetch_fault_in_loop(void *ctx)
+{
+	return run_stuck(less_faults) ?: stuck_ret;
+}
+
 static int count_cb(__u64 i, int *calls)
 {
 	(*calls)++;
diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c b/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c
index d6cd5f370fd8..c1d81a1372cc 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c
@@ -29,6 +29,24 @@ static __noinline int counts_to_1000(void)
 	return cnt;
 }
 
+/* x86 divides by R0 with a temporary register. Returns 1. */
+__u64 big = 1ULL << 62;
+
+static __always_inline __u64 divides(void)
+{
+	__u64 a = big;
+
+	asm volatile ("r0 = %[a]; %[a] /= r0" : [a]"+r"(a) :: "r0");
+	return a;
+}
+
+SEC("?fentry")
+int tracer(void *ctx)
+{
+	divides();
+	return 0;
+}
+
 /* The calls that had the time for a short loop before they used it up */
 int calls, counted_to_1000;
 
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 a1a13c9b8236..709c3a12ea40 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
@@ -242,25 +242,29 @@ int spin_under_timer(void *ctx)
 	return 102;
 }
 
-/*
- * Extension prog. A function that can unwind cannot be replaced: an extension ends in its main
- * prog. With a loop that may_goto stops that is replaced_global(). plain_global() cannot unwind.
- */
-__noinline int replaced_global(int i)
-{
-	return spin() + i;
-}
+int nested, nested_cnt;
 
-SEC("tc")
-int freplace_target(void *ctx)
+/* The prog runs on top of itself on each trip. That doesn't give it more time. */
+SEC("tcx/egress")
+int nests(struct __sk_buff *skb)
 {
-	int i, n = 10;
+	__u64 t0 = bpf_ktime_get_ns();
 
-	for (i = 0; i < TRIES; i++)
-		n += replaced_global(zero);
-	return n;
+	if (nested) {
+		nested_cnt = counts_to_1000();
+		return 2;
+	}
+	nested = 1;
+	while (can_loop) {
+		bpf_clone_redirect(skb, 1, 0);
+		/* give up, so that the test fails and doesn't lock up */
+		if (bpf_ktime_get_ns() - t0 > 2000 * 1000 * 1000)
+			break;
+	}
+	return 10;
 }
 
+/* Extension prog */
 int plain_global_calls;
 
 /* It counts its calls: the compiler must not make one call of the calls in a loop */
@@ -280,6 +284,27 @@ int freplace_plain_target(void *ctx)
 	return n;
 }
 
+/* Tracing progs run on each trip. Returns 10 when the loop gets to its end. */
+__u64 trips, traced_calls;
+
+__noinline int traced_global(int i)
+{
+	traced_calls++;
+	return i;
+}
+
+SEC("tc")
+int calls_in_loop(void *ctx)
+{
+	__u64 i;
+
+	for (i = zero; i < trips && can_loop; i++) {
+		bpf_get_prandom_u32();
+		traced_global(zero);
+	}
+	return 10;
+}
+
 /*
  * Tail calls
  */
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 5/7] bpf, arm64: Keep the state of may_goto in x24
  2026-12-05  3:37 ` [PATCH bpf-next 5/7] bpf, arm64: Keep the state of may_goto in x24 Alexei Starovoitov
@ 2026-12-05  4:18   ` bot+bpf-ci
  0 siblings, 0 replies; 13+ messages in thread
From: bot+bpf-ci @ 2026-12-05  4:18 UTC (permalink / raw)
  To: alexei.starovoitov, bpf
  Cc: daniel, andrii, eddyz87, memxor, ast, andrii, daniel, martin.lau,
	eddyz87, yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 1390 bytes --]

> bpf, arm64: Keep the state of may_goto in x24

TL;DR: Nit only: call_needs_may_goto_fill() in the arm64 JIT appears identical
to the x86 helper from the previous patch; could it move to
include/linux/filter.h and be shared?

> diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
> --- a/arch/arm64/net/bpf_jit_comp.c
> +++ b/arch/arm64/net/bpf_jit_comp.c

[ ... ]

> +static bool call_needs_may_goto_fill(const struct bpf_prog *prog, const struct bpf_insn *call)
> +{
> +	return call > prog->insnsi && insn_is_may_goto_mov(call - 1) &&
> +	       call[-1].off == BPF_MAY_GOTO_SPILL_CALL;
> +}

This isn't a bug, but is call_needs_may_goto_fill() identical to the helper
of the same name added to arch/x86/net/bpf_jit_comp.c by the previous patch?

It only tests generic BPF insns against the BPF_MAY_GOTO_SPILL_CALL contract
documented in include/linux/filter.h, and the neighbouring predicates for that
contract, insn_is_may_goto_mov() and insn_is_jit_may_goto(), already live there
as static inlines.

Could it go into include/linux/filter.h next to insn_is_may_goto_mov(), so the
x86 and arm64 JITs share one definition?


---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/47475675368

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 6/7] bpf: Keep the state of may_goto in the task on other archs
  2026-12-05  3:38 ` [PATCH bpf-next 6/7] bpf: Keep the state of may_goto in the task on other archs Alexei Starovoitov
@ 2026-12-05  4:18   ` bot+bpf-ci
  0 siblings, 0 replies; 13+ messages in thread
From: bot+bpf-ci @ 2026-12-05  4:18 UTC (permalink / raw)
  To: alexei.starovoitov, bpf
  Cc: daniel, andrii, eddyz87, memxor, ast, andrii, daniel, martin.lau,
	eddyz87, yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3270 bytes --]

> bpf: Keep the state of may_goto in the task on other archs

TL;DR: Possible behaviour change: setting has_may_goto in the in-task path may
make freplace of a subprog fail with -EOPNOTSUPP on riscv, powerpc64,
loongarch and s390. Is that intended? It is undocumented and untested.

> diff --git a/include/linux/bpf.h b/include/linux/bpf.h
> --- a/include/linux/bpf.h
> +++ b/include/linux/bpf.h

[ ... ]

> @@ -2000,9 +2000,7 @@ struct bpf_prog_aux {
>  	bool arena_stack_entry;
>  	struct bpf_prog **func;
>  	struct bpf_prog_aux *main_prog_aux;
> -	/* main prog: there when the prog has timed may_goto */
> -	struct bpf_timed_may_goto __percpu *timed_may_goto;
> -	/* main prog: the JIT gets may_goto as an insn */
> +	/* main prog: the prog has timed may_goto */
>  	bool has_may_goto;

Redefining has_may_goto from "the JIT gets may_goto as an insn" to "the prog
has timed may_goto" changes what bpf_check_attach_target() sees on these
archs.  Is the new freplace refusal intended there?

bpf_check_attach_target() uses the flag like this:

    /* x86: the extension doesn't preserve the register with the state of may_goto */
    if (subprog && aux->has_may_goto && prog_extension) {
        bpf_log(log, "Cannot replace a subprog of a program with may_goto\n");
        return -EOPNOTSUPP;
    }

On the parent commit has_may_goto stayed false on riscv, powerpc64,
loongarch and s390, so such an extension could load.  Now it fails with
-EOPNOTSUPP.

The reason given in that comment only applies when the state is kept in a
CPU register.  Here the state lives in current->bpf_may_goto_state, and an
extension with may_goto is a main prog, so insert_may_goto_save_restore()
saves and restores the caller's state around it.

The commit message does not mention the new refusal, and the test added
later in the series (test_freplace_refused) returns early from
serial_test_timed_may_goto() unless the arch is x86_64 or aarch64, so
nothing covers it on these archs.  If it is intended, should the commit
message and the "x86:" comment say so?  Otherwise, should the check test
may_goto_in_reg or bpf_jit_supports_may_goto_insn() instead of
has_may_goto?

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c

[ ... ]

> @@ -3372,32 +3378,32 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
>  			insn_buf[10] = BPF_JMP_IMM(BPF_JSLT, BPF_REG_AX, 0, 0);
>  			prog->jit_required = 1;
> +			prog->aux->has_may_goto = true;

This is where the in-task branch now sets has_may_goto, which was
previously set only in the may_goto_insn branch (x86/arm64).

A freplace program attached to a global subprog of a target with any
may_goto, including may_gotos the verifier adds itself for loop guards and
recursion checks, now fails to load on riscv, powerpc64, loongarch and
s390.  Could the "x86:" check in bpf_check_attach_target() be limited to
JITs that keep the state in a register, or the changelog be updated to
state that the refusal now applies to every arch?


---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/47475675368

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 4/7] bpf, x86: Keep the state of may_goto in %r11
  2026-12-05  3:37 ` [PATCH bpf-next 4/7] bpf, x86: Keep the state of may_goto in %r11 Alexei Starovoitov
@ 2026-12-05  4:29   ` bot+bpf-ci
  0 siblings, 0 replies; 13+ messages in thread
From: bot+bpf-ci @ 2026-12-05  4:29 UTC (permalink / raw)
  To: alexei.starovoitov, bpf
  Cc: daniel, andrii, eddyz87, memxor, ast, andrii, daniel, martin.lau,
	eddyz87, yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 1457 bytes --]

> bpf, x86: Keep the state of may_goto in %r11

TL;DR: Nit only: the comment on the landings array in struct jit_context
should mention may_goto, since max_landings now counts it too.

> diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
> --- a/arch/x86/net/bpf_jit_comp.c
> +++ b/arch/x86/net/bpf_jit_comp.c

[ ... ]

> @@ -5051,7 +5289,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
>  	if (!addrs)
>  		goto out_addrs;
>  	for (i = 0; i < prog->len; i++)
> -		ctx.max_landings += bpf_is_pad_goto(&prog->insnsi[i]);
> +		ctx.max_landings += bpf_is_pad_goto(&prog->insnsi[i]) ||
> +				    insn_is_jit_may_goto(&prog->insnsi[i]);
>  	if (ctx.max_landings) {
>  		ctx.landings = kvmalloc_objs(*ctx.landings, ctx.max_landings);
>  		if (!ctx.landings)

This isn't a bug, but the comment on the landings array in struct
jit_context still reads:

	/*
	 * Room for one landing per unwind_goto and cancel_goto of the prog.
	 * Each pass fills the array again. ...
	 */
	struct jit_landing *landings;
	int max_landings;

Now that max_landings also counts each may_goto, and do_jit() takes a landing
for its slow path, could the comment mention may_goto as well?


---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/47475675368

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11
  2026-12-05  3:38 ` [PATCH bpf-next 7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11 Alexei Starovoitov
@ 2026-12-05  4:51   ` sashiko-bot
  0 siblings, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-12-05  4:51 UTC (permalink / raw)
  To: Alexei Starovoitov, bpf

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] selftests/bpf: fetch_fault_in_loop() fails on arm64 CPUs
  without LSE atomics
- [Low] selftests/bpf: nests() 2s bailout lacks iteration guard for
  131071 trips
--

commit 5645b13a4a71b76c527f8d3a4d37bbf30c734be9
Author: Alexei Starovoitov <ast@kernel.org>

selftests/bpf: Test may_goto state across calls and clobbers of %r11

This commit adds BPF selftests verifying that timed may_goto loops still
cancel across callback helpers, traced functions, instructions that clobber
%r11, and nested program invocations, and checks that freplace on such
programs is refused.

> diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto.c b/tools/testing/selftests/bpf/progs/timed_may_goto.c
> index 250ea6ca4d9ed..037ddb81d38f5 100644
> --- a/tools/testing/selftests/bpf/progs/timed_may_goto.c
> +++ b/tools/testing/selftests/bpf/progs/timed_may_goto.c
> @@ -256,6 +256,88 @@ int loop_not_inlined(void *ctx)

[ ... ]

> +/* The arena has no pages. The access is skipped and fetches 0. */
> +static bool less_faults(struct bpf_rb_node *a, const struct bpf_rb_node *b)
> +{
> +	__u64 *p = (void *)__PAGE_SIZE, n = zero;
> +
> +	asm volatile ("r0 = %[arena] ll" :: __imm_addr(arena) : "r0");
> +	bpf_addr_space_cast(p, 0, 1);
> +	while (n < 1 << 24 && can_loop)
> +		n += 1 + __sync_fetch_and_or(p, 1);
> +	stuck_ret = n > 100 && n < 1 << 24;
> +	return false;
> +}
> +
> +SEC("tc")
> +__description("timed may_goto: fault of a fetching atomic in a loop")
> +__success __retval(1)
> +int fetch_fault_in_loop(void *ctx)
> +{
> +	return run_stuck(less_faults) ?: stuck_ret;
> +}

[Severity: Medium]
Will fetch_fault_in_loop() fail to load on arm64 CPUs without LSE atomics?

timed_may_goto.c builds for both x86 and arm64, and fetch_fault_in_loop()
expects unconditional load success. On arm64 without ARM64_HAS_LSE_ATOMICS,
bpf_jit_supports_insn() rejects fetching arena atomics (LL/SC does not
support BPF_PROBE_ATOMIC), so atomic_ptr_type_ok() returns -EACCES.

Restricting fetch_fault_in_loop() with __arch_x86_64 (matching
arena_atomics.c) or skipping when LSE is unavailable would avoid failing the
suite on non-LSE arm64 hosts.

[ ... ]

> 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 a1a13c9b8236e..709c3a12ea402 100644
> --- a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
> +++ b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
> @@ -242,25 +242,29 @@ int spin_under_timer(void *ctx)

[ ... ]

> +/* The prog runs on top of itself on each trip. That doesn't give it more time. */
> +SEC("tcx/egress")
> +int nests(struct __sk_buff *skb)
>  {
> -	int i, n = 10;
> +	__u64 t0 = bpf_ktime_get_ns();
>  
> -	for (i = 0; i < TRIES; i++)
> -		n += replaced_global(zero);
> -	return n;
> +	if (nested) {
> +		nested_cnt = counts_to_1000();
> +		return 2;
> +	}
> +	nested = 1;
> +	while (can_loop) {
> +		bpf_clone_redirect(skb, 1, 0);
> +		/* give up, so that the test fails and doesn't lock up */
> +		if (bpf_ktime_get_ns() - t0 > 2000 * 1000 * 1000)
> +			break;
> +	}
> +	return 10;
>  }

[Severity: Low]
Can the 2-second bailout in nests() fire before may_goto has a chance to
unwind?

Because the first bpf_may_goto_slowpath() call at trip 65,535 only
initializes the start time and reloads 65,534 trips, nests() cannot unwind
until trip 131,071.

Each outer trip runs bpf_clone_redirect() (skb_clone(), pskb_expand_head(),
and tcx egress dispatch) plus counts_to_1000() and two bpf_ktime_get_ns()
calls. On debug kernels or slow virtualized guests, the 2-second timeout can
expire first and return 10, spuriously failing test_nested().

Guarding the timeout check with an outer iteration count of at least two
slowpath rounds (as loop_calls_subprog_with_65534_iterations() in
timed_may_goto.c does) would prevent false failures.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261205033801.1046411-1-alexei.starovoitov@gmail.com?part=7

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register
  2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
                   ` (6 preceding siblings ...)
  2026-12-05  3:38 ` [PATCH bpf-next 7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11 Alexei Starovoitov
@ 2026-12-05  6:40 ` patchwork-bot+netdevbpf
  7 siblings, 0 replies; 13+ messages in thread
From: patchwork-bot+netdevbpf @ 2026-12-05  6:40 UTC (permalink / raw)
  To: Alexei Starovoitov; +Cc: bpf, daniel, andrii, eddyz87, memxor

Hello:

This series was applied to bpf/bpf-next.git (master)
by Alexei Starovoitov <ast@kernel.org>:

On Sat,  5 Dec 2026 03:37:54 +0000 you wrote:
> From: Alexei Starovoitov <ast@kernel.org>
> 
> may_goto cancels a prog that loops for too long. It counts iterations in
> per-cpu memory that all invocations of the prog share. When one preempts
> another, a loop can run forever or get cancelled too early.
> 
> Give each invocation its own state and keep it in %r11 on x86-64, in x24
> on arm64 and in current on other archs. It also makes may_goto faster: two
> insns on x86-64 and arm64.
> 
> [...]

Here is the summary with links:
  - [bpf-next,1/7] selftests/bpf: Don't depend on the expansion of may_goto
    https://git.kernel.org/bpf/bpf-next/c/a83f2ed3b12a
  - [bpf-next,2/7] selftests/bpf: Wait longer in parallel tests of libarena
    https://git.kernel.org/bpf/bpf-next/c/e1e53046006e
  - [bpf-next,3/7] bpf: Keep the state of may_goto per invocation
    https://git.kernel.org/bpf/bpf-next/c/cd0a0f04b3ba
  - [bpf-next,4/7] bpf, x86: Keep the state of may_goto in %r11
    https://git.kernel.org/bpf/bpf-next/c/2539ded09076
  - [bpf-next,5/7] bpf, arm64: Keep the state of may_goto in x24
    https://git.kernel.org/bpf/bpf-next/c/b42a10318cd0
  - [bpf-next,6/7] bpf: Keep the state of may_goto in the task on other archs
    https://git.kernel.org/bpf/bpf-next/c/cc475cf3f992
  - [bpf-next,7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11
    https://git.kernel.org/bpf/bpf-next/c/97a85c11e9ec

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] 13+ messages in thread

end of thread, other threads:[~2026-12-05  6:40 UTC | newest]

Thread overview: 13+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-05  3:37 [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register Alexei Starovoitov
2026-12-05  3:37 ` [PATCH bpf-next 1/7] selftests/bpf: Don't depend on the expansion of may_goto Alexei Starovoitov
2026-12-05  3:37 ` [PATCH bpf-next 2/7] selftests/bpf: Wait longer in parallel tests of libarena Alexei Starovoitov
2026-12-05  3:37 ` [PATCH bpf-next 3/7] bpf: Keep the state of may_goto per invocation Alexei Starovoitov
2026-12-05  3:37 ` [PATCH bpf-next 4/7] bpf, x86: Keep the state of may_goto in %r11 Alexei Starovoitov
2026-12-05  4:29   ` bot+bpf-ci
2026-12-05  3:37 ` [PATCH bpf-next 5/7] bpf, arm64: Keep the state of may_goto in x24 Alexei Starovoitov
2026-12-05  4:18   ` bot+bpf-ci
2026-12-05  3:38 ` [PATCH bpf-next 6/7] bpf: Keep the state of may_goto in the task on other archs Alexei Starovoitov
2026-12-05  4:18   ` bot+bpf-ci
2026-12-05  3:38 ` [PATCH bpf-next 7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11 Alexei Starovoitov
2026-12-05  4:51   ` sashiko-bot
2026-12-05  6:40 ` [PATCH bpf-next 0/7] bpf: Keep the state of may_goto in a register patchwork-bot+netdevbpf

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox