Cancellations
Subsystems (21)
Kumar Kartikeya Dwivedi
maintainerPATCH 47/73 bpf: Remove the stack walk of bpf_throw()
In reply to Kumar Kartikeya DwivediFrom: Alexei Starovoitov <[email protected]>
bpf_throw() still has a body that walks the stack up to the main program and calls the exception callback there. No program calls the kfunc any
more: the verifier replaces each call of it by a jump to a landing pad. Programs and libbpf name the function, so it stays in BTF, with a WARN_ON_ONCE() for a body.
Remove what served the walk. For each piece, what it did and what replaces it:
bpf_stack_walker(), The walk from bpf_throw() up to the
struct bpf_throw_ctx main program. Each frame leaves
through its landing pad instead.
bpf_exception_cb The pointer through which bpf_throw()
called the exception callback. A landing pad of the main program calls the callback with a call insn.
exception_boundary, The bits that told a JIT to emit the
exception_cb exception boundary and the prologue of
the callback. Nothing sets or reads them any more.
stack_arg_sp_adjust Where bpf_throw() found the registers
that the main program saved on x86-64. Nothing sets or reads it any more.
real_func_cnt func_cnt plus the hidden subprog of the
default exception callback, which no longer exists. Its readers use func_cnt.
bpf_jit_supports_exceptions() "The stack can be walked from a kfunc
up to the main program." A program with bpf_throw() needs bpf_jit_supports_unwind() instead.
bpf_throw() was notrace, NOKPROBE_SYMBOL() and not instrumented by KASAN, because it did not return. It is an ordinary function now.
bpf_prog_has_invocation_budget() asked bpf_jit_supports_exceptions() too, because the report of a recursion that is out of stack walks the stack. So a recursive program was rejected where the stack cannot be walked, on x86-64 without ORC, with "JIT does not support recursive calls". Such a program loads there now. When its recursion is out of stack, arch_bpf_stack_walk() finds nothing and there is no report.
arch_bpf_stack_walk() stays: BPF streams and bpf_prog_find_from_stack() use it.
--- arch/arm64/net/bpf_jit_comp.c | 10 ------- arch/powerpc/net/bpf_jit_comp.c | 5 ---- arch/s390/net/bpf_jit_comp.c | 9 ------ arch/x86/net/bpf_jit_comp.c | 9 ------ include/linux/bpf.h | 5 ---- include/linux/filter.h | 5 +--- kernel/bpf/core.c | 15 ++++------ kernel/bpf/fixups.c | 2 -- kernel/bpf/helpers.c | 53 +++++---------------------------- kernel/bpf/syscall.c | 4 +-- scripts/gdb/linux/bpf.py | 4 +-- 11 files changed, 17 insertions(+), 104 deletions(-)
arch/arm64/net/bpf_jit_comp.c +0 -10
@@ -4002,16 +4002,6 @@ u64 bpf_arch_uaddress_limit(void)return 0 ; } -bool bpf_jit_supports_exceptions (void ) -{ -/* We unwind through both kernel frames starting from within bpf_throw -* call and BPF frames. Therefore we require FP unwinder to be enabled -* to walk kernel frames and reach BPF frames in the stack trace. -* ARM64 kernel is always compiled with CONFIG_FRAME_POINTER=y -*/ -return true; -} -bool bpf_jit_supports_arena (void ) {return true;
arch/powerpc/net/bpf_jit_comp.c +0 -5
@@ -552,11 +552,6 @@ void bpf_jit_free(struct bpf_prog *fp)bpf_prog_unlock_free (fp); } -bool bpf_jit_supports_exceptions (void ) -{ -return IS_ENABLED (CONFIG_PPC64 ); -} -bool bpf_jit_supports_subprog_tailcalls (void ) {return IS_ENABLED (CONFIG_PPC64 );
arch/s390/net/bpf_jit_comp.c +0 -9
@@ -3059,15 +3059,6 @@ bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)return true; } -bool bpf_jit_supports_exceptions (void ) -{ -/* -* Exceptions require unwinding support, which is always available, -* because the kernel is always built with backchain. -*/ -return true; -} -void arch_bpf_stack_walk (bool (*consume_fn)(void *,u64 ,u64 ,u64 ),void *cookie) {
arch/x86/net/bpf_jit_comp.c +0 -9
@@ -5141,15 +5141,6 @@ void bpf_jit_free(struct bpf_prog *prog)bpf_prog_unlock_free (prog); } -bool bpf_jit_supports_exceptions (void ) -{ -/* We unwind through both kernel frames (starting from within bpf_throw -* call) and BPF frames. Therefore we require ORC unwinder to be enabled -* to walk kernel frames and reach BPF frames in the stack trace. -*/ -return IS_ENABLED (CONFIG_UNWINDER_ORC ); -} -bool bpf_jit_supports_private_stack (void ) {return true;
include/linux/bpf.h +0 -5
@@ -1918,7 +1918,6 @@ struct bpf_prog_aux {u32 stack_depth;u32 id;u32 func_cnt;/* used by non-func prog as the number of func progs */ -u32 real_func_cnt;/* includes hidden progs, only used for JIT and freeing progs */ u32 exception_callback_subprog;/* index in func[], 0 if there is none */ u32 func_idx;/* 0 for non-func prog, the index in func array for func prog */ u32 attach_btf_id;/* in-kernel BTF type id to attach to */
@@ -1949,8 +1948,6 @@ struct bpf_prog_aux {bool func_proto_unreliable;bool tail_call_reachable;bool xdp_has_frags; -bool exception_cb; -bool exception_boundary;bool jits_use_priv_stack;bool priv_stack_requested;bool changes_pkt_data;
@@ -2007,8 +2004,6 @@ struct bpf_prog_aux {int cgroup_atype;/* enum cgroup_bpf_attach_type */ struct bpf_map *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE ];char name[BPF_OBJ_NAME_LEN ]; -u64 (*bpf_exception_cb)(u64 cookie,u64 sp,u64 bp,u64 ,u64 ); -u16 stack_arg_sp_adjust;u16 freplace_link_cnt;/* counts freplace links extending this prog */ #ifdef CONFIG_SECURITY void *security;
include/linux/filter.h +1 -4
@@ -1410,7 +1410,6 @@ u64 bpf_fault_unwind_target(u64 end);bool bpf_jit_supports_stack_args (void );bool bpf_jit_supports_arena_args (void );bool bpf_jit_supports_far_kfunc_call (void ); -bool bpf_jit_supports_exceptions (void );bool bpf_jit_supports_ptr_xchg (void );bool bpf_jit_supports_arena (void );bool bpf_jit_supports_insn (struct bpf_insn *insn,bool in_arena);
@@ -1427,13 +1426,11 @@ bool bpf_jit_supports_fsession(void);* emit_stack_check() knows. * - All may_goto of the prog share one time slice. That is the timed form, which only JITed * progs get, see bpf_do_misc_fixups(). The other form counts in each frame. -* - A walk of the stack finds the prog when there is no room, to tell user space, see -* bpf_prog_report_recursion(). */ static inline bool bpf_prog_has_invocation_budget (const struct bpf_prog *prog) {return (IS_ENABLED (CONFIG_X86_64 ) ||IS_ENABLED (CONFIG_ARM64 )) && prog->jit_requested && -bpf_jit_supports_timed_may_goto () &&bpf_jit_supports_exceptions (); +bpf_jit_supports_timed_may_goto (); }struct bpf_jit_arg_abi {
kernel/bpf/core.c +5 -10
@@ -844,7 +844,7 @@ static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp) {int i; -for (i =0 ; i < fp->aux->real_func_cnt; i++) +for (i =0 ; i < fp->aux->func_cnt; i++)bpf_prog_kallsyms_del (fp->aux->func[i]); }
@@ -1636,7 +1636,7 @@ int bpf_jit_get_func_addr(const struct bpf_prog *prog,if (!extra_pass) addr =NULL ;else if (prog->aux->func && - imm >=0 && imm < prog->aux->real_func_cnt) + imm >=0 && imm < prog->aux->func_cnt) addr = (u8 *)prog->aux->func[imm]->bpf_func;else return -EINVAL ;
@@ -3586,7 +3586,7 @@ static void bpf_prog_free_images(struct work_struct *work)int i; aux = container_of(to_rcu_work(work), struct bpf_prog_aux, rwork); -for (i =0 ; i < aux->real_func_cnt; i++) { +for (i =0 ; i < aux->func_cnt; i++) {/* We can just unlink the subprog poke descriptor table as * it was originally linked to the main program and is also * released along with it.
@@ -3594,7 +3594,7 @@ static void bpf_prog_free_images(struct work_struct *work) aux->func[i]->aux->poke_tab =NULL ;bpf_jit_free (aux->func[i]); } -if (aux->real_func_cnt) { +if (aux->func_cnt) {kvfree (aux->func);bpf_prog_unlock_free (aux->prog); }else {
@@ -3612,7 +3612,7 @@ static void bpf_prog_free_deferred(struct work_struct *work)* A prog that still runs when its last reference goes needs its symbols, * by which its exception table is found. It has ended by now. */ - ksyms = aux->real_func_cnt || !list_empty (&aux->ksym.lnode); + ksyms = aux->func_cnt || !list_empty (&aux->ksym.lnode);bpf_prog_kallsyms_del_all (aux->prog);#ifdef CONFIG_BPF_SYSCALL bpf_free_kfunc_btf_tab (aux->kfunc_btf_tab);
@@ -4042,11 +4042,6 @@ int __weak bpf_arch_text_invalidate(void *dst, size_t len)return -ENOTSUPP ; } -bool __weak bpf_jit_supports_exceptions (void ) -{ -return false; -} -bool __weak bpf_jit_supports_private_stack (void ) {return false;
kernel/bpf/fixups.c +0 -2
@@ -2177,7 +2177,6 @@ static int jit_subprogs(struct bpf_verifier_env *env)*/ func[i]->aux->func = func; func[i]->aux->func_cnt = env->subprog_cnt; - func[i]->aux->real_func_cnt = env->subprog_cnt; }for (i =0 ; i < env->subprog_cnt; i++) { old_bpf_func = func[i]->bpf_func;
@@ -2238,7 +2237,6 @@ static int jit_subprogs(struct bpf_verifier_env *env) prog->aux->fault_pad = func[0 ]->aux->fault_pad; prog->aux->func = func; prog->aux->func_cnt = env->subprog_cnt; - prog->aux->real_func_cnt = env->subprog_cnt; prog->aux->exception_callback_subprog = env->exception_callback_subprog;bpf_prog_jit_attempt_done (prog);return 0 ;
kernel/bpf/helpers.c +7 -46
60 lines not on this page · raw message
kernel/bpf/syscall.c +2 -2
@@ -3216,7 +3216,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at* period before we can tear down JIT memory since symbols * are already exposed under kallsyms. */ -__bpf_prog_put_noref (prog, prog->aux->real_func_cnt); +__bpf_prog_put_noref (prog, prog->aux->func_cnt);return err; free_prog:
@@ -5071,7 +5071,7 @@ static int bpf_prog_map_addrs(const struct bpf_prog *prog, struct maple_tree *mt/* the id of the subprog that starts at insn 'start' */ static u32 bpf_prog_find_func (const struct bpf_prog *prog,u32 start) { -u32 l =0 , r = prog->aux->real_func_cnt, m; +u32 l =0 , r = prog->aux->func_cnt, m;while (r - l >1 ) { m = (l + r) /2 ;
scripts/gdb/linux/bpf.py +2 -2
@@ -88,8 +88,8 @@ def list_progs(): # func[0] is the current prog. aux = prog["aux"] func = aux["func"] - real_func_cnt = int(aux["real_func_cnt"]) - for i in range(1, real_func_cnt): + func_cnt = int(aux["func_cnt"]) + for i in range(1, func_cnt): progs.append(func[i]) return progs
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 48/73 bpf: Find at a site that a frame holds more than a landing pad releases
In reply to Kumar Kartikeya DwivediA landing pad has at most eight releases apart from the sections that it leaves (BPF_PAD_MAX_ENTS). Each reference or lock that a frame holds needs one, and so does a pointer in a hidden slot. A frame that holds more gets no landing pad, wherever the pointers are.
Currently the verifier finds that late. When a state reaches a site, visit_refs() reports "too much is held" only if a reference that has a location would need a ninth release. A pointer without a location waits for the hidden slots, and whether those fit is decided when the pass is over. That is too late for a loop that acquires a reference in each trip and has no exit but a site:
for (;;)
p = bpf_ringbuf_reserve(&rb, 8, 0);A leaked reference is normally found at an exit, and no state of this loop reaches one. Its states hold one more reference with each trip, and the program is rejected only when the budget of the passes is used up.
Count what the frame holds when a state reaches a site, before anything else. If it is more than a landing pad releases, the verifier cannot generate a pad for that state, and a path-sensitive run finds the error after a few trips:
landing pad of may_goto at 12: conflict: too much is held
A lock taken with bpf_res_spin_lock_irqsave() is two references and one release, so it counts once.
What visit_refs() reported until now is a different case. No single state holds too much, but the states that reach the site hold different things, and each needs a release. The log now says "the paths to the site hold more different things than a pad releases" for it.
A may_goto of the program is about to become a site, and a loop whose only exit is its may_goto is then such a loop.
--- include/linux/bpf_verifier.h | 3 ++- kernel/bpf/pads.c | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-)
include/linux/bpf_verifier.h +2 -1
@@ -485,7 +485,8 @@ enum bpf_pad_class {enum bpf_pad_conflict {BPF_NO_CONFLICT ,BPF_CONFLICT_SECTIONS_DIFFER , -BPF_CONFLICT_TOO_MUCH , +BPF_CONFLICT_TOO_MUCH ,/* one state holds more than a pad releases */ +BPF_CONFLICT_PLAN_FULL ,/* the states together hold more different things */ BPF_CONFLICT_SLOTS_FULL ,/* the function has more hidden slots than a pad releases */ BPF_CONFLICT_NO_RELEASE ,BPF_CONFLICT_NOT_ALWAYS_HELD ,
kernel/bpf/pads.c +14 -2
@@ -1236,12 +1236,21 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,const struct bpf_reference_state *ref;struct bpf_pad_ent new, *ent, *prev;struct bpf_pad_nulls nulls; -int i, j, arg, pass, err; +int i, j, arg, pass, pos, err;/* the pad of a call runs after it: its locations are what is live at the next insn */ insn_idx += plan->kind ==BPF_SITE_CALL ;for (i =0 ; i < plan->nr_ents; i++) plan->ents[i].ref =-1 ; +/* +* Each reference needs a release of its own, also a pointer without a location, which takes +* a hidden slot. A loop that acquires in each trip and has no exit but this site is +* rejected here: no state of it reaches an exit, where a leak is found. +*/ +for (i = st->frame[st->curframe]->entry_refs, pos =0 ; i < st->acquired_refs; i++) + pos += !i || st->refs[i -1 ].type !=REF_TYPE_RES_LOCK_IRQ ; +if (pos >BPF_PAD_MAX_ENTS ) +return BPF_CONFLICT_TOO_MUCH ;for (pass =0 ; pass <2 ; pass++) {for (i = st->frame[st->curframe]->entry_refs; i < st->acquired_refs; i++) { ref = &st->refs[i];
@@ -1269,8 +1278,9 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan, ent =match_ent (plan, &new, !pass);if (!ent && !pass)continue ; +/* the states together need more releases than a pad has */ if (!ent && plan->nr_ents ==BPF_PAD_MAX_ENTS ) -return BPF_CONFLICT_TOO_MUCH ; +return BPF_CONFLICT_PLAN_FULL ;if (!ent) ent =add_ent (plan, &new, plan->nr_ents);if (!ent)
@@ -3024,6 +3034,8 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_padstatic const char *const why[] = { [BPF_CONFLICT_SECTIONS_DIFFER ] ="the number of sections differs" , [BPF_CONFLICT_TOO_MUCH ] ="too much is held" , + [BPF_CONFLICT_PLAN_FULL ] = +"the paths to the site hold more different things than a pad releases" , [BPF_CONFLICT_SLOTS_FULL ] ="the function has more hidden slots than a pad has entries" , [BPF_CONFLICT_NO_RELEASE ] ="the program can call nothing that releases a resource" ,
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 48/73] bpf: Find at a site that a frame holds more than a landing pad releases
TL;DR: The new early count in visit_refs() may reject programs that loaded before: at call sites, the hand-over retry that would move a passed reference into the callee is never tried, so loading…
Quoted 1 line
bpf: Find at a site that a frame holds more than a landing pad releases
TL;DR: The new early count in visit_refs() may reject programs that loaded
before: at call sites, the hand-over retry that would move a passed reference into the callee is never tried, so loading fails with "too much is held".
Quoted 3 lines
kernel/bpf/pads.c +0
-0
[ ... ]
kernel/bpf/pads.c static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan, · line 1286
Quoted 10 lines
kernel/bpf/pads.c +9
-0@@ -1269,8 +1278,9 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan, +/* +* Each reference needs a release of its own, also a pointer without a location, which takes +* a hidden slot. A loop that acquires in each trip and has no exit but this site is +* rejected here: no state of it reaches an exit, where a leak is found. +*/ +for (i = st->frame[st->curframe]->entry_refs, pos =0 ; i < st->acquired_refs; i++) + pos += !i || st->refs[i -1 ].type !=REF_TYPE_RES_LOCK_IRQ ; +if (pos >BPF_PAD_MAX_ENTS ) +return BPF_CONFLICT_TOO_MUCH ;
Can this early count make a program fail to load that loaded before the patch?
At a BPF_SITE_CALL plan (check_unwound_arrival()->unwind_frame()-> bpf_pad_visit()->visit_refs()), the caller frame's refs[] can include a pointer P that the caller passed to a static subprog in R1 and kept no copy of. The callee releases P on its normal path, but it can unwind before that release.
Before the patch, a state holding 8 located references plus P filled 8 entries, and P took the no-location branch (plan->no_place = err; continue;). settle_plan() then returned BPF_CONFLICT_NO_PLACE, which conflict_of_ref() treats as a reference conflict, so note_causes() set env->ref_conflict and sub[s].asks_args |= sub[s].releases_args. try_more()->hand_over_more() then made the callee own the argument, and on the next pass the caller held 8 at the call site, which fits.
With the patch, the same first-pass state gives pos = 9 > BPF_PAD_MAX_ENTS, and visit_refs() returns BPF_CONFLICT_TOO_MUCH before the main loop. conflict_of_ref() has no case for it:
switch (plan->conflict) {
case BPF_CONFLICT_NO_PLACE:
...
default:
return false;So note_causes() sets neither ref_conflict nor asks_args, try_more() returns false because of !env->ref_conflict, and the load fails with "too much is held". The hand-over that would have brought the frame within the limit is never tried. The same applies to the takes_refs and handing back steps of try_more(), which are also gated on ref_conflict.
The commit message says "If it is more than a landing pad releases, the verifier cannot generate a pad for that state". That holds for one pass, but at a call site the count includes references that the hand-over passes would move into the callee.
Could the early check skip BPF_SITE_CALL states where the excess is references that bpf_pad_handed_ref() could hand over, or could conflict_of_ref() return true for BPF_CONFLICT_TOO_MUCH when plan->no_place is set?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 49/73 bpf: Cancel the program when the time of its own may_goto is up
In reply to Kumar Kartikeya DwivediA may_goto of the program, which can_loop and cond_break expand to, is a jump that is taken when the time slice of the invocation is over:
do {
p = bpf_map_lookup_elem(&map, &key);
} while (!p && can_loop);
v = *p;Currently the program continues at the target of the jump. Here it would continue with p == NULL, and the verifier rejects it for that. Where the verifier accepts the code at the target, the program continues with half of a result: a list that was not walked to its end, a lock that was not taken. No user of can_loop or cond_break in the selftests or in the scx schedulers is known to recover from that.
A may_goto of the verifier jumps to a landing pad, and the kernel cancels the program. Do the same for a may_goto of the program. The landing pads release what the frames hold, and the program returns the value of its program type.
What changes for programs that load today:
- The code at the target of the jump no longer runs after a time-out. arena_spin_lock() does not return -ETIMEDOUT: the program ends in the lock.
- A program is rejected if the verifier cannot generate a landing pad for a may_goto of the program, or for a call above it.
- A program that was rejected for the code at the target loads, like the loop above.
- A global function with such a loop can unwind, so an extension cannot replace it and fexit cannot attach to it.
- The time that is up stays up for the invocation, as before. After a function that cannot be cancelled has used it up, the next may_goto in a function that can be cancelled ends the program.
A may_goto of the program stays a plain jump in three cases:
- It is 'may_goto +0', or it jumps over nothing but insns like itself. The verifier removes such an insn.
- It is the form that counts trips, where no JIT runs the timed form. BPF_MAX_LOOPS trips are a bound of the loop, not a time that is up.
- Its function cannot be cancelled.
The third case is decided once for all frames of a function, because the verifier rewrites an insn in one way for all of them. The code marks such a function 'stuck'. It does so when a helper without an unwind label for its callback calls the function, and when a frame that cannot be cancelled calls it or reaches its may_goto. A frame of a marked function that has a caller in the program marks what it calls, and skip_faults() sets the same mark. A frame cannot be cancelled if its function has no exit insn, if the program is loaded without CAP_PERFMON, or if it has a caller in the program and the JIT has no unwind_exit.
Three things need care:
- The program can still continue after a time-out in a function that only bpf_loop() or bpf_for_each_map_elem() calls. The existing check at its start returns 1 if the time is up, the helper ends its loop, and the program continues until its next may_goto. The check is not a site. A comment at the check says why.
- retarget_may_gotos() makes the insn jump to its landing pad before dead code is removed. No state takes the jump, so its old target can be dead code. The insn would become 'goto +0', and nothing would stop the loop.
- The jump stays an edge of the control flow graph and of liveness. So a loop whose only exit is its may_goto is not a loop without an exit, and a register that the program reads only at the target is live at the insn, where a landing pad can use it.
In the main pass check_may_goto_site() makes the insn a site of a new kind, BPF_SITE_MAY_GOTO, and hidden slots serve it like a may_goto of the verifier. A function can be marked late in a pass, after a state was cancelled at its may_goto or a frame of it made a call. The verifier then repeats the pass with the mark set from its start. The mark is kept for every later pass. That is safe, because a marked function behaves as it does today. It is also needed: a pass that does not reach the call that sets the mark could reject a program that loads today.
Tests that relied on the jump now expect the value of the program type, use up the time in a function that cannot be cancelled, or give the loop a second exit.
--- include/linux/bpf_verifier.h | 28 +- kernel/bpf/fixups.c | 83 ++++- kernel/bpf/pads.c | 154 +++++++- kernel/bpf/verifier.c | 189 +++++++++- .../selftests/bpf/prog_tests/may_goto_far.c | 23 +- .../selftests/bpf/prog_tests/timed_may_goto.c | 89 ++++- .../selftests/bpf/progs/may_goto_priv_stack.c | 8 +- tools/testing/selftests/bpf/progs/stream.c | 2 +- .../selftests/bpf/progs/timed_may_goto.c | 332 +++++++++++++----- .../selftests/bpf/progs/timed_may_goto_ext.c | 22 +- .../selftests/bpf/progs/timed_may_goto_user.c | 169 +++++++-- .../bpf/progs/verifier_arena_stack.c | 27 +- .../bpf/progs/verifier_bpf_fastcall.c | 12 +- .../selftests/bpf/progs/verifier_equations.c | 9 +- .../bpf/progs/verifier_iterating_callbacks.c | 25 +- .../bpf/progs/verifier_linked_scalars.c | 7 +- .../selftests/bpf/progs/verifier_may_goto_1.c | 17 +- .../selftests/bpf/progs/verifier_passes.c | 26 +- .../selftests/bpf/progs/verifier_patch_list.c | 100 ++++-- .../selftests/bpf/progs/verifier_stack_arg.c | 8 +- 20 files changed, 1082 insertions(+), 248 deletions(-)
include/linux/bpf_verifier.h +26 -2
@@ -462,6 +462,7 @@ enum bpf_site_kind {BPF_SITE_CALL ,BPF_SITE_FAULT ,/* an access to arena that faults */ BPF_SITE_THROW ,/* a call of bpf_throw() */ + BPF_SITE_MAY_GOTO, /* a may_goto of the program, see check_may_goto_site() */ };/* The classes of resources that a landing pad releases */
@@ -1310,6 +1311,8 @@ struct bpf_insn_aux_data {/* below flags are initialized once */ u32 bb_end:1; /* last instruction of a basic block */ u32 guard_place:1; /* it is the place for may_goto if the loop needs one */ +/* a may_goto that jumps over nothing but may_gotos: bpf_opt_remove_nops() removes it */ + u32 may_goto_nop:1;/* true if instruction is a call to a helper function that * accepts callback function as a parameter. */
@@ -1548,11 +1551,27 @@ struct bpf_subprog_info { bool did_unwind: 1;/* * It did so at a site with no other way out, see bpf_pads_must_unwind(). A fault in arena -* has one: the access is skipped. +* has one: the access is skipped. So has a may_goto of the program: in a stuck subprog it +* jumps. */ bool must_unwind: 1; -/* it did so at a site that the program keeps for sure, see site_is_certain() */ +/* +* It did so at a site that the program keeps for sure, see site_is_certain(), and that is +* no access to arena. +*/ bool unwinds_for_sure: 1; +/* +* may_goto_unwinds: in this pass a frame of it was cancelled at a may_goto of the program. +* stuck: it cannot be cancelled. In all its frames, in this pass and in every later one, a +* may_goto of the program jumps, see stuck_frame_calls(). +*/ + bool may_goto_unwinds: 1; + bool stuck: 1; +/* +* In this pass a frame of it made a call that did not mark the callee stuck. If the subprog +* is marked stuck later, the pass is repeated, see stuck_frame_calls(). +*/ + bool made_calls: 1;/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */ bool below_conflict: 1;/*
@@ -1560,6 +1579,8 @@ struct bpf_subprog_info {* references the arguments of the call had, see bpf_pad_states_meet() */ bool arg_refs_differ: 1; +/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */ +u8 left_at;/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */ u8 no_slots: 4;/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */
@@ -2262,6 +2283,7 @@ void bpf_flow_new_pass(struct bpf_verifier_env *env);void bpf_flow_drop_guards (struct bpf_verifier_env *env);bool bpf_flow_guard_is_guess (struct bpf_verifier_env *env,int idx);int bpf_flow_place_guards (struct bpf_verifier_env *env); +void bpf_mark_may_goto_nops (struct bpf_verifier_env *env);/* verifier.c, for flow.c */ int bpf_flow_loop_enter (struct bpf_verifier_env *env,struct bpf_loop **backedge_loop,bool *starts_leftover);
@@ -2326,6 +2348,8 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan, struct bpf_insn *buf, struct bpf_insn_aux_data *aux);void bpf_pad_log (struct bpf_verifier_env *env,int insn_idx,const struct bpf_pad_plan *plan);void bpf_pad_log_handed_over (struct bpf_verifier_env *env,int subprog,u8 args); +void bpf_pad_note_left (struct bpf_verifier_env *env,struct bpf_subprog_info *sub, +const struct bpf_pad_plan *plan,enum bpf_site_kind kind);bool bpf_pad_must_unwind (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan);void bpf_pads_must_unwind (struct bpf_verifier_env *env);void bpf_pads_mark_used (struct bpf_verifier_env *env);
kernel/bpf/fixups.c +79 -4
119 lines not on this page · raw message
kernel/bpf/pads.c +141 -13
253 lines not on this page · raw message
kernel/bpf/verifier.c +178 -11
298 lines not on this page · raw message
tools/testing/selftests/bpf/prog_tests/may_goto_far.c +14 -9
@@ -18,7 +18,7 @@ static struct bpf_insn *fill(struct bpf_insn *insn, int cnt, int reg)* away: * * r6 = r7 = 0, but not a constant for the verifier -* r8 = 2 +* r8 = 3 * r9 = 0 * r0 = r8 x FILL_CNT or 1 * 1: if r6 == r9 goto +1
@@ -31,16 +31,21 @@ static struct bpf_insn *fill(struct bpf_insn *insn, int cnt, int reg)* 3: r0 = r8 x N when off is positive * 4: exit * -* The prog returns 0 when may_goto jumps to its target and 2 when -* it lands in one of 'r0 = r8' areas. There are no constants between -* may_goto and its target to keep the distance when constants are blinded. +* When may_goto expires the prog is unwound: the insn does not go to the +* target that the program gives it, but to a landing pad behind the last +* insn, which is far too. It is a tc prog: it returns 2, TC_ACT_SHOT, when +* may_goto jumps to the pad, 3 when it lands in one of the 'r0 = r8' areas, +* and 0, which r0 has in the loop, when it lands on an exit: the last one +* is one insn short of the pad. There are no constants between may_goto +* and its target to keep the distance when constants are blinded. * * With 'subprog' all of that is a subprog. */ static void test_far (int off,bool subprog) { - LIBBPF_OPTS(bpf_prog_load_opts, opts, .prog_flags = BPF_F_SLEEPABLE); -LIBBPF_OPTS (bpf_test_run_opts, topts); +LIBBPF_OPTS (bpf_prog_load_opts, opts); +char pkt[64 ] = {}; + LIBBPF_OPTS(bpf_test_run_opts, topts, .data_in = pkt, .data_size_in = sizeof(pkt));int front = off <0 ?1 :FILL_CNT ;int mid = off <0 ? -off -5 :1 ;int back = off <0 ?FILL_CNT : off -1 ;
@@ -61,7 +66,7 @@ static void test_far(int off, bool subprog) *insn++ =BPF_ALU64_IMM (BPF_RSH ,BPF_REG_6 ,63 ); *insn++ =BPF_MOV64_REG (BPF_REG_7 ,BPF_REG_0 ); *insn++ =BPF_ALU64_IMM (BPF_RSH ,BPF_REG_7 ,63 ); - *insn++ =BPF_MOV64_IMM (BPF_REG_8 ,2 ); + *insn++ =BPF_MOV64_IMM (BPF_REG_8 ,3 ); *insn++ =BPF_MOV64_IMM (BPF_REG_9 ,0 ); insn =fill (insn, front,BPF_REG_8 ); *insn++ =BPF_JMP_REG (BPF_JEQ ,BPF_REG_6 ,BPF_REG_9 ,1 );
@@ -74,14 +79,14 @@ static void test_far(int off, bool subprog) insn =fill (insn, back,BPF_REG_8 ); *insn++ =BPF_EXIT_INSN (); - fd =bpf_prog_load (BPF_PROG_TYPE_SYSCALL ,NULL ,"GPL" , insns, insn - insns, &opts); + fd =bpf_prog_load (BPF_PROG_TYPE_SCHED_CLS ,NULL ,"GPL" , insns, insn - insns, &opts);free (insns);if (!ASSERT_GE (fd,0 ,"prog_load" ))return ; err =bpf_prog_test_run_opts (fd, &topts);ASSERT_OK (err,"test_run" ); -ASSERT_EQ (topts.retval,0 ,"retval" ); +ASSERT_EQ (topts.retval,2 ,"retval" );close (fd); }
tools/testing/selftests/bpf/prog_tests/timed_may_goto.c +71 -18
140 lines not on this page · raw message
tools/testing/selftests/bpf/progs/may_goto_priv_stack.c +5 -3
@@ -5,13 +5,15 @@#include "../../../include/linux/filter.h" #include "bpf_misc.h" -/* r0-r5 after the loop and the number of iterations */ +/* r0-r5 in the last trip of the loop and the number of iterations */ __u64 regs_64[7 ];__u64 regs_128[7 ];/* * fentry prog with 64 or more bytes of stack uses private stack. * Loop until may_goto expires. r0-r5 should stay zero. +* When may_goto expires the prog is unwound: what follows the loop does not run, so each trip +* stores the registers. */ #define TIMED_MAY_GOTO_PRIV_STACK (size, func) \ SEC("fentry/" #func) \
@@ -30,7 +32,6 @@ __naked void priv_stack_##size(void) \"1:" \".8byte %[may_goto];" \"r6 += 1;" \ -"goto 1b;" \"*(u64 *)(r7 + 0) = r0;" \"*(u64 *)(r7 + 8) = r1;" \"*(u64 *)(r7 + 16) = r2;" \
@@ -38,11 +39,12 @@ __naked void priv_stack_##size(void) \"*(u64 *)(r7 + 32) = r4;" \"*(u64 *)(r7 + 40) = r5;" \"*(u64 *)(r7 + 48) = r6;" \ +"goto 1b;" \"r0 = 0;" \"exit;" \ : \ : [regs]"i"(®s_##size), \ - __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 2, 0)) \ + __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 9, 0)) \ : __clobber_all); \ }
tools/testing/selftests/bpf/progs/stream.c +1 -1
@@ -74,7 +74,7 @@ __arch_arm64__arch_s390x __arch_riscv64__arch_loongarch -__success __retval(0) +__success __retval(-ECANCELED) __stderr("ERROR: Timeout detected for may_goto instruction") __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}") __stderr("Call trace:\n"
tools/testing/selftests/bpf/progs/timed_may_goto.c +247 -85
618 lines not on this page · raw message
tools/testing/selftests/bpf/progs/timed_may_goto_ext.c +20 -2
@@ -15,9 +15,27 @@ static __noinline int spins(void)return bpf_ktime_get_ns () - t0 >100 *1000 *1000 ; } -/* Each call of an extension prog is an invocation: one of its two calls spins. */ +/* +* Each call of an extension prog is an invocation, with its own time. When that is up the +* extension is unwound, to its own exit: the function that it replaces returns the value of an +* unwound prog of the type that it extends, and the caller goes on. +*/ +static __noinline int counts_to_1000(void) +{ +int i, cnt =0 ; + +for (i =0 ; i <1000 && can_loop; i++) + cnt++; +return cnt; +} + +/* The calls that had the time for a short loop before they used it up */ +int calls, counted_to_1000; + SEC("freplace")int replacement (int i) { -return spins () +spins () + i; + calls++; + counted_to_1000 +=counts_to_1000 () ==1000 ; +return 10 +spins () +spins () + i; }
tools/testing/selftests/bpf/progs/timed_may_goto_user.c +136 -33
307 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +21 -6
@@ -1032,7 +1032,11 @@ __naked void may_goto_keeps_r12(void) : __clobber_all); } -/* counts the calls and spins until the time of may_goto is up */ +/* +* Counts the calls, takes its time in a loop that has a trip count, and gets to one may_goto. The +* one that finds the time up is the last insn of its kind in the call: the callback returns, and +* nothing is unwound. +*/ static __naked __noinline __used long spin_cb (void ) { asm volatile (
@@ -1040,9 +1044,12 @@ static __naked __noinline __used long spin_cb(void)"r3 = *(u64 *)(r2 + 0);" "r3 += 1;" "*(u64 *)(r2 + 0) = r3;" +"r4 = 1000;" "1:" +"r4 += -1;" +"if r4 != 0 goto 1b;" ".8byte %[may_goto];" -"goto 1b;" +"r4 = 1;" "r0 = 0;" "exit;" :
@@ -1051,10 +1058,16 @@ static __naked __noinline __used long spin_cb(void) : __clobber_all); } +/* +* The call after the one that found the time up returns 1 in its first insns, before it takes a +* frame in the stack in arena: bpf_loop() ends, and the prog, which has no may_goto, goes on. +* The helper counts one call more than the callback, some calls ran, and the slot of the prog in +* the stack in arena is as it was: 20 + 1 + 100. +*/ SEC("syscall") __description("arena stack: bpf_loop() ends when the time of may_goto is up") __success __retval(121) -/* the second call of the callback returns 1 before it takes a stack */ +/* 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 ("exit" )
@@ -1075,10 +1088,12 @@ __naked void loop_ends_early(void)"r3 += -8;" "r4 = 0;" "call %[bpf_loop];" -/* 2 calls, 1 of them ran */ -"r0 *= 10;" +/* the last call did not run */ "r1 = *(u64 *)(r10 - 8);" -"r0 += r1;" +"r0 -= r1;" +"r0 *= 20;" +"if r1 == 0 goto +1;" +"r0 += 1;" ".8byte %[ldx];" /* r1 = *(u64 *)(r12 - 8) */ "r0 += r1;" "exit;"
tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c +10 -2
@@ -949,7 +949,8 @@ __xlated("...") __xlated("10: r2 = ") __xlated("12: r2 = &(void __percpu *)(r2)")__xlated ("13: r13 = *(u64 *)(r2 +0)" ) -__xlated("14: if r13 == 0x0 goto pc+6") +/* 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" )
@@ -958,6 +959,9 @@ __xlated("19: *(u64 *)(r2 +0) = r13")/* may_goto expansion ends */ __xlated("20: *(u64 *)(r10 -8) = r1")__xlated ("21: exit" ) +/* the landing pad */ +__xlated("22: r0 = 0") +__xlated("23: exit") __success__naked void may_goto_interaction_x86_64 (void ) {
@@ -992,7 +996,8 @@ __xlated("7: call bpf_get_smp_processor_id") __xlated("8: r2 = ") __xlated("10: r2 = &(void __percpu *)(r2)")__xlated ("11: r13 = *(u64 *)(r2 +0)" ) -__xlated("12: if r13 == 0x0 goto pc+6") +/* 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" )
@@ -1001,6 +1006,9 @@ __xlated("17: *(u64 *)(r2 +0) = r13")/* may_goto expansion ends */ __xlated("18: *(u64 *)(r10 -8) = r1")__xlated ("19: exit" ) +/* the landing pad */ +__xlated("20: r0 = 0") +__xlated("21: exit") __success__naked void may_goto_interaction (void ) {
tools/testing/selftests/bpf/progs/verifier_equations.c +7 -2
@@ -821,12 +821,17 @@ ONE_TEST(cond_of_low_half_bad, BAD_WRITE, 8, COND_OF_LOW_HALF(-1)) ONE_TEST(and_of_two_values, __success, 8, TWO_ANDS(7))ONE_TEST (and_of_two_values_bad,BAD_WRITE ,8 ,TWO_ANDS (255 )) -/* The jump compares a number with itself. It gives no trip count. */ +/* +* The jump compares a number with itself. It gives no trip count. The loop is left when the clock +* says 0: the jump of may_goto ends the prog. + */ONE_TEST (jump_that_does_not_count, __failure __msg("invalid write to stack R8 off=0 size=1"), 8, "r7 = 0; r8 = r10; r8 += -24; r9 = r10; r9 += -256;" "1:" "r0 = 0;" -"2:" MAY_GOTO(2) +"2:" "call %[bpf_ktime_get_ns];" + "if r0 == 0 goto +3;" + MAY_GOTO(2)"r9 += 1;" "if r9 == r9 goto 2b;" "*(u8 *)(r8 + 0) = r7;"
tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c +14 -11
@@ -590,19 +590,24 @@ int cond_break3(const void *ctx)return loop (); } +/* +* A socket filter that is unwound returns 0. Where may_goto jumps, without a JIT, the prog goes +* on and returns 1. +*/ SEC("socket") -__success __retval(1) +__load_if_JITed() +__success __retval(0) int cond_break4(const void *ctx) {int cnt = zero;for (;;) { -/* should eventually break out of the loop */ +/* should eventually end the prog, and not break out of the loop */ cond_break; cnt++; } -/* if we looped a bit, it's a success */ -return cnt >1 ?1 :0 ; +/* if we looped a bit, it's 1 */ +return cnt >1 ?1 :2 ; } static __noinline int static_subprog(void)
@@ -618,24 +623,22 @@ static __noinline int static_subprog(void) } SEC("socket") -__success __retval(1) +__load_if_JITed() +__success __retval(0) int cond_break5(const void *ctx) {int cnt1 = zero, cnt2; -/* -* There is one time slice for all may_goto of the prog. When it's used up a function that -* is called after that makes no iteration. So this loop has an end. -*/ +/* This loop has an end: it does not use up the time slice of the prog. */ for (; cnt1 <100 ;) { cond_break; cnt1++; } +/* The loop of the subprog does. The prog is unwound from there. */ cnt2 =static_subprog (); -/* main and subprog have to loop a bit */ -return cnt1 >1 && cnt2 >1 ?1 :0 ; +return cnt1 >1 && cnt2 >1 ?1 :2 ; }#define ARR2_SZ 1000
tools/testing/selftests/bpf/progs/verifier_linked_scalars.c +6 -1
@@ -812,7 +812,10 @@ LINK_TEST(and_cuts_in_the_middle, TOO_FAR,LINK_TEST (and_rounds_down_far,TOO_FAR ,"r6 &= 0xff; r7 = r6; r7 &= 0xf0; if r7 > 7 goto 1f;" ) -/* r7 is 4 * trip + 8, r8 is 8 * trip. The loop has no trip count, so the products wrap. */ +/* +* r7 is 4 * trip + 8, r8 is 8 * trip. The loop has no trip count, so the products wrap. It is +* left when the random number is 0: the jump of may_goto ends the prog. + */#define STRIDE_TEST (name, verdict, body) \ SEC("raw_tp") \ verdict \
@@ -823,6 +826,8 @@ __naked void name(void) \"r8 = 0;" \"*(u64 *)(r10 - 8) = r8;" \"2:" \ +"call %[bpf_get_prandom_u32];" \ +"if r0 == 0 goto +4;" \".8byte %[may_goto];" \"r7 += 4;" \"r8 += 8;" \
tools/testing/selftests/bpf/progs/verifier_may_goto_1.c +12 -5
@@ -94,11 +94,11 @@ __xlated("2: r0 = &(void __percpu *)(r0)") __xlated("3: *(u64 *)(r0 +0) = 65535") __xlated("4: *(u64 *)(r0 +8) = 0")__xlated ("5: *(u64 *)(r0 +16) = 0" ) -/* may_goto, r0 is dead */ +/* may_goto, r0 is dead. When the time is up it goes to the landing pad of the prog. */ __xlated("6: r0 = ") __xlated("8: r0 = &(void __percpu *)(r0)") __xlated("9: r13 = *(u64 *)(r0 +0)") -__xlated("10: if r13 == 0x0 goto pc+6") +__xlated("10: if r13 == 0x0 goto pc+8") __xlated("11: r13 -= 1") __xlated("12: if r13 != 0x0 goto pc+2")__xlated ("13: r13 = r0" )
@@ -107,6 +107,9 @@ __xlated("15: *(u64 *)(r0 +0) = r13") __xlated("16: r0 = 1") __xlated("17: r0 = 2")__xlated ("18: exit" ) +/* the landing pad */ +__xlated("19: r0 = 0") +__xlated("20: exit") __success__naked void may_goto_batch_2 (void ) {
@@ -125,6 +128,8 @@ __naked void may_goto_batch_2(void)/* * Use bpf_get_prandom_u32() to prevent DCE from removing the checks. * retval: 0=all ok, 1-6=R0-R5 clobbered. +* The loop makes more trips than may_goto counts before it reads the clock, and ends by its own +* count: a loop that waits for its time to be up ends the prog, and the checks never run. */ SEC("syscall")__description ("timed may_goto preserves R0-R5" )
@@ -152,8 +157,11 @@ __naked void timed_may_goto_preserves_regs(void)"r4 += r6;" "r5 = 0x6666;" "r5 += r6;" +"r7 = 70000;" +"7:" ".8byte %[may_goto];" -".8byte %[loop];" +"r7 -= 1;" +"if r7 != 0 goto 7b;" "r0 -= r6;" "r1 -= r6;" "r2 -= r6;"
@@ -176,8 +184,7 @@ __naked void timed_may_goto_preserves_regs(void) "6: r0 = 6; exit;" : : __imm(bpf_get_prandom_u32), - __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 1, 0)), - __imm_insn(loop, BPF_RAW_INSN(BPF_JMP | BPF_JA, 0, 0, -2, 0)) + __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 2, 0)) : __clobber_all); }
tools/testing/selftests/bpf/progs/verifier_passes.c +21 -5
@@ -823,8 +823,10 @@ __naked void thresholds_over_budget(void)"r0 = *(u8 *)(r1 + 0);" ".rept 500;" "r6 = 0;" -"3:" MAY_GOTO(10) +"3:" MAY_GOTO(11)"call %[bpf_get_prandom_u32];" +/* the way to what follows the loop: the jump of may_goto ends the prog */ +"if r0 == 2 goto 5f;" "if r0 & 1 goto 4f;" "if r6 >= 60000 goto 4f;" "r6 += 1;"
@@ -834,7 +836,7 @@ __naked void thresholds_over_budget(void)"r1 = 0;" "call long_dead_code;" "goto 3b;" -"r6 >>= 10;" +"5: r6 >>= 10;" "r1 = r9;" "r1 += r6;" "r0 = *(u8 *)(r1 + 0);"
@@ -2577,13 +2579,21 @@ int leak_made_up_in_loop(struct __sk_buff *skb)return 0 ; } +/* +* The time of may_goto that is up ends the prog, and no state takes its jump. These loops have +* another way out, so that what follows them is verified. +*/ +#define OR_BREAK if (bpf_get_prandom_u32() & 1) break + SEC("tc") __description("held: a loop acquires and does not release") __failure __msg("BPF_EXIT instruction in main prog cannot be used inside bpf_preempt_disable") int loop_only_acquires(void *unused) { -while (can_loop) +while (can_loop) { +OR_BREAK ;bpf_preempt_disable (); + }return 0 ; }
@@ -2591,6 +2601,7 @@ int loop_only_acquires(void *unused)void *prev =NULL , *cur =NULL ; \ \while (can_loop) { \ +OR_BREAK ; \if (prev) \bpf_ringbuf_discard (prev,0 ); \ prev = cur; \
@@ -2625,8 +2636,10 @@ int loop_drops_the_pointer(void *unused) {void *cur =NULL ; -while (can_loop) +while (can_loop) { +OR_BREAK ; cur =bpf_ringbuf_reserve (&rb,8 ,0 ); + }if (cur)bpf_ringbuf_discard (cur,0 );return 0 ;
@@ -3120,7 +3133,10 @@ __naked void peel_does_not_starve(void) { ASM(VALUE_IN_R9 "r6 = 0;" -"1:" MAY_GOTO(2) + /* the way to what follows the loop: the jump of may_goto ends the prog */ +"1: call %[bpf_get_prandom_u32];" + "if r0 == 0 goto +3;" + MAY_GOTO(2)"r6 += 1;" "goto 1b;" "call %[bpf_get_prandom_u32];"
tools/testing/selftests/bpf/progs/verifier_patch_list.c +67 -33
165 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_stack_arg.c +6 -2
@@ -982,9 +982,13 @@ static long spins_then_reads_8args(long a, long b, long c, long d, long e, long ); } +/* +* The callee is unwound when the time is up: it does not get to the loads of its args, which +* are behind the jump of may_goto, and tc drops the packet. +*/ SEC("tc") -__description("stack_arg: the time of may_goto is up, then the callee reads its args") -__success __retval(876) +__description("stack_arg: the time of may_goto is up, the callee with args in the stack is unwound") +__success __retval(2) __naked void stack_arg_may_goto_timeout_in_callee(void) { asm volatile (
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up
TL;DR: - Selftests may fail on JITs without unwind support (s390x, riscv64, powerpc64, loongarch): may_goto_far, cond_break5, stack_arg - Inaccurate may_goto_nop comment and commit message…
Quoted 1 line
bpf: Cancel the program when the time of its own
may_gotois up
TL;DR:
- Selftests may fail on JITs without unwind support (s390x, riscv64, powerpc64, loongarch): may_goto_far, cond_break5, stack_arg
- Inaccurate may_goto_nop comment and commit message
- Misplaced prototype and stale test comment (nits)
Quoted 3 lines
include/linux/bpf_verifier.h +0
-0
[ ... ]
include/linux/bpf_verifier.h struct bpf_insn_aux_data { · line 1315
Quoted 6 lines
include/linux/bpf_verifier.h +2
-0@@ -1310,6 +1311,8 @@ struct bpf_insn_aux_data {/* below flags are initialized once */ u32 bb_end:1; /* last instruction of a basic block */ u32 guard_place:1; /* it is the place for may_goto if the loop needs one */ +/* a may_goto that jumps over nothing but may_gotos: bpf_opt_remove_nops() removes it */ + u32 may_goto_nop:1;
Does this comment match what bpf_mark_may_goto_nops() actually marks?
The walk also skips 'ja' nops and every self addr_space_cast, so in 'may_goto +1; ja +0; r0 = 0' the may_goto is marked even though it does not jump over only may_gotos.
Also, bpf_opt_remove_nops() does not always remove a marked insn. Its own comment says "If the cast stays, so does the may_goto that jumps over it", and insn_is_nop() keeps insns with indirect_target or nospec set, which bpf_mark_may_goto_nops() does not check. When the program is not is_priv, sanitize_dead_code() runs and no nops are removed at all.
The commit message repeats this with "The verifier removes such an insn". Would something like "a may_goto that jumps only over nops and casts that may become nops; it is not a site, and bpf_opt_remove_nops() usually removes it" be accurate?
[ ... ]
include/linux/bpf_verifier.h void bpf_flow_new_pass(struct bpf_verifier_env *env); · line 2287
Quoted 6 lines
include/linux/bpf_verifier.h +1
-0@@ -2262,6 +2283,7 @@ void bpf_flow_new_pass(struct bpf_verifier_env *env);void bpf_flow_drop_guards (struct bpf_verifier_env *env);bool bpf_flow_guard_is_guess (struct bpf_verifier_env *env,int idx);int bpf_flow_place_guards (struct bpf_verifier_env *env); +void bpf_mark_may_goto_nops (struct bpf_verifier_env *env);/* verifier.c, for flow.c */
this isn't a bug, but this prototype sits in the flow.c block of bpf_verifier.h while bpf_mark_may_goto_nops() is defined in kernel/bpf/fixups.c and called from bpf_check(). Could it move to the '/* Functions in fixups.c, called from bpf_check() */' block next to bpf_opt_remove_nops() and bpf_lower_cast_mov()?
[ ... ]
Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/may_goto_far.c +0
-0
[ ... ]
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/may_goto_far.c +1
-1@@ -74,14 +79,14 @@ static void test_far(int off, bool subprog) insn =fill (insn, back,BPF_REG_8 ); *insn++ =BPF_EXIT_INSN (); - fd =bpf_prog_load (BPF_PROG_TYPE_SYSCALL ,NULL ,"GPL" , insns, insn - insns, &opts); + fd =bpf_prog_load (BPF_PROG_TYPE_SCHED_CLS ,NULL ,"GPL" , insns, insn - insns, &opts);
tools/testing/selftests/bpf/prog_tests/may_goto_far.c static void test_far(int off, bool subprog) · line 91
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/may_goto_far.c +1
-1free (insns);if (!ASSERT_GE (fd,0 ,"prog_load" ))return ; err =bpf_prog_test_run_opts (fd, &topts);ASSERT_OK (err,"test_run" ); -ASSERT_EQ (topts.retval,0 ,"retval" ); +ASSERT_EQ (topts.retval,2 ,"retval" );close (fd); }
Does this expectation hold on every architecture? Retval 2 only holds where the may_goto is a cancellation site. For the four 'subprog' subtests the may_goto is in subprog 1, which has a caller in the program, so it can be cancelled only when bail_unwinds is set:
si[s].bail_unwinds = si[s].can_unwind ||
(s && env->prog->jit_requested &&
bpf_jit_supports_unwind() && ...);Only the x86 and arm64 JITs override bpf_jit_supports_unwind(). On s390, powerpc, riscv and loongarch, which do support the timed may_goto, frame_cannot_unwind() returns BPF_CONFLICT_CANNOT_UNWIND, the subprog is marked stuck and the insn stays a plain jump:
if (sub->stuck || frame_cannot_unwind(env, env->cur_state)) {
...
sub->stuck = true;
return 0;
}After the time is up the jump goes to the target the program gives it, r0 is 0 from 'r0 = r9', and the program returns 0, so ASSERT_EQ(topts.retval,
2) fails. The same happens with the interpreter (bpf_jit_enable=0), where jit_requested is false and every subtest returns 0.
may_goto_far is not in DENYLIST.s390x, and s390x runs test_progs in BPF CI. timed_may_goto.c, in contrast, skips when !is_jit_enabled() and stops before its unwinding checks on anything but x86_64 and aarch64.
Should the subprog subtests be skipped, or expect 0, when the JIT cannot unwind, and should the test skip without a JIT?
Also, this isn't a bug, but the header comment above test_far() still begins 'Syscall prog that loops until may_goto expires', while the load now uses BPF_PROG_TYPE_SCHED_CLS.
[ ... ]
Quoted 3 lines
tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c +0
-0
[ ... ]
Quoted 15 lines
SEC("socket")tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c +3
-5-__success __retval(1) +__load_if_JITed() +__success __retval(0)int cond_break5 (const void *ctx) {int cnt1 = zero, cnt2; -/* -* There is one time slice for all may_goto of the prog. When it's used up a function that -* is called after that makes no iteration. So this loop has an end. -*/ +/* This loop has an end: it does not use up the time slice of the prog. */ for (; cnt1 <100 ;) { cond_break;
tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c static __noinline int static_subprog(void) · line 642
Quoted 10 lines
tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c +2
-2cnt1++; } +/* The loop of the subprog does. The prog is unwound from there. */ cnt2 =static_subprog (); -/* main and subprog have to loop a bit */ -return cnt1 >1 && cnt2 >1 ?1 :0 ; +return cnt1 >1 && cnt2 >1 ?1 :2 ; }
Will cond_break5 pass on JITs that cannot unwind? __load_if_JITed() only skips the interpreter, and the test has no __arch_x86_64/__arch_arm64 tag.
The time slice is used up in static_subprog(), whose frame has a caller in the program. Its cond_break is cancelled only if the subprog has bail_unwinds, and frame_cannot_unwind() returns BPF_CONFLICT_CANNOT_UNWIND for '!frame_is_top(st) && !sub->bail_unwinds'. Only x86 and arm64 override bpf_jit_supports_unwind(); s390x, riscv64, powerpc64 and loongarch use the weak default of false but return true from bpf_jit_supports_timed_may_goto().
There check_may_goto_site() marks static_subprog stuck and the may_goto stays a plain jump. The commit message says this too: "a frame cannot be cancelled if ... it has a caller in the program and the JIT has no unwind_exit". static_subprog() then leaves its loop with a large cnt, main has no may_goto after the call, and the program returns 1 instead of 0.
Before this patch the test expected 1 and passed on every JIT. Now verifier_iterating_callbacks/cond_break5 would fail on s390x, which BPF CI runs, and on riscv64, powerpc64 and loongarch. cond_break4 is not affected because its loop is in the main prog.
Should cond_break5 carry the same __arch_x86_64/__arch_arm64 tags used by the other unwinding tests in this patch, or expect 1 where the subprog cannot unwind?
[ ... ]
Quoted 3 lines
tools/testing/selftests/bpf/progs/verifier_stack_arg.c +0
-0
[ ... ]
Quoted 4 lines
tools/testing/selftests/bpf/progs/verifier_stack_arg.c +0
-0@@ -982,9 +982,13 @@ static long spins_then_reads_8args(long a, long b, long c, long d, long e, long ); }
tools/testing/selftests/bpf/progs/verifier_stack_arg.c static long spins_then_reads_8args(long a, long b, long c, long d, long e, long · line 992
Quoted 10 lines
tools/testing/selftests/bpf/progs/verifier_stack_arg.c +6
-2+/* +* The callee is unwound when the time is up: it does not get to the loads of its args, which +* are behind the jump of may_goto, and tc drops the packet. +*/ SEC("tc") -__description("stack_arg: the time of may_goto is up, then the callee reads its args") -__success __retval(876) +__description("stack_arg: the time of may_goto is up, the callee with args in the stack is unwound") +__success __retval(2)__naked void stack_arg_may_goto_timeout_in_callee (void )
Does __retval(2) hold on riscv64? This test has no __arch_ tag and sits in the block guarded by:
#if (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64) || \
(defined(__TARGET_ARCH_riscv) && __riscv_xlen == 64)) && \
defined(__BPF_FEATURE_STACK_ARGUMENT)riscv64 implements bpf_jit_supports_timed_may_goto() but not bpf_jit_supports_unwind(). spins_then_reads_8args() is a subprog called from main, so frame_is_top() is false and bail_unwinds is false there. frame_cannot_unwind() then returns BPF_CONFLICT_CANNOT_UNWIND, check_may_goto_site() marks the function stuck and the may_goto stays a plain jump. When the time is up the callee loads its stack args and the program returns 876 as before, so verifier_stack_arg fails on riscv64 (it is not in DENYLIST.riscv64).
verifier_patch_list.c in the same patch handles this split with __arch_x86_64 __arch_arm64 on patch_list_insert_in_front and a separate patch_list_insert_in_front_no_pads for s390x, riscv64 and loongarch. Should this test get the same treatment, with a riscv64 variant that still expects 876?
[ ... ]
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 50/73 bpf: Reject a program that has no landing pad for a fault in arena
In reply to Kumar Kartikeya DwivediCurrently a fault in arena cancels the program only where the verifier has a landing pad for the access. Where it has none, the access is skipped and the program continues. Here the states at the load are in different numbers of sections, so a fault in the load is skipped:
bpf_rcu_read_lock();
if (x)
bpf_preempt_disable();
v = node->val; /* no page at node */So a program that loads does not tell which of its faults end it.
Remove this fallback. An access to arena becomes a site like any other, and hidden slots serve it. In the example the function gets a hidden slot for the section that only some paths enter, and the fault cancels the program. check_arena_site() marks a site without a landing pad as failed, as unwind_frame() does. So the verifier also lets calls clear hidden slots and takes a hand-over back before it rejects for an access to arena.
What changes for programs that load today:
- Every fault in arena in a function that can be cancelled ends the program.
- A program is rejected if the verifier cannot generate a landing pad, even with hidden slots, for an access to arena in such a function or for a call above the access. Until now it loaded and the access was skipped. An access in nine RCU sections is an example, because a landing pad leaves at most eight.
An access that faults is still skipped where the JIT has no unwind_exit, which is every JIT but those of x86-64 and arm64, and in a function that cannot be cancelled. That is the 'stuck' mark that makes a may_goto of the program a plain jump. It holds for all frames of a function, so an async callback that is marked skips the access also when the kernel calls it.
One case remains in which a call gets no landing pad and the program loads. A cancelled state comes back to a call whose frame cannot be cancelled, and the functions below the call were cancelled only at accesses to arena and at their own may_goto. bpf_pad_skip_faults(), which was skip_faults(), marks those functions and has the pass repeated.
As today, a fault does not cancel the caller across three boundaries: an extension ends at its own exit, the callee of a tail call that a subprog makes returns into that subprog, and what a kfunc or a helper touches in arena is not an access of the program.
--- include/linux/bpf_verifier.h | 25 +-- kernel/bpf/pads.c | 161 +++++++++++------- kernel/bpf/verifier.c | 161 +++++++----------- .../selftests/bpf/progs/arena_atomics.c | 99 +++++++++-- .../selftests/bpf/progs/arena_skipped.h | 11 -- .../selftests/bpf/progs/verifier_arena.c | 43 +---- .../bpf/progs/verifier_arena_large.c | 54 +----- 7 files changed, 272 insertions(+), 282 deletions(-) delete mode 100644 tools/testing/selftests/bpf/progs/arena_skipped.h
include/linux/bpf_verifier.h +15 -10
@@ -1296,7 +1296,7 @@ struct bpf_insn_aux_data {/* a subprog returned here without a pointer to release, and its R0 may not be 0 */ u64 call_brings_nothing:1;/* An access to arena, see check_arena_site() */ - u64 fault_skips:1; /* a fault is skipped: no pad, or the frame cannot be cancelled */ + u64 fault_skips:1; /* a fault is skipped: its subprog cannot be cancelled */ u64 fault_empty:1; /* in this pass a state that holds nothing passed without a record */ u64 fault_unwinds:1; /* in the final program a fault goes to 'fault_pad' of the subprog */ u64 unwind_goto_follows:1; /* the verifier added an unwind_goto after the insn */
@@ -1551,22 +1551,25 @@ struct bpf_subprog_info { bool did_unwind: 1;/* * It did so at a site with no other way out, see bpf_pads_must_unwind(). A fault in arena -* has one: the access is skipped. So has a may_goto of the program: in a stuck subprog it -* jumps. +* and a may_goto of the program have one: in a stuck subprog the fault is skipped and the +* may_goto jumps. */ bool must_unwind: 1; -/* -* It did so at a site that the program keeps for sure, see site_is_certain(), and that is -* no access to arena. -*/ +/* it did so at a site that the program keeps for sure, see site_is_certain() */ bool unwinds_for_sure: 1;/* -* may_goto_unwinds: in this pass a frame of it was cancelled at a may_goto of the program. +* soft_unwinds: in this pass a frame of it was cancelled at a may_goto of the program or at +* an access to arena. * stuck: it cannot be cancelled. In all its frames, in this pass and in every later one, a -* may_goto of the program jumps, see stuck_frame_calls(). +* may_goto of the program jumps and a fault in arena is skipped, see stuck_frame_calls(). */ - bool may_goto_unwinds: 1; + bool soft_unwinds: 1; bool stuck: 1; +/* +* 'pad_skip_gen' of the env when bpf_pad_skip_faults() walked the subprog and the subprogs +* that were cancelled below it. While the two are equal, all of them are marked stuck. +*/ +u32 skip_gen;/* * In this pass a frame of it made a call that did not mark the callee stuck. If the subprog * is marked stuck later, the pass is repeated, see stuck_frame_calls().
@@ -1802,6 +1805,7 @@ struct bpf_verifier_env {u64 pass_max_cost;/* see bpf_undo_precision() */ bool aborted;/* a thaw does not take it back */ bool no_mem;/* a table cannot grow, see bpf_check_limits() */ +u32 pad_skip_gen;/* see 'skip_gen' of struct bpf_subprog_info */ /* What a pass writes. Each pass starts from the snapshot. */ struct_group_tagged(bpf_env_per_pass, per_pass, int err; /* the first error */
@@ -2353,6 +2357,7 @@ void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *subool bpf_pad_must_unwind (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan);void bpf_pads_must_unwind (struct bpf_verifier_env *env);void bpf_pads_mark_used (struct bpf_verifier_env *env); +int bpf_pad_skip_faults (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan);int bpf_pads_settle (struct bpf_verifier_env *env);bool bpf_pads_conflict (struct bpf_verifier_env *env,const struct bpf_insn_aux_data *aux);void bpf_pads_note_causes (struct bpf_verifier_env *env);
kernel/bpf/pads.c +97 -64
289 lines not on this page · raw message
kernel/bpf/verifier.c +64 -97
271 lines not on this page · raw message
tools/testing/selftests/bpf/progs/arena_atomics.c +82 -17
131 lines not on this page · raw message
tools/testing/selftests/bpf/progs/arena_skipped.h deleted +0 -11
@@ -1,11 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#pragma once - -extern void bpf_rcu_read_lock(void) __ksym; -extern void bpf_rcu_read_unlock(void) __ksym; - -/* A fault in the arena ends the prog. In nine RCU sections it is skipped: a pad leaves eight. */ -#define __nine (x) ({ x; x; x; x; x; x; x; x; x; }) -#define skip_faults () __nine(bpf_rcu_read_lock()) -#define unwind_faults () __nine(bpf_rcu_read_unlock()) -#define skipped (expr) ({ long __v; skip_faults(); __v = (expr); unwind_faults(); __v; })
tools/testing/selftests/bpf/progs/verifier_arena.c +8 -35
93 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_arena_large.c +6 -48
73 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 50/73] bpf: Reject a program that has no landing pad for a fault in arena
TL;DR: Nits only: three code comments in the arena landing-pad patch look inaccurate or incomplete (the "faulted access not verified" claim, a dropped kfunc case, the bail_unwinds restart…
Quoted 1 line
bpf: Reject a program that has no landing pad for a fault in arena
TL;DR: Nits only: three code comments in the arena landing-pad patch look inaccurate or incomplete (the "faulted access not verified" claim, a dropped kfunc case, the bail_unwinds restart description). No functional bug is reported.
Quoted 1 line
kernel/bpf/pads.c +0
-0
[ ... ]
kernel/bpf/pads.c static bool plan_is_stuck(const struct bpf_pad_plan *plan) · line 2518
Quoted 10 lines
/*
+ * Is the conflict of @plan an error? It is one at every site: a prog that goes on from a loop that
+ * was out of time, or from an access that faulted, was not verified. But not where the frame cannot
+ * unwind and the site has another way out, seebpf_pad_must_unwind(): what comes back to a call
+ * there is stuck, seebpf_pad_skip_faults().
*/
static boolplan_rejects(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan){kernel/bpf/pads.c +1
-0+return plan->conflict && (bpf_pad_must_unwind (env, plan) || !plan_is_stuck (plan)); }
This isn't a bug, but is the claim that a prog that goes on "from an access that faulted, was not verified" accurate?
In a function that can be cancelled, check_arena_site() pushes the cancelled copy of the state with push_unwind_edge() and the normal path goes on through the access:
frame->fault_edge = true;
return push_unwind_edge(env, BPF_SITE_FAULT);On that normal path check_mem_access() leaves the destination of an arena load unknown:
} else if (reg->type == PTR_TO_ARENA) {
if (t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);So a skipped fault (load reads 0, store not done) is an execution that the main pass already verified. bpf_pad_must_unwind() itself says the access can be skipped when it faults, and check_arena_site() keeps the skip as the fallback for stuck functions and JITs without unwind_exit.
The statement holds for may_goto of the program, where check_may_goto_site() returns 1 and no state takes the jump. For faults the reason given in the commit message is that "a program that loads does not tell which of its faults end it". Could the comment say that instead?
Quoted 1 line
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 8 lines
/*
+ * The current frame calls @subprog, with a call, callx or a helper that has an unwind label. If the
+ * frame cannot be cancelled, or its function is 'stuck' and has a caller in the program, a
+ * cancellation of @subprog would have nowhere to go. So mark @subprog 'stuck' too, see
+ *check_may_goto_site(). If a state has left @subprog before, or a frame of @subprog has made a
+ * call before, the pass is repeated with the mark set from its start.
*/
static voidstuck_frame_calls(struct bpf_verifier_env *env, int subprog)
This isn't a bug, but the old comment listed "a call, callx, a helper or a kfunc that has a landing pad for its callback", and the new one drops the kfunc.
push_callback_call() is reached from check_kfunc_call() as well as check_helper_call(), and it calls stuck_frame_calls(env, subprog) unconditionally, before the insn_has_cb_pad() test:
stuck_frame_calls(env, subprog);
...
if (!insn_has_cb_pad(insn)) {
err = subprog_cannot_unwind(env, subprog);That covers the bpf_rbtree_add kfunc, which has an unwind label through kfunc_has_cb_pad(). Could the comment say "a helper or a kfunc" again, and mention that the call is made whether or not the helper has an unwind label?
[ ... ]
kernel/bpf/verifier.c static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
Quoted 9 lines
kernel/bpf/verifier.c +2
-0/* +* A repeated run starts with bail_unwinds as subprog_cannot_unwind() left it. Any +* other run starts from the first value: it may not get to the call that clears it. */ if (!env->pass_again) initial->subprogs[i].bail_unwinds = initial->subprogs[i].bail_unwinds_at_first;else if (env->faults_late) initial->subprogs[i].bail_unwinds &= env->subprog_info[i].bail_unwinds;
This isn't a bug, but the comment says a repeated run starts with bail_unwinds as subprog_cannot_unwind() left it, while the code carries the value over only when env->faults_late is set.
do_check_all() also repeats a pass through pass_needs_restart() for env->restart with bpf_flow_loops_lost_bound(), env->guards_late and env->pads_late. In that case pass_again is true, faults_late is false, and the snapshot keeps its old value. For example push_callback_call() -> subprog_cannot_unwind() sets sub->bail_unwinds = false for a callback without a callback pad without setting faults_late, and a pass repeated for a loop or guard reason then starts with bail_unwinds == true again.
The value is cleared again at the call, so nothing breaks, but could the comment say that the value is carried only when the pass is repeated because of faults_late, and why other repeats may start from the snapshot value?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 51/73 bpf: Log why a call is a site and which functions cannot be cancelled
In reply to Kumar Kartikeya DwivediA call is a site when a function below it can leave with unwind_exit. When the verifier cannot generate a landing pad for the call, the program is rejected. Currently the log names the call, but not what makes it a site. Print a line before the error that names the kinds of site at which the functions below the call are cancelled or unwind:
what the call at 12 calls is left at: may_goto of the program landing pad of call at 12: conflict: too much is held
The kinds are "may_goto" for one of the verifier, "recursion check", "arena access", "bpf_throw", "may_goto of the program" and "unwind_exit", separated by commas. They come from 'left_at' of the functions. The program's own unwind_exit is not a site, so 'left_at' gets a bit for it.
The verifier also decides two things about a function that change what it does at run time, and the log shows neither. A function that is marked as one that cannot be cancelled has may_gotos that jump and accesses to arena that are skipped. A function with hidden slots has stores and stack that the program did not ask for. Print one line for each such function at log level 2, after the landing pads. Each of these is one line of the log, and "cannot unwind" stands for "cannot be cancelled":
func#1 cannot unwind, the call at 23 has no landing pad for it: its may_goto jumps, its arena accesses are skipped
func#2 cannot unwind, func#1 calls it at 106 and cannot unwind: its may_goto jumps, its arena accesses are skipped
func#3 has hidden slots for: rcu refs
A line names the insn at which the function was marked, because the mark is kept for later passes and the pass that is loaded may not reach that insn. The insn is one of four:
- "the call at N has no landing pad for it": the call hands the function to a helper that has no unwind label for it.
- "func#M calls it at N and cannot unwind": the frame that calls cannot be cancelled, or its function is marked.
- "it came back to the call at N in func#M, which cannot unwind": a cancelled state came back from the function to a call in a frame that cannot be cancelled.
- "at N": a frame of the function that cannot be cancelled reached its own may_goto or access to arena.
bpf_subprog_set_stuck() now sets the mark in all places and records the first insn that did.
--- include/linux/bpf_verifier.h | 27 +++++++- kernel/bpf/pads.c | 120 +++++++++++++++++++++++++++++------ kernel/bpf/verifier.c | 16 +++-- 3 files changed, 138 insertions(+), 25 deletions(-)
include/linux/bpf_verifier.h +26 -1
@@ -501,6 +501,16 @@ enum bpf_pad_conflict { BPF_CONFLICT_NO_ROOM, }; +/* How a subprog was found to be one that cannot be cancelled, see 'stuck' of bpf_subprog_info */ +enum bpf_stuck_by { +BPF_STUCK_NO_PAD =1 ,/* a call passes it to a helper that has no unwind label for it */ +BPF_STUCK_CALLED ,/* a frame that cannot be cancelled calls it */ +/* a frame of it that cannot be cancelled reached its own may_goto or access to arena */ +BPF_STUCK_AT_SITE , +/* a cancelled state came back from it to a call in a frame that cannot be cancelled */ +BPF_STUCK_CAME_BACK , +}; +/* * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument, a test and * the call. The 5 are one insn that saves the value and four that leave the frame.
@@ -1565,6 +1575,9 @@ struct bpf_subprog_info {*/ bool soft_unwinds: 1; bool stuck: 1; +/* how it was found to be stuck, enum bpf_stuck_by, and at which insn. For the log. */ +u8 stuck_by; +u32 stuck_insn;/* * 'pad_skip_gen' of the env when bpf_pad_skip_faults() walked the subprog and the subprogs * that were cancelled below it. While the two are equal, all of them are marked stuck.
@@ -1617,6 +1630,17 @@ static inline bool bpf_subprog_unwinds(const struct bpf_subprog_info *sub)return sub->can_unwind || (sub->recursive && sub->bail_unwinds); } +/* Mark @sub as stuck. The log names the first insn that marked it, see bpf_pads_log(). */ +static inline void bpf_subprog_set_stuck (struct bpf_subprog_info *sub,enum bpf_stuck_by by, +u32 insn_idx) +{ +if (sub->stuck) +return ; + sub->stuck = true; + sub->stuck_by = by; + sub->stuck_insn = insn_idx; +} +/* The stack depth of @sub with its hidden slots and words */ static inline u32 bpf_stack_depth_with_slots (const struct bpf_subprog_info *sub) {
@@ -2357,7 +2381,8 @@ void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *subool bpf_pad_must_unwind (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan);void bpf_pads_must_unwind (struct bpf_verifier_env *env);void bpf_pads_mark_used (struct bpf_verifier_env *env); -int bpf_pad_skip_faults (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan); +int bpf_pad_skip_faults (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan, +int insn_idx);int bpf_pads_settle (struct bpf_verifier_env *env);bool bpf_pads_conflict (struct bpf_verifier_env *env,const struct bpf_insn_aux_data *aux);void bpf_pads_note_causes (struct bpf_verifier_env *env);
kernel/bpf/pads.c +102 -18
202 lines not on this page · raw message
kernel/bpf/verifier.c +10 -6
@@ -3426,7 +3426,7 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)/* If a state left @subprog or a frame of it made a call before, the pass is repeated. */ env->faults_late |= did_unwind || ((sub->soft_unwinds || sub->made_calls) && !sub->stuck); sub->bail_unwinds = false; - sub->stuck = true; +bpf_subprog_set_stuck (sub,BPF_STUCK_NO_PAD , env->insn_idx);return 0 ; }
@@ -22044,7 +22044,7 @@ static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog) } env->faults_late |= sub->soft_unwinds || sub->made_calls || (sub->did_unwind && sub->bail_unwinds); - sub->stuck = true; +bpf_subprog_set_stuck (sub,BPF_STUCK_CALLED , env->insn_idx); }/* This insn is a site of @kind. Push a copy of the current state that leaves its frame here. */
@@ -22130,7 +22130,7 @@ static int check_may_goto_site(struct bpf_verifier_env *env)return 0 ;if (sub->stuck ||frame_cannot_unwind (env, env->cur_state)) { env->faults_late |= (sub->soft_unwinds || sub->made_calls) && !sub->stuck; - sub->stuck = true; +bpf_subprog_set_stuck (sub,BPF_STUCK_AT_SITE , env->insn_idx);return 0 ; } sub->soft_unwinds = true;
@@ -22164,7 +22164,7 @@ static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_sreturn 0 ;if (sub->stuck ||frame_cannot_unwind (env, st)) { env->faults_late |= (sub->soft_unwinds || sub->made_calls) && !sub->stuck; - sub->stuck = true; +bpf_subprog_set_stuck (sub,BPF_STUCK_AT_SITE , env->insn_idx); aux->fault_skips = true;return 0 ; }
@@ -22376,7 +22376,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state* sites that can be skipped. Mark them 'stuck', which stuck_frame_calls() missed. */ if (stuck && kind ==BPF_SITE_CALL && !bpf_pad_must_unwind (env, plan)) - err =bpf_pad_skip_faults (env, plan); + err =bpf_pad_skip_faults (env, plan, insn_idx);if (plan->conflict) goto out; }
@@ -24617,7 +24617,11 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia* 'stuck' is kept for every later run. A function with the mark behaves as it does * without cancellation, and a run that misses the call that sets it could fail. */ - initial->subprogs[i].stuck |= env->subprog_info[i].stuck; +if (env->subprog_info[i].stuck && !initial->subprogs[i].stuck) { + initial->subprogs[i].stuck = true; + initial->subprogs[i].stuck_by = env->subprog_info[i].stuck_by; + initial->subprogs[i].stuck_insn = env->subprog_info[i].stuck_insn; + }/* releases_args adds up. asks_args is that of the last pass with an error. */ initial->subprogs[i].releases_args |= env->subprog_info[i].releases_args; initial->subprogs[i].asks_args = env->subprog_info[i].asks_args;
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 51/73] bpf: Log why a call is a site and which functions cannot be cancelled
TL;DR: Verifier log may misreport why a bpf_rbtree_add comparator cannot unwind, blaming a missing landing pad instead of the node's fields; the BPF_STUCK_NO_PAD comment and commit message are…
Quoted 1 line
bpf: Log why a call is a site and which functions cannot be cancelled
TL;DR: Verifier log may misreport why a bpf_rbtree_add comparator cannot unwind, blaming a missing landing pad instead of the node's fields; the BPF_STUCK_NO_PAD comment and commit message are inaccurate.
Quoted 3 lines
include/linux/bpf_verifier.h +0
-0
[ ... ]
include/linux/bpf_verifier.h enum bpf_pad_conflict { · line 506
Quoted 3 lines
include/linux/bpf_verifier.h +3
-0+/* How a subprog was found to be one that cannot be cancelled, see 'stuck' of bpf_subprog_info */ +enum bpf_stuck_by { +BPF_STUCK_NO_PAD =1 ,/* a call passes it to a helper that has no unwind label for it */
Is this description accurate for every user of BPF_STUCK_NO_PAD?
subprog_cannot_unwind() is also called from check_kfunc_call() for the comparator of bpf_rbtree_add, and that kfunc does have an unwind label:
static bool kfunc_has_cb_pad(u32 btf_id)
{
return is_bpf_rbtree_add_kfunc(btf_id);
}The comparator is marked there because the node type has fields with destructors (or NMI-unsafe fields in a tracing program), not because a label is missing.
With BPF_HAS_CB_PADS, a level 2 log then prints "func#C cannot unwind, the call at N has no landing pad for it" for the bpf_rbtree_add call, which points at the call instead of the node type.
Should the comment and the log text say that the helper or kfunc cannot pass on a cancelled callback, or should the bpf_rbtree_add case get its own stuck_by value?
[ ... ]
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
kernel/bpf/verifier.c static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog) · line 3431
Quoted 8 lines
kernel/bpf/verifier.c +1
-1@@ -3426,7 +3426,7 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)/* If a state left @subprog or a frame of it made a call before, the pass is repeated. */ env->faults_late |= did_unwind || ((sub->soft_unwinds || sub->made_calls) && !sub->stuck); sub->bail_unwinds = false; - sub->stuck = true; +bpf_subprog_set_stuck (sub,BPF_STUCK_NO_PAD , env->insn_idx);return 0 ; }
subprog_cannot_unwind() always records BPF_STUCK_NO_PAD, and the commit message says the resulting line means "the call hands the function to a helper that has no unwind label for it".
That is only true for the push_callback_call() caller, which calls it when !insn_has_cb_pad(insn). The two callers in the is_bpf_rbtree_add_kfunc() branch of check_kfunc_call() mark the comparator because dropping the node would run field destructors (or NMI-unsafe code), even though bpf_rbtree_add has an unwind label:
check_kfunc_call()
if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
/* When the comparator unwinds, the kfunc drops the node at its
* unwind label. ...
err = subprog_cannot_unwind(env, meta.subprogno);These calls run before push_callback_call() -> stuck_frame_calls(), so a comparator that is not yet stuck gets BPF_STUCK_NO_PAD, and the log claims a missing landing pad when the real reason is the node's fields.
Could this use a separate enum value for the rbtree_add cases, or wording that does not claim a missing label?
[ ... ]
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 52/73 bpf: Add cancel_goto and cancel_exit, which only the verifier emits
In reply to Kumar Kartikeya DwivediThe landing pads of the verifier leave a function with unwind_exit, the insn that a program uses for its own unwinding in C++ or Rust. So when the kernel cancels a program inside a callee, the caller sees an ordinary unwind. If the caller has an unwind_goto of its own after the call, the cancellation lands in the program's landing pad, which is code like any other and can continue running:
call spins
unwind_goto +1
exit
r0 = 42 <- the program's landing pad
exit
The loop in spins() runs out of time, the kernel cancels the program in spins(), and the program returns 42. A cancelled program must not be able to continue, whether it ran out of time or stack, faulted in arena or called bpf_throw().
A call can now end in three ways: the callee returns, unwinds, or is cancelled, and the caller has to tell the last two apart. unwind_goto and unwind_exit tell a return from an unwind by where the callee returns to, without a register. Do the same for a cancellation, with a second pair of insns:
cancel_exit BPF_JMP | BPF_EXIT with BPF_CANCEL_EXIT in src_reg. Leaves
a frame like unwind_exit, but returns to the cancel_goto after the call, never to an unwind_goto.
cancel_goto BPF_JMP32 | BPF_JCOND with BPF_CANCEL_GOTO in src_reg, the
offset in imm. Follows a call, or the unwind_goto of a call, and jumps to the landing pad of the caller.
call spins
unwind_goto +2 <- spins() left with unwind_exit
cancel_goto pad <- spins() left with cancel_exit
Like unwind_goto, cancel_goto is not a jump that is taken. A JIT turns it into an exception table entry for the call, so neither insn costs anything when the callee returns.
A flag in a register, set before unwind_exit and tested after the call, does not work in place of the two insns. It is lost in a helper that calls a callback: bpf_loop() is a C frame between the callback and its caller, and what it leaves in a register is up to the compiler. It would also be a second insn that every later rewrite of an exit has to keep before it, where cancel_exit carries the meaning itself.
The passes that run after the main pass treat a cancel_goto like an unwind_goto, through bpf_is_pad_goto(): the hard wiring of dead branches keeps one whose target is alive, the zero extension of what a call returns goes after it, and it is counted for the exception table. bpf_check_unwind_gotos() reports a cancel_goto that follows neither a call nor the unwind_goto of a call as a verifier bug, and also a cancel_exit in the main program, which the kernel calls.
bpf_cancel_target() is for cancel_exit what bpf_unwind_target() is for unwind_exit. Add the weak default, which returns the address unchanged. A JIT that supports the two insns overrides it.
A program cannot contain either insn: both values of src_reg are above what the uapi defines, and check_jmp_fields() rejects them. Nothing emits them yet.
--- include/linux/filter.h | 37 +++++++++++++++++++++++++++++++-- kernel/bpf/core.c | 9 +++++++++ kernel/bpf/disasm.c | 9 ++++++++- kernel/bpf/fixups.c | 46 ++++++++++++++++++++++++++++++++---------- kernel/bpf/verifier.c | 2 ++ 5 files changed, 89 insertions(+), 14 deletions(-)
include/linux/filter.h +35 -2
@@ -295,7 +295,23 @@ static inline bool insn_is_mov_percpu_addr(const struct bpf_insn *insn) .off = 0, \ .imm = 1 }) -/* gotol, and unwind_goto that the verifier adds, have 32 bits for the offset */ +/* +* The two insns of a cancellation. Only the verifier emits them, see kernel/bpf/pads.c. A program +* that has one is rejected, see check_jmp_fields(). +* +* cancel_exit: BPF_JMP | BPF_EXIT with BPF_CANCEL_EXIT in src_reg. It leaves a frame like +* unwind_exit, but returns to the cancel_goto after the call and never to an unwind_goto, so that +* no landing pad of the program can catch a cancellation. +* cancel_goto: BPF_JMP32 | BPF_JCOND with BPF_CANCEL_GOTO in src_reg, the offset in imm. It +* follows a call, or the unwind_goto of a call. +*/ +#define BPF_CANCEL_GOTO 2 +#define BPF_CANCEL_EXIT 2 + +static_assert (BPF_CANCEL_GOTO >BPF_UNWIND_GOTO ); +static_assert (BPF_CANCEL_EXIT >BPF_UNWIND_EXIT ); + +/* gotol, cancel_goto and an unwind_goto that the verifier adds have a 32 bit offset, in imm */ static inline bool bpf_jmp_offset_is_imm (const struct bpf_insn *insn) {return insn->code == (BPF_JMP32 |BPF_JA ) || insn->code == (BPF_JMP32 |BPF_JCOND );
@@ -317,7 +333,23 @@ static inline bool bpf_is_unwind_exit(const struct bpf_insn *insn)return insn->code == (BPF_JMP |BPF_EXIT ) && insn->src_reg ==BPF_UNWIND_EXIT ; } -/* The caller of the main prog doesn't tell unwind_exit from exit */ +static inline bool bpf_is_cancel_goto (const struct bpf_insn *insn) +{ +return insn->code == (BPF_JMP32 |BPF_JCOND ) && insn->src_reg ==BPF_CANCEL_GOTO ; +} + +static inline bool bpf_is_cancel_exit (const struct bpf_insn *insn) +{ +return insn->code == (BPF_JMP |BPF_EXIT ) && insn->src_reg ==BPF_CANCEL_EXIT ; +} + +/* unwind_goto or cancel_goto: no code, an exception table entry for the insn before it */ +static inline bool bpf_is_pad_goto (const struct bpf_insn *insn) +{ +return bpf_is_unwind_goto (insn) ||bpf_is_cancel_goto (insn); +} + +/* The caller of the main prog cannot tell unwind_exit or cancel_exit from exit */ static inline bool bpf_prog_can_unwind (const struct bpf_prog *prog) {return bpf_is_subprog (prog);
@@ -1406,6 +1438,7 @@ bool bpf_jit_supports_kfunc_ret_reg_pair(void);bool bpf_jit_supports_unwind (void );bool bpf_jit_supports_hmul (void );u64 bpf_unwind_target (u64 ret_addr); +u64 bpf_cancel_target (u64 ret_addr);u64 bpf_fault_unwind_target (u64 end);bool bpf_jit_supports_stack_args (void );bool bpf_jit_supports_arena_args (void );
kernel/bpf/core.c +9 -0
@@ -3863,6 +3863,15 @@ u64 __weak bpf_unwind_target(u64 ret_addr)return ret_addr; } +/* +* The same for cancel_exit and the cancel_goto after the call. Without a JIT that overrides this +* the verifier emits no cancel_exit. +*/ +u64 __weak bpf_cancel_target (u64 ret_addr) +{ +return ret_addr; +} +/* * Where the program continues after a fault in an access to arena whose native code ends at @end: * at the target of the unwind_goto after the access, or at @end, which skips the access. A JIT
kernel/bpf/disasm.c +8 -1
@@ -10,6 +10,8 @@/* Only defined by the non-UAPI linux/filter.h, which this file cannot use. */ #define BPF_PROBE_ATOMIC 0xe0#define BPF_ATOMIC_LOCAL 0x1000 +#define BPF_CANCEL_GOTO 2 +#define BPF_CANCEL_EXIT 2#define __BPF_FUNC_STR_FN (x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)static const char *const func_id_str[] = {
@@ -408,12 +410,17 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs, insn->src_reg == BPF_UNWIND_GOTO) {verbose (cbs->private_data,"(%02x) unwind_goto pc%+d" , insn->code, insn->imm); + } else if (insn->code == (BPF_JMP32 | BPF_JCOND) && + insn->src_reg == BPF_CANCEL_GOTO) { +verbose (cbs->private_data,"(%02x) cancel_goto pc%+d" , + insn->code, insn->imm); } else if (insn->code == (BPF_JMP32 | BPF_JA)) {verbose (cbs->private_data,"(%02x) gotol pc%+d" , insn->code, insn->imm); } else if (insn->code == (BPF_JMP | BPF_EXIT)) {verbose (cbs->private_data,"(%02x) %s" , insn->code, - insn->src_reg ==BPF_UNWIND_EXIT ?"unwind_exit" :"exit" ); + insn->src_reg ==BPF_UNWIND_EXIT ?"unwind_exit" : + insn->src_reg ==BPF_CANCEL_EXIT ?"cancel_exit" :"exit" ); } else if (BPF_SRC(insn->code) == BPF_X) { verbose(cbs->private_data, "(%02x) if %c%d %s %c%d goto pc%+d",
kernel/bpf/fixups.c +35 -11
108 lines not on this page · raw message
kernel/bpf/verifier.c +2 -0
@@ -23652,6 +23652,7 @@ static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) }return 0 ;case BPF_EXIT : +/* Only the verifier emits cancel_exit, see BPF_CANCEL_EXIT. */ if (BPF_SRC (insn->code) !=BPF_K || insn->imm !=0 || insn->src_reg >BPF_UNWIND_EXIT || insn->dst_reg !=BPF_REG_0 || class ==BPF_JMP32 ) {
@@ -23660,6 +23661,7 @@ static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) }return 0 ;case BPF_JCOND : +/* The same for cancel_goto and for the form of unwind_goto with a 32 bit offset. */ if (insn->code != (BPF_JMP |BPF_JCOND ) || insn->src_reg >BPF_UNWIND_GOTO || insn->dst_reg || insn->imm) {verbose (env,"invalid may_goto imm %d\n" , insn->imm);
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 53/73 bpf: Give the unwind label of a helper a second way in
In reply to Kumar Kartikeya DwivediCurrently the unwind label of a helper serves unwind_exit only: the helper releases what it holds and leaves to the unwind_goto after its own call. A callback that leaves with cancel_exit needs the same label, but the helper then has to leave to the cancel_goto after its call, or the cancellation would come out in a landing pad of the program. So the helper has to learn which insn its callback left with.
A flag in a register cannot tell it, because the helper is the C frame in which such a flag is lost. bpf_for_each_map_elem() calls the op of the map, which calls the callback, and what the op leaves in a register after its own unwind label is up to the compiler. The exception table cannot name a second label either, because a return address has one entry.
Tell the helper the way a caller is told, by the address that the callback returns to. The exception table entry of bpf_call_cb() now points to a stub with two entry points, BPF_CB_PAD_OFF and BPF_CB_CANCEL_OFF bytes from its start. On x86-64 the stub is:
nop
clc <- unwind_exit returns here
jnc 1f
stc <- cancel_exit returns here
1: sbb %ecx, %ecx kind: 0 if the carry flag is clear
jmp <unwind label>
bpf_call_cb() returns the result in a new argument, kind, and bpf_unwind_leave(kind) looks up the target of the same kind for the return address of the helper, with bpf_cancel_target() if kind is not 0. The stub is out of line and computes kind in rcx, which the call clobbers anyway, so the helper pays nothing for it when the callback returns. On arm64 each entry point branches to a C label of its own that sets kind, so that no register has to carry it.
bpf_for_each_map_elem() is two C frames. The op of the map leaves with bpf_unwind_leave(kind), which takes it to the matching entry point in the helper, and the helper leaves with the same kind. Only R0 of the callback gets through a helper, so no code may read R2 after the call of a helper as a value of the callback.
When the callback returns, the helpers run the same code as before on x86-64 with clang, with two exceptions: bpf_for_each_map_elem() is shorter, and bpf_find_vma() pays five more pushes and pops per call for fewer loads and stores. Nothing enters the second entry point yet. The verifier emits no cancel_exit, and the lookup of both JITs still returns the start of the stub, which runs into the first entry point.
--- include/linux/bpf_unwind.h | 103 +++++++++++++++++++++++++++---------- kernel/bpf/arraymap.c | 8 +-- kernel/bpf/bpf_iter.c | 15 +++--- kernel/bpf/hashtab.c | 17 +++--- kernel/bpf/helpers.c | 11 ++-- kernel/bpf/ringbuf.c | 17 +++--- kernel/bpf/task_iter.c | 10 ++-- 7 files changed, 114 insertions(+), 67 deletions(-)
include/linux/bpf_unwind.h +75 -28
@@ -6,18 +6,20 @@* The unwind label of a helper, which the identifiers call a pad. * * A helper that calls a callback is a C frame between the callback and the BPF code that called -* the helper. For the callback to leave with unwind_exit, the helper calls it with bpf_call_cb() -* and names a label, at which it continues when the callback does not return: +* the helper. For the callback to leave with unwind_exit or cancel_exit, the helper calls it with +* bpf_call_cb() and names a label, at which it continues when the callback does not return: * -* bpf_call_cb(cb, a1, a2, a3, a4, a5, r0, unwound); +* bpf_call_cb(cb, a1, a2, a3, a4, a5, r0, kind, unwound); * ... * unwound: * rcu_read_unlock(); <- the helper releases what it holds -* bpf_unwind_leave(); <- and returns to the unwind_goto after its own -* return r0; call, with R0 of the callback alone +* bpf_unwind_leave(kind); <- and returns to the unwind_goto or cancel_goto +* return r0; after its own call, with R0 of the callback alone * -* The return address of the callback has an exception table entry, EX_TYPE_BPF, for the label. -* unwind_exit of the callback finds the entry with bpf_unwind_target() and returns there. +* The return address of the callback has an exception table entry, EX_TYPE_BPF, that points to a +* stub with two entry points. unwind_exit returns to the one at BPF_CB_PAD_OFF and cancel_exit to +* the one at BPF_CB_CANCEL_OFF, see bpf_unwind_target() and bpf_cancel_target(). The stub sets +* 'kind' and jumps to the label. It is out of line, so a callback that returns costs nothing. * * A function with an unwind label must be: * - noinline. bpf_unwind_leave() rewrites the return address of the function that it is in, so
@@ -83,6 +85,15 @@#define BPF_KCFI_CHECK (type)#endif +/* +* The offsets of the two entry points in the stub. unwind_exit returns after a nop. A stack walk +* looks up the insn before a return address, and for a sample that is taken while the callback +* returns to the stub that has to be an insn of the stub. cancel_exit returns after the clc and +* the jnc. +*/ +#define BPF_CB_PAD_OFF 1 +#define BPF_CB_CANCEL_OFF 4 +/* * The registers that the call clobbers are outputs, so that the compiler uses none of them for * another operand. r0 is rax after the call and at the label: the outputs of an asm goto are
@@ -90,8 +101,15 @@* before the call, never after it, so the return address stays the byte after the call. The * arguments are evaluated before the register variables are set, because a call among them, * instrumentation included, would clobber the variables. +* +* The stub is in a subsection after the code, where nothing falls into it. unwind_exit returns +* after the nop at 4, with the carry flag clear from there on. cancel_exit returns to 5, which +* sets the flag. sbb turns the flag into 'kind', in rcx, which the call clobbers anyway. objtool +* reaches 4 through the exception table and 5 as the fall-through of the jnc, although the jnc +* is always taken. The jnc is spelled in bytes so that its length does not depend on the +* assembler. */ -#define __bpf_call_cb (type, fn, a1, a2, a3, a4, a5, r0, unwound) \ +#define __bpf_call_cb (type, fn, a1, a2, a3, a4, a5, r0, kind, unwound) \ do { \ u64 __f = (u64)(long)(fn), __1 = (u64)(long)(a1), __2 = (u64)(long)(a2), \ __3 = (u64)(long)(a3), __4 = (u64)(long)(a4), __5 = (u64)(long)(a5); \
@@ -99,13 +117,21 @@ do { \ register u64 __a5 asm("r8") = __5; \ registeru64 __c5 asm("r8" ); \ registeru64 __c11 asm("r11" ); \ -u64 __c1, __c2, __c3, __c4; \ +u64 __c1, __c2, __c3; \ \ asm_goto_output(BPF_KCFI_CHECK(type) \" " CALL_NOSPEC "\n" \"1:\n" \ - _ASM_EXTABLE_TYPE(1b, %l[unwound], EX_TYPE_BPF) \ - : "=a"(r0), "=D"(__c1), "=S"(__c2), "=d"(__c3), "=c"(__c4), \ +" .subsection 1\n" \ +"4: nop\n" \ +" clc\n" \ +" .byte 0x73, 0x01\n" /* jnc 6f */ \ +"5: stc\n" \ +"6: sbb %%ecx, %%ecx\n" \ + " jmp %l[" __stringify(unwound) "]\n" \ +" .previous\n" \ + _ASM_EXTABLE_TYPE(1b ,4b ,EX_TYPE_BPF ) \ + : "=a"(r0), "=D"(__c1), "=S"(__c2), "=d"(__c3), "=c"(kind), \ "=r"(__c5), "=r"(__c11) \: [thunk_target] " r"(__fn), " D "(__1), " S "(__2), " d"(__3), \ " c"(__4), " r"(__a5) \
@@ -115,17 +141,18 @@ do { \/* * Make the function that this is inlined into return to the target of the unwind_goto after its -* call. The return address is the word below the canonical frame address. Nothing checks that a -* target was found: after 'unwind_goto +0' the target is the return address itself, because the -* JIT emits no code for unwind_goto. +* call, or of the cancel_goto if @kind, which the stub of bpf_call_cb() set, is not 0. The return +* address is the word below the canonical frame address. Nothing checks that a target was found: +* after 'unwind_goto +0' the target is the return address itself, because the JIT emits no code +* for unwind_goto. * The store is the last thing before the return, into the frame of the function itself, so a * compiler may take it for a dead store. Hence WRITE_ONCE(). */ -static __always_inline void bpf_unwind_leave(void) +static __always_inline void bpf_unwind_leave(u64 kind) {unsigned long *slot = (unsigned long *)__builtin_dwarf_cfa () -1 ; -WRITE_ONCE (*slot,bpf_unwind_target (*slot)); +WRITE_ONCE (*slot, kind ?bpf_cancel_target (*slot) :bpf_unwind_target (*slot)); }#elif defined(CONFIG_ARM64 ) && defined(CONFIG_CC_HAS_ASM_GOTO_OUTPUT )
@@ -166,15 +193,23 @@ static __always_inline void bpf_unwind_leave(void)#define BPF_CB_CLOBBER_X18 "x18",#endif +/* The offsets of the two entry points in the stub: the second one is two insns in */ +#define BPF_CB_PAD_OFF 0 +#define BPF_CB_CANCEL_OFF 8 +/* * r0 is x0, which only a register variable can name, and gcc does not keep such a variable across * a call. KCOV puts a call at the head of each block, and an asm goto ends its block, so C code * after it would read x0 too late on either edge. So the assembly moves x0 to r0 itself, after -* the call and where unwind_exit returns to, out of line. For the same reason the arguments are -* evaluated before the register variables are set. +* the call and at both entry points. For the same reason the arguments are evaluated before the +* register variables are set. +* unwind_exit returns to 3 and cancel_exit to 4. Each branches to a C label of its own that sets +* 'kind'. A register for it would have to be one that the call keeps, and the helper would save +* that register also when the callback returns. */ -#define __bpf_call_cb (type, fn, a1, a2, a3, a4, a5, r0, unwound) \ +#define __bpf_call_cb (type, fn, a1, a2, a3, a4, a5, r0, kind, unwound) \ do { \ + __label__ __prog, __cancel; \ u64 __f = (u64)(long)(fn), __1 = (u64)(long)(a1), __2 = (u64)(long)(a2), \ __3 = (u64)(long)(a3), __4 = (u64)(long)(a4), __5 = (u64)(long)(a5); \ register u64 __fn asm("x15") = __f; \
@@ -195,7 +230,9 @@ do { \"1: mov %[ret], x0\n" \" .subsection 1\n" \"3: mov %[ret], x0\n" \ - " b %l[" __stringify(unwound) "]\n" \ +" b %l[__prog]\n" \ +"4: mov %[ret], x0\n" \ +" b %l[__cancel]\n" \" .previous\n" \ __ASM_EXTABLE_RAW("1b" ,"3b" ,__stringify (EX_TYPE_BPF ),"0" ) \ : [ret] "=r"(r0), "=r"(__c0), "=r"(__c1), "=r"(__c2), \
@@ -204,7 +241,14 @@ do { \ "r"(__a4) \ : "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", \" x14", " x16", " x17", BPF_CB_CLOBBER_X18 " x30", " memory", " cc" \ -: unwound); \ +: __prog, __cancel); \ +break; \ +__prog: \ +(kind) = 0; \ +goto unwound; \ +__cancel: \ +(kind) = 1; \ +goto unwound; \ } while (0) /*
@@ -224,12 +268,12 @@ do { \* 20 pushes first, so the copy is plain. The copy is read and written in assembly, because KASAN * poisons the shadow call stack. */ -static __always_inline void bpf_unwind_leave(void) +static __always_inline void bpf_unwind_leave(u64 kind) {unsigned long *slot = (unsigned long *)__builtin_frame_address (0 ) +1 ;unsigned long old = *slot;unsigned long from =ptrauth_strip_kernel_insn_pac (old); -unsigned long to =bpf_unwind_target (from), sig = to; +unsigned long to = kind ?bpf_cancel_target (from) :bpf_unwind_target (from), sig = to;WARN_ON_ONCE (to == from);#ifdef CONFIG_ARM64_PTR_AUTH_KERNEL
@@ -260,20 +304,23 @@ static __always_inline void bpf_unwind_leave(void)#else -#define BPF_HAS_CB_PADS 0 +#define BPF_HAS_CB_PADS 0 +#define BPF_CB_PAD_OFF 0 +#define BPF_CB_CANCEL_OFF 0#define BPF_CB_PAD_TYPE (name, type) -#define __bpf_call_cb (type, fn, a1, a2, a3, a4, a5, r0, unwound) \ +#define __bpf_call_cb (type, fn, a1, a2, a3, a4, a5, r0, kind, unwound) \ do { \ (r0) = ((bpf_callback_t)(void *)(fn))((u64)(long)(a1), (u64)(long)(a2), \ (u64)(long)(a3), (u64)(long)(a4), \ (u64)(long)(a5)); \ + (kind) = 0; \ if (0) \ goto unwound; \ } while (0) -static __always_inline void bpf_unwind_leave(void) +static __always_inline void bpf_unwind_leave(u64 kind) { }
@@ -285,7 +332,7 @@ static __always_inline void bpf_unwind_leave(void)*/ BPF_CB_PAD_TYPE (__bpf_callback_fn,typeof (*(bpf_callback_t )0 )); -#define bpf_call_cb (fn, a1, a2, a3, a4, a5, r0, unwound) \ - __bpf_call_cb(__bpf_callback_fn, fn, a1, a2, a3, a4, a5, r0, unwound) +#define bpf_call_cb (fn, a1, a2, a3, a4, a5, r0, kind, unwound) \ + __bpf_call_cb(__bpf_callback_fn, fn, a1, a2, a3, a4, a5, r0, kind, unwound)#endif /* _LINUX_BPF_UNWIND_H */
kernel/bpf/arraymap.c +4 -4
@@ -807,7 +807,7 @@ static noinline notrace long bpf_for_each_array_elem(struct bpf_map *map, bpf_cau32 i, key, num_elems =0 ;struct bpf_array *array;bool is_percpu; -u64 ret =0 ; +u64 ret =0 , kind;void *val;cant_migrate ();
@@ -824,7 +824,7 @@ static noinline notrace long bpf_for_each_array_elem(struct bpf_map *map, bpf_ca val =array_map_elem_ptr (array, i); num_elems++; key = i; -bpf_call_cb (callback_fn, map, &key, val, callback_ctx,0 , ret, unwound); +bpf_call_cb (callback_fn, map, &key, val, callback_ctx,0 , ret, kind, unwound);/* return value: 0 - continue, 1 - stop and return */ if (ret)break ;
@@ -833,8 +833,8 @@ static noinline notrace long bpf_for_each_array_elem(struct bpf_map *map, bpf_careturn num_elems; unwound: -/* The callback left with unwind_exit: nothing to drop here */ -bpf_unwind_leave (); +/* The callback left with unwind_exit or cancel_exit. Nothing is held here. */ +bpf_unwind_leave (kind);return ret; }NOKPROBE_SYMBOL (bpf_for_each_array_elem);
kernel/bpf/bpf_iter.c +8 -7
@@ -760,14 +760,15 @@ BPF_CALL_x(4, noinline notrace, bpf_for_each_map_elem, struct bpf_map *, map, vo void *, callback_ctx, u64, flags) {#if BPF_HAS_CB_PADS -u64 ret; +u64 ret, kind;__bpf_call_cb (__bpf_for_each_op, map->ops->map_for_each_callback, map, callback_fn, - callback_ctx, flags,0 , ret, unwound); + callback_ctx, flags,0 , ret, kind, unwound);return ret; unwound: -bpf_unwind_leave (); +/* The map function left the way the callback did, and so does the helper */ +bpf_unwind_leave (kind);return ret;#else /* The fallback of __bpf_call_cb() calls through bpf_callback_t, and kCFI would trap */
@@ -790,7 +791,7 @@ BPF_CALL_x(4, noinline notrace, bpf_loop, u32, nr_loops, void *, callback_fn, vo u64, flags) {bpf_callback_t callback = (bpf_callback_t )callback_fn; -u64 ret; +u64 ret, kind;u32 i;/* Note: these safety checks are also verified when bpf_loop
@@ -803,7 +804,7 @@ BPF_CALL_x(4, noinline notrace, bpf_loop, u32, nr_loops, void *, callback_fn, voreturn -E2BIG ;for (i =0 ; i < nr_loops; i++) { -bpf_call_cb (callback, i, callback_ctx,0 ,0 ,0 , ret, unwound); +bpf_call_cb (callback, i, callback_ctx,0 ,0 ,0 , ret, kind, unwound);/* return value: 0 - continue, 1 - stop and return */ if (ret)return i +1 ;
@@ -812,8 +813,8 @@ BPF_CALL_x(4, noinline notrace, bpf_loop, u32, nr_loops, void *, callback_fn, voreturn i; unwound: -/* The callback left with unwind_exit: the loop is over, and so is the helper */ -bpf_unwind_leave (); +/* The callback left with unwind_exit or cancel_exit. Nothing is held here. */ +bpf_unwind_leave (kind);return ret; }NOKPROBE_SYMBOL (bpf_loop);
kernel/bpf/hashtab.c +9 -8
@@ -2530,7 +2530,7 @@ static noinline notrace long bpf_for_each_hash_elem(struct bpf_map *map, bpf_calstruct bucket *b;void *key, *val;bool is_percpu; -u64 ret =0 ; +u64 ret =0 , kind;cant_migrate ();
@@ -2557,7 +2557,8 @@ static noinline notrace long bpf_for_each_hash_elem(struct bpf_map *map, bpf_cal val =htab_elem_value (elem, map->key_size); } num_elems++; -bpf_call_cb (callback_fn, map, key, val, callback_ctx,0 , ret, unwound); +bpf_call_cb (callback_fn, map, key, val, callback_ctx,0 , ret, kind, + unwound);/* return value: 0 - continue, 1 - stop and return */ if (ret) {rcu_read_unlock ();
@@ -2570,9 +2571,9 @@ static noinline notrace long bpf_for_each_hash_elem(struct bpf_map *map, bpf_calreturn num_elems; unwound: -/* The callback left with unwind_exit, inside the RCU section of the bucket */ +/* The callback left with unwind_exit or cancel_exit: leave the RCU section of the bucket */ rcu_read_unlock (); -bpf_unwind_leave (); +bpf_unwind_leave (kind);return ret; }NOKPROBE_SYMBOL (bpf_for_each_hash_elem);
@@ -3436,7 +3437,7 @@ static noinline notrace long bpf_each_rhash_elem(struct bpf_map *map, bpf_callbavoid *prev_key =NULL ;struct rhtab_elem *elem;int num_elems =0 ; -u64 ret =0 ; +u64 ret =0 , kind;cant_migrate ();
@@ -3454,7 +3455,7 @@ static noinline notrace long bpf_each_rhash_elem(struct bpf_map *map, bpf_callbabreak ; num_elems++;bpf_call_cb (callback_fn, map, elem->data,rhtab_elem_value (elem, map->key_size), - callback_ctx,0 , ret, unwound); + callback_ctx,0 , ret, kind, unwound);if (ret)break ;
@@ -3465,9 +3466,9 @@ static noinline notrace long bpf_each_rhash_elem(struct bpf_map *map, bpf_callbareturn num_elems; unwound: -/* The callback left with unwind_exit, under RCU */ +/* The callback left with unwind_exit or cancel_exit: leave the RCU section */ rcu_read_unlock (); -bpf_unwind_leave (); +bpf_unwind_leave (kind);return ret; }NOKPROBE_SYMBOL (bpf_each_rhash_elem);
kernel/bpf/helpers.c +5 -6
@@ -2846,7 +2846,7 @@ static __always_inline long __bpf_rbtree_add(struct bpf_rb_root *root,struct rb_node *parent =NULL , *n = &node->rb_node;bpf_callback_t cb = (bpf_callback_t )less;bool leftmost = true; -u64 r0; +u64 r0, kind;/* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately * check the latter
@@ -2859,7 +2859,7 @@ static __always_inline long __bpf_rbtree_add(struct bpf_rb_root *root,while (*link) { parent = *link; -bpf_call_cb (cb, node, parent,0 ,0 ,0 , r0, unwound); +bpf_call_cb (cb, node, parent,0 ,0 ,0 , r0, kind, unwound);if (r0) { link = &parent->rb_left; }else {
@@ -2875,13 +2875,12 @@ static __always_inline long __bpf_rbtree_add(struct bpf_rb_root *root, unwound:/* -* The comparator left with unwind_exit. The node is not in the tree, and -* the caller has let go of it: unlink it for whoever else holds it, as -* bpf_rb_root_free() does, and drop it, as the error path above does. +* The comparator left with unwind_exit or cancel_exit, and the program has given up the +* node. Clear the owner, so that others who hold the node can add it again, and drop it. */ smp_store_release (&node->owner,NULL );__bpf_obj_drop_impl ((void *)n - off, rec, false); -bpf_unwind_leave (); +bpf_unwind_leave (kind);return r0; }
kernel/bpf/ringbuf.c +8 -9
@@ -822,7 +822,8 @@ BPF_CALL_x(4, noinline notrace, bpf_user_ringbuf_drain, struct bpf_map *, map,long samples, discarded_samples =0 , ret =0 ;bpf_callback_t callback = (bpf_callback_t )callback_fn;u64 wakeup_flags =BPF_RB_NO_WAKEUP |BPF_RB_FORCE_WAKEUP ; -bool unwound = false; +/* 0, or how the callback left: 1 after unwind_exit, 2 after cancel_exit */ +u64 kind, unwound =0 ;int busy =0 ;if (unlikely (flags & ~wakeup_flags))
@@ -854,17 +855,15 @@ BPF_CALL_x(4, noinline notrace, bpf_user_ringbuf_drain, struct bpf_map *, map, }bpf_dynptr_init (&dynptr, sample,BPF_DYNPTR_TYPE_LOCAL ,0 , size); -bpf_call_cb (callback, &dynptr, callback_ctx,0 ,0 ,0 , ret, unwound_at); +bpf_call_cb (callback, &dynptr, callback_ctx,0 ,0 ,0 , ret, kind, unwound_at);if (0 ) { unwound_at:/* -* The callback left with unwind_exit. The sample is -* consumed and counted like after a return, so that -* the wakeup below is sent for it, and the helper -* leaves through the door below, as the error paths -* do, with the r0 of the callback. +* The callback left with unwind_exit or cancel_exit. Consume and count the +* sample as after a return, so that the wakeup is sent for it, then leave +* the way the error paths do. */ - unwound = true; + unwound =1 + !!kind; }__bpf_user_ringbuf_sample_release (rb, size, flags);if (unwound) {
@@ -885,7 +884,7 @@ BPF_CALL_x(4, noinline notrace, bpf_user_ringbuf_drain, struct bpf_map *, map,else if (!(flags &BPF_RB_NO_WAKEUP ) && samples >0 )irq_work_queue (&rb->work);if (unwound) -bpf_unwind_leave (); +bpf_unwind_leave (unwound -1 );return ret; }NOKPROBE_SYMBOL (bpf_user_ringbuf_drain);
kernel/bpf/task_iter.c +5 -5
@@ -763,7 +763,7 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, sbool __maybe_unused mmput_needed = false;struct mm_struct *mm;int ret = -ENOENT ; -u64 r0; +u64 r0, kind;if (flags)return -EINVAL ;
@@ -817,7 +817,7 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, s* verifier checks it as an RCU read-side critical section. */ rcu_read_lock (); -bpf_call_cb (callback_fn, task, vma, callback_ctx,0 ,0 , r0, unwound); +bpf_call_cb (callback_fn, task, vma, callback_ctx,0 ,0 , r0, kind, unwound);rcu_read_unlock (); ret =0 ; }
@@ -831,8 +831,8 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, s unwound:/* -* The callback left with unwind_exit, under the mmap lock and in the -* RCU section. The way out is the same as after a return. +* The callback left with unwind_exit or cancel_exit. Leave the RCU section, drop the mmap +* lock and put the mm, as after a return. */ rcu_read_unlock ();bpf_mmap_unlock_mm (work, mm);
@@ -840,7 +840,7 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, sif (mmput_needed)mmput_async (mm);#endif -bpf_unwind_leave (); +bpf_unwind_leave (kind);return r0; }NOKPROBE_SYMBOL (bpf_find_vma);
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 53/73] bpf: Give the unwind label of a helper a second way in
TL;DR: On x86, the new unwind stub's nop may let an optimized kprobe on the preceding function's tail corrupt the return target, executing garbage. Fixed later in the series; please fold the fix in…
Quoted 1 line
bpf: Give the unwind label of a helper a second way in
TL;DR: On x86, the new unwind stub's nop may let an optimized kprobe on the preceding function's tail corrupt the return target, executing garbage. Fixed later in the series; please fold the fix in for bisectability.
Quoted 3 lines
include/linux/bpf_unwind.h +0
-0
[ ... ]
Quoted 4 lines
include/linux/bpf_unwind.h +0
-0@@ -99,13 +117,21 @@ do { asm_goto_output(BPF_KCFI_CHECK(type) \" " CALL_NOSPEC "\n" \"1:\n" \
include/linux/bpf_unwind.h do { · line 128
Quoted 10 lines
include/linux/bpf_unwind.h +9
-1- _ASM_EXTABLE_TYPE(1b, %l[unwound], EX_TYPE_BPF) \ +" .subsection 1\n" \ +"4: nop\n" \ +" clc\n" \ +" .byte 0x73, 0x01\n" /* jnc 6f */ \ +"5: stc\n" \ +"6: sbb %%ecx, %%ecx\n" \ + " jmp %l[" __stringify(unwound) "]\n" \ +" .previous\n" \ + _ASM_EXTABLE_TYPE(1b ,4b ,EX_TYPE_BPF ) \
In this commit the x86 bpf_unwind_target() is unchanged and still returns '(unsigned long)&e->fixup + e->fixup', which is now stub+0, the nop. The commit message says so: "the lookup of both JITs still returns the start of the stub, which runs into the first entry point."
Since x86 does not select LD_DEAD_CODE_DATA_ELIMINATION, the subsection 1 stubs of a translation unit land after the last function in that unit's .text, with no symbol covering them. kallsyms then counts the stubs as part of that last function, which need not be on the kprobe blacklist.
Can an optimized kprobe on the tail of that function cover the stub's nop? can_optimize() looks only for extable keys and jumps into the range, so it cannot see a ret target such as the stub entry, and nop and ret are both boostable in can_boost().
For example, if the tail is 'pop %rbx; pop %r12; ret' (4 bytes), a probe at 'pop %rbx' copies those 4 bytes plus the stub's nop. The 5-byte jmp then covers stub+0. A callback that leaves bpf_loop() or bpf_for_each_map_elem() through unwind_exit would return into the last byte of the jmp's rel32 and execute garbage. Before this commit the target was a label inside the helper, which is notrace/NOKPROBE.
The same intermediate state also contradicts the rule documented at BPF_CB_PAD_OFF, "A stack walk looks up the insn before a return address ... that has to be an insn of the stub", because stub+0-1 is outside the stub.
This is fixed later in the series by 6d04b6a4d90c ("bpf, x86: Return to cancel_goto at cancel_exit"), which changes the nop to int3 and makes the lookup add BPF_CB_PAD_OFF/BPF_CB_CANCEL_OFF. Could those two changes be folded into this commit so it is safe to bisect on x86? Otherwise, could the old in-function target be kept until the JIT lookup honours BPF_CB_PAD_OFF?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 54/73 bpf, x86: Put the landing of unwind_goto after the function
In reply to Kumar Kartikeya DwivediCurrently the x86-64 JIT emits the landing of an unwind_goto right after the call, and every call that returns jumps over it. With a private stack the code is:
call foo
pop r9 <- exit returns here
jmp 1f
pop r9 <- unwind_exit returns here
jmp <target of unwind_goto>
1:
So each call with a landing pays a jump, for code that runs only when the callee unwinds. A cancel_goto is going to get a landing too, and the verifier is going to add a cancel_goto after every call of a function that the kernel can cancel.
Emit the landings after the last insn of the function instead, as the arm64 JIT does:
call foo
pop r9 <- exit returns here
...
leave; ret
pop r9 <- unwind_exit returns here
jmp <target of unwind_goto>
An unwind_goto now only records the bytes that follow the native call and its target, and do_jit() emits the recorded landings after the loop over the insns. An unwind_goto with nothing to redo has no landing, as before. The keys of the exception table entries do not change.
Three points need care:
- The landings have the same size in every pass of the JIT, because their jumps always have a 32 bit offset. So the image stops shrinking exactly when the body does.
- The exception table entries are written only when the image is allocated. The landings then start at addrs[insn_cnt], where the pass before ended the body.
- The length that do_jit() returns includes the landings, so jited_len covers them. A landing is entered by ret and left by a direct jump, so it needs no ENDBR.
private_stack_unwinds of verifier_unwind.c expects the new layout.
--- arch/x86/net/bpf_jit_comp.c | 101 ++++++++++++++---- .../selftests/bpf/progs/verifier_unwind.c | 7 +- 2 files changed, 87 insertions(+), 21 deletions(-)
arch/x86/net/bpf_jit_comp.c +82 -19
@@ -288,6 +288,18 @@ int bpf_arch_text_invalidate(void *dst, size_t len)return IS_ERR_OR_NULL (text_poke_set (dst,0xcc , len)); } +/* +* A LANDING: where unwind_exit of a callee comes back to when the call has code +* behind its native call, like 'pop r9'. That code, done once more, and a jump +* to the insn that unwind_goto goes to. The landings stand behind the body of +* the function, see do_jit(). +*/ +struct jit_landing { +u8 code[16 ]; +u8 len; +int to; +}; +struct jit_context {int cleanup_addr;/* Epilogue code offset */
@@ -298,6 +310,14 @@ struct jit_context {*/ int tail_call_direct_label;int tail_call_indirect_label; + +/* +* Room for one landing per unwind_goto of the prog. Each pass fills it +* again. It lives as long as addrs[]: the extra pass of a prog with +* subprogs has it from the first call of bpf_int_jit_compile(). +*/ +struct jit_landing *landings; +int max_landings; };/* Maximum number of bytes emitted while JITing one eBPF insn */
@@ -2452,6 +2472,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int */* the bytes emitted after the native call of the last call insn */ u8 after_call[16 ], *ret_addr;int after_call_len =0 ; +/* the number of landings in this pass, and their size in bytes so far */ +int nr_landings =0 , tail =0 ;int err; stack_depth = bpf_prog->aux->stack_depth;
@@ -3459,38 +3481,47 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int */* unwind_goto. The verifier expanded may_goto. */ case BPF_JMP |BPF_JCOND : -case BPF_JMP32 |BPF_JCOND : +case BPF_JMP32 |BPF_JCOND : { +int to = i +bpf_jmp_offset (insn); +int target = addrs[to]; +struct jit_landing *landing; +/* an access to arena is in front: no call, nothing to redo */ if (BPF_CLASS (insn[-1 ].code) !=BPF_JMP ) after_call_len =0 ; -if (!after_call_len) { - err =add_unwind_exentry (bpf_prog, image, rw_image, &excnt, - addrs[i -1 ], - addrs[i +bpf_jmp_offset (insn)]); -if (err) -return err; -break ; - }/* * What follows the native call, like 'pop r9', has to be -* done on the way to the pad too: +* done on the way to the pad too. Not in the way of what +* returns: the landing goes behind the body of the +* function, and the next insn follows the call. * call foo * pop r9 <- exit returns here -* jmp 1f +* ... +* leave; ret +* ... * pop r9 <- unwind_exit returns here * jmp pad -* 1: +* addrs[insn_cnt] is where the body ended in the pass before. +* The entry is written when no insn moves any more. */ +if (after_call_len) { +if (nr_landings >= ctx->max_landings) { +pr_err ("bpf_jit: landings bug\n" ); +return -EFAULT ; + } + landing = &ctx->landings[nr_landings++]; +memcpy (landing->code, after_call, after_call_len); + landing->len = after_call_len; + landing->to = to; + target = addrs[insn_cnt] + tail; + tail += after_call_len +5 ; + } err =add_unwind_exentry (bpf_prog, image, rw_image, &excnt, - addrs[i -1 ] - after_call_len, addrs[i -1 ] +2 ); + addrs[i -1 ] - after_call_len, target);if (err)return err; -EMIT2 (0xEB , after_call_len +5 ); -memcpy (prog, after_call, after_call_len); - prog += after_call_len; -EMIT1_off32 (0xE9 , addrs[i +bpf_jmp_offset (insn)] - - (addrs[i -1 ] +2 + after_call_len +5 ));break ; + }case BPF_JMP |BPF_TAIL_CALL :if (imm32)
@@ -3825,6 +3856,30 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * prog = temp; } +/* +* Emit the landings after the last insn. Their jumps always have a 32 +* bit offset, so they have the same size in every pass and the image +* stops shrinking when the body does. addrs[insn_cnt] stays the end of +* the body, and the returned length includes the landings. +*/ +for (i =0 ; i < nr_landings; i++) { +const struct jit_landing *landing = &ctx->landings[i]; + +memcpy (prog, landing->code, landing->len); + prog += landing->len; +EMIT1_off32 (0xE9 , addrs[landing->to] - (proglen + landing->len +5 )); + ilen = prog - temp; +if (image) { +if (unlikely (proglen + ilen > oldproglen)) { +pr_err ("bpf_jit: fatal error\n" ); +return -EFAULT ; + } +memcpy (rw_image + proglen, temp, ilen); + } + proglen += ilen; + prog = temp; + } +if (image && excnt != bpf_prog->aux->num_exentries) {pr_err ("extable is not populated\n" );return -EFAULT ;
@@ -4887,6 +4942,13 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr addrs =kvmalloc_objs (*addrs, prog->len +1 );if (!addrs) goto out_addrs; +for (i =0 ; i < prog->len; i++) + ctx.max_landings +=bpf_is_unwind_goto (&prog->insnsi[i]); +if (ctx.max_landings) { + ctx.landings =kvmalloc_objs (*ctx.landings, ctx.max_landings); +if (!ctx.landings) + goto out_addrs; + }/* * Before first pass, make a rough estimation of addrs[]
@@ -4899,7 +4961,6 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr } ctx.cleanup_addr = proglen; skip_init_addrs: -/* * Jumps are sized by the insns they jump over, which start at * their maximum size, so no insn grows from one pass to the
@@ -5019,6 +5080,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prbpf_prog_fill_jited_linfo (prog, addrs +1 ); out_addrs:kvfree (addrs); +kvfree (ctx.landings);if (!image && priv_stack_ptr) {free_percpu (priv_stack_ptr); prog->aux->priv_stack_ptr =NULL ;
@@ -5123,6 +5185,7 @@ void bpf_jit_free(struct bpf_prog *prog)bpf_jit_binary_pack_finalize (jit_data->header, jit_data->rw_header);kvfree (jit_data->addrs); +kvfree (jit_data->ctx.landings);kfree (jit_data); } prog->bpf_func = (void *)prog->bpf_func -cfi_get_offset ();
tools/testing/selftests/bpf/progs/verifier_unwind.c +5 -2
@@ -1198,7 +1198,9 @@ static unsigned long may_unwind_big_stack(void)/* * x86-64 keeps the pointer to the private stack in r9 and saves it around a call. -* The value that is read back in the pad is there only when r9 is restored. +* The value that is read back in the pad is there only when r9 is restored: on the way of +* unwind_exit a landing behind the last insn of the prog does that. What returns goes on with +* the exit that follows the call. */ SEC("raw_tp")__description ("unwind: private stack, the callee unwinds" )
@@ -1210,7 +1212,8 @@ __jited(" pushq %r9") __jited("...") /* call depth accounting */ __jited(" callq 0x{{.*}}") __jited(" popq %r9") -__jited(" jmp L{{.*}}") +__jited("L{{.*}}: leave") +__jited("...") __jited(" popq %r9") __jited(" jmp L{{.*}}") __arch_arm64
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 55/73 bpf, x86: Return to cancel_goto at cancel_exit
In reply to Kumar Kartikeya DwivediTeach the x86-64 JIT the two insns. cancel_exit emits the code of unwind_exit with bpf_cancel_target() in place of bpf_unwind_target(). cancel_goto is an exception table entry for the call before it, like unwind_goto. It has a key of its own, so that unwind_exit never finds the entry of a cancel_goto, nor cancel_exit that of an unwind_goto. Where code follows the native call, each of the two has a landing after the function:
call foo returns to ret_addr
pop r9
...
leave; ret
pop r9; jmp A <- unwind_goto A: { .insn = ret_addr - 1 }
pop r9; jmp B <- cancel_goto B: { .insn = ret_addr - 2 }These cases need care:
- No insn may start at a key, so that a fault cannot hit the entry. 'call *%rax' of callx has 2 bytes, so it gets an empty REX prefix when a cancel_goto follows it.
- The code of an access to arena can end in an insn of 2 bytes. A cancel_goto never follows such an access, and the JIT fails if it finds one there.
- The exception table is sorted by address. When a call has both insns, the entry of the cancel_goto is added second and takes the place of the entry of the unwind_goto, which moves up.
- The landing of a cancel_goto does not redo 'mov rsi, rdx' after a kfunc that returns 16 bytes, because R2 after cancel_exit is not the second half of what the kfunc returned.
The lookup is one function for both keys. For a callback that a helper called, it now adds the offset of the entry point to the address of the stub of bpf_call_cb(): BPF_CB_PAD_OFF or BPF_CB_CANCEL_OFF. Nothing runs the first byte of the x86-64 stub any more, and it becomes an int3. The jump of an optimized kprobe before the stub could cover a nop and end after the first entry point. Such a jump never covers an int3.
Both lookups become notrace and are put on the kprobe blacklist, because the kernel is going to find the program by the address that they return to. The verifier emits neither insn yet.
--- arch/x86/net/bpf_jit_comp.c | 221 ++++++++++++++++++++++++++---------- include/linux/bpf_unwind.h | 14 ++- 2 files changed, 168 insertions(+), 67 deletions(-)
arch/x86/net/bpf_jit_comp.c +160 -61
@@ -10,6 +10,7 @@#include <linux/if_vlan.h> #include <linux/bitfield.h> #include <linux/bpf.h> +#include <linux/bpf_unwind.h> #include <linux/bpf_verifier.h> #include <linux/memory.h> #include <linux/sort.h>
@@ -289,10 +290,8 @@ int bpf_arch_text_invalidate(void *dst, size_t len) }/* -* A LANDING: where unwind_exit of a callee comes back to when the call has code -* behind its native call, like 'pop r9'. That code, done once more, and a jump -* to the insn that unwind_goto goes to. The landings stand behind the body of -* the function, see do_jit(). +* 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. */ struct jit_landing {u8 code[16 ];
@@ -312,9 +311,9 @@ struct jit_context {int tail_call_indirect_label;/* -* Room for one landing per unwind_goto of the prog. Each pass fills it -* again. It lives as long as addrs[]: the extra pass of a prog with -* subprogs has it from the first call of bpf_int_jit_compile(). +* Room for one landing per unwind_goto and cancel_goto of the prog. +* Each pass fills the array again. It is allocated and freed together +* with addrs[], so the extra pass of a prog with subprogs has it too. */ struct jit_landing *landings;int max_landings;
@@ -728,20 +727,29 @@ static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip) *pprog = prog; } -static void __emit_indirect_call (u8 **pprog,int reg,bool ereg) +static void __emit_indirect_call (u8 **pprog,int reg,bool ereg,bool rex) {u8 *prog = *pprog;if (ereg)EMIT1 (0x41 ); +else if (rex) +EMIT1 (0x40 );EMIT2 (0xFF ,0xD0 + reg); *pprog = prog; } -/* call *bpf_reg */ -static int emit_indirect_call (u8 **pprog,int bpf_reg,u8 *ip) +/* +* call *bpf_reg +* +* @rex: a cancel_goto follows the call. Its extable entry is 2 bytes before the +* return address, and no insn may start there, see CANCEL_EXKEY. 'call *%rax' +* is 2 bytes long, so give it a REX prefix with no bits set, which only adds a +* byte. The call of a thunk is 5 bytes long. +*/ +static int emit_indirect_call (u8 **pprog,int bpf_reg,u8 *ip,bool rex) {u8 *prog = *pprog;int reg = reg2hex[bpf_reg];
@@ -753,7 +761,7 @@ static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip) err =emit_call (&prog,its_thunk (reg +8 *ereg), ip); }else if (cpu_feature_enabled (X86_FEATURE_RETPOLINE_LFENCE )) {EMIT_LFENCE (); -__emit_indirect_call (&prog, reg, ereg); +__emit_indirect_call (&prog, reg, ereg, rex); }else if (cpu_feature_enabled (X86_FEATURE_RETPOLINE )) {OPTIMIZER_HIDE_VAR (reg);if (cpu_feature_enabled (X86_FEATURE_CALL_DEPTH ))
@@ -761,7 +769,7 @@ static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)else err =emit_call (&prog, &__x86_indirect_thunk_array[reg +8 *ereg], ip); }else { -__emit_indirect_call (&prog, reg, ereg); +__emit_indirect_call (&prog, reg, ereg, rex); } *pprog = prog;
@@ -2349,11 +2357,31 @@ static void adjust_cmp_imm(u32 *op, s32 *imm)* replaces the return address of its frame with bpf_unwind_target() of it. * ret_addr - 1, because what follows the call can have an entry of its own. * No insn starts there, so a fault cannot hit the entry. +* +* unwind_goto can also follow an access to arena. ret_addr is then the end of +* the code of the access, and a fault in the access goes to the target, see +* bpf_fault_unwind_target(). +* +* cancel_goto is the same for cancel_exit and bpf_cancel_target(). Its entry +* is at ret_addr - 2, because the unwind_goto of the same call has the one at +* ret_addr - 1. No insn starts there either: a call that cancel_goto follows +* is at least 3 bytes long, see emit_indirect_call(). cancel_goto never +* follows an access to arena, whose code can end in an insn of 2 bytes. +*/ +#define UNWIND_EXKEY 1 +#define CANCEL_EXKEY 2 + +/* +* Add the extable entry of an unwind_goto or a cancel_goto with the key @key. +* +* @after_unwind: the entry before this one is that of the unwind_goto of the +* same call. The table is sorted by address and the key of cancel_goto is the +* lower one, so the new entry takes that slot and the other one moves up. */ static int add_unwind_exentry (struct bpf_prog *prog,u8 *image,u8 *rw_image,int *excnt, -int ret_addr,int target) +int ret_addr,int target,int key,bool after_unwind) { -struct exception_table_entry *ex; +struct exception_table_entry *ex, *rw;s64 delta;if (!prog->aux->extable)
@@ -2363,54 +2391,80 @@ static int add_unwind_exentry(struct bpf_prog *prog, u8 *image, u8 *rw_image, inreturn -EFAULT ; } ex = &prog->aux->extable[(*excnt)++]; - delta = image + ret_addr -1 - (u8 *)&ex->insn; +/* switch ex to rw buffer for writes */ + rw = (void *)rw_image + ((void *)ex - (void *)image); +if (after_unwind) { +/* insn is relative to the address of the entry, which moves */ + *rw = rw[-1 ]; + rw->insn -=sizeof (*rw); + ex--; + rw--; + } + delta = image + ret_addr - key - (u8 *)&ex->insn;if (!is_simm32 (delta)) {pr_err ("extable->insn doesn't fit into 32-bit\n" );return -EFAULT ; } -/* switch ex to rw buffer for writes */ - ex = (void *)rw_image + ((void *)ex - (void *)image); - ex->insn = delta; - ex->fixup = target - ret_addr; - ex->data =EX_TYPE_BPF ; + rw->insn = delta; + rw->fixup = target - ret_addr; + rw->data =EX_TYPE_BPF ;return 0 ; }/* -* The verifier made sure that unwind_goto follows a call in a prog. When the -* kernel called an async callback, it's exit. A helper that calls a callback -* has a pad when it wants one, see bpf_call_cb(). +* Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with +* cancel_exit, @key CANCEL_EXKEY, returns to. +* The verifier made sure that unwind_goto follows a call in a prog, and +* cancel_goto where the callee has cancel_exit. When the kernel called an async +* callback, it's exit. A helper that calls a callback has a pad when it wants +* one, see bpf_call_cb(). */ -u64 bpf_unwind_target (u64 ret_addr) +static u64 unwind_target (u64 ret_addr,int key) {const struct exception_table_entry *e; - e =search_bpf_extables (ret_addr -1 ); + e =search_bpf_extables (ret_addr - key);if (e)return ret_addr + e->fixup;/* -* The pad of a helper that called a callback with bpf_call_cb(): its -* entries are the EX_TYPE_BPF ones of the kernel and module tables. -* Anything else at a return address is some caller's own fixup, and -* what a JIT keyed there is a fixup of the insn after the call. +* A helper that called the frame with bpf_call_cb() has an EX_TYPE_BPF +* entry at the return address itself. An entry of another type there +* is the fixup of the insn after some call. The entry points to the +* stub of the helper's unwind label, which has one entry point for +* unwind_exit and one for cancel_exit. */ e =search_kernel_exception_table (ret_addr);if (!e) e =search_module_extables (ret_addr);if (e && (e->data &EX_DATA_TYPE_MASK ) ==EX_TYPE_BPF ) -return (unsigned long )&e->fixup + e->fixup; +return (unsigned long )&e->fixup + e->fixup + + (key ==CANCEL_EXKEY ?BPF_CB_CANCEL_OFF :BPF_CB_PAD_OFF );/* * No pad. That is how it ends when the kernel called an async callback * or the main prog of an extension: it's exit. A call in a prog of what * can unwind has unwind_goto behind it, which is an entry also when the -* pad is the next insn. So a return address in a prog without an entry -* is an unwind_exit that gets lost: the verifier sent it to a pad. +* pad is the next insn, and cancel_goto behind a call of what has +* cancel_exit. So a return address in a prog without an entry is an +* unwind_exit or a cancel_exit that gets lost: the verifier sent it to +* a pad. */ scoped_guard (rcu) WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));return ret_addr; } +u64 notrace bpf_unwind_target(u64 ret_addr) +{ +return unwind_target (ret_addr,UNWIND_EXKEY ); +} +NOKPROBE_SYMBOL (bpf_unwind_target); + +u64 notrace bpf_cancel_target(u64 ret_addr) +{ +return unwind_target (ret_addr,CANCEL_EXKEY ); +} +NOKPROBE_SYMBOL (bpf_cancel_target); +/* * Return where a program continues after a fault in an access to arena whose * code ends at @end: at the target of the unwind_goto after the access, or at
@@ -2418,16 +2472,31 @@ u64 bpf_unwind_target(u64 ret_addr)*/ u64 bpf_fault_unwind_target (u64 end) { -const struct exception_table_entry *e =search_bpf_extables (end -1 ); +const struct exception_table_entry *e =search_bpf_extables (end -UNWIND_EXKEY );return e ? end + e->fixup : end; }/* -* unwind_exit: fix the return address of this frame. r0 and r2 are returned. -* So is BPF_REG_ARENA_SP, when it's used. +* Return true if a cancel_goto follows @call, directly or after the unwind_goto +* of the call. @cnt insns follow @call in the prog. +*/ +static bool call_has_cancel_goto (const struct bpf_insn *call,int cnt) +{ +if (cnt &&bpf_is_unwind_goto (call +1 )) { + call++; + cnt--; + } +return cnt &&bpf_is_cancel_goto (call +1 ); +} + +/* +* 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. */ -static int emit_unwind_ret_addr (u8 **pprog,u8 *ip,bool arena_sp) +static int emit_unwind_ret_addr (u8 **pprog,u8 *ip,bool arena_sp,void *target) {u8 *prog = *pprog, *start = prog;
@@ -2435,7 +2504,7 @@ static int emit_unwind_ret_addr(u8 **pprog, u8 *ip, bool arena_sp)if (arena_sp)push_r9 (&prog);EMIT4 (0x48 ,0x8B ,0x7D ,0x08 );/* mov rdi, [rbp + 8] */ -if (emit_rsb_call (&prog, bpf_unwind_target, ip + (prog - start))) +if (emit_rsb_call (&prog, target, ip + (prog - start)))return -EINVAL ;EMIT4 (0x48 ,0x89 ,0x45 ,0x08 );/* mov [rbp + 8], rax */ if (arena_sp)
@@ -2471,7 +2540,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *s32 arena_sp_off =0 ;/* the bytes emitted after the native call of the last call insn */ u8 after_call[16 ], *ret_addr; -int after_call_len =0 ; +/* 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 */ int nr_landings =0 , tail =0 ;int err;
@@ -3443,6 +3513,11 @@ 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); +/* +* The landing of cancel_goto ends here: after cancel_exit RDX +* is not the second half of what the kfunc returned. +*/ + after_call_cancel_len = prog - ret_addr;/* * A kfunc returning more than 8 bytes hands the second * half back in RDX (the native ABI's second return reg),
@@ -3470,54 +3545,75 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *push_r9 (&prog); ip +=2 ; } -if (emit_indirect_call (&prog, insn->dst_reg, ip)) +if (emit_indirect_call (&prog, insn->dst_reg, ip, +call_has_cancel_goto (insn, insn_cnt - i)))return -EINVAL ; ret_addr = prog;if (priv_frame_ptr)pop_r9 (&prog); - after_call_len = prog - ret_addr; + after_call_len = after_call_cancel_len = prog - ret_addr;memcpy (after_call, ret_addr, after_call_len);break ; -/* unwind_goto. The verifier expanded may_goto. */ +/* unwind_goto, cancel_goto. The verifier expanded may_goto. */ case BPF_JMP |BPF_JCOND :case BPF_JMP32 |BPF_JCOND : { +bool cancel_goto =bpf_is_cancel_goto (insn); +/* 'call; unwind_goto; cancel_goto', and this is the second one */ +bool after_unwind = cancel_goto && i >1 &&bpf_is_unwind_goto (insn -1 ); +int key = cancel_goto ?CANCEL_EXKEY :UNWIND_EXKEY ;int to = i +bpf_jmp_offset (insn);int target = addrs[to]; +/* how many bytes of after_call[] the landing of this insn repeats */ +int len = cancel_goto ? after_call_cancel_len : after_call_len;struct jit_landing *landing; -/* an access to arena is in front: no call, nothing to redo */ -if (BPF_CLASS (insn[-1 ].code) !=BPF_JMP ) - after_call_len =0 ; +if (BPF_CLASS (insn[-1 - after_unwind].code) !=BPF_JMP ) { +if (cancel_goto) { +pr_err ("bpf_jit: cancel_goto follows no call\n" ); +return -EFAULT ; + } +/* after an access to arena: no call, nothing to repeat */ + after_call_len = after_call_cancel_len = len =0 ; + }/* -* What follows the native call, like 'pop r9', has to be -* done on the way to the pad too. Not in the way of what -* returns: the landing goes behind the body of the -* function, and the next insn follows the call. +* Neither insn emits code here, only an extable entry for the +* call before it, see UNWIND_EXKEY. Where code follows the +* native call, like 'pop r9', the entry points to a landing, +* which repeats that code and jumps to the target. The landings +* go after the last insn, so that a call that returns does not +* jump over them: +* * call foo -* pop r9 <- exit returns here +* pop r9 <- exit returns here, to ret_addr * ... * leave; ret -* ... -* pop r9 <- unwind_exit returns here -* jmp pad -* addrs[insn_cnt] is where the body ended in the pass before. -* The entry is written when no insn moves any more. +* pop r9; jmp pad <- unwind_exit returns here, key ret_addr - 1 +* pop r9; jmp cancel_pad <- cancel_exit returns here, key ret_addr - 2 +* +* The entry is written once the image is allocated. The landings +* then start at addrs[insn_cnt], where the pass before ended the +* body. */ -if (after_call_len) { +if (len) {if (nr_landings >= ctx->max_landings) {pr_err ("bpf_jit: landings bug\n" );return -EFAULT ; } landing = &ctx->landings[nr_landings++]; -memcpy (landing->code, after_call, after_call_len); - landing->len = after_call_len; +memcpy (landing->code, after_call, len); + landing->len = len; landing->to = to; target = addrs[insn_cnt] + tail; - tail += after_call_len +5 ; + tail += len +5 ; } +/* +* The return address of the native call: the code of the call +* insn ends where the first goto after it begins. +*/ err =add_unwind_exentry (bpf_prog, image, rw_image, &excnt, - addrs[i -1 ] - after_call_len, target); + addrs[i -1 - after_unwind] - after_call_len, + target, key, after_unwind);if (err)return err;break ;
@@ -3792,7 +3888,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)) +emit_unwind_ret_addr (&prog, ip, arena_sp, 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))return -EINVAL ;if (seen_exit) { jmp_offset = ctx->cleanup_addr - addrs[i] + moved;
@@ -4943,7 +5042,7 @@ 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_unwind_goto (&prog->insnsi[i]); + ctx.max_landings +=bpf_is_pad_goto (&prog->insnsi[i]);if (ctx.max_landings) { ctx.landings =kvmalloc_objs (*ctx.landings, ctx.max_landings);if (!ctx.landings)
include/linux/bpf_unwind.h +8 -6
@@ -86,10 +86,12 @@#endif /* -* The offsets of the two entry points in the stub. unwind_exit returns after a nop. A stack walk -* looks up the insn before a return address, and for a sample that is taken while the callback -* returns to the stub that has to be an insn of the stub. cancel_exit returns after the clc and -* the jnc. +* The offsets of the two entry points in the stub. unwind_exit returns after an int3 that nothing +* runs. A stack walk looks up the insn before a return address, and for a sample that is taken +* while the callback returns to the stub that has to be an insn of the stub. It is not a nop, +* because the 5 byte jump of an optimized kprobe before the stub could cover a nop and end after +* the entry point. No such jump covers an int3, see copy_optimized_instructions(), or the jnc +* before the second entry point, where cancel_exit returns. */ #define BPF_CB_PAD_OFF 1#define BPF_CB_CANCEL_OFF 4
@@ -103,7 +105,7 @@* instrumentation included, would clobber the variables. * * The stub is in a subsection after the code, where nothing falls into it. unwind_exit returns -* after the nop at 4, with the carry flag clear from there on. cancel_exit returns to 5, which +* after the int3 at 4, with the carry flag clear from there on. cancel_exit returns to 5, which * sets the flag. sbb turns the flag into 'kind', in rcx, which the call clobbers anyway. objtool * reaches 4 through the exception table and 5 as the fall-through of the jnc, although the jnc * is always taken. The jnc is spelled in bytes so that its length does not depend on the
@@ -123,7 +125,7 @@ do { \" " CALL_NOSPEC "\n" \"1:\n" \" .subsection 1\n" \ -"4: nop\n" \ +"4: int3\n" \" clc\n" \" .byte 0x73, 0x01\n" /* jnc 6f */ \"5: stc\n" \
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 56/73 bpf, arm64: Return to cancel_goto at cancel_exit
In reply to Kumar Kartikeya DwivediTeach the arm64 JIT the two insns, as on x86-64. cancel_exit emits the code of unwind_exit with bpf_cancel_fixup() in place of bpf_unwind_fixup(). cancel_goto is an exception table entry for the call before it, like unwind_goto, with a key of its own. After the call of a helper or a kfunc, each of the two has a landing after the epilogue, because a helper returns R0 in x0 alone:
bl helper returns to ret_addr
mov x8, x0
...
<epilogue>
mov x8, x0; b A <- unwind_goto A: { .insn = ret_addr - 1 }
mov x8, x0; b B <- cancel_goto B: { .insn = ret_addr - 2 }Both keys are inside the four bytes of the bl. No insn starts there, so a fault cannot hit either entry.
Three cases need care:
- The exception table is sorted by address. When a call has both insns, the unwind_goto adds no entry itself. The cancel_goto after it adds both entries, its own first.
- The two landings of such a call stand in the order of the insns, which is the order in which build_landings() gets to them.
- A cancel_goto never follows an access to arena, and the JIT fails if it finds one there.
The lookup changes as on x86-64. It is one function for both keys, it adds BPF_CB_PAD_OFF or BPF_CB_CANCEL_OFF to the address of the stub of bpf_call_cb(), and both lookups become notrace and are put on the kprobe blacklist. The verifier emits neither insn yet.
--- arch/arm64/net/bpf_jit_comp.c | 175 +++++++++++++++++++++++++--------- 1 file changed, 132 insertions(+), 43 deletions(-)
arch/arm64/net/bpf_jit_comp.c +132 -43
@@ -10,6 +10,7 @@#include <linux/arm-smccc.h> #include <linux/bitfield.h> #include <linux/bpf.h> +#include <linux/bpf_unwind.h> #include <linux/cfi.h> #include <linux/extable.h> #include <linux/filter.h>
@@ -1655,11 +1656,14 @@ static int add_exception_handler(const struct bpf_verifier_env *env,return 0 ; } -/* unwind_goto after the call of a helper or a kfunc, which return r0 in x0 alone */ -static bool unwind_goto_after_helper (const struct bpf_insn *insn) +/* 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) {const struct bpf_insn *call = insn -1 ; +/* '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 ; }
@@ -1674,8 +1678,15 @@ static bool unwind_goto_after_helper(const struct bpf_insn *insn)* a helper, see build_landings(). * After an access to arena, ret_addr is the end of the code of the access, and * a fault in the access goes to the target, see bpf_fault_unwind_target(). +* +* cancel_goto is the same for cancel_exit, with the entry at ret_addr - 2, +* because the unwind_goto of the same call has the one at ret_addr - 1. Both +* keys are inside the call insn. cancel_goto never follows an access to arena. */ -static int add_unwind_exentry (struct jit_ctx *ctx,int ret_addr,int target) +#define UNWIND_EXKEY 1 +#define CANCEL_EXKEY 2 + +static int add_unwind_exentry (struct jit_ctx *ctx,int ret_addr,int target,int key) {struct exception_table_entry *ex;off_t ins_offset;
@@ -1689,7 +1700,7 @@ static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target)return -EINVAL ; ex = &ctx->prog->aux->extable[ctx->exentry_idx]; - ins_offset = (long )&ctx->ro_image[ret_addr] -1 - (long )&ex->insn; + ins_offset = (long )&ctx->ro_image[ret_addr] - key - (long )&ex->insn;if (WARN_ON_ONCE (ins_offset >=0 || ins_offset <INT_MIN ))return -ERANGE ;
@@ -1704,10 +1715,39 @@ static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target) }/* -* The landings of the pads after the calls of helpers and kfuncs, past the -* epilogue, where nothing falls into them: 'mov x8, x0; b pad' each, see the -* unwind_goto case of build_insn(). They go in after the body, when the pads -* are placed and the entries are in, and each fills in the fixup of its entry. +* Add the extable entry of @insn, an unwind_goto or cancel_goto after a call +* that returns to @ret_addr. If the insn gets a landing, *@landing is the index +* of the entry, and build_landings() fills in the fixup. +*/ +static int add_goto_exentry (struct jit_ctx *ctx,const struct bpf_insn *insn,int ret_addr, +int *landing) +{ +int i = insn - ctx->prog->insnsi; +int target = ctx->offset[i +1 +bpf_jmp_offset (insn)]; + +if (goto_after_helper (insn)) { + *landing = ctx->exentry_idx; + target = ret_addr; + } +return add_unwind_exentry (ctx, ret_addr, target, +bpf_is_cancel_goto (insn) ?CANCEL_EXKEY :UNWIND_EXKEY ); +} + +/* +* Emit the landings after the epilogue. r0 is x8, so 'mov x8, x0' follows a +* call. A helper or a kfunc that leaves through its unwind label skips the mov, +* so an unwind_goto or cancel_goto after its call gets a landing, which does +* the mov and branches to the target: +* +* bl helper returns to ret_addr +* mov x8, x0 +* ... +* <epilogue> +* mov x8, x0; b pad <- unwind_exit returns here, key ret_addr - 1 +* 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. */ static int build_landings (struct jit_ctx *ctx) {
@@ -1718,8 +1758,9 @@ static int build_landings(struct jit_ctx *ctx)const struct bpf_insn *insn = &prog->insnsi[i];int ret_addr, jmp_offset; -if (!bpf_is_unwind_goto (insn) || !unwind_goto_after_helper (insn)) +if (!bpf_is_pad_goto (insn) || !goto_after_helper (insn))continue ; +/* unwind_goto emits no code, so this also holds for the cancel_goto after it */ ret_addr = ctx->offset[i] -1 ;if (ctx->image) {struct exception_table_entry *ex;
@@ -1738,40 +1779,59 @@ static int build_landings(struct jit_ctx *ctx) }/* -* The verifier made sure that unwind_goto follows a call in a prog. When the -* kernel called an async callback, it's exit. A helper that calls a callback -* has a pad when it wants one, see bpf_call_cb(). +* Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with +* cancel_exit, @key CANCEL_EXKEY, returns to. +* The verifier made sure that unwind_goto follows a call in a prog, and +* cancel_goto where the callee has cancel_exit. When the kernel called an async +* callback, it's exit. A helper that calls a callback has a pad when it wants +* one, see bpf_call_cb(). */ -u64 bpf_unwind_target (u64 ret_addr) +static u64 unwind_target (u64 ret_addr,int key) {const struct exception_table_entry *e; - e =search_bpf_extables (ret_addr -1 ); + e =search_bpf_extables (ret_addr - key);if (e)return ret_addr + e->fixup;/* -* The pad of a helper that called a callback with bpf_call_cb(): its -* entries are the EX_TYPE_BPF ones of the kernel and module tables. -* Anything else at a return address is some caller's own fixup, and -* what a JIT keyed there is a fixup of the insn after the call. +* A helper that called the frame with bpf_call_cb() has an EX_TYPE_BPF +* entry at the return address itself. An entry of another type there +* is the fixup of the insn after some call. The entry points to the +* stub of the helper's unwind label, which has one entry point for +* unwind_exit and one for cancel_exit. */ e =search_kernel_exception_table (ret_addr);if (!e) e =search_module_extables (ret_addr);if (e && e->type ==EX_TYPE_BPF ) -return (unsigned long )&e->fixup + e->fixup; +return (unsigned long )&e->fixup + e->fixup + + (key ==CANCEL_EXKEY ?BPF_CB_CANCEL_OFF :BPF_CB_PAD_OFF );/* * No pad. That is how it ends when the kernel called an async callback * or the main prog of an extension: it's exit. A call in a prog of what * can unwind has unwind_goto behind it, which is an entry also when the -* pad is the next insn. So a return address in a prog without an entry -* is an unwind_exit that gets lost: the verifier sent it to a pad. +* pad is the next insn, and cancel_goto behind a call of what has +* cancel_exit. So a return address in a prog without an entry is an +* unwind_exit or a cancel_exit that gets lost: the verifier sent it to +* a pad. */ scoped_guard (rcu) WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));return ret_addr; } +u64 notrace bpf_unwind_target(u64 ret_addr) +{ +return unwind_target (ret_addr,UNWIND_EXKEY ); +} +NOKPROBE_SYMBOL (bpf_unwind_target); + +u64 notrace bpf_cancel_target(u64 ret_addr) +{ +return unwind_target (ret_addr,CANCEL_EXKEY ); +} +NOKPROBE_SYMBOL (bpf_cancel_target); +/* * Return where a program continues after a fault in an access to arena whose * code ends at @end: at the target of the unwind_goto after the access, or at
@@ -1779,7 +1839,7 @@ u64 bpf_unwind_target(u64 ret_addr)*/ u64 bpf_fault_unwind_target (u64 end) { -const struct exception_table_entry *e =search_bpf_extables (end -1 ); +const struct exception_table_entry *e =search_bpf_extables (end -UNWIND_EXKEY );return e ? end + e->fixup : end; }
@@ -1792,12 +1852,21 @@ static long bpf_unwind_fixup(u64 lr)return bpf_unwind_target (ret_addr) - ret_addr; } +/* The same for cancel_exit */ +static long bpf_cancel_fixup (u64 lr) +{ +u64 ret_addr =ptrauth_strip_kernel_insn_pac (lr); + +return bpf_cancel_target (ret_addr) - ret_addr; +} +/* -* unwind_exit: return to the pad. LR in the frame record is signed. Instead of -* signing the address of the pad, let the epilogue authenticate LR as it is and -* add the offset of the pad to it. r0 and r2 are returned. +* unwind_exit, cancel_exit: return to the pad. LR in the frame record is +* signed. Instead of signing the address of the pad, let the epilogue +* authenticate LR as it is and add the offset of the pad to it, which @fixup +* returns. r0 and r2 are returned. */ -static void emit_unwind_exit (struct jit_ctx *ctx) +static void emit_unwind_exit (struct jit_ctx *ctx,long (*fixup)(u64 lr)) {const u8 tmp = bpf2a64[TMP_REG_1 ];const u8 r0 = bpf2a64[BPF_REG_0 ];
@@ -1805,7 +1874,7 @@ static void emit_unwind_exit(struct jit_ctx *ctx)emit (A64_PUSH (r0, r2,A64_SP ), ctx);emit (A64_LDR64I (A64_R (0 ),A64_FP ,8 ), ctx); -emit_call ((u64 )bpf_unwind_fixup, ctx); +emit_call ((u64 )fixup, ctx);emit (A64_MOV (1 , tmp,A64_R (0 )), ctx);emit (A64_POP (r0, r2,A64_SP ), ctx);build_epilogue (ctx, false, true);
@@ -2427,37 +2496,57 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insnif (emit_bpf_tail_call (ctx))return -EFAULT ;break ; -/* unwind_goto. The verifier expanded may_goto. */ +/* unwind_goto, cancel_goto. The verifier expanded may_goto. */ case BPF_JMP |BPF_JCOND :case BPF_JMP32 |BPF_JCOND : { +bool cancel_goto =bpf_is_cancel_goto (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 target = ctx->offset[i +1 +bpf_jmp_offset (insn)]; +int j;/* -* 'bl foo; mov x8, x0' is in front. After the call of a subprog -* the pad doesn't miss the mov: r0 is x8 in the subprog too, its -* epilogue copies x8 to x0 and leaves x8 as it is. A helper that -* leaves to the pad returns r0 in x0 alone, so the pad after its -* call is entered through a landing past the epilogue, see -* build_landings(), which fills in the fixup of the entry. +* 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 +* it: the cancel_goto adds both entries, its own first. */ -if (unwind_goto_after_helper (insn)) { - ctx->landing_ex[ctx->landing_idx++] = ctx->exentry_idx; - target = ret_addr; - }else if (BPF_CLASS (insn[-1 ].code) !=BPF_JMP ) { +if (!cancel_goto && i +1 < ctx->prog->len &&bpf_is_cancel_goto (insn +1 )) +break ; +if (BPF_CLASS (insn[-1 - after_unwind].code) !=BPF_JMP ) { +if (cancel_goto) { +pr_err_once ("cancel_goto at insn %d follows no call\n" , i); +return -EFAULT ; + }/* After an access to arena. Its last insn is the one that can fault. */ ret_addr = ctx->idx; } - ret =add_unwind_exentry (ctx, ret_addr, target); +/* +* Else 'bl foo; mov x8, x0' is in front. After the call of a subprog +* the target doesn't miss the mov: r0 is x8 in the subprog too, and +* its epilogue copies x8 to x0 and leaves x8 as it is. After the +* call of a helper the entry points to a landing. +*/ + ret =add_goto_exentry (ctx, insn, ret_addr, &landing[after_unwind]); +if (!ret && after_unwind) + ret =add_goto_exentry (ctx, insn -1 , ret_addr, &landing[0 ]);if (ret)return ret; +/* build_landings() emits the landings in the order of the insns */ +for (j =0 ; j <2 ; j++) +if (landing[j] >=0 ) + ctx->landing_ex[ctx->landing_idx++] = landing[j];break ; }/* function return */ case BPF_JMP |BPF_EXIT :if (bpf_is_unwind_exit (insn) &&bpf_prog_can_unwind (ctx->prog)) { -emit_unwind_exit (ctx); +emit_unwind_exit (ctx, bpf_unwind_fixup); +break ; + } +if (bpf_is_cancel_exit (insn) &&bpf_prog_can_unwind (ctx->prog)) { +emit_unwind_exit (ctx, bpf_cancel_fixup);break ; }/* Optimization: when last instruction is EXIT,
@@ -2812,8 +2901,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr goto out_off;for (i =1 ; i < prog->len; i++) -if (bpf_is_unwind_goto (&prog->insnsi[i]) && -unwind_goto_after_helper (&prog->insnsi[i])) +if (bpf_is_pad_goto (&prog->insnsi[i]) && +goto_after_helper (&prog->insnsi[i])) nr_landings++;if (nr_landings) { ctx.landing_ex =kvzalloc_objs (int, nr_landings);
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 57/73 bpf: Use cancel_exit to leave a frame that the kernel cancels
In reply to Kumar Kartikeya DwivediCurrently the generated pads leave a function with unwind_exit. So where a caller has an unwind_goto of its own after the call, a cancellation enters the program's landing pad, and the program can continue running.
Emit cancel_exit and cancel_goto instead:
- A generated pad at a site leaves with cancel_exit, and so does the stack check of a recursive function. A function that only the kernel calls still leaves with exit.
- The verifier adds a cancel_goto after each call whose callee can be cancelled. It jumps to the generated pad of that call. Where the program has an unwind_goto after the call, the cancel_goto follows it.
try { call wait
v = wait(); unwind_goto catch <- wait() threw on its own
} catch (...) { cancel_goto pad <- wait() was cancelled
v = 0; ...
} catch: ...
exit
pad: r0 = 0
exitcancel_exit returns to a cancel_goto only, and unwind_exit to an unwind_goto only. So a cancellation enters no landing pad of the program, and none can end it. The program returns the value that the kernel chooses for its type.
What changes for programs that load today:
- A landing pad of the program that ran when a callee was cancelled no longer runs then, not even one that only cleans up and continues unwinding, such as a C++ destructor. The generated pad releases what the verifier knows the frame to hold. Later patches let a cancellation run such cleanup pads again.
- A call above a site is now a site itself, also where the program has an unwind_goto after it. A program is rejected if a frame holds something there that no generated pad can release.
In the main pass, a state whose callee did not return carries a mark. The new value BPF_CANCELLED says that the callee was cancelled. Such a state never takes the program's unwind_goto. Its frame is cancelled in turn at the call, a site of the new kind BPF_SITE_CANCEL_CALL. The verifier does not merge two states that differ in the mark, and the bits that record whether a function can unwind (did_unwind, can_unwind, must_unwind, unwinds_for_sure) each get a twin for cancellation.
The pads that the verifier generates for the program's own unwinding stay (BPF_SITE_CALL). Where a callee leaves with unwind_exit and the caller has no unwind_goto after the call, the verifier adds one, with a pad that leaves with unwind_exit in turn. Such a pad no longer serves a cancellation, so it is always on the way to a landing pad of the program. Until now it passed R0 on only in a program with bpf_throw(). Now the rule is the same in every program, and verifier.rst has it as a table:
- In a static function the pad passes on R0, a pointer as well as a number, and R2 if the function returns two registers.
- In a global function the pad passes nothing on, because the callers are verified separately and only see a scalar return value. R0 is the value that the kernel chooses for the program type.
These cases need care:
- R2 is 0 at every cancel_exit, so that the code after a cancel_goto reads nothing of the cancelled frame.
- The program's unwind_goto takes its 32 bit form where a cancel_goto follows it, so that the patch list never puts a jump between the two. If no state reached the program's unwind_goto, it is dead code, and the cancel_goto goes right after the call.
- Neither insn may be the target of a jump, because a JIT may put a landing where the insn is. bpf_check_unwind_gotos() reports as a verifier bug an unwind_goto or cancel_goto that jumps to one of the two, and any jump to a cancel_goto after an unwind_goto.
- The inlined bpf_loop() passes on a cancelled callback like one that left with unwind_exit, with four more insns.
The tests that expected the program's landing pad to catch a cancellation now expect the value that the kernel chooses. pad_forgets of verifier_budget loads, because the landing pad of the program that made it fail is no longer entered.
--- Documentation/bpf/verifier.rst | 92 ++++- include/linux/bpf_verifier.h | 149 ++++++- kernel/bpf/const_fold.c | 11 +- kernel/bpf/core.c | 20 +- kernel/bpf/fixups.c | 374 +++++++++++++----- kernel/bpf/pads.c | 235 +++++++---- kernel/bpf/verifier.c | 372 +++++++++++------ .../bpf/progs/pro_epilogue_arena_stack.c | 2 +- .../bpf/progs/verifier_arena_stack.c | 27 +- .../selftests/bpf/progs/verifier_budget.c | 75 ++-- .../selftests/bpf/progs/verifier_patch_list.c | 5 +- 11 files changed, 956 insertions(+), 406 deletions(-)
Documentation/bpf/verifier.rst +73 -19
@@ -749,7 +749,7 @@ if the loop ends because ===================================== ========================================= k of s is at most 2^32 k grows in each trip and has a bound; the largest k + 1 is the *trip count* -each trip runs ``may_goto`` it leaves the loop after some time or +each trip runs ``may_goto`` it stops the loop after some time or some number of trips each trip takes from an iterator an iterator has an end none of these holds the verifier adds ``may_goto``
@@ -915,10 +915,10 @@ Cancellation ============ The kernel *cancels* a program when it has to end the program before the -program returns by itself: a ``may_goto`` of the verifier is taken, the stack -check of a recursive function fails, an access to arena faults, or the program -calls ``bpf_throw()``. Each frame of the program then releases what it holds, -and the program returns a value that the kernel chooses. +program returns by itself: a ``may_goto`` is taken, the stack check of a +recursive function fails, an access to arena faults, or the program calls +``bpf_throw()``. Each frame of the program then releases what it holds, and the +program returns a value that the kernel chooses. An insn at which the kernel can cancel the program is a *site*: one of these four insns, or a call whose callee can be cancelled. For each site the verifier
@@ -937,7 +937,9 @@ what the frame holds at the site and leaves the frame:: exit When the time is up, ``may_goto`` jumps to the pad, and the program ends without -getting to ``*p``. +getting to ``*p``. A ``may_goto`` of the program is a site too, where a JIT +gives it a time limit: when the time is up, the code at its target does not +run. Where it counts trips, it stays a plain jump. The pad of a function that the kernel called ends in ``exit``. The main function returns the value that the kernel chooses for the program type, see
@@ -947,21 +949,22 @@ errno. It is 0 in the listings here. After ``bpf_throw()`` it is the argument of ``bpf_throw()``. If the program has an exception callback, the pad of the main function calls it with the value and returns what the callback returns. -The pad of a function that the program called ends in ``unwind_exit``. That -insn returns to the ``unwind_goto`` after the call, which jumps to the landing +The pad of a function that the program called ends in ``cancel_exit``. That +insn returns to the ``cancel_goto`` after the call, which jumps to the landing pad of the call in the caller. So the frames are cancelled one by one. When a -callback is cancelled, its helper returns to the ``unwind_goto`` after its own -call. The verifier adds the ``unwind_goto`` where the program has none. +callback is cancelled, its helper returns to the ``cancel_goto`` after its own +call. Only the verifier emits these two insns. ``cancel_goto`` is an entry of +the exception table and no code, so a call that returns pays nothing for it. A function *cannot be cancelled* if it has neither ``exit`` nor a call of ``bpf_throw()``, or if the program is loaded without ``CAP_PERFMON``. A -function that the program calls cannot be cancelled either if the JIT lacks -``unwind_exit``, which only the JITs of x86-64 and arm64 have, or if its caller -is a helper that cannot pass a cancellation on. In such a function a loop that -needs a ``may_goto`` of the verifier, a recursion and ``bpf_throw()`` reject -the program. An access to arena that faults is skipped there, in every function -on a JIT without ``unwind_exit``, and where the verifier cannot generate a -landing pad for it. +function that the program calls cannot be cancelled either if the JIT lacks the +two insns, which only the JITs of x86-64 and arm64 have, if its caller is a +helper that cannot pass a cancellation on, or if its caller cannot be +cancelled. In such a function a loop that needs a ``may_goto`` of the verifier, +a recursion and ``bpf_throw()`` reject the program, and a ``may_goto`` of the +program is a plain jump. An access to arena that faults is skipped there, and +in every function on a JIT without the two insns. Landing pads ------------
@@ -1022,7 +1025,8 @@ callee returns with it, the caller holds it again, see ``hand_over_refs()``:: pad: r1 = r6 call bpf_task_release r0 = 0 - unwind_exit + r2 = 0 + cancel_exit The landing pad of the call releases nothing, and nothing is added at run time. A call hands over a pointer in one of ``R1`` - ``R5`` that the callee reads and
@@ -1078,6 +1082,55 @@ landing pad needs them, in these cases: Both are tried only where the program would be rejected without them, see `All passes`_. +The program's own unwinding +--------------------------- + +A program can unwind by itself, as C++ and Rust do. ``unwind_exit`` leaves a +function, and the ``unwind_goto`` after the call jumps to a landing pad that +the program has. "Landing pad" alone is always one that the verifier generates. +The program's landing pad is code like any other: it can catch and continue +running. A cancelled program must not continue. So ``cancel_exit`` returns to a +``cancel_goto`` only, and ``unwind_exit`` to an ``unwind_goto`` only. Where the +program has an ``unwind_goto`` after a call, the ``cancel_goto`` follows it:: + + try { call wait + v = wait(); unwind_goto catch <- wait() threw on its own + } catch (...) { cancel_goto pad <- wait() was cancelled + v = 0; ... + } catch: ... + exit + pad: r0 = 0 + exit + +A cancellation enters no landing pad of the program, so the program cannot +catch it. + +Where a callee leaves with ``unwind_exit`` and the caller has no +``unwind_goto`` after the call, the verifier adds one, with a landing pad that +releases what the frame holds and leaves with ``unwind_exit`` in turn. What a +landing pad of the program further up reads depends on the functions in +between: + +===================================== ========================================= +the function in between what gets through it +===================================== ========================================= +a static function ``R0`` as ``unwind_exit`` left it, a + pointer as well as a number, and ``R2`` + if the function returns two registers +a global function that has a landing what that pad leaves at its +pad of its own at the call ``unwind_exit``: a number, or a pointer + to arena +a global function without one nothing: ``R0`` is the value that the + kernel chooses, see + ``bpf_cancelled_retval()``, and ``R2`` + is 0 if the function returns two + registers +===================================== ========================================= + +A global function is different because its callers are checked without it and +only see a number as its return value. A compiler that wants an object to get +through a global function gives the call there a landing pad of its own. + After an error ==============
@@ -1451,7 +1504,8 @@ A landing pad has no barrier, and no speculative state is checked on the way to one. So only a program that is loaded with ``CAP_PERFMON`` gets landing pads and can have ``unwind_exit``, ``unwind_goto`` and ``bpf_throw()``. Without it no function can be cancelled, see `Cancellation`_: a loop that needs a -``may_goto`` of the verifier and a recursion are rejected. +``may_goto`` of the verifier and a recursion are rejected, and a ``may_goto`` +of the program is a plain jump. Some mechanisms depend on a capability. The last line is there because the cpu can go past the jump that a proof needs:
include/linux/bpf_verifier.h +128 -21
282 lines not on this page · raw message
kernel/bpf/const_fold.c +5 -6
@@ -300,13 +300,12 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)struct const_arg_info *c = &ci[r];/* -* The revisit of a call with a callback that unwound -* carries the r0 of the callback, see check_helper_call(): -* r0 is no constant of that insn. +* A callback that unwinds goes back to the call of its helper with its own +* R0, see check_helper_call(), so R0 is no constant before such a call. An +* unwind_goto of the program need not follow: a generated pad passes R0 on +* too, see bpf_pad_passes_on(). */ -if (r ==BPF_REG_0 && i +1 < insn_cnt && -bpf_is_sync_callback_calling_insn (&insns[i]) && - (bpf_is_unwind_goto (&insns[i +1 ]) || env->has_throw)) +if (r ==BPF_REG_0 &&bpf_is_sync_callback_calling_insn (&insns[i]))continue ;switch (c->state) {case CONST_ARG_CONST : {
kernel/bpf/core.c +14 -6
@@ -437,6 +437,8 @@ static int patch_insn_target(const struct bpf_patch_image *img, const struct bpf tgt = p->jmp_to; }else if (idx +1 == p->jmp2) { tgt = p->jmp2_to; + }else if (idx +1 == p->jmp3) { + tgt = p->jmp3_to; }else if (idx == p->self) { tgt = p->off + rel +1 ; }else {
@@ -561,6 +563,7 @@ int __bpf_patch_list_insert(struct bpf_patch_list *pl, const struct bpf_prog *pr p->self += cnt; p->jmp += p->jmp ? cnt :0 ; p->jmp2 += p->jmp2 ? cnt :0 ; + p->jmp3 += p->jmp3 ? cnt :0 ; }memcpy (insn, insns, cnt *sizeof (*insns)); p->len += cnt;
@@ -571,7 +574,7 @@ int __bpf_patch_list_insert(struct bpf_patch_list *pl, const struct bpf_prog *pr/* * 'insn' of the last patch goes to insn 'to' of the old image, however far that is. * With 'back' it goes to the last insns of the patch of insn 'to - 1'. -* A patch has two such jumps at most, and the second one has no 'back'. +* A patch has three such jumps at most, and only the first one has 'back'. */ void bpf_patch_list_jump (struct bpf_patch_list *pl,const struct bpf_insn *insn,u32 to,u32 back) {
@@ -580,13 +583,18 @@ void bpf_patch_list_jump(struct bpf_patch_list *pl, const struct bpf_insn *insn,if (p->jmp) {/* -* There is no room for a third one, nor for 'back' of the second one. Such a jump -* goes out of the program: bpf_patch_list_build() fails for it. +* A patch has no room for a fourth jump, nor for 'back' of a later one. Make such a +* jump lead out of the program, so that bpf_patch_list_build() fails. */ -if (WARN_ON_ONCE (p->jmp2 || back)) +if (WARN_ON_ONCE (p->jmp3 || back)) to =U32_MAX ; - p->jmp2 = jmp; - p->jmp2_to = to; +if (p->jmp2) { + p->jmp3 = jmp; + p->jmp3_to = to; + }else { + p->jmp2 = jmp; + p->jmp2_to = to; + }return ; } p->jmp = jmp;
kernel/bpf/fixups.c +266 -108
564 lines not on this page · raw message
kernel/bpf/pads.c +160 -75
469 lines not on this page · raw message
kernel/bpf/verifier.c +245 -127
623 lines not on this page · raw message
tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c +1 -1
@@ -83,7 +83,7 @@ __xlated("*(u64 *)(r12 -8) = 10") __xlated("...")__xlated ("call pc+" ) /* a fault in the stack of the subprog unwinds */ -__xlated ("unwind_goto pc+" ) +__xlated ("cancel_goto pc+" ) /* give the stack back, then the epilogue */ __xlated("w12 += -16")__xlated ("if w12 & 0x10 goto pc+5" )
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +15 -12
@@ -5,6 +5,8 @@#include "../../../include/linux/filter.h" #include "bpf_misc.h" +#define __exception_cb (name) __attribute__((btf_decl_tag("exception_callback:" #name))) + #if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64) struct {
@@ -218,10 +220,22 @@ static __naked __noinline __used long goes_down(void) : __clobber_all); } +/* +* The kernel unwinds the prog, and no code of the prog runs behind the call: what the prog returns +* is up to the exception callback, which runs when the frames are gone. +*/ +__noinline int used_between_8k_and_32k(__u64 cookie) +{ +unsigned long used = last_r12 - first_r12; + +return used >=8192 && used <=32736 ; +} +/* The check of a recursion looks at the kernel stack. It fails before 32K of arena are used. */ SEC("syscall") __description("arena stack: recursion ends in the stack") __success __retval(1) +__exception_cb (used_between_8k_and_32k) __naked void recursion(void) { asm volatile (
@@ -230,23 +244,12 @@ __naked void recursion(void) "r2 = %[first_r12] ll;" "*(u64 *)(r2 + 0) = r1;" "call goes_down;" -".8byte %[unwind_goto];" -"r1 = %[last_r12] ll;" -"r1 = *(u64 *)(r1 + 0);" -"r2 = %[first_r12] ll;" -"r2 = *(u64 *)(r2 + 0);" -"r1 -= r2;" "r0 = 0;" -"if r1 < 8192 goto +2;" -"if r1 > 32736 goto +1;" -"r0 = 1;" "exit;" : : __imm_addr(first_r12), -__imm_addr (last_r12), __imm_insn(adj, ADJ(32)), -__imm_insn (mov,MOV (BPF_REG_1 )), -__imm_insn (unwind_goto,BPF_RAW_INSN (BPF_JMP |BPF_JCOND ,0 ,BPF_UNWIND_GOTO ,0 ,0 )) + __imm_insn(mov, MOV(BPF_REG_1)) : __clobber_all); }
tools/testing/selftests/bpf/progs/verifier_budget.c +46 -29
171 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_patch_list.c +3 -2
@@ -416,7 +416,7 @@ __arch_x86_64__arch_arm64 __success __xlated("27: call pc+10") -__xlated("28: unwind_goto pc-15") +__xlated("28: cancel_goto pc-15") __xlated("...") __xlated("37: exit")__xlated ("38: r0 = " )
@@ -433,7 +433,8 @@ __xlated("56: if r1 != 0x0 goto pc-12") __xlated("57: r0 = 0") __xlated("58: exit") __xlated("59: r0 = 0") -__xlated("60: unwind_exit") +__xlated("60: r2 = 0") +__xlated("61: cancel_exit")__naked void patch_list_insert_in_front (void ) {INSERT_IN_FRONT ;
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 57/73] bpf: Use cancel_exit to leave a frame that the kernel cancels
TL;DR: Nit only: the new insert_unwind_gotos() comment documents an @stubbed parameter that doesn't exist until a later patch in the series. Could that sentence move to that patch?
Quoted 1 line
bpf: Use
cancel_exitto leave a frame that the kernel cancels
TL;DR: Nit only: the new insert_unwind_gotos() comment documents an @stubbed parameter that doesn't exist until a later patch in the series. Could that sentence move to that patch?
Quoted 3 lines
kernel/bpf/fixups.c +0
-0
[ ... ]
Quoted 9 lines
/*
- * Addunwind_gotoafter the calls that are sites, seecheck_unwound_arrival(), and after the [ ... ]
+ * Addunwind_gotoandcancel_gotoafter the sites, now that the pads are in the program. @added is
+ * the number of insns appended to each subprog, @stubbed the number of itsunwind_gotoswith a
+ * stub. An access to arena that is a site gets anunwind_goto, and so does a call without one to [ ... ]
*/
static intinsert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
The new header comment of insert_unwind_gotos() documents "@stubbed the number of its unwind_gotos with a stub", but the function takes only (env, added) and nothing in this commit creates a stub.
The parameter and the stubs first appear in a later commit of the series, 696e1c8c75a1 ("bpf: Emit the stub, the entry and the remainder of a cleanup pad"), which changes the signature to insert_unwind_gotos(env, added, stubbed).
Could the @stubbed sentence be dropped here and added in that later commit?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 58/73 bpf: Check that a helper whose callback may unwind has an unwind label
In reply to Kumar Kartikeya DwivediCurrently the verifier knows which helpers and kfuncs have an unwind label from two lists that are kept by hand, helper_has_cb_pad() and kfunc_has_cb_pad(), and it takes every map_for_each_callback() op to have one. Nothing checks the lists against the functions.
A function that is in a list and has no unwind label is not noticed at run time. unwind_exit or cancel_exit of its callback looks up a return address in the text of the kernel and finds no exception table entry. That is no error for the lookup, because a frame that the kernel called, such as an async callback, has no entry either. So the callback returns to its helper as if it had not unwound, the program continues, and nothing warns.
Check when a program is loaded. Where the lists say that a call has an unwind label, check_cb_pad() looks for an exception table entry of bpf_call_cb() in the function that is called: the helper, the kfunc, and for bpf_for_each_map_elem() also the op of the map. If there is none, the load fails with a verifier bug. If bpf_find_vma() lost its label, the message would be:
verifier bug: bpf_find_vma has no landing pad for its callback
The message says "landing pad" where it means the unwind label.
func_has_cb_pad() finds the entry with what a JIT has already. It walks the exception table of the kernel, or of the module that has the function, and asks bpf_unwind_target() about every entry whose key is inside the function. The lookup returns another address only for an entry of bpf_call_cb().
The lists are trusted without a check in two cases:
- Without kallsyms, because the size of a function is not known.
- In a kernel whose JIT does not unwind, where no callback unwinds.
--- arch/arm64/net/bpf_jit_comp.c | 13 +++--- arch/x86/net/bpf_jit_comp.c | 13 +++--- include/linux/bpf_verifier.h | 3 ++ kernel/bpf/verifier.c | 77 +++++++++++++++++++++++++++++++++-- 4 files changed, 88 insertions(+), 18 deletions(-)
arch/arm64/net/bpf_jit_comp.c +6 -7
@@ -1807,13 +1807,12 @@ static u64 unwind_target(u64 ret_addr, int key)return (unsigned long )&e->fixup + e->fixup + (key ==CANCEL_EXKEY ?BPF_CB_CANCEL_OFF :BPF_CB_PAD_OFF );/* -* No pad. That is how it ends when the kernel called an async callback -* or the main prog of an extension: it's exit. A call in a prog of what -* can unwind has unwind_goto behind it, which is an entry also when the -* pad is the next insn, and cancel_goto behind a call of what has -* cancel_exit. So a return address in a prog without an entry is an -* unwind_exit or a cancel_exit that gets lost: the verifier sent it to -* a pad. +* No entry: the kernel called the frame, as it calls an async callback +* or the main prog of an extension, and the frame returns like exit. +* In a prog, unwind_goto or cancel_goto follows every call whose callee +* can leave this way, so a return address in a prog is a bug here. A +* helper without an unwind label would not show: the verifier checks +* for that at load time, see check_cb_pad(). */ scoped_guard (rcu) WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
arch/x86/net/bpf_jit_comp.c +6 -7
@@ -2440,13 +2440,12 @@ static u64 unwind_target(u64 ret_addr, int key)return (unsigned long )&e->fixup + e->fixup + (key ==CANCEL_EXKEY ?BPF_CB_CANCEL_OFF :BPF_CB_PAD_OFF );/* -* No pad. That is how it ends when the kernel called an async callback -* or the main prog of an extension: it's exit. A call in a prog of what -* can unwind has unwind_goto behind it, which is an entry also when the -* pad is the next insn, and cancel_goto behind a call of what has -* cancel_exit. So a return address in a prog without an entry is an -* unwind_exit or a cancel_exit that gets lost: the verifier sent it to -* a pad. +* No entry: the kernel called the frame, as it calls an async callback +* or the main prog of an extension, and the frame returns like exit. +* In a prog, unwind_goto or cancel_goto follows every call whose callee +* can leave this way, so a return address in a prog is a bug here. A +* helper without an unwind label would not show: the verifier checks +* for that at load time, see check_cb_pad(). */ scoped_guard (rcu) WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
include/linux/bpf_verifier.h +3 -0
@@ -1902,6 +1902,9 @@ struct bpf_verifier_env {bool run_over_budget;/* in one of its functions, see find_failing_path() */ bool restart;/* see bpf_flow_next_is_no_bound() */ bool guards_late;/* see bpf_flow_needs_guard() */ +/* the helpers and kfuncs whose unwind label was found, see check_cb_pad() */ +unsigned long cb_pads[8 ]; +u8 cb_pad_cnt;bool pads_late;/* a global subprog unwinds: see settle_late_unwinds() */ bool faults_late;/* a site is not what it seemed: see check_arena_site() */ bool pad_releases;/* see release_frame_resources() */
kernel/bpf/verifier.c +73 -4
101 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label
TL;DR: Commit message only: the quoted "verifier bug" log line omits the appended condition suffix and the possible WARN_ONCE splat.
Quoted 1 line
bpf: Check that a helper whose callback may unwind has an unwind label
TL;DR: Commit message only: the quoted "verifier bug" log line omits the appended condition suffix and the possible WARN_ONCE splat.
Quoted 21 lines
bpf: Check that a helper whose callback may unwind has an unwind label
Currently the verifier knows which helpers and kfuncs have an unwind label from two lists that are kept by hand,
helper_has_cb_pad()andkfunc_has_cb_pad(), and it takes everymap_for_each_callback()op to have one. Nothing checks the lists against the functions.
A function that is in a list and has no unwind label is not noticed at run time.unwind_exitorcancel_exitof its callback looks up a return address in the text of the kernel and finds no exception table entry. That is no error for the lookup, because a frame that the kernel called, such as an async callback, has no entry either. So the callback returns to its helper as if it had not unwound, the program continues, and nothing warns.
Check when a program is loaded. Where the lists say that a call has an unwind label,check_cb_pad()looks for an exception table entry ofbpf_call_cb()in the function that is called: the helper, the kfunc, and forbpf_for_each_map_elem()also the op of the map. If there is none, the load fails with a verifier bug. Ifbpf_find_vma()lost its label, the message would be:
verifier bug:bpf_find_vmahas no landing pad for its callback
The message says "landing pad" where it means the unwind label.
Quoted 2 lines
[ ... ]Signed-off-by Kumar Kartikeya Dwivedi <[email protected]>
The commit message quotes the log line for a missing unwind label as:
verifier bug: bpf_find_vma has no landing pad for its callback
check_cb_pad() reports through verifier_bug_if(), which appends the stringified condition to the format:
verifier_bug(env, fmt " (" #cond ")", ##args);so the printed line would be:
verifier bug: bpf_find_vma has no landing pad for its callback (!func_has_cb_pad(addr))
verifier_bug() also goes through BPF_WARN_ONCE(), which is WARN_ONCE() under CONFIG_DEBUG_KERNEL.
Should the quoted message include the " (!func_has_cb_pad(addr))" suffix, and mention the warning splat?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 59/73 bpf: Find the landing pads of a program that can only clean up
In reply to Kumar Kartikeya DwivediA cancelled frame leaves with cancel_exit and returns to the cancel_goto after its call, never to an unwind_goto. So a cancellation enters no landing pad of the program, not even one that could not catch it. Most landing pads that a C++ or Rust compiler emits are of that kind: they run destructors or drop glue and then unwind further with unwind_exit. When the kernel cancels the program in a callee, the destructor does not run, and what it does for the program is lost: a lock word in arena stays taken, memory in arena is not freed.
Call a landing pad of the program a cleanup pad if it can only clean up and continue unwinding. From its first insn,
- no path in the function reaches an insn that returns to the caller, which is exit, a tail call, LD_ABS or LD_IND, and
- some path reaches unwind_exit.
The goal is that a cancellation runs the cleanup pads of the frames that it leaves. A landing pad of the program that can continue running, such as a catch clause, is still never entered.
The same pad code then serves the program's own unwinding and a cancellation, so the frame has to remember which of the two is under way. It does so in a hidden word, the "cancelled" word of the frame:
what the program has what the verifier makes of it
call foo call foo
unwind_goto pad unwind_goto stub
... cancel_goto entry
pad: call dtor ...
unwind_exit pad: call dtor gotol rest
stub: cancelled = 0 <- own unwinding
gotol pad
entry: cancelled = 1 <- cancellation
r0 = 0
gotol pad
rest: if cancelled == 0 goto +N
release what the frame still holds cancel_exit
unwind_exit
The stub runs when the callee left with unwind_exit, the entry when the callee was cancelled. The entry puts 0 into R0, where the program's own unwinding has the object that it threw. The code at rest, the remainder of the pad, replaces its unwind_exit. A frame that the program unwinds still leaves with unwind_exit. A cancelled frame leaves with cancel_exit and the value of the cancellation, which is the kernel's value or the cookie of bpf_throw(), so no landing pad of the program in a caller can catch it.
As the first step, find the cleanup pads. bpf_find_cleanup_pads() applies the two rules to the control flow graph and marks the unwind_goto of each cleanup pad ('cleanup_pad' in its aux data). The answer depends on the insns alone, so it is the same in every pass.
Some landing pads of the program need care:
- A tail call that is taken and an LD_ABS that fails leave the frame without an exit insn. The graph gives these insns an exit insn of the function as a successor, which can be an unwind_exit. So the first rule names the insns themselves, and that edge is not followed.
- The landing pad of a noexcept function calls std::terminate() and never reaches unwind_exit. The second rule leaves it out.
- Landing pads that share their last insns are judged one by one, each from its first insn. The landing pad of a try block can reach a handler, so it is no cleanup pad, even if it ends in the same unwind_exit as the landing pad of a destructor.
At log level 2 the verifier says for each landing pad of the program whether it "only resumes", which is a cleanup pad, "returns" or "has no unwind_exit". Nothing calls bpf_find_cleanup_pads() yet.
--- include/linux/bpf_verifier.h | 3 + kernel/bpf/pads.c | 114 +++++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+)
include/linux/bpf_verifier.h +3 -0
@@ -1373,6 +1373,8 @@ struct bpf_insn_aux_data { u32 calls_callback:1;/* true if some jump or call instruction targets this instruction */ u32 jump_target:1; +/* an unwind_goto of the program that leads to a cleanup pad, see bpf_find_cleanup_pads() */ + u32 cleanup_pad:1;/* it can read or write the frame of a caller, in a call with a known callee */ u32 reads_outer:1; u32 writes_outer:1;
@@ -2500,6 +2502,7 @@ int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_paint bpf_pad_insns_after (const struct bpf_subprog_info *sub,const struct bpf_pad_note **notes,int nr,const struct bpf_pad_note *note,struct bpf_insn *buf);void bpf_pads_log (struct bpf_verifier_env *env); +int bpf_find_cleanup_pads (struct bpf_verifier_env *env);int bpf_copy_verifier_state (struct bpf_verifier_env *env,struct bpf_verifier_state *dst_state,const struct bpf_verifier_state *src);
kernel/bpf/pads.c +114 -0
123 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 60/73 bpf: Don't let hidden stack words turn on the private stack
In reply to Kumar Kartikeya DwivediCurrently the hidden words that the verifier adds for landing pads count as stack of the program when check_max_stack_depth() decides whether a function gets a private stack. One condition is that the stack, as the JIT rounds it, has 64 bytes or more, and a private stack makes the prologue and every call in the function more expensive. So one hidden word takes a function of 48 bytes to 56, which rounds to 64. Every function in which a cancellation enters a cleanup pad is going to have a hidden word of its own, the "cancelled" word.
Decide by what the insns of the program use. Record that stack_depth includes the hidden words ('hidden_in_depth'), and take them off before the depth is compared with BPF_PRIV_STACK_MIN_SIZE.
The slots of bpf_fastcall spills that were removed need the same. They stay in a frame that has hidden words below them, and so far they count as stack of the program there. Record that in 'fastcall_spills_gone', and count only what lies above them.
Where the hidden words are kept does not change: on the private stack of a function that has one, and on the kernel stack of any other.
--- include/linux/bpf_verifier.h | 30 ++++++++++++++++++++++++++++++ kernel/bpf/pads.c | 7 ++----- kernel/bpf/verifier.c | 29 ++++++++++++++++++++--------- 3 files changed, 52 insertions(+), 14 deletions(-)
include/linux/bpf_verifier.h +30 -0
@@ -1574,6 +1574,11 @@ struct bpf_subprog_info { bool ret_reg_pair: 1;/* true if bpf_fastcall stack region is used by functions that can't be inlined */ bool keep_fastcall_stack: 1; +/* +* Its bpf_fastcall spills are removed, but their slots stay in the frame, because the +* hidden words are below them, see check_max_stack_depth() +*/ + bool fastcall_spills_gone: 1; bool changes_pkt_data: 1; bool might_sleep: 1; bool uses_arena_sp: 1;
@@ -1665,6 +1670,8 @@ struct bpf_subprog_info {u8 owns_args;/* its hidden slots and words take that many words of 8 bytes below its stack */ u8 hidden_words; +/* stack_depth includes the hidden words, see bpf_stack_take_hidden_words() */ + bool hidden_in_depth: 1;u8 code_stack_args;/* the pad that releases nothing, for all accesses to arena with 'fault_unwinds'. 0: none */ u32 fault_pad;
@@ -1708,6 +1715,29 @@ static inline u32 bpf_stack_depth_with_slots(const struct bpf_subprog_info *sub)return round_up (sub->stack_depth,BPF_REG_SIZE ) + sub->hidden_words *BPF_REG_SIZE ; } +/* +* The hidden words become part of the stack of @sub for good. They are below the slots of its +* bpf_fastcall spills, so check_max_stack_depth() no longer cuts those slots off the frame. +*/ +static inline void bpf_stack_take_hidden_words (struct bpf_subprog_info *sub) +{ + sub->stack_depth =bpf_stack_depth_with_slots (sub); + sub->hidden_in_depth = true; +} + +/* +* How much stack the insns of the program use in @sub: without the hidden words, and without the +* slots of removed bpf_fastcall spills, which stay in a frame that has hidden words below them +*/ +static inline u32 bpf_stack_depth_of_prog (const struct bpf_subprog_info *sub) +{ +if (!sub->hidden_in_depth) +return sub->stack_depth; +if (sub->fastcall_spills_gone) +return -sub->fastcall_stack_off; +return sub->stack_depth - sub->hidden_words *BPF_REG_SIZE ; +} +static inline u16 bpf_in_stack_arg_cnt (const struct bpf_subprog_info *sub) {if (sub->stack_args_from_code)
kernel/bpf/pads.c +2 -5
@@ -3476,11 +3476,8 @@ int bpf_pads_settle(struct bpf_verifier_env *env)/* all accesses of the program to its stack are known: the hidden words go below them */ for (s =0 ; !env->faults_late && s < env->subprog_cnt; s++) { sub = &env->subprog_info[s]; -if (!sub->hidden_words) -continue ; - sub->stack_depth =bpf_stack_depth_with_slots (sub); -/* check_max_stack_depth() would put the stack of the callees there */ - sub->keep_fastcall_stack = true; +if (sub->hidden_words) +bpf_stack_take_hidden_words (sub); }return 0 ; }
kernel/bpf/verifier.c +20 -9
@@ -6345,10 +6345,21 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)find_subprog_properties (env, true);/* see bpf_remove_fastcall_spills_fills() */ -for (s =0 ; s < env->subprog_cnt; s++) -for (int i = si[s].start; i < si[s +1 ].start && !si[s].keep_fastcall_stack; i++) -if (env->insn_aux_data[i].fastcall_spills_num) +for (s =0 ; s < env->subprog_cnt; s++) { +for (int i = si[s].start; i < si[s +1 ].start && !si[s].keep_fastcall_stack; i++) { +if (!env->insn_aux_data[i].fastcall_spills_num) +continue ; +/* +* The hidden words lie below the slots of the removed spills, so the frame +* cannot shrink: only record that the program no longer uses the slots. +*/ +if (si[s].hidden_in_depth) + si[s].fastcall_spills_gone = true; +else si[s].stack_depth = -si[s].fastcall_stack_off; +break ; + } + }for (int i =0 ; i < env->subprog_cnt; i++) {if (si[i].has_tail_call) {
@@ -6395,8 +6406,11 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)* Request private stack support only if the subprog stack * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to * avoid jit penalty if the stack usage is small. +* Only the stack that the insns of the program use counts: the hidden words of +* the landing pads must not make a small function pay for a private stack. */ -if (round_up_stack_depth (env, si[s].stack_depth) >=BPF_PRIV_STACK_MIN_SIZE ) { +if (round_up_stack_depth (env,bpf_stack_depth_of_prog (&si[s])) >= +BPF_PRIV_STACK_MIN_SIZE ) { si[s].priv_stack_mode =PRIV_STACK_ADAPTIVE ; env->prog->aux->jits_use_priv_stack = true; }
@@ -6426,11 +6440,8 @@ static int try_max_stack_depth(struct bpf_verifier_env *env, bool with_slots)return -ENOMEM ;for (s =0 ; with_slots && s < env->subprog_cnt; s++) { sub = &env->subprog_info[s]; -if (!sub->hidden_words) -continue ; - sub->stack_depth =bpf_stack_depth_with_slots (sub); -/* or check_max_stack_depth() takes the spills of bpf_fastcall off the stack */ - sub->keep_fastcall_stack = true; +if (sub->hidden_words) +bpf_stack_take_hidden_words (sub); } env->log.level =0 ; err =check_max_stack_depth (env);
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 60/73] bpf: Don't let hidden stack words turn on the private stack
TL;DR: Excluding hidden words from the private-stack decision may move small frames to the kernel stack, so a deep subprog chain that loaded before could now fail with -EINVAL; the changelog says…
Quoted 1 line
bpf: Don't let hidden stack words turn on the private stack
TL;DR: Excluding hidden words from the private-stack decision may move small frames to the kernel stack, so a deep subprog chain that loaded before could now fail with -EINVAL; the changelog says placement is unchanged.
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 6 lines
kernel/bpf/verifier.c +0
-0@@ -6392,14 +6403,17 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)continue ; }/* * Request private stack support only if the subprog stack * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
kernel/bpf/verifier.c static int check_max_stack_depth(struct bpf_verifier_env *env) · line 6416
Quoted 10 lines
kernel/bpf/verifier.c +4
-1* avoid jit penalty if the stack usage is small. +* Only the stack that the insns of the program use counts: the hidden words of +* the landing pads must not make a small function pay for a private stack. */ -if (round_up_stack_depth (env, si[s].stack_depth) >=BPF_PRIV_STACK_MIN_SIZE ) { +if (round_up_stack_depth (env,bpf_stack_depth_of_prog (&si[s])) >= +BPF_PRIV_STACK_MIN_SIZE ) { si[s].priv_stack_mode =PRIV_STACK_ADAPTIVE ; env->prog->aux->jits_use_priv_stack = true; }
This changes which frames count against the combined kernel stack limit, so a program that loaded before this patch can now be rejected.
A PRIV_STACK_ADAPTIVE subprog is left out of the chain sum, because subprog_stack_size() returns only its outgoing args:
if (sub->priv_stack_mode == PRIV_STACK_ADAPTIVE)
return args;
return round_up_stack_depth(env, sub->stack_depth + args);Before the patch, hidden words that took a frame to 64 bytes or more gave it a private stack, which removed the whole frame from the sum that check_call_depth() compares with env->stack_limit.
After the patch, a frame whose program stack rounds below 64 stays on the kernel stack, and adds stack_depth (hidden words included) to the chain.
bpf_hidden_slots_fit() runs this same check_max_stack_depth() as a trial via try_max_stack_depth(env, true). If the trial now fails while the check without hidden words passes, take_value_word() returns BPF_CONFLICT_NO_ROOM, plan_rejects() is true in bpf_pads_settle(), and the load fails with -EINVAL ("no room in the stack for the value").
For example, take a tracing program on an arch with a private stack but no large stack (riscv64, ppc64), so env->stack_limit = MAX_BPF_STACK =
512. With a static chain of 9 subprogs, each with 48 bytes of program stack and one hidden word:
before: each frame is 56 bytes, rounds to 64, goes to the private
stack, chain sum is about 0
after: each frame stays on the kernel stack at 64 bytes,
9 * 64 = 576 > 512, so the hidden words do not fit (without them 9 * 48 = 432 fits)
The last paragraph of the commit message says "Where the hidden words are kept does not change", but for every frame that loses its private stack the hidden words move from the private stack to the kernel stack.
Could the changelog state this trade-off? Or should a frame fall back to the private stack when the hidden words do not fit in the kernel stack chain?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 61/73 bpf: Add a landing pad per site for frames that are cancelled already
In reply to Kumar Kartikeya DwivediAt each site the verifier records what the frame holds (struct bpf_pad_plan) and generates one landing pad from the record.
Once a cancellation runs cleanup pads, a frame can reach a site while it is cancelled already: a destructor that the cleanup pad calls faults in arena, loops until its time is up, or calls a function that is cancelled in turn. Give the states of such a frame a record and a landing pad of their own at the site, selected by the new flag BPF_SITE_CANCELLED on the kind of the site. A cancelled frame differs in three ways:
- It leaves with cancel_exit at every kind of site, or with exit in a function that only the kernel calls. At a call that the program's own unwinding returns to, it passes nothing on in R0.
- It leaves with the value of the cancellation that is under way. In a program with bpf_throw() its landing pad loads that value from the value word and stores nothing there.
- It does not hold what a frame holds that reaches the same insn without being cancelled.
Also let struct pad_buf record where each landing pad ends, and find a landing pad with the same insns by a hash. The code that is going to stand around a cleanup pad does not end in a single exit insn, which is how collect_pads() finds the end of a landing pad so far.
No state leaves a cancelled frame at a site yet. No functional change.
--- include/linux/bpf_verifier.h | 25 ++++++- kernel/bpf/fixups.c | 122 +++++++++++++++++++++++++++-------- kernel/bpf/pads.c | 36 +++++++---- kernel/bpf/verifier.c | 3 + 4 files changed, 143 insertions(+), 43 deletions(-)
include/linux/bpf_verifier.h +22 -3
@@ -469,15 +469,33 @@ enum bpf_site_kind {BPF_SITE_MAY_GOTO ,/* a may_goto of the program, see check_may_goto_site() */ /* a call whose callee was cancelled, with or without an unwind_goto of the program */ BPF_SITE_CANCEL_CALL , +/* +* A flag on top of a kind: the frame that reaches the site is cancelled already. Such +* frames have a plan and a landing pad of their own at the site. +*/ + BPF_SITE_CANCELLED = 0x10, }; +static inline enum bpf_site_kind bpf_site_base (enum bpf_site_kind kind) +{ +return kind & ~BPF_SITE_CANCELLED ; +} + +static inline bool bpf_site_is_cancelled (enum bpf_site_kind kind) +{ +return kind &BPF_SITE_CANCELLED ; +} +/* The site is a call whose callee did not return: it left with unwind_exit or was cancelled */ static inline bool bpf_site_is_call (enum bpf_site_kind kind) { -return kind ==BPF_SITE_CALL || kind ==BPF_SITE_CANCEL_CALL ; +return bpf_site_base (kind) ==BPF_SITE_CALL ||bpf_site_base (kind) ==BPF_SITE_CANCEL_CALL ; } -/* The kernel cancels the frame at a site of @kind */ +/* +* The kernel cancels the frame at a site of @kind. That includes a call in a frame that is +* cancelled already whose callee left with unwind_exit. +*/ static inline bool bpf_site_is_cancel (enum bpf_site_kind kind) {return kind !=BPF_SITE_CALL ;
@@ -2460,7 +2478,8 @@ static inline bool bpf_pad_passes_on(const struct bpf_verifier_env *env, int substatic inline bool bpf_site_has_value (const struct bpf_verifier_env *env,int subprog,enum bpf_site_kind kind) { -if (bpf_pad_rethrows (env, subprog, kind)) +/* a frame that is cancelled already has the value in its value word */ +if (bpf_site_is_cancelled (kind) ||bpf_pad_rethrows (env, subprog, kind))return false;return env->has_throw && (bpf_site_is_call (kind) || kind ==BPF_SITE_THROW ); }
kernel/bpf/fixups.c +94 -28
189 lines not on this page · raw message
kernel/bpf/pads.c +24 -12
@@ -2350,7 +2350,10 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,for (class =0 ; class <BPF_PAD_NR_SECTIONS ; class++)for (i =0 ; i <pad_enters (plan, class); i++) buf[n++] =enter_call (class); -if (plan_saves_value (env, plan, subprog)) { +if (bpf_site_is_cancelled (plan->kind) && env->has_throw) { +/* the value of the first cancellation, which the entry of the cleanup pad stored */ + buf[n++] =BPF_LDX_MEM (BPF_DW , dst,BPF_REG_FP , value_off); + }else if (plan_saves_value (env, plan, subprog)) { buf[n++] =BPF_LDX_MEM (BPF_DW , dst,BPF_REG_FP , value_off);if (pair) buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_FP,
@@ -2455,6 +2458,9 @@ bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_planconst struct bpf_subprog_info *sub;int s; +/* the frame was being unwound when it got to the site: what began that is asked */ +if (bpf_site_is_cancelled (plan->kind)) +return false;if (!bpf_site_is_call (plan->kind))return plan->kind !=BPF_SITE_FAULT && plan->kind !=BPF_SITE_MAY_GOTO ;/* the callees came back cancelled or with unwind_exit, by the kind of the site */
@@ -2525,8 +2531,8 @@ static const char * const site_kind[] = {*/ static u16 kinds_of_plan (const struct bpf_pad_plan *plan,u16 kinds) { -return plan->kind ==BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT - : kinds &LEFT_AT_UNWIND_EXIT ; +return bpf_site_base (plan->kind) ==BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT + : kinds &LEFT_AT_UNWIND_EXIT ; }/*
@@ -2565,7 +2571,7 @@ static int sites_of_subprogs(struct bpf_verifier_env *env)if (!plan->used)continue ;if (!bpf_site_is_call (plan->kind)) { - kinds |=BIT (plan->kind); + kinds |=BIT (bpf_site_base (plan->kind));continue ; }bpf_pad_for_each_callee (plan, c)
@@ -2713,7 +2719,7 @@ static int slot_words(const struct bpf_pad_note *note)/* Does the pad of @plan run in a frame that has set up its hidden slots? */ static bool plan_has_slots (const struct bpf_pad_plan *plan) { -return plan->kind !=BPF_SITE_RECURSION && !plan->conflict; +return bpf_site_base (plan->kind) !=BPF_SITE_RECURSION && !plan->conflict; }/* Does @plan have room for @slots releases instead of those that it has of @group? */
@@ -3247,9 +3253,13 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad };int j; -/* a call has one for what the kernel unwinds, and one for unwind_exit of the program */ -verbose (env,"landing pad of %s at %d%s: " , site_kind[plan->kind], i, - plan->kind ==BPF_SITE_CALL ?" for unwind_exit" :"" ); +/* +* A call can have a pad for a cancellation and one for the program's unwind_exit. Every +* site can have one more for the frames that are cancelled already. +*/ +verbose (env,"landing pad of %s at %d%s%s: " , site_kind[bpf_site_base (plan->kind)], i, +bpf_site_base (plan->kind) ==BPF_SITE_CALL ?" for unwind_exit" :"" , +bpf_site_is_cancelled (plan->kind) ?" in a frame that the kernel unwinds" :"" );for (j = plan->nr_ents -1 ; !plan->conflict && j >=0 ; j--)print_ent (env, &plan->ents[j]);if (plan->conflict)
@@ -3300,7 +3310,7 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pavoid bpf_pad_note_left (struct bpf_verifier_env *env,struct bpf_subprog_info *sub,const struct bpf_pad_plan *plan,enum bpf_site_kind kind) { - sub->left_at |=bpf_site_is_call (kind) ?sites_below (env, plan) :BIT (kind); + sub->left_at |=bpf_site_is_call (kind) ?sites_below (env, plan) :BIT (bpf_site_base (kind)); }/* Did bpf_pad_skip_faults() walk @sub, and has no call in or below it got a new callee since? */
@@ -3448,7 +3458,8 @@ int bpf_pads_settle(struct bpf_verifier_env *env)continue ; err =settle_plan (env, plan); sub =bpf_find_containing_subprog (env, i); -if (!err &&plan_saves_value (env, plan, sub - env->subprog_info)) +if (!err && (plan_saves_value (env, plan, sub - env->subprog_info) || + (bpf_site_is_cancelled (plan->kind) && env->has_throw))) err =take_value_word (env, sub);if (err <0 )return err;
@@ -3575,7 +3586,7 @@ static void note_causes(struct bpf_verifier_env *env, int insn_idx, const structbpf_pad_for_each_callee (plan, s) sub[s].asks_args |= sub[s].releases_args; } -if (plan->kind !=BPF_SITE_CANCEL_CALL ) +if (bpf_site_base (plan->kind) !=BPF_SITE_CANCEL_CALL )return ;bpf_pad_for_each_callee (plan, s) sub[s].below_conflict = true;
@@ -3621,7 +3632,8 @@ static void note_causes_below(struct bpf_verifier_env *env)break ;for (i = sub[s].start; i < sub[s +1 ].start; i++) {for (below = aux[i].pad_plans; below; below = below->next) { -if (below->kind !=BPF_SITE_CANCEL_CALL || !below->visited) +if (bpf_site_base (below->kind) !=BPF_SITE_CANCEL_CALL || + !below->visited)continue ;/* * The frame is left at this call, whatever what it calls
kernel/bpf/verifier.c +3 -0
@@ -22444,6 +22444,9 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p {int s; +/* A cancelled frame came through an entry, which the program may not keep. */ +if (bpf_site_is_cancelled (plan->kind)) +return false;switch (plan->kind) {case BPF_SITE_GUARD :return !bpf_flow_guard_is_guess (env, insn_idx);
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 62/73 bpf: Verify a cleanup pad for a frame that is cancelled
In reply to Kumar Kartikeya DwivediCurrently a state that returns from a call cancelled is cancelled in turn at that call, through the generated pad, whatever landing pad the program has there. Before a cancellation can run a cleanup pad, the verifier has to check the pad for the cancelled frame: with 0 in R0, and with what the frame holds when its callee is cancelled.
Add that to the main pass. Nothing calls bpf_find_cleanup_pads() yet, so no program is verified differently.
When a cancelled state returns to a call whose unwind_goto leads to a cleanup pad, in a function that can be cancelled, enter_cleanup_pad() marks the frame as cancelled (BPF_FRAME_CANCELLED), puts 0 into R0 and takes the jump of the unwind_goto. The mark is never cleared, and the verifier does not merge two states that differ in it. So the cleanup pad is verified a second time, and an error on that path rejects the program like any other. The log names the path:
from 16 to the landing pad at 20 of func#1: the kernel unwinds
A cancelled frame never returns to its caller. It has two ways out. Both leave with cancel_exit, or with exit in a function that only the kernel calls, and with the value of the cancellation:
- It reaches the unwind_exit of the pad. The program has released what it wanted to, and the remainder releases what the frame still holds. For that the unwind_exit is a site of the new kind BPF_SITE_REMAINDER.
- It reaches a site inside the pad: a destructor loops until its time is up, faults in arena, calls bpf_throw() or calls a function that is cancelled in turn. The frame leaves through the landing pad that the site has for frames that are cancelled already, and the rest of the cleanup does not run.
The call itself gets a record of the new kind BPF_SITE_CANCEL_ENTRY, which says that its cancel_goto leads to the entry of the cleanup pad.
Some cases need care:
- exit, a tail call and LD_ABS cannot be reached from a cleanup pad, so a cancelled frame at one of them is a verifier bug.
- A cleanup pad can jump back before its call, so a cancelled frame need not run cleanup code only. The verifier relies on one thing: no insn that the frame can reach returns to the caller.
- If a callee of the pad leaves with unwind_exit, the unwind_goto that the pad has for it is taken and the frame stays cancelled. If the callee is cancelled and its call has a cleanup pad of its own, the frame continues in that pad.
- In a program with bpf_throw() the entry has to keep the value that cancel_exit left in R0, so R0 must be a number at the call. bpf_throw() in a cancelled frame drops its cookie, because the frame has its value already.
- A function that is verified separately for a call out of a cancelled frame is kept apart from its other calls (BPF_FRAME_BELOW). The pad passes other arguments than the rest of the program does.
- A function can turn out to be one that cannot be cancelled after a state entered a cleanup pad in it. The pass is then repeated and enters no cleanup pad in that function.
A cleanup pad that a cancellation can reach is entered, or the program is rejected. So a cancelled frame that has no landing pad, at a site inside the cleanup pad or at its unwind_exit, is an error of the pass as at any site. bpf_pads_settle() raises it when the pass is over, because only then is it known whether the program has the entry that the frame came through. It now looks at all sites before it raises the first error, so that the next pass can react to every one. If a cancelled frame has no landing pad because of a reference, the callees of the calls of its function that lead to a cleanup pad ask for a hand-over, see ask_below_cleanup_pads().
A cancellation can also reach a cleanup pad only because two calls are verified together: a callee whose loop has a trip count for each call and none for both is cancelled when its time is up. An error that follows can be anywhere, and the pass that keeps the two calls apart has none. So after a pass with any error, note_entered() marks every function in which a state entered a cleanup pad, and the next pass keeps apart the calls after which a state did. No verdict rests on the marks. Only a load that is rejected pays for them, in load time up to the limit on the cost of a rejected load.
--- include/linux/bpf_verifier.h | 43 ++++- kernel/bpf/fixups.c | 36 +++- kernel/bpf/pads.c | 321 +++++++++++++++++++++++++++-------- kernel/bpf/verifier.c | 229 ++++++++++++++++++++++--- 4 files changed, 521 insertions(+), 108 deletions(-)
include/linux/bpf_verifier.h +41 -2
@@ -469,6 +469,13 @@ enum bpf_site_kind {BPF_SITE_MAY_GOTO ,/* a may_goto of the program, see check_may_goto_site() */ /* a call whose callee was cancelled, with or without an unwind_goto of the program */ BPF_SITE_CANCEL_CALL , +/* +* Such a call whose unwind_goto leads to a cleanup pad. The frame does not leave: its +* cancel_goto leads to the entry of the cleanup pad, see enter_cleanup_pad(). +*/ +BPF_SITE_CANCEL_ENTRY , +/* an unwind_exit of the program in a cancelled frame: the remainder replaces it */ +BPF_SITE_REMAINDER ,/* * A flag on top of a kind: the frame that reaches the site is cancelled already. Such * frames have a plan and a landing pad of their own at the site.
@@ -481,15 +488,17 @@ static inline enum bpf_site_kind bpf_site_base(enum bpf_site_kind kind)return kind & ~BPF_SITE_CANCELLED ; } +/* The frame that reaches the site is cancelled already */ static inline bool bpf_site_is_cancelled (enum bpf_site_kind kind) { -return kind &BPF_SITE_CANCELLED ; +return (kind &BPF_SITE_CANCELLED ) || kind ==BPF_SITE_REMAINDER ; }/* The site is a call whose callee did not return: it left with unwind_exit or was cancelled */ static inline bool bpf_site_is_call (enum bpf_site_kind kind) { -return bpf_site_base (kind) ==BPF_SITE_CALL ||bpf_site_base (kind) ==BPF_SITE_CANCEL_CALL ; +return bpf_site_base (kind) ==BPF_SITE_CALL ||bpf_site_base (kind) ==BPF_SITE_CANCEL_CALL || + kind ==BPF_SITE_CANCEL_ENTRY ; }/*
@@ -807,6 +816,7 @@ struct bpf_func_state {bool in_rcu_callback_fn;/* parent_id of the args that are gone when this frame returns */ u32 frame_id; +u32 cancelled;/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */ /* * Bit f: the frame, or a subprog that returned to it, released a lock or irq flags of * frame f. If the frame returns, a store after its call clears the hidden slot. If not,
@@ -903,6 +913,22 @@ struct bpf_equations {u32 clean_sym_cnt;/* after the last bpf_equations_clean() */ }; +/* The marks in 'cancelled' of struct bpf_func_state */ +enum { +/* The frame is cancelled and runs a cleanup pad, see enter_cleanup_pad(). Never cleared. */ +BPF_FRAME_CANCELLED =1 , +/* +* The first frame of a function that is verified separately, for a call out of a frame +* that has a mark. It only keeps the function apart from its other calls. +*/ +BPF_FRAME_BELOW =2 , +}; + +static inline bool bpf_frame_is_cancelled (const struct bpf_func_state *frame) +{ +return frame->cancelled &BPF_FRAME_CANCELLED ; +} +/* 'unwound' of struct bpf_verifier_state: how the callee left when it did not return */ enum {/*
@@ -1665,11 +1691,20 @@ struct bpf_subprog_info { bool made_calls: 1;/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */ bool below_conflict: 1; +/* +* scratch of bpf_pads_note_causes(): a cancelled frame of it got no landing pad because +* of a reference, see ask_below_cleanup_pads() +*/ + bool cleanup_pad_ref_conflict: 1;/* * In this pass the verifier merged states in a callee of it that differ in which * references the arguments of the call had, see bpf_pad_states_meet() */ bool arg_refs_differ: 1; +/* it has an unwind_goto that leads to a cleanup pad, see bpf_find_cleanup_pads() */ + bool has_cleanup_pads: 1; +/* a cancellation enters one of its cleanup pads, see bpf_mark_subprogs_that_unwind() */ + bool enters_cleanup_pads: 1;/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */ u16 left_at;/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
@@ -1688,6 +1723,8 @@ struct bpf_subprog_info {u8 owns_args;/* its hidden slots and words take that many words of 8 bytes below its stack */ u8 hidden_words; +/* take_value_word() found no room for the value word, in this bpf_pads_settle() */ + bool no_value_word: 1;/* stack_depth includes the hidden words, see bpf_stack_take_hidden_words() */ bool hidden_in_depth: 1;u8 code_stack_args;
@@ -2525,6 +2562,8 @@ size_t bpf_pad_plans_free(struct bpf_insn_aux_data *aux);void bpf_pads_new_round (struct bpf_verifier_env *env);void bpf_pads_move (struct bpf_verifier_env *env,struct bpf_pads_moved *moved,bool save);size_t bpf_pads_free_moved (struct bpf_pads_moved *moved,u32 cnt); +struct bpf_pad_plan *bpf_pad_enter (struct bpf_verifier_env *env, +const struct bpf_verifier_state *st,int call_idx);struct bpf_pad_plan *bpf_pad_visit (struct bpf_verifier_env *env,const struct bpf_verifier_state *st,int insn_idx,enum bpf_site_kind kind);
kernel/bpf/fixups.c +28 -8
@@ -659,6 +659,10 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_ {int s; +/* without 'enters_cleanup_pads' no frame of the function is cancelled already */ +if (bpf_site_is_cancelled (plan->kind) && + !bpf_find_containing_subprog (env, i)->enters_cleanup_pads) +return false;switch (bpf_site_base (plan->kind)) {case BPF_SITE_GUARD :return env->insn_aux_data[i].loop_guard;
@@ -674,12 +678,15 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_return true;return false;case BPF_SITE_CANCEL_CALL : +case BPF_SITE_CANCEL_ENTRY :if (!plan->visited)return false;bpf_pad_for_each_callee (plan, s)if (env->subprog_info[s].can_cancel)return true;return false; +case BPF_SITE_REMAINDER : +return plan->visited;case BPF_SITE_FAULT :return !env->insn_aux_data[i].fault_skips;case BPF_SITE_MAY_GOTO :
@@ -690,13 +697,16 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_ }/* -* The main pass looked at more ways to unwind than the program has in the end: a loop that has a -* trip count after all has no may_goto. Find the subprogs that get cancel_exit: those that are left -* at a site where the kernel unwinds. And those that get unwind_exit: they have a call with no -* unwind_goto, to which unwind_exit of the program comes back. A call is a site if it calls one of -* them: of one kind, of the other, or of both. The main pass asks the same when a global subprog -* unwinds, see settle_late_unwinds(). The main program leaves with exit: it is marked for -* bpf_check_attach_target(), see bpf_insert_sites(). +* Decide how each subprog can be left, from the sites that the program keeps: +* +* can_cancel the kernel can cancel it at a site: it gets cancel_exit +* can_unwind unwind_exit of a callee comes back to a call of it that has no +* unwind_goto: it gets unwind_exit +* enters_cleanup_pads a cancellation enters one of its cleanup pads +* +* A call is a site only if a callee has the matching bit, so the walk repeats until nothing +* changes. The main program leaves with exit but is marked too, for bpf_check_attach_target(). +* With @in_pass the main pass asks the same question and is charged for the walk. */ int bpf_mark_subprogs_that_unwind (struct bpf_verifier_env *env,bool in_pass) {
@@ -706,6 +716,8 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)bool changed, unwinds, cancels;int i, k, s, err; +for (s =0 ; s < env->subprog_cnt; s++) + env->subprog_info[s].enters_cleanup_pads = false; do { changed = false; /* callees come first: only callx and a cycle of calls take more than one round */
@@ -716,6 +728,12 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)for (k =0 ; k < env->subprog_cnt; k++) { s = env->subprog_topo_order[k]; sub = &env->subprog_info[s]; +for (i = sub->start; sub->has_cleanup_pads && !sub->enters_cleanup_pads && + i < sub[1 ].start; i++) { + plan =bpf_pad_plan (&aux[i],BPF_SITE_CANCEL_ENTRY ); +if (plan &&bpf_site_is_used (env, i, plan)) + sub->enters_cleanup_pads = changed = true; + }if ((sub->can_unwind && sub->can_cancel) || (s && !sub->bail_unwinds))continue ; unwinds = sub->can_unwind;
@@ -724,7 +742,9 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass) cancels |= aux[i].loop_guard || (aux[i].fault_empty && !aux[i].fault_skips);for (plan = aux[i].pad_plans; plan; plan = plan->next) { -if (!bpf_site_is_used (env, i, plan)) +/* at an entry the frame continues in its cleanup pad */ +if (plan->kind ==BPF_SITE_CANCEL_ENTRY || + !bpf_site_is_used (env, i, plan))continue ;if (bpf_site_is_cancel (plan->kind)) cancels = true;
kernel/bpf/pads.c +247 -74
511 lines not on this page · raw message
kernel/bpf/verifier.c +205 -24
381 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 62/73] bpf: Verify a cleanup pad for a frame that is cancelled
TL;DR: Commit message only: the claim that no program is verified differently looks wrong, since bpf_pads_settle() changes (deferred rejection, new cost charge) may alter pass count, cost or verdict…
Quoted 1 line
bpf: Verify a cleanup pad for a frame that is cancelled
TL;DR: Commit message only: the claim that no program is verified differently looks wrong, since bpf_pads_settle() changes (deferred rejection, new cost charge) may alter pass count, cost or verdict for all programs.
Quoted 10 lines
Currently a state that returns from a call cancelled is cancelled in turn at that call, through the generated pad, whatever landing pad the program has there. Before a cancellation can run a cleanup pad, the verifier has to check the pad for the cancelled frame: with 0 in R0, and with what the frame holds when its callee is cancelled.
Add that to the main pass. Nothing callsbpf_find_cleanup_pads()yet, so no program is verified differently.
[ ... ]
It now looks at all sites before it raises the first error, so that the next pass can react to every one.
Quoted 2 lines
[ ... ]Signed-off-by Kumar Kartikeya Dwivedi <[email protected]>
The message says "Nothing calls bpf_find_cleanup_pads() yet, so no program is verified differently." Is that accurate?
The bpf_pads_settle() part of the patch does not depend on bpf_find_cleanup_pads(). check_pass() calls it after every error-free pass, for every program, including programs without any unwind_goto:
ret = mark_used_sites(env, initial) ?: bpf_pads_settle(env);
Two changes in it affect existing programs.
First, the rejection is deferred until all plans have been seen:
/* the first one is the one that the log names */
if (!reject)
at = i;
reject = reject ?: plan;
...
if (reject) {
bpf_pad_log(env, at, reject);
return -EINVAL;
}Before the patch, the first plan_rejects() plan returned -EINVAL at once, so later used plans were never settled and their conflict (for example NOT_ALWAYS_HELD, SECTIONS_DIFFER or NO_ROOM) stayed 0. Now every used plan is settled, so bpf_find_unproven_after_pass() (through bpf_pads_conflict()) and bpf_pads_note_causes() see more conflicts, and the next pass keeps apart a different set of calls.
bpf_pad_skip_faults() also now runs for stuck sites that come after a rejecting plan. If it marks a new subprog stuck, env->faults_late is set, and do_check_all() takes the branch:
if (ret && env->faults_late && !env->over_limit)
and repeats the pass, where before the program went on to partitioning or rejection. So the number of passes, the budget used and possibly the verdict can change for programs that have no cleanup pads.
Second, a new cost charge runs on every settle:
err = bpf_add_cost_and_check(env, env->prog->len + BPF_PAD_MAX_ENTS * plans, BPF_COST_XREG);
This adds 16 * (len + 8 * plans) to every successful pass of every program, so the limits are reached sooner.
The paragraph of the message that says "It now looks at all sites before it raises the first error" does describe the first change, so that one appears intended. But the unconditional claim that no program is verified differently is wrong as written, and someone bisecting a change in verifier behavior (pass count, cost, or a verdict near the limit) to this commit would be misled.
Could the claim be qualified, or could the bpf_pads_settle() change (deferred rejection plus the cost charge) be split into its own patch? Both are still present at the end of the series.
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 63/73 bpf: Reject a program whose cleanup pad a cancellation cannot enter
In reply to Kumar Kartikeya DwivediA cleanup pad that a cancellation can reach is entered, or the program is rejected. The verifier never skips one silently: a destructor that does not run shows only when the kernel cancels the program, under load, as a lock word in arena that stays locked. Two things are missing for that rule: the hidden words that a cancelled frame needs, and a log that names the cleanup pad that a rejection is about.
Give every function in which a cancellation enters a cleanup pad its "cancelled" word, and in a program with bpf_throw() the value word. take_cleanup_pad_words() takes them after all other hidden words, so they never take the room of a word that the program needs in order to load. A function whose stack has no room for them rejects the program.
A landing pad for a cancelled frame asks for no hidden slots, because a path that only a cancellation takes must not cost the normal path a store. It does use the hidden slots that the function has for another site. So code that needs a hidden slot, such as a loop in an RCU section that only one path enters, rejects the program when a cancelled frame can reach it.
state_is_in_cleanup_pad() tells a state that has a cancelled frame, or that runs a function which such a frame called. Its calls hand no reference over and clear no hidden slot of a caller. So what such a state releases of a caller costs the functions on the stack their hidden slots for that kind of resource.
bpf_pad_log() now prints a line before the conflict that says what a cleanup pad has to do with it, for example (one line in the log):
the kernel would enter the landing pad at 18 of the call at 11: what the pad leaves at unwind_exit at 27 cannot be released
A frame does not know which entry it came through. So the log names the first cleanup pad of the function that reaches the insn on the control flow graph and counts the others, in a walk that runs for the log only and is not charged. Where a cleanup pad may have released or overwritten what a caller holds, the log names the callee and says "may", because it is not known which pad did it.
At the unwind_exit of a cleanup pad only R0 is live. So the remainder can release sections, a lock at a constant address, an object in the stack of the frame, a pointer in R0 and what is in hidden slots. A pointer in R6-R9 that the cleanup pad does not release still rejects the program.
--- include/linux/bpf_verifier.h | 15 ++ kernel/bpf/pads.c | 448 +++++++++++++++++++++++++++++------ kernel/bpf/verifier.c | 11 +- 3 files changed, 399 insertions(+), 75 deletions(-)
include/linux/bpf_verifier.h +15 -0
@@ -626,6 +626,9 @@ struct bpf_pad_plan {bool visited;bool used;/* the program keeps the site, see bpf_pads_mark_used() */ bool failed;/* a state made the conflict an error of the pass */ +/* for bpf_pad_log(): a state came from a cancelled frame or below one, and one did not */ +bool from_cleanup_pad; +bool from_normal;/* * How many sections of each class the frame has entered since its call. Less than 0: it * has left that many sections of its callers, and the pad enters them again.
@@ -642,6 +645,8 @@ struct bpf_pad_plan {/* enum bpf_pad_conflict: no location has a pointer. No error if a hidden slot has it. */ u8 no_place;u8 no_irq_place;/* the same for irq flags in the stack of a caller */ +/* the groups that it asked hidden slots for, bits by enum bpf_pad_group: settle_slots() */ +u8 asked_slots;u8 nr_ents;bool ordered;/* see order_ents() */ struct bpf_pad_ent *ents;/* oldest first. The pad releases the last one first. */
@@ -1577,6 +1582,11 @@ struct bpf_subprog_info {* The value word: its landing pads keep the value there over their calls. */ s16 value_off; +/* +* The "cancelled" word of a function in which a cancellation enters a cleanup pad: 0 from +* the first insn of the function on, 1 once the frame is cancelled. +*/ +s16 cancelled_off;/* * The pending word: an argument waits there over the call of a subprog, the address of irq * flags that the subprog saves or a pointer that it releases, see bpf_pad_note_return()
@@ -1709,6 +1719,11 @@ struct bpf_subprog_info {u16 left_at;/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */ u8 no_slots: 4; +/* +* Of those, the groups that it lost because a state in a cleanup pad for a cancellation +* released something of a caller. For the log, see bpf_pad_log(). +*/ + u8 no_slots_cleanup_pad: 4;/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */ u8 slots: 4;/*
kernel/bpf/pads.c +381 -67
605 lines not on this page · raw message
kernel/bpf/verifier.c +3 -8
@@ -22586,14 +22586,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state stuck = plan->conflict ==BPF_CONFLICT_CANNOT_UNWIND || plan->conflict ==BPF_CONFLICT_NO_EXIT ;/* -* There is no other way out. Not for may_goto of the program, an access to arena -* and a call above them either, but in a subprog that cannot unwind, and whether -* it is one may be found later in the pass. Then this error was none, see -* do_check_all(). -* It is an error also where a landing pad of the program that the kernel entered -* has a part in it: what came back to the call left a frame below through such -* a pad, or the state got here out of one, in a function that the pad calls. -* The kernel enters the pad or the program is rejected. +* A missing landing pad is an error, unless the frame cannot be cancelled and the +* site can be skipped. If the function turns out later in the pass to be one that +* cannot be cancelled, do_check_all() drops the error. */ if (plan->conflict && certain && (bpf_pad_must_unwind (env, plan) || !stuck)) {bpf_pad_log (env, insn_idx, plan);
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 63/73] bpf: Reject a program whose cleanup pad a cancellation cannot enter
TL;DR: - Comment and log text may misstate why a function lost hidden slots (e.g. callee returning with a lock); verifier log only - Comment saying only rejected loads pay for the marks may be…
Quoted 1 line
bpf: Reject a program whose cleanup pad a cancellation cannot enter
TL;DR:
- Comment and log text may misstate why a function lost hidden slots (e.g. callee returning with a lock); verifier log only
- Comment saying only rejected loads pay for the marks may be inaccurate; nit
Quoted 3 lines
include/linux/bpf_verifier.h +0
-0
[ ... ]
include/linux/bpf_verifier.h struct bpf_subprog_info { · line 1726
Quoted 10 lines
include/linux/bpf_verifier.h +5
-0@@ -1708,8 +1718,13 @@ struct bpf_subprog_info {/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */ u16 left_at;/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */ u8 no_slots: 4; +/* +* Of those, the groups that it lost because a state in a cleanup pad for a cancellation +* released something of a caller. For the log, see bpf_pad_log(). +*/ + u8 no_slots_cleanup_pad: 4;
Does this comment match what sub_no_slots() records?
The writer sets the bit for any reason, not only for a release of a caller:
static void sub_no_slots(struct bpf_subprog_info *sub, const struct bpf_verifier_state *st,
u8 groups)
{
sub->no_slots |= groups;
if (state_is_in_cleanup_pad(st))
sub->no_slots_cleanup_pad |= groups;
}Some callers in bpf_pad_note_return() are about what the callee acquired:
sub_no_slots(sub, st, BIT(BPF_PAD_GROUP_LOCKS)); /* callee returns holding a lock */
A cancelled frame's cleanup pad can call a static subprog that returns holding a bpf_res_spin_lock. In that case nr_locks reaches sub_no_slots() with state_is_in_cleanup_pad(st) true, so no_slots_cleanup_pad gets LOCKS although nothing of a caller was released.
print_cleanup_pad_conflict() then prints "what its code releases of a caller may keep func#%d from getting hidden slots", and the stated reason is wrong for that case.
Should the recording be limited to the release paths, or should the comment and the log line say "what its code did"? Only the verifier log is affected, not acceptance or rejection.
[ ... ]
Quoted 1 line
include/linux/bpf_verifier.h +0
-0@@ -3976,7 +4288,9 @@ static bool insn_returns(const struct bpf_insn *insn)
[ ... ]
Quoted 8 lines
* The pass has an error, and a cancellation entered a cleanup pad in it: a state went through the
* entry of a call, seebpf_pad_enter(). That may be so only because two calls are verified
* together, like the calls ofcount()above with a cleanup pad after them. The error can then be
* anywhere, and the pass that keeps the two calls apart has none. So after a pass with any error,
* mark every function in which a state entered a cleanup pad, fornote_causes_below(). No verdict
* rests on the marks. Only a load that is rejected pays for them, in load time. */
static voidnote_entered(struct bpf_verifier_env *env)
Is "Only a load that is rejected pays for them" accurate?
note_entered() runs from bpf_pads_note_causes() after any pass with an error, and check_pass() does:
if (ret && env->err) bpf_pads_note_causes(env);
Say pass 0 fails on a conflict at a site in function G that has nothing to do with cleanup pads, while a cancellation entered a cleanup pad in function F without a conflict. note_entered() marks F, so pass 1 also keeps apart the jumps around F's calls and the loops below them. If pass 1 has no error, do_check_all() accepts the load, which has still paid for the marks.
The count() case described in the same comment also has the accepted load paying for the extra pass. Would something like "Only a load that has a pass with an error pays for them, in load time" be closer to the code?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 64/73 bpf: Find the code that a cleanup pad can reach
In reply to Kumar Kartikeya DwivediThe "cancelled" word is going to be written only where a frame enters a landing pad of the program: by the stub and by the entry. That is enough only if no frame reaches code that reads the word without passing one of the two. So the verifier has to know which code a frame can run on either side of those two edges. Find that out on the control flow graph, in bpf_find_cleanup_pads():
- Pad code is what can be reached from the first insn of a cleanup pad. A cancelled frame starts there and follows edges of the graph, so it runs pad code and nothing else.
- The normal path is what can be reached from the first insn of the function without the jump of an unwind_goto.
- The rest is the program's landing pad of a typed catch, until it returns to the normal path or joins pad code. No cancelled frame runs it.
call a normal path
unwind_goto 1f
call b
unwind_goto 2f
exit
2: if r0 != 7 goto 3f a typed catch
r0 = 0
exit
1: call dtor pad code
3: unwind_exit
A function is mixed if one of its insns is pad code and on the normal path as well: the normal path falls into a cleanup pad or jumps to it, a cleanup pad jumps back before its call, or the function has no exit. In any other function a frame gets from the normal path into pad code in two ways only: by the jump of an unwind_goto, and through an entry.
A tail call, LD_ABS or LD_IND has an edge to the exit insn that stands for its return. That edge is not followed, as in the search for cleanup pads. The exit is often the unwind_exit that the cleanup pads end in, and a tail call on the normal path would make the function mixed for no reason.
The result depends on the insns alone. Nothing reads it yet.
--- include/linux/bpf_verifier.h | 4 ++ kernel/bpf/pads.c | 125 +++++++++++++++++++++++++++++------ 2 files changed, 110 insertions(+), 19 deletions(-)
include/linux/bpf_verifier.h +4 -0
@@ -1424,6 +1424,8 @@ struct bpf_insn_aux_data { u32 jump_target:1;/* an unwind_goto of the program that leads to a cleanup pad, see bpf_find_cleanup_pads() */ u32 cleanup_pad:1; +/* pad code: a cleanup pad of its function reaches the insn, see bpf_find_cleanup_pads() */ + u32 cleanup_pad_code:1;/* it can read or write the frame of a caller, in a call with a known callee */ u32 reads_outer:1; u32 writes_outer:1;
@@ -1713,6 +1715,8 @@ struct bpf_subprog_info { bool arg_refs_differ: 1;/* it has an unwind_goto that leads to a cleanup pad, see bpf_find_cleanup_pads() */ bool has_cleanup_pads: 1; +/* "mixed": an insn of it is pad code and on the normal path, see bpf_find_cleanup_pads() */ + bool cleanup_pads_mixed: 1;/* a cancellation enters one of its cleanup pads, see bpf_mark_subprogs_that_unwind() */ bool enters_cleanup_pads: 1;/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
kernel/bpf/pads.c +106 -19
154 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 64/73] bpf: Find the code that a cleanup pad can reach
TL;DR: The comment and commit message say a function with no exit is "mixed", but the code only sets that when an insn is both pad and normal code. The wording looks inaccurate and may mislead…
Quoted 1 line
bpf: Find the code that a cleanup pad can reach
TL;DR: The comment and commit message say a function with no exit is "mixed", but the code only sets that when an insn is both pad and normal code. The wording looks inaccurate and may mislead readers of later commits.
Quoted 5 lines
A function is mixed if one of its insns is pad code and on the normal path as well: the normal path falls into a cleanup pad or jumps to it, a cleanup pad jumps back before its call, or the function has no exit. In any other function a frame gets from the normal path into pad code in two ways only: by the jump of an
unwind_goto, and through an entry.
[ ... ]
Quoted 3 lines
kernel/bpf/pads.c +0
-0
[ ... ]
Quoted 4 lines
+ * A function is MIXED ('
cleanup_pads_mixed') if one of its insns is pad code and on the normal path
+ * as well: the normal path falls or jumps into a cleanup pad, a cleanup pad jumps back before its
+ * call, or the function has no exit. In any other function a frame gets from the normal path into
+ * pad code in two ways only: by the jump of anunwind_goto, and through an entry.
[ ... ]
kernel/bpf/pads.c static bool insn_returns(const struct bpf_insn *insn) · line 4345
Quoted 7 lines
kernel/bpf/pads.c +7
-0+for (s =0 ; s < env->subprog_cnt; s++) { + sub = &env->subprog_info[s]; +for (i = sub->start; sub->has_cleanup_pads && i < sub[1 ].start; i++) { + aux[i].cleanup_pad_code =test_bit (i, pad); +if (sub->cleanup_pads_mixed || !test_bit (i, pad) || !test_bit (i, normal)) +continue ; + sub->cleanup_pads_mixed = true;
Is "or the function has no exit" accurate, both in this comment and in the commit message? cleanup_pads_mixed is only set when one insn has both the pad and the normal bit set, and there is no separate no-exit case.
If "no exit" means exit_idx == U32_MAX, as in frame_cannot_unwind(), such a function has no unwind_exit, so bpf_find_cleanup_pads() finds no cleanup pad in it. has_cleanup_pads stays false and find_pad_code() never looks at the function.
If it means no plain exit, the function is still not necessarily mixed:
call g
unwind_goto +2
r0 = 0
unwind_exit
call dtor
unwind_exitThe normal path is {0,1,2,3} and the pad code is {4,5}. They share no insn, so the function is not mixed although it has no exit.
A function without a plain exit only becomes mixed indirectly: its landing pads that continue the function are classified as cleanup pads, and the code they run then overlaps the normal path.
The next commit, 696e1c8c75a1 ("bpf: Emit the stub, the entry and the remainder of a cleanup pad"), uses cleanup_pads_mixed to decide whether a function clears the "cancelled" word at its first insn and gets no stubs. A reader who trusts this sentence would expect any function without an exit to take that path.
The comment also contains a second paragraph that repeats the claim as "any pad of a function that has no exit". b27a88cc13c8 ("bpf: End the path at a call of a global subprog that never returns") removes that second copy, but the first paragraph keeps the sentence up to c916df4614a0, the end of the series.
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 65/73 bpf: Emit the stub, the entry and the remainder of a cleanup pad
In reply to Kumar Kartikeya DwivediCurrently the verifier can check a cleanup pad for a cancelled frame, but it emits none of the code around the pad. Emit the code of the listing in "bpf: Find the landing pads of a program that can only clean up": the stub, the entry, the remainder, and the second landing pad of a site that a cancelled frame can reach. No program gets any of it until bpf_find_cleanup_pads() is called.
In a program without bpf_throw(), with V for the kernel's value:
stub: cancelled = 0 rest: ax = cancelled
gotol pad if ax == 0 goto +3
entry: cancelled = 1 r0 = V
r0 = 0 r2 = 0
gotol pad cancel_exit unwind_exit
The "cancelled" word is written only on the two edges that take a frame from the normal path into a landing pad of the program:
- The callee left with unwind_exit. The unwind_goto after the call leads to a stub, which clears the word and jumps to the program's landing pad. A JIT takes the target of unwind_goto from the offset of the insn alone, so no JIT changes.
- The callee was cancelled. The cancel_goto of the call leads to the entry and not to a generated pad. The entry sets the word without reading it first. In a program with bpf_throw() it also stores R0, the value of the cancellation, in the value word.
Nothing on the normal path writes the word, and a function does not clear it at its first insn. What a function pays on the normal path is the word itself and the stack frame that it needs: a function that had no stack gets one. Two kinds of code are different:
- A call in pad code can be made by a frame that is cancelled already. Its unwind_goto gets no stub. A stub would clear the word, the frame would leave with the program's unwind_exit, and a landing pad of the program in a caller could catch the cancellation. Its entry tests the word and stores only if it is 0, so the first cancellation decides what the program returns.
- A mixed function clears the word at its first insn, with one store per call. It has no stub, and all its entries test. There code that reads the word can be reached from the first insn without passing a stub or an entry. The store stands before the first insn, where a jump back to that insn does not reach it.
An unwind_exit that a cancelled frame can reach becomes a jump to the remainder. There a cancelled frame runs the landing pad that the verifier generated for the unwind_exit, and a frame that the program unwinds runs unwind_exit as before.
A site that a frame can reach both cancelled and not has two landing pads and one target. The target is a test of the word with both pads after it, unless the two have the same insns. That includes an access to arena at which nothing is held. Such accesses share one landing pad per function, which loads V, and a cancelled frame needs the value of its cancellation, so the access gets an unwind_goto of its own.
The word is never read before it is written. Only pad code reads it: an entry after a call in pad code, the test before the two landing pads of a site, and the remainder. In a function that is not mixed, a frame gets from the normal path into pad code only through a stub or an entry that stores. This matters because a frame finds in the word what an earlier frame left there, and code that reads 1 treats the frame as cancelled.
So every unwind_goto of the program whose target is not dead code gets a stub, unless its call is in pad code, also where the program's landing pad is no cleanup pad: a typed catch that does not match joins pad code. The emission fails the load with a verifier bug unless each unwind_goto has a stub exactly where it needs one, every reader of the word is pad code, and the main pass saw no cancelled frame take an unwind_goto that has a stub or reach an entry that does not test.
Code with the same insns is shared, as landing pads are, except for an entry, which jumps to its own cleanup pad. The new code has no nospec barrier, like the landing pads: a program with unwind_goto is loaded with CAP_PERFMON.
--- include/linux/bpf_verifier.h | 39 ++- kernel/bpf/fixups.c | 601 ++++++++++++++++++++++++++++------- kernel/bpf/pads.c | 90 +++++- kernel/bpf/verifier.c | 54 +--- 4 files changed, 621 insertions(+), 163 deletions(-)
include/linux/bpf_verifier.h +36 -3
@@ -649,6 +649,13 @@ struct bpf_pad_plan {u8 asked_slots;u8 nr_ents;bool ordered;/* see order_ents() */ +/* BPF_SITE_CANCEL_ENTRY: its entry need not test the "cancelled" word: collect_pads() */ +bool untested; +/* +* BPF_SITE_CANCEL_ENTRY: a frame that was cancelled already reached the entry, so its call +* is in pad code. collect_pads() checks that against the control flow graph. +*/ +bool cancelled_visit;struct bpf_pad_ent *ents;/* oldest first. The pad releases the last one first. */ /* before[i]: bits of the entries that entry i must stand before, see put_before() */ u8 before[BPF_PAD_MAX_ENTS ];
@@ -738,6 +745,9 @@ struct bpf_pad_note { u8 entry: 1; }; +/* 'clear_stub' of an unwind_goto that gets no stub */ +#define BPF_CLEAR_STUB_NONE U32_MAX +/* The plans and the notes of an insn in the snapshot of a pass, see bpf_pads_move() */ struct bpf_pads_moved {struct bpf_pad_plan *plans;
@@ -1403,6 +1413,11 @@ struct bpf_insn_aux_data { u64 fault_unwinds:1; /* in the final program a fault goes to 'fault_pad' of the subprog */ u64 unwind_goto_follows:1; /* the verifier added an unwind_goto after the insn */ u64 cancel_goto_follows:1; /* the verifier added a cancel_goto after the insn */ +/* +* An unwind_goto of the program: a cancelled frame took its jump, so its call is in pad +* code. collect_stubs() checks that the control flow graph says the same. +*/ + u64 cancelled_takes:1; );/* what one pass gives to the next pass, see bpf_flow_new_pass() */
@@ -1429,6 +1444,11 @@ struct bpf_insn_aux_data {/* it can read or write the frame of a caller, in a call with a known callee */ u32 reads_outer:1; u32 writes_outer:1; +/* +* An unwind_goto of the program: 1 + the offset of its stub in the pads of the subprog, see +* collect_stubs(). BPF_CLEAR_STUB_NONE: no stub, its call is in pad code. 0: not decided. +*/ +u32 clear_stub;/* * Per-instruction summary of stack slots in the current frame * that this instruction may write, may read, and that are live before it.
@@ -1585,8 +1605,9 @@ struct bpf_subprog_info {*/ s16 value_off;/* -* The "cancelled" word of a function in which a cancellation enters a cleanup pad: 0 from -* the first insn of the function on, 1 once the frame is cancelled. +* The "cancelled" word: 1 in a frame that runs a cleanup pad for a cancellation, 0 in one +* that runs it for the program's own unwinding. Only the stubs and the entries of the +* function write it, or the first insn of a mixed function. */ s16 cancelled_off;/*
@@ -1783,6 +1804,15 @@ static inline void bpf_subprog_set_stuck(struct bpf_subprog_info *sub, enum bpf_ sub->stuck_insn = insn_idx; } +/* +* Does the first insn of @sub clear its "cancelled" word? Only in a mixed function, see +* bpf_pad_entry_insns(). In any other function the stubs and the entries write the word. +*/ +static inline bool bpf_subprog_clears_cancelled (const struct bpf_subprog_info *sub) +{ +return sub->cancelled_off && sub->cleanup_pads_mixed; +} +/* The stack depth of @sub with its hidden slots and words */ static inline u32 bpf_stack_depth_with_slots (const struct bpf_subprog_info *sub) {
@@ -2603,7 +2633,10 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env);bool bpf_pad_can_be_shared (const struct bpf_pad_plan *plan);int bpf_hidden_slots_fit (struct bpf_verifier_env *env);int bpf_pad_slot_notes (struct bpf_verifier_env *env,int s,const struct bpf_pad_note **notes); -int bpf_pad_entry_insns (const struct bpf_pad_note **notes,int nr,struct bpf_insn *buf); +int bpf_pad_entry_insns (const struct bpf_subprog_info *sub,const struct bpf_pad_note **notes, +int nr,struct bpf_insn *buf); +int bpf_pad_cancel_entry_insns (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan, +int subprog,struct bpf_insn *buf);int bpf_pad_insns_before (const struct bpf_subprog_info *sub,const struct bpf_pad_note **notes,int nr,const struct bpf_pad_note *note,struct bpf_insn *buf); int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
kernel/bpf/fixups.c +489 -112
777 lines not on this page · raw message
kernel/bpf/pads.c +82 -8
128 lines not on this page · raw message
kernel/bpf/verifier.c +14 -40
67 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 66/73 bpf: Let the entry of a cleanup pad save the pointers of the frame
In reply to Kumar Kartikeya DwivediCurrently the remainder of a cleanup pad can release little. A release needs the pointer in a register or stack slot that is live, and at the unwind_exit of the pad only R0 is. So a task in R6 that the cleanup pad does not release rejects the program.
Add save words: hidden words of the frame in which the entry keeps the pointers that the frame holds in R6-R9 or in a stack slot. With a task in R6 and one save word:
entry: cancelled = 1 rest: ax = cancelled
r0 = r6 if ax == 0 goto +6
*(u64 *)(r10 - 16) = r0 r1 = *(u64 *)(r10 - 16)
r0 = 0 if r1 == 0 goto +1
gotol pad call bpf_task_release
r0 = V
r2 = 0
cancel_exit
unwind_exitWhere the frame leaves, the state says what it still holds, and the save word is one more location of the pointer. The rules, see visit_saves():
- Only a pointer is saved. The address of irq flags, an iterator or a dynptr in the stack of a caller is not, because the pad can write to those slots. Nor is the address of a lock that only a register has. The cleanup pad has to release these itself, unless they have a location where the frame leaves.
- Word j is for the j-th reference that the frame holds at the call. A word without a pointer is cleared, so calls at which the frame holds one object and two can share a remainder.
- A word keeps its pointer when the cleanup pad releases the object. A pad that releases on one of two paths only is rejected, as before.
- A word holds one kind of object in all frames of a function. The type of the pointer says what releases it, and no register may have the pointer any more where the frame leaves.
- If the states at a call do not agree on what the frame holds, or a word would get a second kind of object, the entry of that call saves nothing and the pass is repeated. Each pass asks again, because the answer depends on what the pass keeps apart.
- An entry that tests the "cancelled" word saves only if the word is 0, and a call hands over no reference that has a save word.
On the normal path a function pays in stack only: 8 bytes per save word, 8 words at most. bpf_hidden_slots_settle() now asks once for all subprogs whether the hidden words fit, and per subprog only if not.
--- include/linux/bpf_verifier.h | 51 +++- kernel/bpf/fixups.c | 10 +- kernel/bpf/pads.c | 553 ++++++++++++++++++++++++++++++----- kernel/bpf/states.c | 1 + kernel/bpf/verifier.c | 52 +++- 5 files changed, 581 insertions(+), 86 deletions(-)
include/linux/bpf_verifier.h +47 -4
@@ -385,6 +385,8 @@ struct bpf_reference_state {u32 diag_id;/* finds the acquire in the report of a leak, it is not renumbered */ /* the insn that brought it into its frame: insn_idx, or a call that returned with it */ int origin; +/* 1 + the save word of the frame that has the pointer, 0 if none, see bpf_pad_enter() */ +u8 saved; union { /* For REF_TYPE_PTR. Compared and hashed as 8 bytes, see same_refs(): no holes. */ struct {
@@ -544,6 +546,7 @@ enum bpf_pad_conflict {BPF_CONFLICT_CALLER_SAVED ,BPF_CONFLICT_NO_VALUE ,BPF_CONFLICT_NO_ROOM , + BPF_CONFLICT_SAVES_DIFFER, };/* How a subprog was found to be one that cannot be cancelled, see 'stuck' of bpf_subprog_info */
@@ -567,6 +570,8 @@ enum bpf_stuck_by {#define BPF_PAD_MAX_INSNS (BPF_PAD_MAX_ENTS * (2 * BPF_PAD_MAX_ARGS + 2) + \ BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 5)#define BPF_PAD_MAX_CANDS 6 +/* The most save words of a function, see 'save_off' of struct bpf_subprog_info */ +#define BPF_PAD_MAX_SAVES BPF_PAD_MAX_ENTS/* * The most insns that keep hidden slots up to date at one call: nine for each of at most * BPF_PAD_MAX_ENTS slots, five that compare and clear it and four that find a free one. Three per
@@ -580,6 +585,8 @@ enum bpf_place_loc {BPF_PLACE_SPILL ,/* 8 bytes of the stack of the frame */ BPF_PLACE_MAP_VALUE ,/* the address of the only value of a map */ BPF_PLACE_IMM ,/* not a pointer: the constant 'delta', the flags of a release */ +/* save word 'at' of a cancelled frame, a BPF_PLACE_SPILL after take_cancelled_words() */ + BPF_PLACE_SAVED, };/* A location: where a landing pad finds the pointer that a release takes */
@@ -594,9 +601,17 @@ struct bpf_pad_place {/* The registers and the stack slots of a frame that are 0 */ struct bpf_pad_nulls {u16 regs; +u16 unsaved;/* the save words in which the entry stored no pointer */ DECLARE_BITMAP(slots, MAX_BPF_STACK_SLOTS); }; +/* The kind of pointer that a save word holds in all frames of a function: what releases it */ +struct bpf_pad_save { +struct bpf_insn release; +u32 obj_type; +bool set; +}; +/* One release of a landing pad: a resource of the frame, the call and where its arguments are */ struct bpf_pad_ent {u32 origin;/* the lowest 'origin' of the references that it stands for */
@@ -606,6 +621,8 @@ struct bpf_pad_ent {u8 class;/* enum bpf_pad_class */ bool rcu;/* an iterator that RCU protects: it is destroyed first */ bool always;/* all states hold it */ +/* BPF_SITE_CANCEL_ENTRY: 1 + the save word where the entry keeps the pointer, 0 if none */ +u8 word;/* per argument of the call: the locations that all states share. The pad uses the first. */ u8 nr_cands[BPF_PAD_MAX_ARGS ];struct bpf_pad_place cand[BPF_PAD_MAX_ARGS ][BPF_PAD_MAX_CANDS ];
@@ -647,8 +664,12 @@ struct bpf_pad_plan {u8 no_irq_place;/* the same for irq flags in the stack of a caller */ /* the groups that it asked hidden slots for, bits by enum bpf_pad_group: settle_slots() */ u8 asked_slots; +/* BPF_SITE_CANCEL_ENTRY: why the entry cannot save pointers, an enum bpf_pad_conflict */ +u8 no_saves;u8 nr_ents;bool ordered;/* see order_ents() */ +/* BPF_SITE_CANCEL_ENTRY: 'ents' are what the frame holds at the call, see visit_saves() */ +bool saves;/* BPF_SITE_CANCEL_ENTRY: its entry need not test the "cancelled" word: collect_pads() */ bool untested;/*
@@ -831,7 +852,12 @@ struct bpf_func_state {bool in_rcu_callback_fn;/* parent_id of the args that are gone when this frame returns */ u32 frame_id; -u32 cancelled;/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */ +u16 cancelled;/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */ +/* +* Bit per save word: the entry stored a pointer there when the frame was cancelled. The +* other words are 0. A word keeps its pointer when the cleanup pad releases the object. +*/ +u16 saved_mask;/* * Bit f: the frame, or a subprog that returned to it, released a lock or irq flags of * frame f. If the frame returns, a store after its call clears the hidden slot. If not,
@@ -1425,6 +1451,11 @@ struct bpf_insn_aux_data { u32 acquires:1; /* a reference or a lock */ u32 releases:1; u32 fault_full:1; /* an access to arena: its plan records every state */ +/* +* An unwind_goto of the program: the entry of its cleanup pad saves no pointers, because +* the states at the call did not agree in an earlier pass, see settle_entries() +*/ + u32 entry_saves_nothing:1;/* below flags are initialized once */ u32 bb_end:1; /* last instruction of a basic block */
@@ -1615,6 +1646,11 @@ struct bpf_subprog_info {* flags that the subprog saves or a pointer that it releases, see bpf_pad_note_return() */ s16 pend_off; +/* the first save word, the others are above it, see bpf_pad_enter() */ +s16 save_off; +u8 save_words; +/* what each save word holds in a cancelled frame, in this pass */ +struct bpf_pad_save saves[BPF_PAD_MAX_SAVES ];u32 insns_total;u32 insns_self;/* offsets in range [stack_depth .. fastcall_stack_off)
@@ -2013,6 +2049,8 @@ struct bpf_verifier_env {bool ref_conflict;bool handed_back;/* what was handed over was taken back, see try_more() */ bool pass_again;/* the pass is repeated, see pass_needs_restart() */ +bool saves_again;/* because what an entry saves changed: settle_entries() */ +bool ask_hidden_slots;/* per subprog from now on, see bpf_hidden_slots_fit() */ bool fallthrough_first;/* see find_failing_path() */ bool run_has_guess;/* see run_path_sensitive() */ u32 failing_path_budget_shift;/* see func_failing_path_budget() */
@@ -2042,7 +2080,10 @@ struct bpf_verifier_env {unsigned long cb_pads[8 ];u8 cb_pad_cnt;bool pads_late;/* a global subprog unwinds: see settle_late_unwinds() */ +bool saves_late;/* what an entry saves changed, see settle_entries() */ bool faults_late;/* a site is not what it seemed: see check_arena_site() */ +bool hidden_slots_unasked;/* see bpf_hidden_slots_fit() */ +bool slots_late;/* no room for hidden words: bpf_hidden_slots_settle() */ bool pad_releases;/* see release_frame_resources() */ bool calls_joined;/* see flow_may_add_instance() */ bool extra_values;/* a state can have constants that no run has */
@@ -2611,8 +2652,8 @@ size_t bpf_pad_plans_free(struct bpf_insn_aux_data *aux);void bpf_pads_new_round (struct bpf_verifier_env *env);void bpf_pads_move (struct bpf_verifier_env *env,struct bpf_pads_moved *moved,bool save);size_t bpf_pads_free_moved (struct bpf_pads_moved *moved,u32 cnt); -struct bpf_pad_plan *bpf_pad_enter (struct bpf_verifier_env *env, -const struct bpf_verifier_state *st,int call_idx); +struct bpf_pad_plan *bpf_pad_enter (struct bpf_verifier_env *env,struct bpf_verifier_state *st, +int call_idx);struct bpf_pad_plan *bpf_pad_visit (struct bpf_verifier_env *env,const struct bpf_verifier_state *st,int insn_idx,enum bpf_site_kind kind);
@@ -2632,11 +2673,13 @@ bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_dvoid bpf_pads_note_causes (struct bpf_verifier_env *env);bool bpf_pad_can_be_shared (const struct bpf_pad_plan *plan);int bpf_hidden_slots_fit (struct bpf_verifier_env *env); +int bpf_hidden_slots_settle (struct bpf_verifier_env *env);int bpf_pad_slot_notes (struct bpf_verifier_env *env,int s,const struct bpf_pad_note **notes);int bpf_pad_entry_insns (const struct bpf_subprog_info *sub,const struct bpf_pad_note **notes,int nr,struct bpf_insn *buf);int bpf_pad_cancel_entry_insns (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan, -int subprog,struct bpf_insn *buf); +int subprog,struct bpf_insn *buf,struct bpf_insn_aux_data *aux); +int bpf_pad_check_saves (struct bpf_verifier_env *env,int s);int bpf_pad_insns_before (const struct bpf_subprog_info *sub,const struct bpf_pad_note **notes,int nr,const struct bpf_pad_note *note,struct bpf_insn *buf); int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
kernel/bpf/fixups.c +7 -3
@@ -875,8 +875,8 @@ struct pad_unit {struct bpf_pad_plan *cancelled; }; -/* The most insns that a unit has */ -#define PAD_UNIT_MAX_INSNS (2 * (BPF_PAD_MAX_INSNS + 4) + 3) +/* The most insns of a unit. An entry has up to four per save word. */ +#define PAD_UNIT_MAX_INSNS (2 * (BPF_PAD_MAX_INSNS + 4) + 3 + 4 * BPF_PAD_MAX_SAVES)/* * Do the two records of @unit give the same landing pad? Both pads are emitted into @buf to
@@ -940,7 +940,7 @@ static int emit_unit(struct bpf_verifier_env *env, int s, enum bpf_site_kind basint n =0 , len;if (base ==BPF_SITE_CANCEL_ENTRY ) { - n +=bpf_pad_cancel_entry_insns (env, unit->plan, s, buf + n); + n +=bpf_pad_cancel_entry_insns (env, unit->plan, s, buf + n, aux + n); buf[n++] =BPF_JMP32_A (0 );return n; }
@@ -1092,6 +1092,10 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *nebool unwinds, cancelled; pads->nr = pads->cnt = pads->stubs =0 ; +/* the entries and the remainders have to agree on the save words */ + n = sub->save_words ?bpf_pad_check_saves (env, s) :0 ; +if (n) +return n; n =collect_stubs (env, s, pads);if (n <0 )return n;
kernel/bpf/pads.c +478 -75
729 lines not on this page · raw message
kernel/bpf/states.c +1 -0
@@ -493,6 +493,7 @@ static bool same_refs(const struct bpf_verifier_state *a, const struct bpf_veriffor (i =0 ; i < a->acquired_refs; i++)if (a->refs[i].type != b->refs[i].type || a->refs[i].id != b->refs[i].id || + a->refs[i].saved != b->refs[i].saved ||memcmp (&a->refs[i].ptr, &b->refs[i].ptr,sizeof (u64)))return false;return true;
kernel/bpf/verifier.c +48 -4
96 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 66/73] bpf: Let the entry of a cleanup pad save the pointers of the frame
TL;DR: - Possible program rejection: extra save words may exhaust stack room, with no fallback - An entry that saves nothing may still claim a save word, so a program can be rejected depending on…
Quoted 1 line
bpf: Let the entry of a cleanup pad save the pointers of the frame
TL;DR:
- Possible program rejection: extra save words may exhaust stack room, with no fallback
- An entry that saves nothing may still claim a save word, so a program can be rejected depending on entry order
- Level 2 log may report saves that are not emitted
Quoted 3 lines
kernel/bpf/pads.c +0
-0
[ ... ]
kernel/bpf/pads.c static bool same_release(const struct bpf_pad_ent *a, const struct bpf_pad_ent * · line 1683
Quoted 9 lines
kernel/bpf/pads.c +9
-0+if (!ent->nr_cands[0 ]) +continue ; + ent->word = j +1 ; + save = &sub->saves[j]; +if (!save->set) + *save = (struct bpf_pad_save ){ .release = ent->release, + .obj_type = ent->obj_type, .set = true }; +if (!ent_is_saved_kind (sub, j, ent)) +return BPF_CONFLICT_SAVES_DIFFER ;
An entry that ends up saving nothing still claims the kind of each save word here.
bpf_pad_enter() calls visit_saves() even when entry_saves_nothing is set, and visit_saves() fills sub->saves[j] from the first state before it finds out that the states disagree. That entry then stores 0 into every word, but its claim stays in sub->saves[] for the rest of the pass and in every repeated pass.
Say function f has two entries, E1 and E2. E1's states disagree (a task in R6 on one path, in R7 on another), so E1 saves nothing and its cleanup pad releases the task itself. E2 holds a socket at position 0 and needs it saved. If E1 is visited first, sub->saves[0] gets the task kind, E2 then gets BPF_CONFLICT_SAVES_DIFFER from ent_is_saved_kind() and saves nothing, and the remainder of E2 has no location for the socket, so the program is rejected. Visited in the other order, the program loads.
The commit message says an entry saves nothing if "a word would get a second kind of object", but here no frame ever stores the first kind in that word.
Should sub->saves[] be claimed only when the entry actually saves, that is when entry_saves_nothing is clear?
[ ... ]
Quoted 6 lines
kernel/bpf/pads.c +1
-1@@ -3465,8 +3764,15 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad/* no generated pad: the entry of a cleanup pad */ if (plan->kind ==BPF_SITE_CANCEL_ENTRY ) { - verbose(env, "landing pad of the program behind the call at %d: the kernel enters it\n", + verbose(env, "landing pad of the program behind the call at %d: the kernel enters it",
kernel/bpf/pads.c static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad · line 3777
Quoted 10 lines
kernel/bpf/pads.c +7
-0i); +for (j =0 ; j < plan->nr_ents; j++) { +if (!plan->ents[j].nr_cands[0 ]) +continue ; +verbose (env,", saves " ); +print_ent (env, &plan->ents[j]); + } +verbose (env,"\n" );return ; }
This isn't a bug in the verifier result, but the level 2 log can report saves that the emitted entry does not make.
print_plan() prints ", saves <ent>" for every ent with a candidate, while the emission and the word count use saved_ent(), which returns NULL for every word when the function has hidden slots for references:
if (sub->slots & BIT(BPF_PAD_GROUP_REFS)) return NULL;
In that case take_cancelled_words() computes save_words = 0 and bpf_pad_cancel_entry_insns() emits no save stores, yet the log still says for example "the kernel enters it, saves ref@M(r6)". The same text can appear in front of a rejection in bpf_pad_log().
Would it be better to print only the ents for which saved_ent() returns non-NULL?
[ ... ]
Quoted 4 lines
kernel/bpf/pads.c +0
-0@@ -3831,19 +4148,95 @@ static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info*/ static int take_cancelled_words (struct bpf_verifier_env *env,struct bpf_subprog_info *sub) {
[ ... ]
kernel/bpf/pads.c static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info · line 4172
Quoted 13 lines
kernel/bpf/pads.c +8
-1+for (i = sub->start; i < sub[1 ].start; i++) { + plan =bpf_pad_plan (&aux[i],BPF_SITE_CANCEL_ENTRY ); +for (j =0 ; plan && j <BPF_PAD_MAX_SAVES ; j++) +if (saved_ent (sub, plan, j)) + words =max (words, j +1 ); + } + sub->hidden_words +=1 + words; err =bpf_hidden_slots_fit (env);if (err <=0 ) { - sub->hidden_words--; + sub->hidden_words -=1 + words;return err ?:1 ; }
Can this reject a program that loaded before this commit?
visit_saves() gives a save word to every pointer that the frame holds in R6-R9 or in a live stack slot at a cancellable call. It runs at the entry, before the cleanup pad is explored, so it cannot know whether the pad releases the object itself. Here "words" is the highest word any entry record uses, not the highest word a pad actually reads.
Take a function whose cleanup pad releases a task held in R6 by itself (r1 = r6; call bpf_task_release; unwind_exit), so nothing is held at unwind_exit. Before this commit only the "cancelled" word was taken (plus the value word with bpf_throw()); now one more word is reserved that the remainder never reads. If the call chain is within 8 bytes of the stack limit or of a rounding boundary, bpf_hidden_slots_fit() fails, and take_cleanup_pad_words() rejects the program with "no room in the stack for the hidden words of func#%d" (-EINVAL).
There is no retry with an entry that saves nothing: settle_entries() has that fallback for BPF_CONFLICT_SAVES_DIFFER and BPF_CONFLICT_TOO_MUCH, but not for lack of stack room. The commit message says a function "pays in stack only: 8 bytes per save word", but not that this can turn an accepted program into a rejected one.
Could the words be counted only up to the highest one that a pad of a cancelled frame reads, or could the entry fall back to saving nothing when the words do not fit?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 67/73 bpf: Run the cleanup pads of a program when the kernel cancels it
In reply to Kumar Kartikeya DwivediCurrently everything that a cancellation needs to run a cleanup pad is in place, but nothing calls bpf_find_cleanup_pads(), so no unwind_goto is marked as leading to a cleanup pad.
Call it from bpf_check(), before the main pass. For a program this means:
- When the kernel cancels the program in a subprog or in a callback, the code at the target of the unwind_goto after the call runs if it is a cleanup pad. R0 is 0 at the target.
- The unwind_exit that this code ends in leaves with the value of the cancellation, whatever is in R0, and no unwind_goto is taken for it. The cancellation continues in the same way with each caller.
- A cancellation still cannot be caught. A landing pad of the program that can continue running is not entered, and a cancelled frame never returns to its caller.
- A cleanup pad is verified a second time, for the cancelled frame. An error on that path rejects the program, also one that loaded before.
A cancellation point inside a cleanup pad behaves as follows:
- If the pad runs for the program's own unwinding, a cancellation starts there as anywhere else.
- If the pad already runs for a cancellation, the frame leaves at that point through a generated pad. The rest of that cleanup does not run, and the program still returns the value of the first cancellation. A call that has a cleanup pad of its own is different: the frame continues in that pad.
- After a time-out the time stays up, so a loop in cleanup code ends at its first may_goto. After a fault in arena, bpf_throw() or a recursion that is too deep, a cleanup pad is not cut short this way.
A program can count on a cleanup pad where a cancellation reaches it. The pad is entered, or the program is rejected and the log says why:
- The stack of the function has no room for the hidden words.
- The verifier cannot release what the frame still holds after the cleanup pad, or at a site that the frame reaches in the pad or in a function that the pad calls. A cancelled frame gets no hidden slots of its own.
- The cleanup pad changes what a caller holds in a way that the generated pad of the caller cannot follow. It unlocks a lock or leaves an RCU section of the caller on some paths only, writes to its irq flags, or releases what a function on the stack needs a hidden slot for.
The destructors of a frame do not run on a cancellation in these cases, and in no other:
- The program's landing pad can return or never reaches unwind_exit: a catch clause, and the landing pad of a noexcept function. Destructors that such a landing pad runs before that do not run either.
- The function cannot be cancelled.
- The frame is the one in which the cancellation starts: the frame of the loop, of the access to arena, of the recursion check or of bpf_throw(). Inlining decides which frame that is.
- The call of a frame above it has no unwind_goto, because the callee is noexcept or nounwind or was inlined.
A function in which a cancellation enters a cleanup pad has hidden words in its frame, and a function that had no stack gets one. Only a mixed function also pays a store per call.
verifier.rst now describes cleanup pads, the "cancelled" word and the save words, and the uapi comment of BPF_UNWIND_GOTO says when the code at its target runs for a cancellation. No existing test changes.
--- Documentation/bpf/verifier.rst | 109 ++++++++++++++++++++++++++++++++- include/uapi/linux/bpf.h | 17 +++++ kernel/bpf/verifier.c | 4 ++ tools/include/uapi/linux/bpf.h | 17 +++++ 4 files changed, 144 insertions(+), 3 deletions(-)
Documentation/bpf/verifier.rst +106 -3
@@ -1032,7 +1032,8 @@ The landing pad of the call releases nothing, and nothing is added at run time. A call hands over a pointer in one of ``R1`` - ``R5`` that the callee reads and that cannot be NULL. It does not hand over an iterator, a dynptr, a reference that was made from another one, or one that another one was made from. It hands -nothing over to a recursive function or to a callback. +nothing over to a recursive function or to a callback, nor while a frame on the +stack is cancelled already, see `Cleanup pads`_. The program is still rejected if the callee has no location for the pointer at one of its sites, if a landing pad of the callee would release under a lock of
@@ -1102,8 +1103,8 @@ program has an ``unwind_goto`` after a call, the ``cancel_goto`` follows it:: pad: r0 = 0 exit -A cancellation enters no landing pad of the program, so the program cannot -catch it. +A cancellation enters a landing pad of the program only if that pad cannot +catch it, see `Cleanup pads`_. Where a callee leaves with ``unwind_exit`` and the caller has no ``unwind_goto`` after the call, the verifier adds one, with a landing pad that
@@ -1131,6 +1132,106 @@ A global function is different because its callers are checked without it and only see a number as its return value. A compiler that wants an object to get through a global function gives the call there a landing pad of its own. +Cleanup pads +------------ + +A *cleanup pad* is a landing pad of the program that can only clean up and +continue unwinding. It runs a destructor of C++ or drop glue of Rust. Two rules +decide it, see ``bpf_find_cleanup_pads()``. From the first insn of the pad, + +- no path in the function reaches an insn that returns to the caller: ``exit``, + a tail call, ``LD_ABS`` or ``LD_IND``, +- some path reaches ``unwind_exit``. + +A cancellation runs the cleanup pads of the frames that it leaves. The same +code then serves the program's own unwinding and a cancellation, so the frame +remembers which of the two is under way in a hidden word of its stack, the +"cancelled" word:: + + what the program has what the verifier makes of it + + call foo call foo + unwind_goto pad unwind_goto stub + ... cancel_goto entry + pad: call dtor ... + unwind_exit pad: call dtor + gotol rest + stub: cancelled = 0 <- own unwinding + gotol pad + entry: cancelled = 1 <- cancellation + r0 = 0 + gotol pad + rest: if cancelled == 0 goto +N + release what the frame still holds + cancel_exit + unwind_exit + +The entry puts 0 into ``R0``, where the program's own unwinding has the object +that it threw. The code at ``rest``, the remainder of the pad, replaces its +``unwind_exit``. A frame that the program unwinds still leaves with +``unwind_exit``. A cancelled frame leaves with ``cancel_exit`` and the value of +the cancellation, whatever is in ``R0``. So no landing pad of the program in a +caller can catch the cancellation, and it continues in the same way with each +caller. + +Nothing on the normal path writes the "cancelled" word. A function in which a +cancellation enters a cleanup pad pays for its hidden words in stack, and a +function that had no stack gets one. A function also pays one store per call, +which clears the word at its entry, if its normal path falls into a cleanup pad +or jumps to it, or if a cleanup pad jumps back before its call. + +The verifier checks a cleanup pad a second time, for the cancelled frame: with +0 in ``R0``, and with what the frame holds when its callee is cancelled, see +``enter_cleanup_pad()``. An error on that path rejects the program. + +The remainder releases what the frame still holds after the cleanup pad. Only +``R0`` is live at the ``unwind_exit`` of the pad. So the entry keeps the +pointers that the frame holds in ``R6`` - ``R9`` or in stack slots in hidden +*save words*, at most 8, see ``visit_saves()``. Only a pointer is saved. The +cleanup pad itself has to release irq flags, an iterator or a dynptr in the +stack of a caller, and a lock whose address only a register holds. If the +states at a call do not agree on what the frame holds, the entry of that call +saves nothing, and the remainder releases only what has a location at the +``unwind_exit``. + +A cleanup pad can have sites of its own. If the pad runs for the program's own +unwinding, a cancellation starts there as anywhere else. If the pad already +runs for a cancellation, the frame leaves at that site through a landing pad. +The rest of the cleanup pad does not run, and the program still returns the +value of the first cancellation. A call that has a cleanup pad of its own is +different: the frame continues in that pad. After a time-out the time stays +up, so a loop in a cleanup pad ends at its first ``may_goto``. After a fault in +arena, ``bpf_throw()`` or a recursion that is too deep, a cleanup pad is not +cut short this way. + +A program can count on a cleanup pad where a cancellation reaches it: the pad +is entered, or the program is rejected. The log then has a line with "the +kernel would enter", which names the cleanup pad where the verifier knows which +one it is. The program is rejected in these cases: + +- The stack of the function has no room for the hidden words. +- The verifier cannot release what the frame still holds after the cleanup pad, + or at a site that the frame reaches in the pad or in a function that the pad + calls. A cancelled frame gets no hidden slots of its own. +- The cleanup pad changes what a caller holds in a way that the landing pad of + the caller cannot follow. It unlocks a lock or leaves an RCU section of the + caller on some paths only, writes to its irq flags, or releases what a + function on the stack needs a hidden slot for. + +The destructors of a frame do not run on a cancellation in these cases, and in +no other: + +- The program's landing pad can return, or never reaches ``unwind_exit``: a + catch clause, and the landing pad of a ``noexcept`` function, which ends in + ``std::terminate()``. Destructors that such a landing pad runs before that + do not run either. +- The function cannot be cancelled. +- The frame is the one in which the cancellation starts: the frame of the loop, + of the access to arena, of the recursion check or of ``bpf_throw()``. + Inlining decides which frame that is. +- The call of a frame above it has no ``unwind_goto``, because the callee is + ``noexcept`` or ``nounwind`` or was inlined. + After an error ==============
@@ -1702,6 +1803,8 @@ budget a limit on the cost of one step cancel the kernel ends the program before it returns by itself, and each frame releases what it holds checked the bytes of a packet that are known to be before its end +cleanup pad a landing pad of the program that can only clean up and + continue unwinding control_deps xregs whose value flows to a jump that can skip an unproven insn correlated two branches: one tests a result that the other one stored
include/uapi/linux/bpf.h +17 -0
@@ -66,6 +66,23 @@ enum bpf_cond_pseudo_jmp {* Follows a call of a bpf subprog, callx, or a call of a helper or kfunc * that calls a callback. Taken when the subprog or the callback left with * BPF_EXIT that has src_reg == BPF_UNWIND_EXIT. +* When the kernel cancels the program in the subprog or the callback, +* for a loop that is out of time, a recursion that is too deep, a fault +* in arena or bpf_throw(), the code at the target runs too if it is a +* cleanup pad: no path from the target gets to BPF_EXIT without +* BPF_UNWIND_EXIT, to a tail call or to BPF_LD_ABS or BPF_LD_IND, and +* some path gets to BPF_EXIT with BPF_UNWIND_EXIT. R0 is 0 at the +* target then. That BPF_EXIT leaves with the value of the cancellation +* whatever is in R0, and no BPF_UNWIND_GOTO is taken for it: the +* cancellation continues in the same way with each caller. +* A program can count on a cleanup pad where a cancellation reaches it: +* the pad is entered, or the program is rejected and the log says why. +* A cancellation does not reach it in a function that cannot be +* cancelled, in the function in which the cancellation starts, and at a +* call that has no BPF_UNWIND_GOTO. And when the time of the program is +* up, a loop in a cleanup pad ends at its first may_goto: what follows +* the loop does not run. +* See Documentation/bpf/verifier.rst. */ BPF_UNWIND_GOTO = 1, };
kernel/bpf/verifier.c +4 -0
@@ -27489,6 +27489,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,if (ret <0 ) goto skip_full_check; + ret =bpf_find_cleanup_pads (env); +if (ret <0 ) + goto skip_full_check; + ret =bpf_flow_place_guards (env);if (ret <0 ) goto skip_full_check;
tools/include/uapi/linux/bpf.h +17 -0
@@ -66,6 +66,23 @@ enum bpf_cond_pseudo_jmp {* Follows a call of a bpf subprog, callx, or a call of a helper or kfunc * that calls a callback. Taken when the subprog or the callback left with * BPF_EXIT that has src_reg == BPF_UNWIND_EXIT. +* When the kernel cancels the program in the subprog or the callback, +* for a loop that is out of time, a recursion that is too deep, a fault +* in arena or bpf_throw(), the code at the target runs too if it is a +* cleanup pad: no path from the target gets to BPF_EXIT without +* BPF_UNWIND_EXIT, to a tail call or to BPF_LD_ABS or BPF_LD_IND, and +* some path gets to BPF_EXIT with BPF_UNWIND_EXIT. R0 is 0 at the +* target then. That BPF_EXIT leaves with the value of the cancellation +* whatever is in R0, and no BPF_UNWIND_GOTO is taken for it: the +* cancellation continues in the same way with each caller. +* A program can count on a cleanup pad where a cancellation reaches it: +* the pad is entered, or the program is rejected and the log says why. +* A cancellation does not reach it in a function that cannot be +* cancelled, in the function in which the cancellation starts, and at a +* call that has no BPF_UNWIND_GOTO. And when the time of the program is +* up, a loop in a cleanup pad ends at its first may_goto: what follows +* the loop does not run. +* See Documentation/bpf/verifier.rst. */ BPF_UNWIND_GOTO = 1, };
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 68/73 bpf: End the path at a call of a global subprog that never returns
In reply to Kumar Kartikeya DwivediCurrently the verifier continues after every call of a global subprog. A global subprog that unwinds on every path never returns, and such functions are common in C++: std::throw_with_nested() is an inline template, which makes it a weak function. A compiler puts what it likes after the call, most often the program's landing pad of that very call:
call throw_with_nested
unwind_goto +0
call dtor <- the landing pad
r0 = 0
unwind_exit
The verifier checks that landing pad for a frame that falls out of the call, which no frame does, and rejects the program when the code is wrong for that state. A cleanup pad there also makes the function mixed.
bpf_compute_might_return() computes for every subprog whether a path from its first insn reaches an exit insn, a tail call, LD_ABS or LD_IND. A path ends at unwind_exit, at a call of bpf_throw() or __bpf_trap(), and at a call of a subprog that does not return, where it continues only at the target of an unwind_goto after that call. A function that calls itself on every path does not return.
In check_func_call(), end the path at a call of a global subprog that does not return. The code after the call becomes dead code unless another path reaches it. Three more changes go with this:
- The search for pad code does not follow the edge from a call of a subprog that does not return, static or global, to the insn after it. A cleanup pad there no longer makes the function mixed.
- A trap, 'goto pc-1', now stays after every such call where the code after it is dead. So far that took an unwind_goto or cancel_goto after the call, or a program without CAP_PERFMON. Should a return ever get there, it finds a trap and not code that was verified for another path.
- The insn after such a call reads R6-R9 and the stack of the frame, for liveness only, as a call of bpf_throw() does. Without an unwind_goto of the program there, the frame leaves through a generated pad, which finds the pointers of the frame in what is live at that insn. The insn is dead code and reads nothing, so a task in R6 needed a hidden slot or rejected the program. An insn that is a jump target is not changed.
A program that was rejected for the code after such a call now loads. R6-R9 and the stack stay live up to such a call, which costs load time.
--- include/linux/bpf_verifier.h | 13 +++++ kernel/bpf/cfg.c | 107 +++++++++++++++++++++++++++++++++++ kernel/bpf/fixups.c | 14 ++++- kernel/bpf/liveness.c | 35 +++++++++++- kernel/bpf/pads.c | 29 +++++----- kernel/bpf/verifier.c | 20 ++++++- 6 files changed, 197 insertions(+), 21 deletions(-)
include/linux/bpf_verifier.h +13 -0
@@ -1670,6 +1670,8 @@ struct bpf_subprog_info { bool in_recursion: 1; /* recursive, or a recursive subprog gets to it */ bool addr_taken: 1; /* callx calls nothing else */ bool via_callx: 1; /* callx calls it */ +/* a path from its first insn returns to the caller, see bpf_compute_might_return() */ + bool might_return: 1; bool tail_call_reachable: 1; bool has_ld_abs: 1; bool is_cb: 1;
@@ -3007,6 +3009,15 @@ u32 bpf_vlog_alignment(u32 pos);const char *bpf_disasm_kfunc_name (void *data,const struct bpf_insn *insn);struct bpf_subprog_info *bpf_find_containing_subprog (struct bpf_verifier_env *env,int off); + +/* A tail call that is taken and an LD_ABS or LD_IND that fails leave the subprog like exit */ +static inline bool bpf_insn_has_hidden_exit (const struct bpf_insn *insn) +{ +return (bpf_helper_call (insn) && insn->imm == BPF_FUNC_tail_call) || + (BPF_CLASS (insn->code) ==BPF_LD && + (BPF_MODE (insn->code) ==BPF_ABS ||BPF_MODE (insn->code) ==BPF_IND )); +} +const char *bpf_subprog_name (const struct bpf_verifier_env *env,int subprog);struct bpf_iarray *bpf_insn_successors (struct bpf_verifier_env *env,u32 idx);
@@ -3044,11 +3055,13 @@ u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);int bpf_find_subprog (struct bpf_verifier_env *env,int off);bool bpf_is_throw_kfunc (struct bpf_insn *insn); +bool bpf_is_trap_kfunc (struct bpf_insn *insn);int bpf_compute_const_regs (struct bpf_verifier_env *env);int bpf_prune_dead_branches (struct bpf_verifier_env *env);int bpf_check_cfg (struct bpf_verifier_env *env);void bpf_free_subprog_jts (struct bpf_verifier_env *env);int bpf_compute_postorder (struct bpf_verifier_env *env); +int bpf_compute_might_return (struct bpf_verifier_env *env);struct bpf_map_desc {struct bpf_map *ptr;
kernel/bpf/cfg.c +107 -0
113 lines not on this page · raw message
kernel/bpf/fixups.c +11 -3
@@ -1748,8 +1748,8 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)struct bpf_insn trap =BPF_JMP_IMM (BPF_JA ,0 ,0 ,-1 );struct bpf_insn *insn = env->prog->insnsi;const int insn_cnt = env->prog->len; -bool unwinds, calls; -int i; +bool unwinds, calls, traps; +int i, callee;for (i =0 ; i < insn_cnt; i++, insn++) { unwinds =bpf_is_pad_goto (insn) && aux_data[i +1 +bpf_jmp_offset (insn)].seen;
@@ -1759,8 +1759,16 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)* its cancel_exit needs cancel_goto. * The cpu predicts that it returns to what follows, or speculates to an exit. * Don't let the removal of dead code put something else there. +* After a call of a subprog that does not return, see bpf_compute_might_return(), +* the trap is kept whoever loads the program: should a return ever get there, it +* must not find code that was verified for another path. */ -if ((unwinds || (calls && !env->bypass_spec_v1)) && !aux_data[i +1 ].seen) { + traps = calls && !env->bypass_spec_v1; +if (calls && !traps &&bpf_pseudo_call (insn)) { + callee =bpf_find_subprog (env, i + insn->imm +1 ); + traps = callee >=0 && !env->subprog_info[callee].might_return; + } +if ((unwinds || traps) && !aux_data[i +1 ].seen) {memcpy (insn +1 , &trap,sizeof (trap)); aux_data[i +1 ].zext_dst = false; aux_data[i +1 ].seen = env->check_cnt;
kernel/bpf/liveness.c +32 -3
@@ -392,9 +392,7 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)* from the subprogram, which is a hidden edge to its exit. A subprogram * with neither an exit insn nor bpf_throw() has no exit to model. */ -if (unlikely ((bpf_helper_call (insn) && insn->imm == BPF_FUNC_tail_call) || - (BPF_CLASS (insn->code) ==BPF_LD && - (BPF_MODE (insn->code) ==BPF_ABS ||BPF_MODE (insn->code) ==BPF_IND )))) { +if (unlikely (bpf_insn_has_hidden_exit (insn))) {u32 exit_idx =bpf_find_containing_subprog (env, idx)->exit_idx;if (exit_idx !=U32_MAX )
@@ -1860,6 +1858,26 @@ static int record_arg_access(struct bpf_verifier_env *env,return err; } +/* +* Is the insn at @idx dead code after a call of a subprog that does not return, see +* bpf_compute_might_return()? The callee comes back to the call only when it unwinds or is +* cancelled. The frame then leaves through a generated pad, which finds the pointers of the frame +* in what is live at this insn. So for liveness the insn reads what the pad may read, as a call of +* bpf_throw() does. That does not apply where the program has an unwind_goto there, nor where a +* jump leads to the insn. +*/ +static bool behind_call_without_return (struct bpf_verifier_env *env,int idx) +{ +const struct bpf_insn *insns = env->prog->insnsi; +int callee; + +if (!idx || !bpf_pseudo_call (&insns[idx -1 ]) ||bpf_is_unwind_goto (&insns[idx]) || +bpf_is_jump_target (env, idx)) +return false; + callee =bpf_find_subprog (env, idx + insns[idx -1 ].imm); +return callee >=0 && !env->subprog_info[callee].might_return; +} +/* Record stack access for a given 'at' state of helper/kfunc/global subprog 'insn' */ static int record_call_access(struct bpf_verifier_env *env, struct func_instance *instance,
@@ -2213,6 +2231,13 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,if (err) goto err_free; +/* the generated pad of the call may read any stack slot of the frame */ +if (behind_call_without_return (env, idx)) { + err =mark_stack_read_all (env, instance, instance->depth, idx, true); +if (err) + goto err_free; + } +if (BPF_CLASS (insn->code) ==BPF_JMP &&BPF_OP (insn->code) ==BPF_CALL ) { err =record_call_access (env, instance, at_in[i], idx);if (err)
@@ -2842,6 +2867,10 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env,break ; } +/* the generated pad of the call may take a pointer from R6-R9 */ +if (behind_call_without_return (env, insn - env->prog->insnsi)) + use |=mask_widen (GENMASK (BPF_REG_9 ,BPF_REG_6 )); + info->def = def; info->use = use; }
kernel/bpf/pads.c +15 -14
@@ -4728,10 +4728,7 @@ static bool insn_returns(const struct bpf_insn *insn) {if (insn->code == (BPF_JMP |BPF_EXIT ))return !bpf_is_unwind_exit (insn); -if (bpf_helper_call (insn) && insn->imm == BPF_FUNC_tail_call) -return true; -return BPF_CLASS (insn->code) ==BPF_LD && - (BPF_MODE (insn->code) ==BPF_ABS ||BPF_MODE (insn->code) ==BPF_IND ); +return bpf_insn_has_hidden_exit (insn); }/*
@@ -4757,16 +4754,11 @@ static bool insn_returns(const struct bpf_insn *insn)* call, or the function has no exit. In any other function a frame gets from the normal path into * pad code in two ways only: by the jump of an unwind_goto, and through an entry. * -* A function is MIXED, 'cleanup_pads_mixed', if one of its insns is pad code and on the normal path -* as well: a pad that the normal path falls into or jumps to, a pad that goes back in front of its -* call, or to the first insn of its function, any pad of a function that has no exit. In every -* other function the two share no insn, and a frame gets from the normal path into pad code in two -* ways only: by the jump of unwind_goto, when a callee left with unwind_exit, and through the entry -* of a pad, when the kernel unwound the callee. -* -* The exit that stands for the return of a tail call or of LD_ABS is no edge here, as it is none -* where the pads are judged: it can be unwind_exit of the code that resumes, and a tail call on -* the normal path would make every such function mixed. +* Two edges are not followed. One goes from a tail call, LD_ABS or LD_IND to the exit insn that +* stands for its return, which is often the unwind_exit of the cleanup pads. The other goes from +* the call of a subprog that does not return, see bpf_compute_might_return(), to the insn after it, +* where a compiler often puts the cleanup pad of that call. A trap stands there if that code is +* dead, see bpf_opt_hard_wire_dead_code_branches(). */ static int find_pad_code (struct bpf_verifier_env *env) {
@@ -4801,6 +4793,15 @@ static int find_pad_code(struct bpf_verifier_env *env)if (!test_bit (i, pad) && !test_bit (i, normal))continue ; insn = &insns[i]; + s =bpf_pseudo_call (insn) ?bpf_find_subprog (env, i +1 + insn->imm) :-1 ; +if (s >=0 && !env->subprog_info[s].might_return) { +/* the callee does not return: only its landing pad follows */ + t = i +1 < len &&bpf_is_unwind_goto (insn +1 ) ? + i +2 +bpf_jmp_offset (insn +1 ) :-1 ; +if (t >=0 &&test_bit (i, pad) && !__test_and_set_bit (t, pad)) + changed = true; +continue ; + } succ =bpf_insn_successors (env, i); cnt =insn_returns (insn) ?min (succ->cnt,1 ) : succ->cnt;for (t =0 ; t < cnt; t++) {
kernel/bpf/verifier.c +19 -1
@@ -12621,6 +12621,13 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, BPF_REG_0); } +/* +* The callee never returns, see bpf_compute_might_return(). Only the states that +* were pushed above come back from the call, so this path ends. +*/ +if (!env->subprog_info[subprog].might_return) +return PROCESS_BPF_EXIT ; +/* continue with next insn after call */ return 0 ; }
@@ -15713,6 +15720,12 @@ bool bpf_is_throw_kfunc(struct bpf_insn *insn) insn->imm == special_kfunc_list[KF_bpf_throw]; } +bool bpf_is_trap_kfunc (struct bpf_insn *insn) +{ +return bpf_pseudo_kfunc_call (insn) && insn->off ==0 && + insn->imm == special_kfunc_list[KF___bpf_trap]; +} +static bool is_bpf_wq_set_callback_kfunc (u32 btf_id) {return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
@@ -16567,7 +16580,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,mark_reg_unknown (env, regs,BPF_REG_0 );reg_set_srange32 (®s[BPF_REG_0 ], -MAX_ERRNO ,-1 );reg_bounds_sync (®s[BPF_REG_0 ]); - }else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { + }else if (bpf_is_trap_kfunc (insn)) {verbose (env,"unexpected __bpf_trap() due to uninitialized variable?\n" );return -EFAULT ; }
@@ -27469,6 +27482,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,if (ret <0 ) goto skip_full_check; +/* needs the topological order of the subprogs, callees first */ + ret =bpf_compute_might_return (env); +if (ret <0 ) + goto skip_full_check; +/* what no JIT can run is reported first */ ret =mark_recursive_subprogs (env);if (ret <0 )
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 68/73] bpf: End the path at a call of a global subprog that never returns
TL;DR: Nits only: the "callee never returns" check is open-coded in three or four places with different spellings; the review suggests a shared helper (and using callee_subprog() in liveness.c) so…
Quoted 1 line
bpf: End the path at a call of a global subprog that never returns
TL;DR: Nits only: the "callee never returns" check is open-coded in three or four places with different spellings; the review suggests a shared helper (and using callee_subprog() in liveness.c) so they cannot drift apart.
Quoted 3 lines
kernel/bpf/fixups.c +0
-0
[ ... ]
kernel/bpf/fixups.c void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) · line 1770
Quoted 5 lines
kernel/bpf/fixups.c +5
-0+ traps = calls && !env->bypass_spec_v1; +if (calls && !traps &&bpf_pseudo_call (insn)) { + callee =bpf_find_subprog (env, i + insn->imm +1 ); + traps = callee >=0 && !env->subprog_info[callee].might_return; + }
This isn't a bug, but the test "this pseudo call calls a subprog that does not return" is open-coded here, in behind_call_without_return() and in find_pad_code(), each time with a differently spelled call target (i + insn->imm + 1, idx + insns[idx - 1].imm, i + 1 + insn->imm).
Could a small helper that takes the index of the call and says whether its callee does not return replace these copies, so the three edges cannot drift apart?
[ ... ]
Quoted 3 lines
kernel/bpf/liveness.c +0
-0
[ ... ]
kernel/bpf/liveness.c static int record_arg_access(struct bpf_verifier_env *env, · line 1879
Quoted 11 lines
kernel/bpf/liveness.c +11
-0+static bool behind_call_without_return (struct bpf_verifier_env *env,int idx) +{ +const struct bpf_insn *insns = env->prog->insnsi; +int callee; + +if (!idx || !bpf_pseudo_call (&insns[idx -1 ]) ||bpf_is_unwind_goto (&insns[idx]) || +bpf_is_jump_target (env, idx)) +return false; + callee =bpf_find_subprog (env, idx + insns[idx -1 ].imm); +return callee >=0 && !env->subprog_info[callee].might_return; +}
This isn't a bug, but liveness.c already has callee_subprog() for looking up the callee of a call. Could behind_call_without_return() use it instead of computing the target by hand?
[ ... ]
Quoted 3 lines
kernel/bpf/pads.c +0
-0
[ ... ]
kernel/bpf/pads.c static int find_pad_code(struct bpf_verifier_env *env) · line 4796
Quoted 5 lines
kernel/bpf/pads.c +3
-0@@ -4801,6 +4793,15 @@ static int find_pad_code(struct bpf_verifier_env *env) insn = &insns[i]; + s =bpf_pseudo_call (insn) ?bpf_find_subprog (env, i +1 + insn->imm) :-1 ; +if (s >=0 && !env->subprog_info[s].might_return) { +/* the callee does not return: only its landing pad follows */
This isn't a bug, but this is the third (and with subprog_might_return() in cfg.c, the fourth) spelling of the same check on a call edge. Would a shared helper, something like bpf_call_returns(env, idx) in the spirit of may_not_return() for might_throw in precision.c, keep these checks consistent?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 69/73 bpf: Tell struct_ops when a program was cancelled
In reply to Kumar Kartikeya DwivediCurrently the kernel code that calls a struct_ops program cannot tell a program that was cancelled from one that ran to its end. A cancelled struct_ops program returns 0, and what 0 means is up to the struct_ops. For ops.select_cpu() of sched_ext it is a CPU. The work of the program is also left half done. When ops.enqueue() of sched_ext faults in arena before it queues its task, the task is in no queue, and sched_ext keeps calling the scheduler until its watchdog finds a task that has not run.
Add a callback, ->cancelled(), to struct bpf_struct_ops. In a program of a struct_ops that sets it, the landing pad that returns to the kernel calls it after all frames have released what they held:
pad: r1 = r6
call bpf_task_release
+ r1 = prog->aux
+ call bpf_prog_report_cancelled <- calls st_ops->unwound(prog)
r0 = 0
exitOnly landing pads that end with exit get the call. They belong to the functions that only the kernel calls: the main program, and an async callback for which the verifier finds no caller in the program. Every other landing pad ends with cancel_exit, and the cancellation continues in the caller.
Three cases need care:
- An async callback that may have a caller in the program has landing pads that end with cancel_exit. When the kernel called such a callback and cancels it, the struct_ops is not told yet.
- The landing pads of the exception callback make no call. The landing pad of the main program that calls it has called ->cancelled() before.
- The call is also made where the program's own unwinding ends the program, at a call without unwind_goto to which an unwind_exit comes back. An unwinding that the program catches is not reported.
->cancelled() runs in the context of the kernel code that called the program, with the locks that this code holds, and it can be reentered. It must not sleep or take a lock that is held around a call of a program.
An async callback can run when no struct_ops map holds the module of the struct_ops any more. So a struct_ops program now holds a reference on that module, and drops it after the grace period that waits for the program to stop running. A module therefore cannot be unloaded while a program of one of its struct_ops is loaded, also when no struct_ops map exists.
--- include/linux/bpf.h | 13 +++++++++++++ include/linux/bpf_verifier.h | 7 ++++--- include/linux/filter.h | 1 + kernel/bpf/core.c | 12 ++++++++++++ kernel/bpf/pads.c | 34 +++++++++++++++++++++++++++++++++- kernel/bpf/syscall.c | 7 ++++++- kernel/bpf/verifier.c | 8 ++++++++ 7 files changed, 77 insertions(+), 5 deletions(-)
include/linux/bpf.h +13 -0
@@ -2297,6 +2297,18 @@ struct btf_member;* reason, if this callback is not defined, the check is skipped as * the struct_ops map will have final verification performed in * @reg. +* @cancelled: A callback that is invoked when an invocation of a program of +* this struct_ops, an op or an async callback of one, was unwound +* up to the kernel, before the invocation returns. No path of the +* program chose what it returns then: it is 0, NULL for a pointer, +* or what bpf_throw() was passed. A struct_ops that cannot take +* this for the result of an op reacts here. The callback runs in +* the context of the program, which for an op is that of its caller +* with the locks that it holds, and it can be reentered. It must +* not sleep and must not take a lock that is held around a call of +* an op: it notes the event and defers the rest. A program of the +* struct_ops holds a reference on @owner for as long as it lives, +* so the callback is there whenever one runs. * @cfi_stubs: Pointer to a structure of stub functions for CFI. These stubs * provide the correct Control Flow Integrity hashes for the * trampolines generated by BPF struct_ops.
@@ -2333,6 +2345,7 @@ struct bpf_struct_ops {void (*unreg)(void *kdata,struct bpf_link *link);int (*update)(void *kdata,void *old_kdata,struct bpf_link *link);int (*validate)(void *kdata); +void (*cancelled)(const struct bpf_prog *prog);void *cfi_stubs;struct module *owner;const char *name;
include/linux/bpf_verifier.h +4 -3
@@ -561,14 +561,15 @@ enum bpf_stuck_by {/* * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument, a test and -* the call. The 5 are two insns that save the value, two that load the value, and 'r2 = 0'. -* emit_pad() adds the insn that leaves the frame, or the call of the exception callback. +* the call. The 8 are two insns that save the value, three that tell the struct_ops, two that +* load the value, and 'r2 = 0'. emit_pad() adds the insn that leaves the frame, or the call of +* the exception callback. */ #define BPF_PAD_MAX_SECTIONS 8#define BPF_PAD_MAX_ENTS 8#define BPF_PAD_MAX_ARGS 2#define BPF_PAD_MAX_INSNS (BPF_PAD_MAX_ENTS * (2 * BPF_PAD_MAX_ARGS + 2) + \ - BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 5) + BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 8)#define BPF_PAD_MAX_CANDS 6/* The most save words of a function, see 'save_off' of struct bpf_subprog_info */ #define BPF_PAD_MAX_SAVES BPF_PAD_MAX_ENTS
include/linux/filter.h +1 -0
@@ -1505,6 +1505,7 @@ 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);bool bpf_helper_changes_pkt_data (enum bpf_func_id func_id);static inline bool bpf_dump_raw_ok (const struct cred *cred)
kernel/bpf/core.c +12 -0
@@ -4138,6 +4138,18 @@ u64 bpf_prog_report_recursion(void)return 0 ; } +/* +* Called by the landing pad that ends an invocation, when the frames have released what they held. +* What the value of an unwound op means is up to the struct_ops. This is the context of the +* program, with the locks of the caller of the op: see what ->cancelled() may do. +* Only programs of a struct_ops that has the callback call it, see bpf_pad_insns(). +*/ +u64 bpf_prog_report_cancelled (struct bpf_prog_aux *aux) +{ + aux->st_ops->cancelled (aux->prog); +return 0 ; +} +u64 bpf_check_timed_may_goto (struct bpf_timed_may_goto *p) {u64 time =ktime_get_mono_fast_ns ();
kernel/bpf/pads.c +33 -1
@@ -2593,6 +2593,31 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_planreturn n; } +/* +* The kernel called @subprog, and its pads end the invocation with exit: the main program, whose +* unwind_exit is exit to the JITs as well, see bpf_prog_can_unwind(), and an async callback that +* cannot leave unwound, see unwind_exit_insn(). They tell a struct_ops that wants to know, see +* bpf_prog_report_cancelled(). +* An async callback that can leave unwound has callers in the program, or is expected to. It has +* one pad for all its frames, which ends in cancel_exit, or in unwind_exit for what the program +* unwinds, and cannot tell who called. Such a pad tells nobody. +* A pad that ends the invocation tells whatever its site is: also the pad of a call without +* unwind_goto to which unwind_exit of a callee came back, which is an unwind of the program's own. +* That tells about more than the kernel has stopped, and it misses nothing that the kernel has: such +* a pad of the main program calls the exception callback, which the kernel can unwind in turn, and +* the pads of that callback tell nobody. +* The exception callback is called by a pad of the main program, which has told already. +*/ +static bool pad_reports (const struct bpf_verifier_env *env,int subprog) +{ +const struct bpf_struct_ops *st_ops = env->prog->aux->st_ops; +const struct bpf_subprog_info *sub = &env->subprog_info[subprog]; + +if (!st_ops || !st_ops->cancelled || sub->is_exception_cb) +return false; +return !subprog || (sub->is_async_cb && !sub->bail_unwinds); +} +/* * Does the pad of a site of @kind in @subprog pass R2 on with R0, see bpf_pad_passes_on()? Only in * a subprog that returns two registers. Its other pads leave with 0 in R2.
@@ -2608,7 +2633,8 @@ static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_ {return (bpf_site_has_value (env, subprog, plan->kind) ||bpf_pad_passes_on (env, subprog, plan->kind)) && - (plan->nr_ents || plan->sections[BPF_PAD_RCU ] || plan->sections[BPF_PAD_PREEMPT ]); + (plan->nr_ents || plan->sections[BPF_PAD_RCU ] || plan->sections[BPF_PAD_PREEMPT ] || +pad_reports (env, subprog)); }
@@ -2620,6 +2646,7 @@ static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_int bpf_pad_insns (struct bpf_verifier_env *env,const struct bpf_pad_plan *plan,int subprog,struct bpf_insn *buf,struct bpf_insn_aux_data *aux) { +struct bpf_insn ld_aux[2 ] = {BPF_LD_IMM64 (BPF_REG_1 , (long )env->prog->aux) };int value_off = env->subprog_info[subprog].value_off;int src =bpf_site_value_reg (plan->kind), dst =BPF_REG_0 ;bool passes_on =bpf_pad_passes_on (env, subprog, plan->kind);
@@ -2645,6 +2672,11 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,for (class =0 ; class <BPF_PAD_NR_SECTIONS ; class++)for (i =0 ; i <pad_enters (plan, class); i++) buf[n++] =enter_call (class); +if (pad_reports (env, subprog)) { + buf[n++] = ld_aux[0 ]; + buf[n++] = ld_aux[1 ]; + buf[n++] =BPF_EMIT_KERNEL_CALL (bpf_prog_report_cancelled); + }if (bpf_site_is_cancelled (plan->kind) && env->has_throw) {/* the value of the first cancellation, which the entry of the cleanup pad stored */ buf[n++] =BPF_LDX_MEM (BPF_DW , dst,BPF_REG_FP , value_off);
kernel/bpf/syscall.c +6 -1
@@ -2463,6 +2463,9 @@ static void __bpf_prog_put_rcu(struct rcu_head *rcu) { struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu); +/* A prog that ran until now may have called ->cancelled(), which is code of the module */ +if (aux->prog->type ==BPF_PROG_TYPE_STRUCT_OPS ) +module_put (aux->mod);btf_put (aux->btf);kvfree (aux->jited_linfo);kvfree (aux->linfo);
@@ -2490,7 +2493,9 @@ static void __bpf_prog_put_rcu_tasks(struct rcu_head *rcu)static void __bpf_prog_put_noref (struct bpf_prog *prog,bool deferred) { -module_put (prog->aux->mod); +/* A struct_ops prog keeps its module over the grace period, see __bpf_prog_put_rcu() */ +if (prog->type !=BPF_PROG_TYPE_STRUCT_OPS ) +module_put (prog->aux->mod);bpf_free_kfunc_tab (prog->aux->kfunc_tab);kfree (prog->aux->ctx_arg_info);if (prog->aux->attach_btf)
kernel/bpf/verifier.c +8 -0
@@ -25643,6 +25643,14 @@ static int check_struct_ops_btf_id(struct bpf_verifier_env *env) prog->aux->st_ops = st_ops; prog->aux->attach_st_ops_member_off = member_off; +/* +* The program holds the module of its struct_ops for as long as it lives: an async callback +* of the program can run when no struct_ops map holds the module any more. +*/ +if (env->attach_btf_mod) { +__module_get (env->attach_btf_mod); + prog->aux->mod = env->attach_btf_mod; + } prog->aux->attach_func_proto = func_proto; prog->aux->attach_func_name = mname;
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 69/73] bpf: Tell struct_ops when a program was cancelled
TL;DR: - The ->cancelled() doc may be inaccurate: with an exception callback, program code chooses the returned value after the call, which could mislead struct_ops authors - Commit message example…
Quoted 1 line
bpf: Tell
struct_opswhen a program was cancelled
TL;DR:
- The ->cancelled() doc may be inaccurate: with an exception callback, program code chooses the returned value after the call, which could mislead struct_ops authors
- Commit message example names st_ops->unwound(), not ->cancelled() (nit)
Quoted 7 lines
bpf: Tell
struct_opswhen a program was cancelled[ ... ]
Add a callback, ->cancelled(), to structbpf_struct_ops. In a program of astruct_opsthat sets it, the landing pad that returns to the kernel calls it after all frames have released what they held:
Quoted 6 lines
pad: r1 = r6
callbpf_task_release
+ r1 =prog->aux
+ callbpf_prog_report_cancelled<- callsst_ops->unwound(prog)
r0 = 0
exit
This isn't a bug, but the example says bpf_prog_report_cancelled() "calls st_ops->unwound(prog)". The patch adds no ->unwound() member, and bpf_prog_report_cancelled() calls aux->st_ops->cancelled(aux->prog). Should this read st_ops->cancelled(prog), to match the "->cancelled()" name used elsewhere in the message?
Quoted 3 lines
include/linux/bpf.h +0
-0
[ ... ]
include/linux/bpf.h struct btf_member; · line 2301
Quoted 6 lines
include/linux/bpf.h +5
-0@@ -2297,6 +2297,18 @@ struct btf_member; +* @cancelled: A callback that is invoked when an invocation of a program of +* this struct_ops, an op or an async callback of one, was unwound +* up to the kernel, before the invocation returns. No path of the +* program chose what it returns then: it is 0, NULL for a pointer, +* or what bpf_throw() was passed. A struct_ops that cannot take
Is this description of the return value accurate when the program has an exception callback?
In the main program, bpf_pad_insns() emits the call of bpf_prog_report_cancelled(), and emit_pad() then appends the call of the exception callback:
n += bpf_pad_insns(env, plan, s, buf + n, aux + n);
if (!s && cb) {
...
buf[n++] = BPF_CALL_REL(0); /* call exception_cb */The op then returns the exception callback's R0. For a struct_ops member returning an integer, check_return_code() accepts any value from it, and the comment of bpf_cancelled_retval() says "If the program has an exception callback, the callback gets the value and chooses what the program returns."
So ->cancelled() can be called for an invocation whose result is chosen by program code after the callback ran. The same applies to the BPF_SITE_CALL pad of the main program, which pad_reports() also reports: with bpf_throw() in the program, the pad returns the R0 that the callee chose.
A struct_ops that relies on this text to treat the result of the op as meaningless could be wrong. Could the doc mention that the exception callback, which runs after ->cancelled(), chooses the returned value? The rewrite of this text later in the series (9fda643a105f, "bpf: Let a struct_ops say what a cancelled program returns") still does not cover the exception callback case.
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 70/73 bpf: Tell struct_ops when cancel_exit returns to the kernel
In reply to Kumar Kartikeya DwivediCurrently ->cancelled() of a struct_ops is called only by landing pads that end with exit. An async callback that may have a caller in the program has landing pads that end with cancel_exit. When the kernel called such a callback and cancels it, nobody tells the struct_ops:
static int tick(void *map, int *key, struct elem *e)
{
while (!ready) <- the time of the loop is up
;
return 0;
} bpf_timer_set_callback(&e->timer, tick); the kernel calls tick()
tick(&timers, &key, e); and so does the program
The landing pad of tick() ends with cancel_exit for both callers. When the program called tick(), cancel_exit returns to the cancel_goto after the call, and a landing pad of the main program tells the struct_ops. When the timer called tick(), cancel_exit finds no cancel_goto and returns to the kernel like exit.
The verifier also assumes a caller in the program for an async callback that calls itself, that has an unwind_exit, or whose address is not loaded directly before the call of the helper that stores it.
cancel_exit looks up its return address at run time. When it finds no cancel_goto and no unwind label of a helper there, and the address is in no BPF program, the kernel called the frame. Call ->cancelled() at that point, through the new bpf_prog_cancelled_to_kernel(). Every cancellation that ends a program now calls ->cancelled() exactly once.
The JITed code of cancel_exit calls the lookup from the frame that it leaves, so the lookup returns into the program, and bpf_prog_ksym_find() finds the program from that address. A kretprobe or an fexit trampoline would replace the address, so the lookup functions are notrace and on the kprobe blacklist. That now includes the two that the arm64 JIT calls.
Two cases need care:
- An unwind_exit of the program that returns to the kernel does not call ->cancelled(). The program chose this way out, as it chooses exit.
- Every helper passes a cancellation on from its unwind label. Kernel code that calls a program with bpf_call_cb() and ends the cancellation there has to call ->cancelled() itself.
--- arch/arm64/net/bpf_jit_comp.c | 45 +++++++++++++++++++++++------------ arch/x86/net/bpf_jit_comp.c | 30 +++++++++++++++-------- include/linux/bpf_unwind.h | 4 +++- include/linux/filter.h | 1 + kernel/bpf/core.c | 37 ++++++++++++++++++++++++---- kernel/bpf/pads.c | 21 +++++++--------- 6 files changed, 95 insertions(+), 43 deletions(-)
arch/arm64/net/bpf_jit_comp.c +30 -15
@@ -1779,16 +1779,18 @@ static int build_landings(struct jit_ctx *ctx) }/* -* Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with -* cancel_exit, @key CANCEL_EXKEY, returns to. -* The verifier made sure that unwind_goto follows a call in a prog, and -* cancel_goto where the callee has cancel_exit. When the kernel called an async -* callback, it's exit. A helper that calls a callback has a pad when it wants -* one, see bpf_call_cb(). +* Return where a frame with the return address @ret_addr returns to when it +* leaves with unwind_exit (@key is UNWIND_EXKEY) or cancel_exit (CANCEL_EXKEY). +* +* @ip is the return address of the lookup. It is in the frame itself when an +* insn of a prog asks, and in a helper for bpf_unwind_leave(). A kretprobe, the +* function graph tracer and an fexit trampoline replace it, so the callers are +* notrace and on the kprobe blacklist. */ -static u64 unwind_target (u64 ret_addr,int key) +static u64 unwind_target (u64 ret_addr,int key,unsigned long ip) {const struct exception_table_entry *e; +bool lost; e =search_bpf_extables (ret_addr - key);if (e)
@@ -1815,19 +1817,27 @@ static u64 unwind_target(u64 ret_addr, int key)* for that at load time, see check_cb_pad(). */ scoped_guard (rcu) - WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1)); + lost =bpf_prog_ksym_find (ret_addr -1 ); +/* +* A cancelled frame that returns to the kernel ends the invocation, and +* only here is that known, so tell the struct_ops. unwind_exit is the +* program's own way out, like exit, and is not reported. See +* bpf_prog_cancelled_to_kernel(). +*/ +if (!WARN_ON_ONCE (lost) && key ==CANCEL_EXKEY ) +bpf_prog_cancelled_to_kernel (ip);return ret_addr; } u64 notrace bpf_unwind_target(u64 ret_addr) { -return unwind_target (ret_addr,UNWIND_EXKEY ); +return unwind_target (ret_addr,UNWIND_EXKEY , _RET_IP_); }NOKPROBE_SYMBOL (bpf_unwind_target); u64 notrace bpf_cancel_target(u64 ret_addr) { -return unwind_target (ret_addr,CANCEL_EXKEY ); +return unwind_target (ret_addr,CANCEL_EXKEY , _RET_IP_); }NOKPROBE_SYMBOL (bpf_cancel_target);
@@ -1843,21 +1853,26 @@ u64 bpf_fault_unwind_target(u64 end)return e ? end + e->fixup : end; } -/* The offset that the epilogue adds to LR once it is authenticated */ -static long bpf_unwind_fixup (u64 lr) +/* +* unwind_exit calls this with the signed LR of its frame. Return the offset +* that the epilogue adds to LR after it has authenticated it. +*/ +static notrace long bpf_unwind_fixup (u64 lr) {u64 ret_addr =ptrauth_strip_kernel_insn_pac (lr); -return bpf_unwind_target (ret_addr) - ret_addr; +return unwind_target (ret_addr,UNWIND_EXKEY , _RET_IP_) - ret_addr; } +NOKPROBE_SYMBOL (bpf_unwind_fixup);/* The same for cancel_exit */ -static long bpf_cancel_fixup (u64 lr) +static notrace long bpf_cancel_fixup (u64 lr) {u64 ret_addr =ptrauth_strip_kernel_insn_pac (lr); -return bpf_cancel_target (ret_addr) - ret_addr; +return unwind_target (ret_addr,CANCEL_EXKEY , _RET_IP_) - ret_addr; } +NOKPROBE_SYMBOL (bpf_cancel_fixup);/* * unwind_exit, cancel_exit: return to the pad. LR in the frame record is
arch/x86/net/bpf_jit_comp.c +20 -10
@@ -2412,16 +2412,18 @@ static int add_unwind_exentry(struct bpf_prog *prog, u8 *image, u8 *rw_image, in }/* -* Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with -* cancel_exit, @key CANCEL_EXKEY, returns to. -* The verifier made sure that unwind_goto follows a call in a prog, and -* cancel_goto where the callee has cancel_exit. When the kernel called an async -* callback, it's exit. A helper that calls a callback has a pad when it wants -* one, see bpf_call_cb(). +* Return where a frame with the return address @ret_addr returns to when it +* leaves with unwind_exit (@key is UNWIND_EXKEY) or cancel_exit (CANCEL_EXKEY). +* +* @ip is the return address of the lookup. It is in the frame itself when an +* insn of a prog asks, and in a helper for bpf_unwind_leave(). A kretprobe, the +* function graph tracer and an fexit trampoline replace it, so the callers are +* notrace and on the kprobe blacklist. */ -static u64 unwind_target (u64 ret_addr,int key) +static u64 unwind_target (u64 ret_addr,int key,unsigned long ip) {const struct exception_table_entry *e; +bool lost; e =search_bpf_extables (ret_addr - key);if (e)
@@ -2448,19 +2450,27 @@ static u64 unwind_target(u64 ret_addr, int key)* for that at load time, see check_cb_pad(). */ scoped_guard (rcu) - WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1)); + lost =bpf_prog_ksym_find (ret_addr -1 ); +/* +* A cancelled frame that returns to the kernel ends the invocation, and +* only here is that known, so tell the struct_ops. unwind_exit is the +* program's own way out, like exit, and is not reported. See +* bpf_prog_cancelled_to_kernel(). +*/ +if (!WARN_ON_ONCE (lost) && key ==CANCEL_EXKEY ) +bpf_prog_cancelled_to_kernel (ip);return ret_addr; } u64 notrace bpf_unwind_target(u64 ret_addr) { -return unwind_target (ret_addr,UNWIND_EXKEY ); +return unwind_target (ret_addr,UNWIND_EXKEY , _RET_IP_); }NOKPROBE_SYMBOL (bpf_unwind_target); u64 notrace bpf_cancel_target(u64 ret_addr) { -return unwind_target (ret_addr,CANCEL_EXKEY ); +return unwind_target (ret_addr,CANCEL_EXKEY , _RET_IP_); }NOKPROBE_SYMBOL (bpf_cancel_target);
include/linux/bpf_unwind.h +3 -1
@@ -34,7 +34,9 @@* which follows bpf_call_cb(), must not fault or have a fixup of its own. * * Without asm goto outputs, and on other architectures, bpf_call_cb() is a plain call and -* BPF_HAS_CB_PADS is 0: the verifier rejects a callback that can unwind. +* BPF_HAS_CB_PADS is 0: the verifier rejects a callback that can unwind. Kernel code that ends a +* cancellation at its label, without bpf_unwind_leave(), has to tell the struct_ops itself, see +* bpf_prog_cancelled_to_kernel(). */ #include <linux/bug.h>
include/linux/filter.h +1 -0
@@ -1506,6 +1506,7 @@ void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_gvoid 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);bool bpf_helper_changes_pkt_data (enum bpf_func_id func_id);static inline bool bpf_dump_raw_ok (const struct cred *cred)
kernel/bpf/core.c +33 -4
@@ -4139,10 +4139,10 @@ u64 bpf_prog_report_recursion(void) }/* -* Called by the landing pad that ends an invocation, when the frames have released what they held. -* What the value of an unwound op means is up to the struct_ops. This is the context of the -* program, with the locks of the caller of the op: see what ->cancelled() may do. -* Only programs of a struct_ops that has the callback call it, see bpf_pad_insns(). +* Tell the struct_ops that its program was cancelled. A landing pad that ends the program with +* exit calls this after all frames have released what they held. Only a program of a struct_ops +* that has ->cancelled() gets the call, see pad_reports() in pads.c. It runs in the context of the +* program, with the locks of the kernel code that called the program. */ u64 bpf_prog_report_cancelled (struct bpf_prog_aux *aux) {
@@ -4150,6 +4150,35 @@ u64 bpf_prog_report_cancelled(struct bpf_prog_aux *aux)return 0 ; } +/* +* Tell the struct_ops that its program was cancelled, where cancel_exit returns to the kernel. +* bpf_cancel_target() of a JIT calls this when it finds no cancel_goto and no unwind label of a +* helper at the return address of the frame, and that address is in no program. The frame is an +* async callback that may also have callers in the program. Its landing pads end in cancel_exit +* for every caller, so they cannot make the call, see pad_reports() in pads.c. Together with +* bpf_prog_report_cancelled(), a cancellation that ends a program calls ->cancelled() exactly once. +* +* @ip is in the code that asked. If that is a helper, in bpf_unwind_leave(), nothing is done. An +* unwind_exit of the program that returns to the kernel does not get here: the program chose that +* way out, as it chooses exit. Kernel code that calls a program with bpf_call_cb() and does not +* pass a cancellation on has to call ->cancelled() itself. +*/ +void bpf_prog_cancelled_to_kernel (unsigned long ip) +{ +const struct bpf_struct_ops *st_ops; +struct bpf_prog *prog; + +scoped_guard (rcu) + prog =bpf_prog_ksym_find (ip); +if (!prog) +return ; +/* The frame keeps the program alive. The struct_ops is that of the main program. */ + prog = prog->aux->main_prog_aux->prog; + st_ops = prog->aux->st_ops; +if (st_ops && st_ops->cancelled) + st_ops->cancelled (prog); +} +u64 bpf_check_timed_may_goto (struct bpf_timed_may_goto *p) {u64 time =ktime_get_mono_fast_ns ();
kernel/bpf/pads.c +8 -13
@@ -2594,19 +2594,14 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan }/* -* The kernel called @subprog, and its pads end the invocation with exit: the main program, whose -* unwind_exit is exit to the JITs as well, see bpf_prog_can_unwind(), and an async callback that -* cannot leave unwound, see unwind_exit_insn(). They tell a struct_ops that wants to know, see -* bpf_prog_report_cancelled(). -* An async callback that can leave unwound has callers in the program, or is expected to. It has -* one pad for all its frames, which ends in cancel_exit, or in unwind_exit for what the program -* unwinds, and cannot tell who called. Such a pad tells nobody. -* A pad that ends the invocation tells whatever its site is: also the pad of a call without -* unwind_goto to which unwind_exit of a callee came back, which is an unwind of the program's own. -* That tells about more than the kernel has stopped, and it misses nothing that the kernel has: such -* a pad of the main program calls the exception callback, which the kernel can unwind in turn, and -* the pads of that callback tell nobody. -* The exception callback is called by a pad of the main program, which has told already. +* Does a pad of @subprog tell the struct_ops that the program was cancelled, see +* bpf_prog_report_cancelled()? Only a pad that ends the invocation with exit does, at every kind of +* site: in the main program, and in an async callback that cannot leave with cancel_exit. +* +* An async callback that may have a caller in the program has pads that end in cancel_exit and +* cannot tell who called. There cancel_exit itself reports when it returns to the kernel, see +* bpf_prog_cancelled_to_kernel(). The exception callback does not report: the pad of the main +* program that calls it has reported already. */ static bool pad_reports (const struct bpf_verifier_env *env,int subprog) {
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 71/73 bpf: Let a struct_ops say what a cancelled program returns
In reply to Kumar Kartikeya DwivediCurrently a cancelled struct_ops program returns 0, or NULL for a pointer. The verifier chooses the value by the program type, and all struct_ops programs have one type. What 0 means is up to the member. For Qdisc_ops::enqueue() it is NET_XMIT_SUCCESS, so the sender is told that the packet is on its way. A cancelled enqueue() did not queue the packet, and its landing pad frees the packet if the program still holds it.
Add a callback, ->cancelled_retval(), to struct bpf_struct_ops. The verifier calls it at load time with the program, and the callback returns the value for the member that the program is attached to, or 0. The value becomes a constant in the program, so it must depend on nothing but the member.
The verifier does not run check_return_code() on the value. So it asks only about a member that returns an integer, for which every value is accepted. A member that returns nothing or a pointer keeps 0, and so does a struct_ops without the callback.
Implement the callback for bpf_qdisc:
enqueue() NET_XMIT_DROP
init() -ECANCELED. With 0, qdisc_create() would attach a qdisc
whose init() was cancelled halfway. With the error it calls destroy() and frees the qdisc, as for any init() that fails.
The other struct_ops in the tree keep 0 for every member:
- For hid_bpf, 0 lets hid-core handle the event or the request as it does without a program.
- bpf_tcp_ops, smc_hs_ctrl and io_uring have no member that returns an errno.
- For sched_ext a cancelled program is a failure of the scheduler as a whole, which ->cancelled() can report.
- binfmt_misc_ops::load() returns an errno, and 0 lets the exec continue. -ECANCELED would suit it, but that choice belongs to its owners.
- tcp_congestion_ops needs values of its own and is not changed here.
--- include/linux/bpf.h | 34 ++++++++++++++++++++++------------ kernel/bpf/verifier.c | 22 +++++++++++++++++++++- net/sched/bpf_qdisc.c | 21 +++++++++++++++++++++ 3 files changed, 64 insertions(+), 13 deletions(-)
include/linux/bpf.h +22 -12
@@ -2297,18 +2297,27 @@ struct btf_member;* reason, if this callback is not defined, the check is skipped as * the struct_ops map will have final verification performed in * @reg. -* @cancelled: A callback that is invoked when an invocation of a program of -* this struct_ops, an op or an async callback of one, was unwound -* up to the kernel, before the invocation returns. No path of the -* program chose what it returns then: it is 0, NULL for a pointer, -* or what bpf_throw() was passed. A struct_ops that cannot take -* this for the result of an op reacts here. The callback runs in -* the context of the program, which for an op is that of its caller -* with the locks that it holds, and it can be reentered. It must -* not sleep and must not take a lock that is held around a call of -* an op: it notes the event and defers the rest. A program of the -* struct_ops holds a reference on @owner for as long as it lives, -* so the callback is there whenever one runs. +* @cancelled: A callback that is invoked when the kernel has cancelled a +* program of this struct_ops, or an async callback of one: it +* ended the program early, at a loop that ran out of time, a +* recursion that is too deep, a fault in arena or bpf_throw(). The +* program has released what it held but has not finished its work. +* It is about to return the value of @cancelled_retval, or the +* argument of bpf_throw(). The callback is passed the main program. +* It runs in the context of the code that called the program, with +* the locks that this code holds, and it can be reentered. It must +* not sleep or take a lock that is held around a call of a +* program. A program holds a reference on @owner, so the callback +* can run when no struct_ops map is left. +* @cancelled_retval: A callback that the verifier invokes when it loads a +* program. It returns the value that the program returns +* when the kernel cancels it, for a member where 0 would be +* wrong, and 0 otherwise. The member is +* prog->aux->attach_st_ops_member_off. The value becomes a +* constant in the program, so it must depend on nothing but +* the member. The callback is invoked only for a member that +* returns an integer. If it is not defined, a cancelled +* program returns 0. * @cfi_stubs: Pointer to a structure of stub functions for CFI. These stubs * provide the correct Control Flow Integrity hashes for the * trampolines generated by BPF struct_ops.
@@ -2346,6 +2355,7 @@ struct bpf_struct_ops {int (*update)(void *kdata,void *old_kdata,struct bpf_link *link);int (*validate)(void *kdata);void (*cancelled)(const struct bpf_prog *prog); +int (*cancelled_retval)(const struct bpf_prog *prog);void *cfi_stubs;struct module *owner;const char *name;
kernel/bpf/verifier.c +21 -1
@@ -22173,6 +22173,23 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedgereturn enter_callback (env, false,NULL ); } +/* +* The value that a cancelled struct_ops program returns. The struct_ops chooses it for the member +* that @prog is attached to, see bpf_struct_ops.cancelled_retval. It is asked only about a member +* that returns an integer, for which check_return_code() accepts every value. A member that +* returns void or a pointer keeps 0. +*/ +static int struct_ops_cancelled_retval (const struct bpf_prog *prog) +{ +const struct bpf_struct_ops *st_ops = prog->aux->st_ops; +const struct btf_type *proto = prog->aux->attach_func_proto; + +if (!st_ops->cancelled_retval || !proto->type || +btf_type_resolve_ptr (prog->aux->attach_btf, proto->type,NULL )) +return 0 ; +return st_ops->cancelled_retval (prog); +} +/* * The value that a cancelled program returns to the kernel. No code of the program chose it, so it * is the value that refuses, drops or changes nothing. That is 0, except for:
@@ -22180,7 +22197,8 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge* tc TC_ACT_SHOT, 0 is TC_ACT_OK * lwt, flow dissector BPF_DROP, 0 is BPF_OK * syscall -ECANCELED, 0 tells user space that all was done -* lsm, the hook returns an errno -EPERM, 0 lets the operation go on +* struct_ops what the struct_ops chooses for the member, or 0 +* lsm, the hook returns an errno -EPERM, 0 allows the operation * the range is [1, 1] 1, hooks that cannot refuse * * Each is a value that check_return_code() accepts. It has to be, because no state is checked with
@@ -22220,6 +22238,8 @@ int bpf_cancelled_retval(struct bpf_verifier_env *env)default :break ; } +if (prog->type ==BPF_PROG_TYPE_STRUCT_OPS ) +return struct_ops_cancelled_retval (prog);if (get_func_retval_range (prog, &range) && range.minval <0 )return -EPERM ;if (!program_returns_void (env) &&return_retval_range (env, &range) && range.minval >0 )
net/sched/bpf_qdisc.c +21 -0
@@ -453,6 +453,26 @@ static int bpf_qdisc_validate(void *kdata)return 0 ; } +/* What a program returns when the kernel cancels it, which ends the program +* early, for example at a loop that runs out of time: +* +* ->enqueue() NET_XMIT_DROP. The program may not have queued the packet, and +* the kernel has freed the packet if the program still held it. +* ->init() -ECANCELED, so that qdisc_create() calls ->destroy() and frees +* the qdisc, as for any ->init() that fails. +* ->dequeue() returns NULL. ->reset() and ->destroy() return nothing. +*/ +static int bpf_qdisc_cancelled_retval (const struct bpf_prog *prog) +{ +u32 moff = prog->aux->attach_st_ops_member_off; + +if (moff == offsetof(struct Qdisc_ops , enqueue)) +return NET_XMIT_DROP ; +if (moff == offsetof(struct Qdisc_ops , init)) +return -ECANCELED ; +return 0 ; +} +static int Qdisc_ops__enqueue (struct sk_buff *skb__ref,struct Qdisc *sch,struct sk_buff **to_free) {
@@ -492,6 +512,7 @@ static struct bpf_struct_ops bpf_Qdisc_ops = { .unreg = bpf_qdisc_unreg, .validate = bpf_qdisc_validate, .check_member = bpf_qdisc_check_member, + .cancelled_retval = bpf_qdisc_cancelled_retval, .init_member = bpf_qdisc_init_member, .init = bpf_qdisc_init, .name = "Qdisc_ops",
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns
TL;DR: Commit message claim that a cancelled hid_bpf program returning 0 behaves as without a program looks inaccurate: hid-core may get a half-rewritten descriptor or event. Fix the changelog, or…
Quoted 1 line
bpf: Let a
struct_opssay what a cancelled program returns
TL;DR: Commit message claim that a cancelled hid_bpf program returning 0 behaves as without a program looks inaccurate: hid-core may get a half-rewritten descriptor or event. Fix the changelog, or return a negative errno for hid_bpf?
Quoted 20 lines
bpf: Let a
struct_opssay what a cancelled program returnsCurrently a cancelled
struct_opsprogram returns 0, or NULL for a pointer. The verifier chooses the value by the program type, and allstruct_opsprograms have one type. What 0 means is up to the member. ForQdisc_ops::enqueue()it isNET_XMIT_SUCCESS, so the sender is told that the packet is on its way. A cancelledenqueue()did not queue the packet, and its landing pad frees the packet if the program still holds it. Add a callback, ->cancelled_retval(), to structbpf_struct_ops. The verifier calls it at load time with the program, and the callback returns the value for the member that the program is attached to, or 0. The value becomes a constant in the program, so it must depend on nothing but the member.
The verifier does not runcheck_return_code()on the value. So it asks only about a member that returns an integer, for which every value is accepted. A member that returns nothing or a pointer keeps 0, and so does astruct_opswithout the callback.
Implement the callback forbpf_qdisc:
enqueue()NET_XMIT_DROP
init()-ECANCELED. With 0,qdisc_create()would attach a qdisc
Quoted 8 lines
whose
init()was cancelled halfway. With the error it callsdestroy()and frees the qdisc, as for anyinit()that fails.
The otherstruct_opsin the tree keep 0 for every member:
- Forhid_bpf, 0 lets hid-core handle the event or the request as it does without a program.
-bpf_tcp_ops,smc_hs_ctrlandio_uringhave no member that returns an errno.
[ ... ]
The commit message says that for hid_bpf, 0 lets hid-core handle the event or the request as it does without a program. Is that accurate for hid_bpf_ops::hid_rdesc_fixup()?
call_hid_bpf_rdesc_fixup() in drivers/hid/bpf/hid_bpf_dispatch.c copies the descriptor into ctx_kern.data, which the program rewrites in place, and then does:
ret = hdev->bpf.rdesc_ops->hid_rdesc_fixup(&ctx_kern.ctx);
if (ret < 0)
goto ignore_bpf;
...
return krealloc(ctx_kern.data, *size, GFP_KERNEL);
ignore_bpf:
kfree(ctx_kern.data);
return rdesc;If a cancelled rdesc_fixup returns 0, for example from a bpf_for() loop that ran out of time halfway through rewriting the buffer, hid-core receives the half-rewritten copy as the report descriptor.
A negative value such as -ECANCELED would take the ignore_bpf path and keep the original descriptor, which is what happens without a program. This is the same kind of case that this patch fixes for Qdisc_ops::init().
hid_device_event() looks similar: with 0, hid-core processes the program's partly modified copy of the event (ctx_kern.data) rather than the original data.
This patch does not change hid behaviour, and no later commit in the series adds a hid_bpf callback. Could the changelog state this correctly? Alternatively, should hid_bpf return a negative errno from a cancelled hid_rdesc_fixup()?
---
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/46579809730
Kumar Kartikeya Dwivedi
maintainerPATCH 72/73 bpf: Give cancelled tcp_congestion_ops programs values that TCP can take
In reply to Kumar Kartikeya DwivediCurrently a cancelled program of tcp_congestion_ops returns 0, and TCP cannot take 0 from every member. A congestion control that is reno, built from the kfuncs of the kernel, shows it on a connection over loopback when the kernel cancels one of its programs:
- ->undo_cwnd() returns the window for a loss that TCP takes back. The window becomes 0, and tcp_snd_cwnd_set() warns.
- ->ssthresh() returns the slow start threshold. When the recovery is over, TCP sets the window to it, and the same warning fires. Then ->cong_avoid() of the program calls tcp_reno_cong_avoid(), and tcp_cong_avoid_ai() divides by the window:
Oops: divide error: 0000 [#1] SMP
RIP: 0010:tcp_cong_avoid_ai+0x50/0x90- ->sndbuf_expand() returns the factor by which TCP sizes the send buffer. With 0 the buffer keeps its first size, 16384 bytes where the same connection with reno has 2626560.
Implement ->cancelled_retval() for tcp_congestion_ops. The value is a constant in the program, and the value that fits is in the socket. No constant is right, so give each member the least value that TCP can work with:
->ssthresh() 2 the least that tcp_reno_ssthresh() returns ->undo_cwnd() 1 the window that TCP itself sets after a timeout ->tso_segs() 1 what tcp_tso_segs() makes of 0 today ->sndbuf_expand() 2 the factor that TCP uses when the member is not
set
The price is a slow connection. After a cancelled ->undo_cwnd() it continues with a window of one segment, and after a cancelled ->ssthresh() the recovery ends with a window of two. The other programs of the congestion control grow the window again if they still run.
The values do not apply to bpf_throw(), whose cookie is what the program returns. A program that returns 0 from these members that way, or with its own return, has a bug of its own.
The other members return nothing. No program can implement ->get_info().
--- net/ipv4/bpf_tcp_ca.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)
net/ipv4/bpf_tcp_ca.c +31 -0
@@ -256,6 +256,36 @@ static int bpf_tcp_ca_validate(void *kdata)return tcp_validate_congestion_control (kdata); } +/* What a program returns when the kernel cancels it, which ends the program +* early, for example at a loop that runs out of time. The value is a constant, +* and TCP cannot take 0 from every program, so each one returns the least +* value that TCP can work with: +* +* ->ssthresh() 2, the least that tcp_reno_ssthresh() returns. With 0 +* the window is 0 when a recovery is over, and +* tcp_cong_avoid_ai() divides by the window. +* ->undo_cwnd() 1, the window that TCP itself sets after a timeout. +* ->tso_segs() 1, which is what tcp_tso_segs() makes of 0. +* ->sndbuf_expand() 2, the factor that tcp_sndbuf_expand() uses without +* this callback. With 0 the send buffer does not grow. +* +* The other programs return nothing, and no program can be ->get_info(). +*/ +static int bpf_tcp_ca_cancelled_retval (const struct bpf_prog *prog) +{ +switch (prog->aux->attach_st_ops_member_off) { +case offsetof(struct tcp_congestion_ops , ssthresh): +return 2 ; +case offsetof(struct tcp_congestion_ops , undo_cwnd): +return 1 ; +case offsetof(struct tcp_congestion_ops , tso_segs): +return 1 ; +case offsetof(struct tcp_congestion_ops , sndbuf_expand): +return 2 ; + } +return 0 ; +} +static u32 bpf_tcp_ca_ssthresh (struct sock *sk) {return 0 ;
@@ -338,6 +368,7 @@ static struct bpf_struct_ops bpf_tcp_congestion_ops = { .init_member = bpf_tcp_ca_init_member, .init = bpf_tcp_ca_init, .validate = bpf_tcp_ca_validate, + .cancelled_retval = bpf_tcp_ca_cancelled_retval, .name = "tcp_congestion_ops", .cfi_stubs = &__bpf_ops_tcp_congestion_ops,/* The struct_ops's function may switch to another struct_ops.
Signature · 1 line
2.53.1-Meta
Kumar Kartikeya Dwivedi
maintainerPATCH 73/73 sched_ext: Treat a cancelled program as a scheduler error
In reply to Kumar Kartikeya DwivediThe kernel can now cancel a BPF program. It ends the program early at a loop that runs out of time, at a fault in arena or at bpf_throw(). The program returns a default value, which is 0 for a program of a scheduler, and does not finish its work.
Currently sched_ext keeps calling a scheduler whose program was cancelled, until the watchdog finds a task that has not run:
void BPF_STRUCT_OPS(cs_enqueue, struct task_struct *p, u64 flags)
{
nr_enqueued++; <- in arena, the page is gone
scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, slice, flags);
}ops.enqueue() is cancelled at the fault, and the task gets into no queue. A cancelled ops.select_cpu() returns 0, which is a CPU, and a cancelled ops.init_task() returns 0, which is success.
The BPF core calls ->cancelled() of struct bpf_struct_ops when a program of the struct_ops was cancelled. Implement it for sched_ext_ops and sched_ext_ops_cid. It finds the scheduler of the program with scx_prog_sched() and calls scx_error() for it, so the error goes exactly where scx_bpf_error() of that program would go. The first cancelled program disables the scheduler, with a runtime error:
program <name> (ops.<member>, id <id>) was unwound, see its stderr stream
The stderr stream of the program says why the kernel cancelled it.
->cancelled() runs in the context of the cancelled program. scx_error() is safe there: it takes no lock and can be called under the rq lock, in a timer callback and in NMI.
Two things stay as they are:
- The callbacks of the scheduler are still called until the disable path has finished, as after scx_bpf_error() today.
- A cancelled program for which scx_prog_sched() finds no scheduler is not reported.
--- kernel/sched/ext/ext.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
kernel/sched/ext/ext.c +21 -0
@@ -9435,6 +9435,25 @@ static int bpf_scx_validate(void *kdata)return 0 ; } +/* +* @prog, an op of a scheduler or an async callback of one, was unwound. +* The op returns 0 without having computed it, which would be taken for a +* CPU or for success, so this is as fatal to the scheduler as scx_bpf_error(). +* The rq lock of the op's caller may be held here. scx_error() only +* claims the exit and leaves the disabling to irq_work and the helper kthread. +*/ +static void bpf_scx_cancelled (const struct bpf_prog *prog) +{ +struct scx_sched *sch; + +guard (rcu)(); + + sch =scx_prog_sched (prog->aux); +if (sch) +scx_error (sch,"program %s (ops.%s, id %u) was unwound, see its stderr stream" , + prog->aux->name, prog->aux->attach_func_name, prog->aux->id); +} +static s32 sched_ext_ops__select_cpu (struct task_struct *p,s32 prev_cpu,u64 wake_flags) {return -EINVAL ; }static void sched_ext_ops__enqueue (struct task_struct *p,u64 enq_flags) {}static void sched_ext_ops__dequeue (struct task_struct *p,u64 enq_flags) {}
@@ -9528,6 +9547,7 @@ static struct bpf_struct_ops bpf_sched_ext_ops = { .init = bpf_scx_init, .update = bpf_scx_update, .validate = bpf_scx_validate, + .cancelled = bpf_scx_cancelled, .name = "sched_ext_ops", .owner =THIS_MODULE , .cfi_stubs = &__bpf_ops_sched_ext_ops
@@ -9605,6 +9625,7 @@ static struct bpf_struct_ops bpf_sched_ext_ops_cid = { .init = bpf_scx_init, .update = bpf_scx_update, .validate = bpf_scx_validate, + .cancelled = bpf_scx_cancelled, .name = "sched_ext_ops_cid", .owner =THIS_MODULE , .cfi_stubs = &__bpf_ops_sched_ext_ops_cid
Signature · 1 line
2.53.1-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v1 73/73] sched_ext: Treat a cancelled program as a scheduler error
TL;DR: - sched_ext now disables schedulers on bpf_throw() with a usable return value; is that intended? - Comment, changelog and exit message ("see its stderr stream") may be inaccurate for…
Quoted 1 line
sched_ext: Treat a cancelled program as a scheduler error
TL;DR:
- sched_ext now disables schedulers on bpf_throw() with a usable return value; is that intended?
- Comment, changelog and exit message ("see its stderr stream") may be inaccurate for bpf_throw()
Quoted 3 lines
kernel/sched/ext/ext.c +0
-0
[ ... ]
Quoted 12 lines
kernel/sched/ext/ext.c +8
-0@@ -9435,6 +9435,25 @@ static int bpf_scx_validate(void *kdata)return 0 ; } +/* +* @prog, an op of a scheduler or an async callback of one, was unwound. +* The op returns 0 without having computed it, which would be taken for a +* CPU or for success, so this is as fatal to the scheduler as scx_bpf_error(). +* The rq lock of the op's caller may be held here. scx_error() only +* claims the exit and leaves the disabling to irq_work and the helper kthread. +*/ +static void bpf_scx_cancelled (const struct bpf_prog *prog)
kernel/sched/ext/ext.c static int bpf_scx_validate(void *kdata) · line 9455
Quoted 10 lines
kernel/sched/ext/ext.c +10
-0+{ +struct scx_sched *sch; + +guard (rcu)(); + + sch =scx_prog_sched (prog->aux); +if (sch) +scx_error (sch,"program %s (ops.%s, id %u) was unwound, see its stderr stream" , + prog->aux->name, prog->aux->attach_func_name, prog->aux->id); +}
The comment says "The op returns 0 without having computed it", and the commit message says "The program returns a default value, which is 0 for a program of a scheduler". Is that accurate for bpf_throw()?
The documentation of ->cancelled in include/linux/bpf.h says the program is about to return the value of @cancelled_retval, or the argument of bpf_throw(). Also, bpf_pad_insns() does this:
if (!subprog && env->exception_callback_subprog)
dst = BPF_REG_1;so after bpf_throw(), or after any cancellation in a scheduler that has an exception callback, the op returns a value the program chose. pad_reports() returns true for every pad of subprog 0, including the bpf_throw() site, so bpf_scx_cancelled() runs for these cases too.
A scheduler that uses bpf_throw() or bpf_assert() with a usable cookie or a fallback exception callback kept running before this series, and is now disabled. Is that intended? If so, could the comment and changelog say that sched_ext deliberately treats bpf_throw() as fatal, rather than giving the unreturned-value rationale?
Also, the exit message says "see its stderr stream", and the commit message says "The stderr stream of the program says why the kernel cancelled it." For bpf_throw() nothing is written to the program's BPF_STDERR stream, since the verifier turns the call into a jump to the landing pad. The cookie passed to bpf_throw() is not in the exit message either.
Could the message say that the program may have called bpf_throw(), or leave out the stream reference when there is nothing to read?
---
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/46579809730