bpf: Keep the state of may_goto in a register
cover bpf: Keep the state of may_goto in a register
From: Alexei Starovoitov <[email protected]>
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(-)
Signature · 1 line
2.55.0
PATCH 1/7 selftests/bpf: Don't depend on the expansion of may_goto
From: Alexei Starovoitov <[email protected]>
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.
--- 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(-)
tools/testing/selftests/bpf/prog_tests/patch_list.c +8 -1
@@ -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; }
tools/testing/selftests/bpf/prog_tests/share_subprogs.c +6 -3
@@ -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);
tools/testing/selftests/bpf/progs/verifier_budget.c +2 -11
@@ -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 )
tools/testing/selftests/bpf/progs/verifier_loop_walk.c +1 -1
@@ -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" )
tools/testing/selftests/bpf/progs/verifier_passes.c +1 -1
@@ -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
tools/testing/selftests/bpf/progs/verifier_trip_count.c +2 -0
@@ -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 ) {
Signature · 1 line
2.55.0
PATCH 2/7 selftests/bpf: Wait longer in parallel tests of libarena
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
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.
--- .../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(-)
tools/testing/selftests/bpf/libarena/selftests/test_parallel_bitmap.bpf.c +1 -1
@@ -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)
tools/testing/selftests/bpf/libarena/selftests/test_parallel_spmc.bpf.c +1 -1
@@ -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
Signature · 1 line
2.55.0
PATCH 3/7 bpf: Keep the state of may_goto per invocation
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
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 <- preemptedA 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.
--- 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(-)
include/linux/bpf.h +4 -0
@@ -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;
include/linux/bpf_verifier.h +9 -0
@@ -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,
include/linux/filter.h +59 -0
77 lines not on this page · raw message
include/linux/sched.h +2 -0
@@ -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;
kernel/bpf/arena.c +1 -0
@@ -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 ; }
kernel/bpf/core.c +29 -0
@@ -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)
kernel/bpf/disasm.c +15 -0
@@ -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",
kernel/bpf/fixups.c +219 -4
273 lines not on this page · raw message
kernel/bpf/helpers.c +3 -0
@@ -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); }
kernel/bpf/rqspinlock.c +2 -0
@@ -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, bobpf_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"; })
kernel/bpf/stream.c +1 -0
@@ -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 ; }
kernel/bpf/verifier.c +19 -0
@@ -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 ;
Signature · 1 line
2.55.0
PATCH 4/7 bpf, x86: Keep the state of may_goto in %r11
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
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.
--- 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(-)
arch/x86/net/bpf_jit_comp.c +303 -59
@@ -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 )¤t_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_imint 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_imif (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_imemit_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_prif (!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;
arch/x86/net/bpf_timed_may_goto.S +12 -5
@@ -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
kernel/bpf/fixups.c +1 -1
@@ -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 ;
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +4 -3
@@ -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)" )
tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c +7 -22
@@ -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 ) {
tools/testing/selftests/bpf/progs/verifier_may_goto_1.c +28 -1
@@ -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 ) +{ + asmvolatile ( +".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.
tools/testing/selftests/bpf/progs/verifier_patch_list.c +39 -57
148 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next 4/7] 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.
Quoted 1 line
bpf, x86: Keep the state of
may_gotoin %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.
Quoted 3 lines
arch/x86/net/bpf_jit_comp.c +0
-0
[ ... ]
arch/x86/net/bpf_jit_comp.c struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr · line 5296
Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +2
-1@@ -5051,7 +5289,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prif (!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
PATCH 5/7 bpf, arm64: Keep the state of may_goto in x24
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
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.
--- 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(-)
arch/arm64/net/bpf_jit_comp.c +172 -31
@@ -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, inint 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_insnemit (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_insnemit_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_prfor (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) {
arch/arm64/net/bpf_timed_may_goto.S +8 -12
@@ -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
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +0 -1
@@ -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" )
tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c +3 -3
@@ -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 ) { asmvolatile ( "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)
tools/testing/selftests/bpf/progs/verifier_may_goto_1.c +1 -1
@@ -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" )
tools/testing/selftests/bpf/progs/verifier_patch_list.c +3 -0
@@ -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" )
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next 5/7] 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?
Quoted 1 line
bpf, arm64: Keep the state of
may_gotoin 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?
Quoted 3 lines
arch/arm64/net/bpf_jit_comp.c +0
-0
[ ... ]
arch/arm64/net/bpf_jit_comp.c static int add_exception_handler(const struct bpf_verifier_env *env, · line 1718
Quoted 5 lines
arch/arm64/net/bpf_jit_comp.c +5
-0+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
PATCH 6/7 bpf: Keep the state of may_goto in the task on other archs
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
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.
--- 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(-)
arch/loongarch/net/bpf_timed_may_goto.S +3 -6
@@ -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
arch/powerpc/net/bpf_timed_may_goto.S +5 -5
@@ -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
arch/riscv/net/bpf_timed_may_goto.S +4 -4
@@ -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 */
arch/s390/net/bpf_timed_may_goto.S +1 -1
@@ -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)
include/linux/bpf.h +1 -3
@@ -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;
include/linux/filter.h +0 -15
@@ -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);
kernel/bpf/core.c +0 -63
75 lines not on this page · raw message
kernel/bpf/fixups.c +100 -109
278 lines not on this page · raw message
kernel/bpf/helpers.c +6 -9
@@ -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);
kernel/bpf/stream.c +3 -1
@@ -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)
tools/testing/selftests/bpf/prog_tests/timed_may_goto.c +1 -1
@@ -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);
tools/testing/selftests/bpf/progs/timed_may_goto.c +7 -7
@@ -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 ) { asmvolatile ( "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; }
tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c +15 -20
@@ -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 ) {
tools/testing/selftests/bpf/progs/verifier_budget.c +1 -4
@@ -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
tools/testing/selftests/bpf/progs/verifier_may_goto_1.c +33 -19
61 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_patch_list.c +12 -12
@@ -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 ;
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next 6/7] 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…
Quoted 1 line
bpf: Keep the state of
may_gotoin 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.
Quoted 3 lines
include/linux/bpf.h +0
-0
[ ... ]
include/linux/bpf.h struct bpf_prog_aux { · line 2004
Quoted 9 lines
include/linux/bpf.h +1
-3@@ -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?
Quoted 3 lines
kernel/bpf/fixups.c +0
-0
[ ... ]
kernel/bpf/fixups.c int bpf_do_misc_fixups(struct bpf_verifier_env *env) · line 3380
Quoted 4 lines
kernel/bpf/fixups.c +1
-0@@ -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
PATCH 7/7 selftests/bpf: Test may_goto state across calls and clobbers of %r11
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
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.
--- .../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(-)
tools/testing/selftests/bpf/prog_tests/timed_may_goto.c +56 -13
@@ -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" ))
tools/testing/selftests/bpf/progs/timed_may_goto.c +82 -0
88 lines not on this page · raw message
tools/testing/selftests/bpf/progs/timed_may_goto_ext.c +18 -0
@@ -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; + + asmvolatile ("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;
tools/testing/selftests/bpf/progs/timed_may_goto_user.c +39 -14
70 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next 7/7] selftests/bpf: Test may_goto state across calls and clobbers of %r11
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]…
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 <[email protected]>
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.
Quoted 5 lines
tools/testing/selftests/bpf/progs/timed_may_goto.c +0
-0@@ -256,6 +256,88 @@ int loop_not_inlined(void *ctx)
[ ... ]
Quoted 10 lines
tools/testing/selftests/bpf/progs/timed_may_goto.c +10
-0+/* 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 ;
tools/testing/selftests/bpf/progs/timed_may_goto.c int loop_not_inlined(void *ctx) · line 339
Quoted 10 lines
tools/testing/selftests/bpf/progs/timed_may_goto.c +10
-0+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.
[ ... ]
Quoted 5 lines
tools/testing/selftests/bpf/progs/timed_may_goto_user.c +0
-0@@ -242,25 +242,29 @@ int spin_under_timer(void *ctx)
[ ... ]
Quoted 13 lines
tools/testing/selftests/bpf/progs/timed_may_goto_user.c +7
-4+/* 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 ;
tools/testing/selftests/bpf/progs/timed_may_goto_user.c int spin_under_timer(void *ctx) · line 265
Quoted 10 lines
tools/testing/selftests/bpf/progs/timed_may_goto_user.c +9
-0+ } + 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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:
Hello:
This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:
Quoted 11 lines · On Sat, 5 Dec 2026 03:37:54 +0000 you wrote:
From: Alexei Starovoitov <[email protected]>
may_gotocancels 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_gotofaster: 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!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html