bpf: Remove the limits on maps, kfuncs, subprogs and special fields
Subsystems (10)
v2 cover bpf: Remove the limits on maps, kfuncs, subprogs and special fields
From: Alexei Starovoitov <[email protected]>
In short: the verifier keeps the maps, kfuncs, subprogs and special fields of a program in arrays of a fixed size. A safe program that needs one more entry is rejected. With this series the arrays grow with the program. What was quadratic or worse below a limit is linear or n log n now. Outside of tools/ the kernel loses 300 lines.
today new patch
maps of a program 64 no limit 7
BTF objects of a program 64 no limit 7
entries of fd_array 4096 no limit 7
kfuncs of a program 256 65536 9
module BTFs of these kfuncs 256 no limit 9
tables of functions, for callx:
pointers in all maps 1048576 no limit 10
pointers in the range of one read 4096 no limit 10
functions that one read can give 1024 no limit 10
sets of functions 4096 no limit 10
subprogs 1024 no limit 16
special fields of a map value 11 no limit 17
special fields of an allocated object 11 512 17
bytes of a name in BTF 512 4096 18
insns under a jump, with those that the
verifier adds 32767 no limit 12
insns of a program that bpftool can dump 524288 no limit 5
maps of a light skeleton 64 see 7 11
programs of a light skeleton 32 see 7 11A table of functions is an array of pointers to subprogs in a read-only map. A program reads a pointer from it and calls it with callx. A special field is a kptr, a bpf_spin_lock, a bpf_timer, a bpf_list_head and the like.
1. Why?
None of these numbers protects the kernel at run time. Each is the size of an array, or it hides an algorithm that does not scale. Such a limit is raised when a real program hits it. Rust crates did that to two of them:
commit 70bcb39a7392 ("bpf: Bump BPF_MAX_SUBPROGS to 1024") and commit 3f4f430fa1b2 ("bpf: Allow BPF_MAX_SUBPROGS targets of a read from a table of functions"). Real code is near the next ones:
subprogs 777 of 1024 the program of rust-bpf [1] in the first
commit
name in BTF 429 of 512 a struct of scx_lavd in rust-bpf
maps 41 of 64 obi_continue_protocol_http() in OBI of
OpenTelemetry
And it is over the limits of a light skeleton:
runtime-security.o of Datadog 627 programs 151 maps
tracee.bpf.o of Tracee 169 programs 87 maps
The author of a program does not choose the number of its maps. Each .data.X and .rodata.X section is a map. Each jump table that clang makes from a switch is a map: with -mcpu=v4 bpf_generic_uprobe.o of Tetragon has 19 of them next to its 66 maps.
2. What bounds BPF_PROG_LOAD now?
size 1000000 insns of a program and 16 MB of BTF, as today.
memory memory.max of the cgroup of the task. There bpf() returns
-ENOMEM. Today the OOM killer ends the task (patch 2).
time A fatal signal ends each long loop. The freezer does not wait
either: the task freezes, then bpf() starts again (patch 1).
A large program also has to get to the end of BPF_PROG_LOAD. Today each signal ends it with -EAGAIN, and libbpf gives up after 5 tries. A task with a profiling timer of 10 ms never gets through a BPF_PROG_LOAD of 11 ms. With patch 1 a signal that does not kill waits for the end.
The limits that hold at run time do not change: the size of the stack, 32 frames, 33 tail calls.
3. What had to scale?
patch question today new
8 dump: which map is in look at all maps maple tree
this ld_imm64?
9 is this kfunc known? sort at each new one hash table
10 is this set of look at all sets hash table
functions known?
13 who calls whom, over matrix of bits, lists of edges,
any number of calls? n^3 / 64, two times nodes + edges
14 what does a table of walk its pointers one node of the
functions call? at each use call graph
15 which decl tags has look at all types a list per type
this argument?
17 which special fields enter a struct for enter it once,
has this type? each member of that copy its fields
type: members^depth
18 is this name valid? read it for each read each byte
type that has it once
19 which insns dominate quadratic n log nthis insn?
Three small tools carry most of it:
bpf_table_next() an array that doubles patch 7 struct bpf_index hash table, key -> number of an entry patch 7 struct bpf_call_graph lists of edges, sorted once: callees patch 13
first, the nodes of a cycle in a row
4. Far jumps
A conditional jump has an offset of 16 bits. The verifier adds insns under
it: inlined map lookups, checks of divisions, may_goto, constant blinding. Then a verified program fails with -ERANGE. 2979 map lookups under one branch are enough. Patch 12 does what an assembler does:
if r1 > r2 goto far -> if r1 > r2 goto +1
goto +1
gotol farWhere all jumps fit, no jump changes. The passes in fixups.c do not compute offsets any more: bpf_patch_list_build() does it for all of them.
5. Fixes
3 A syscall program and the target of its tail call get the same
context. Its size is compared with the first program only.
4 bpf_loop() is inlined with a call of its callback, also when the
callback is removed as dead code.
5 A program of more than 524288 insns loads and cannot be dumped. 6 btf_resolve() does not see a type that holds itself through
ptr -> typedef -> array. Only the limits of the later walks end that loop, and patch 17 removes one of them. With patch 6 such BTF is refused.
6. What else changes for users?
- The rules on calls look only at insns that the main pass has seen. A call, a tail call, LD_ABS or bpf_throw() in dead code rejects nothing (patch 13).
- A map value with 12 kptrs had no struct btf_record at all. It has one now. So the map needs CAP_BPF, and it cannot be mmaped or BPF_F_RDONLY_PROG (patch 17).
- -ENOMEM in front of the JIT fails BPF_PROG_LOAD. There is no fall back to the interpreter (patch 2).
- The loader program of a light skeleton gets -EINTR from bpf_sys_bpf(). It got -EAGAIN (patch 1).
- An extension that does tail calls cannot attach to a syscall program that does none (patch 3).
- The tags of subprogs that make calls change, and so do their names in kallsyms (patch 16).
- x86-32, riscv32, parisc and sparc64 have no gotol in the JIT. A program with a far jump is not JITed there, like a program that has gotol in its source (patch 12).
7. What stays?
65536 kfuncs JITs find a kfunc by insn->off: 16 bits.
4096 bytes of a name A search by name takes types x length.
512 special fields An allocated object has 4096 bytes at most.
4096 entries of For unprivileged programs. They have 4096 insns.
fd_array
10000 chains of calls In the analysis of stack liveness.
32 levels of types In btf_resolve().
64 KB of context For the loader program of a light skeleton: 16 bytes for a map, 4 for a program.
bpf_flow_reset() It looks at all insns after each global subprog.
A fatal signal ends that loop.
The tests are in the patch that changes the behaviour (7, 10, 12, 13, 17) and in patches 20 and 21. Where a program above an old limit can be unsafe, an unsafe twin of it must fail.
v1 -> v2:
- Patch 1: bpf() starts again after a freeze also when the command has BPF_COMMON_ATTRS. It returned -EINTR. Patch 21 tests it (BPF CI bot).
- Patch 10: allocate a set of functions in front of its entry in the index. If that allocation failed in a round that is done again, the next round found the entry and no set behind it (sashiko).
- Patch 12: the test 'far jump over a far jump' relaxed no jump: both had an offset of 32767. Now they have 32766 and 32768: the second one is far and takes the first one along. The test looks at the insns (BPF CI bot).
- Patch 20: live_recursion runs on x86-64 and arm64 only: other JITs refuse the recursion with another message. The far_pad tests need the JIT (sashiko).
[1] https://github.com/4ast/rust-bpf
Alexei Starovoitov (21):
bpf: Stop a load only when the loader is killed or has to freeze
bpf: Fail the load when there is no memory
bpf: Give a syscall program the largest context when it does tail
calls
bpf: Do not inline bpf_loop() when its callback is dead code
bpf: Dump programs that have more than 524288 insns
bpf: Resolve BTF structs and arrays first
bpf: Remove the limits on maps, BTFs and fd_array of a program
bpf: Do not scan all maps for each insn and each subprog
bpf: Remove the limits on kfuncs of a program
bpf: Remove the limits on tables of functions
libbpf: Size the tables of the loader program from the object
bpf: Relax jumps that patches push out of range
bpf: Keep the call graph in lists of edges
bpf: Find the effects of callees on the call graph
bpf: Link the decl tags of a type
bpf: Remove BPF_MAX_SUBPROGS
bpf: Walk each type once when looking for special fields
bpf: Raise the limit on the length of BTF names
bpf: Find dominators in O(n log n)
selftests/bpf: Test programs above the old limits selftests/bpf: Test limits of the load with raw programs
arch/sparc/net/bpf_jit_comp_64.c | 7 +-
arch/x86/net/bpf_jit_comp.c | 12 +-
include/linux/bpf.h | 5 -
include/linux/bpf_verifier.h | 162 ++-
kernel/bpf/btf.c | 503 +++----
kernel/bpf/cfg.c | 428 +++---
kernel/bpf/check_btf.c | 13 +-
kernel/bpf/const_fold.c | 8 +-
kernel/bpf/core.c | 368 +++---
kernel/bpf/diagnostics.c | 8 +-
kernel/bpf/fixups.c | 702 +++-------
kernel/bpf/flow.c | 99 +-
kernel/bpf/join.c | 2 +-
kernel/bpf/liveness.c | 66 +-
kernel/bpf/log.c | 2 +-
kernel/bpf/loops.c | 189 +--
kernel/bpf/scev.c | 32 +-
kernel/bpf/syscall.c | 126 +-
kernel/bpf/verifier.c | 1164 ++++++-----------
net/bpf/test_run.c | 20 +-
tools/lib/bpf/bpf_gen_internal.h | 3 +-
tools/lib/bpf/gen_loader.c | 157 +--
tools/lib/bpf/libbpf.c | 8 +-
tools/testing/selftests/bpf/Makefile.skel | 2 +-
.../{blinding_log.c => blinding_far_jump.c} | 38 +-
.../selftests/bpf/prog_tests/fd_array.c | 36 +-
.../selftests/bpf/prog_tests/no_limits.c | 465 +++++++
.../selftests/bpf/prog_tests/verifier.c | 4 +
.../selftests/bpf/progs/cpumask_common.h | 3 -
.../selftests/bpf/progs/cpumask_failure.c | 5 +-
.../testing/selftests/bpf/progs/many_progs.c | 36 +
.../bpf/progs/test_global_func_deep_stack.c | 12 +-
.../selftests/bpf/progs/verifier_and.c | 2 +-
.../selftests/bpf/progs/verifier_bounds.c | 14 +-
.../bpf/progs/verifier_callx_dead_cb.c | 60 +
.../selftests/bpf/progs/verifier_callx_many.c | 31 +-
.../selftests/bpf/progs/verifier_movsx.c | 4 +-
.../selftests/bpf/progs/verifier_no_limits.c | 224 ++++
.../selftests/bpf/progs/verifier_patch_list.c | 146 ++-
.../selftests/bpf/progs/verifier_tailcall.c | 4 +-
.../selftests/bpf/progs/verifier_unpriv.c | 2 +-
.../selftests/bpf/progs/verifier_unwind.c | 32 +
tools/testing/selftests/bpf/verifier/calls.c | 3 +-
43 files changed, 2924 insertions(+), 2283 deletions(-)
rename tools/testing/selftests/bpf/prog_tests/{blinding_log.c => blinding_far_jump.c} (51%)
create mode 100644 tools/testing/selftests/bpf/prog_tests/no_limits.c
create mode 100644 tools/testing/selftests/bpf/progs/many_progs.c
create mode 100644 tools/testing/selftests/bpf/progs/verifier_callx_dead_cb.c
create mode 100644 tools/testing/selftests/bpf/progs/verifier_no_limits.cSignature · 1 line
2.55.0
PATCH v2 1/21 bpf: Stop a load only when the loader is killed or has to freeze
From: Alexei Starovoitov <[email protected]>
Any pending signal stops the verifier with -EAGAIN. A loader with a profiling timer never loads a program that takes longer than one period:
timer: |--10ms--|--10ms--|--10ms--|
load: |--------X EAGAIN
|--------X EAGAIN ... libbpf gives up after 5 tries
Use one helper for all long loops. Add it to the loops that had no
check: cfg, const_fold, stack liveness and CO-RE relocations.
event load fatal signal stops system or cgroup freezer stops, the task freezes, bpf() starts again other signals goes on
The restart is not visible in user space. A loader program gets -EINTR from bpf_sys_bpf(), it got -EAGAIN. Unprivileged loaders wait for one
lock: test the same condition when they get it, so the queue drains.
SIGSTOP, ptrace and signals with a handler wait for the end of the load. A tool that stops and continues a task all the time is one more timer.
--- include/linux/bpf_verifier.h | 16 ++++++++++++++++ kernel/bpf/cfg.c | 2 +- kernel/bpf/check_btf.c | 4 ++-- kernel/bpf/const_fold.c | 4 ++++ kernel/bpf/fixups.c | 20 +++----------------- kernel/bpf/flow.c | 29 +++++++++++------------------ kernel/bpf/liveness.c | 20 ++++++++++++-------- kernel/bpf/loops.c | 22 ++++------------------ kernel/bpf/scev.c | 10 ++++------ kernel/bpf/syscall.c | 9 ++++++++- kernel/bpf/verifier.c | 14 +++++++------- 11 files changed, 72 insertions(+), 78 deletions(-)
include/linux/bpf_verifier.h +16 -0
@@ -10,6 +10,22 @@#include <linux/tnum.h> #include <linux/cnum.h> #include <linux/math64.h> /* for div_s64_rem() */ +#include <linux/freezer.h> +#include <linux/sched/signal.h> + +/* +* For each loop that can run long. The caller returns -EINTR. +* killed the task dies +* freezer waits the task freezes, then bpf() starts again +* other signals wait for the end of the load +*/ +static inline bool bpf_must_abort (void ) +{ +cond_resched (); +return task_sigpending (current) && + (__fatal_signal_pending (current) ||freezing (current) || + (READ_ONCE (current->jobctl) &JOBCTL_TRAP_FREEZE )); +}/* * Mathematical modulo, the residue of 'v' modulo 'step', normalized to [0, step).
kernel/bpf/cfg.c +1 -1
@@ -686,7 +686,7 @@ int bpf_check_cfg(struct bpf_verifier_env *env)while (env->cfg.cur_stack >0 ) {int t = insn_stack[env->cfg.cur_stack -1 ]; - ret =visit_insn (t, env); + ret =bpf_must_abort () ? -EINTR :visit_insn (t, env);switch (ret) {case DONE_EXPLORING : insn_state[t] =EXPLORED ;
kernel/bpf/check_btf.c +2 -2
@@ -402,8 +402,8 @@ int bpf_check_core_relo(struct bpf_verifier_env *env,break ; } - err =bpf_core_apply (&ctx, &core_relo, i, - &prog->insnsi[core_relo.insn_off /8 ]); + err =bpf_must_abort () ? -EINTR : +bpf_core_apply (&ctx, &core_relo, i, &prog->insnsi[core_relo.insn_off /8 ]);if (err)break ;bpfptr_add (&u_core_relo, rec_size);
kernel/bpf/const_fold.c +4 -0
@@ -278,6 +278,10 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env) } redo: +if (bpf_must_abort ()) { +kvfree (ci_in); +return -EINTR ; + } changed = false;for (i = env->cfg.cur_postorder -1 ; i >=0 ; i--) {int idx = env->cfg.insn_postorder[i];
kernel/bpf/fixups.c +3 -17
@@ -6,7 +6,6 @@#include <linux/filter.h> #include <linux/vmalloc.h> #include <linux/perf_event.h> -#include <linux/sched/signal.h> #include <net/xdp.h> #include "disasm.h"
@@ -165,19 +164,6 @@ static int get_callee_stack_depth(struct bpf_verifier_env *env, }#endif -/* -* A post-verification rewriting pass can queue a patch for each instruction -* of a large program. Keep the primitives that queue them killable and -* preemptible. -*/ -static bool bpf_rewrite_must_abort (void ) -{ -if (fatal_signal_pending (current)) -return true; -cond_resched (); -return false; -} -/* * Queue the replacement of insn 'off' by 'patch[0..len)' until * bpf_patch_list_commit(), see __bpf_patch_list_add(). Replacing one insn by
@@ -190,7 +176,7 @@ struct bpf_insn *bpf_patch_list_add(struct bpf_verifier_env *env, u32 off,struct bpf_patch_list *pl = &env->patch_list;struct bpf_insn_patch *p = pl->cnt ? &pl->patches[pl->cnt -1 ] :NULL ; -if (bpf_rewrite_must_abort ()) +if (bpf_must_abort ())return ERR_PTR (-EINTR ); if (verifier_bug_if(!len || off >= env->prog->len ||
@@ -221,7 +207,7 @@ int bpf_patch_list_del(struct bpf_verifier_env *env, u32 off) {struct bpf_patch_list *pl = &env->patch_list; -if (bpf_rewrite_must_abort ()) +if (bpf_must_abort ())return -EINTR ; if (verifier_bug_if(off >= env->prog->len ||
@@ -240,7 +226,7 @@ int bpf_patch_list_insert(struct bpf_verifier_env *env, u32 off,struct bpf_insn_patch *p = pl->cnt ? &pl->patches[pl->cnt -1 ] :NULL ;int err; -if (bpf_rewrite_must_abort ()) +if (bpf_must_abort ())return -EINTR ; if (verifier_bug_if(!cnt || off >= env->prog->len ||
kernel/bpf/flow.c +11 -18
@@ -504,11 +504,10 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env)if (!loop)continue ;/* a deep nest of loops takes long */ -if (signal_pending (current)) { - ret = -EAGAIN ; +if (bpf_must_abort ()) { + ret = -EINTR ;break ; } -cond_resched (); loop->rt_bounded =flow_loop_is_bounded (env, h);/* also when it's bounded: the main pass may find that it's not */ flow_place_guards (env, h, seen);
@@ -884,11 +883,10 @@ int bpf_flow_compute_kinds(struct bpf_verifier_env *env)for (n =0 ; lost; n++) { lost = false;/* a chain of calls takes a round for each link */ -if (signal_pending (current)) { - err = -EAGAIN ; +if (bpf_must_abort ()) { + err = -EINTR ;break ; } -cond_resched ();for (j =0 ; j < cnt; j++) {/* it has callees first */ s = env->subprog_topo_order[n &1 ? j : cnt -1 - j];
@@ -1068,11 +1066,10 @@ static int flow_compute_need_const(struct bpf_verifier_env *env, struct flow_nee again:while (any && changed) { changed = false; -if (signal_pending (current)) { - err = -EAGAIN ; +if (bpf_must_abort ()) { + err = -EINTR ;break ; } -cond_resched ();for (s =0 ; callx && s < env->subprog_cnt; s++)if (env->subprog_info[s].addr_taken) callx_regs |= need[env->subprog_info[s].start].regs;
@@ -1619,11 +1616,10 @@ static int flow_compute_rungs(struct bpf_verifier_env *env) depth++;if (depth >=LOOP_STACK_SIZE )continue ; -if (signal_pending (current)) { - err = -EAGAIN ; +if (bpf_must_abort ()) { + err = -EINTR ;break ; } -cond_resched (); err =flow_compute_loop_rungs (env, at, total, h); }kvfree (at);
@@ -2737,12 +2733,10 @@ static int flow_merge(struct bpf_verifier_env *env, struct flow_set *set,int prev = s->prev_insn_idx; again: -if (signal_pending (current)) { - err = -EAGAIN ; +if (bpf_must_abort ()) { + err = -EINTR ; goto err_free; } -if (need_resched ()) -cond_resched ();/* again after a join: an offset may not be a constant any more, a pointer may be gone */ flow_shape_ctx (&s->st, &s->shape);
@@ -3397,7 +3391,7 @@ void bpf_flow_print_way(struct bpf_verifier_env *env, u64 log_pos, int head, intif (!cnt ||bpf_vlog_stash (&env->log, log_pos, &stash)) goto out; env->prev_linfo =NULL ; -while (cnt-- && !signal_pending (current)) { +while (cnt-- && !bpf_must_abort ()) { w = &way[cnt];if (w->s) {verbose (env,"from %d to %d:" , w->s->prev_insn_idx, w->head);
@@ -3409,7 +3403,6 @@ void bpf_flow_print_way(struct bpf_verifier_env *env, u64 log_pos, int head, intbpf_verbose_insn (env, &insns[i]);verbose (env,"\n" ); } -cond_resched (); }bpf_vlog_unstash (&env->log, &stash); out:
kernel/bpf/liveness.c +12 -8
@@ -456,7 +456,7 @@ static inline bool update_insn(struct bpf_verifier_env *env, struct func_instanc }/* Fixed-point computation of @live_before marks */ -static void update_instance (struct bpf_verifier_env *env,struct func_instance *instance) +static int update_instance (struct bpf_verifier_env *env,struct func_instance *instance) {u32 i, frame, po_start, po_end;int *insn_postorder = env->cfg.insn_postorder;
@@ -469,6 +469,8 @@ static void update_instance(struct bpf_verifier_env *env, struct func_instance * po_end = (subprog +1 )->postorder_start;/* repeat until fixed point is reached */ do { + if (bpf_must_abort()) + return -EINTR; changed = false; for (frame = 0; frame <= instance->depth; frame++) { if (!instance->frames[frame])
@@ -482,6 +484,7 @@ static void update_instance(struct bpf_verifier_env *env, struct func_instance * } } }while (changed); +return 0 ; } static bool is_live_before(struct func_instance *instance, u32 insn_idx, u32 frameno, u32 half_spi,
@@ -2130,6 +2133,9 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,struct bpf_iarray *succ;int ti; + err = -EINTR ; +if (bpf_must_abort ()) + goto err_free;if (!arg_is_visited (&at_in[i][0 ]) && !arg_is_visited (&at_in[i][1 ]))continue ;
@@ -2365,8 +2371,8 @@ static int analyze_subprog(struct bpf_verifier_env *env,return -E2BIG ; } -if (need_resched ()) -cond_resched (); +if (bpf_must_abort ()) +return -EINTR ;/* * When an instance is reused (must_write_initialized == true),
@@ -2524,8 +2530,7 @@ static int analyze_subprog(struct bpf_verifier_env *env,if (err)return err; } -update_instance (env, instance); -return 0 ; +return update_instance (env, instance); out_free:if (prev_instance)
@@ -2872,11 +2877,10 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env) changed = false;/* a cycle of calls takes a round for each link */ -if (signal_pending (current)) { - err = -EAGAIN ; +if (bpf_must_abort ()) { + err = -EINTR ; goto out; } -cond_resched ();for (i =0 ; i < env->cfg.cur_postorder; ++i) {int insn_idx = env->cfg.insn_postorder[i];struct insn_live_regs *live = &state[insn_idx];
kernel/bpf/loops.c +4 -18
@@ -2,7 +2,6 @@/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */ #include <linux/slab.h> -#include <linux/sched/signal.h> #include <linux/bpf_verifier.h> static bool is_cfg_jump (struct bpf_insn *insn)
@@ -107,7 +106,6 @@ static int compute_subprog_idoms(struct bpf_verifier_env *env, struct bpf_iarrayint po_last = (subprog +1 )->postorder_start -1 ;int *idoms = env->idoms;int po_num, pred; -u32 work =0 ;bool changed; idoms[start] = start;
@@ -123,11 +121,8 @@ static int compute_subprog_idoms(struct bpf_verifier_env *env, struct bpf_iarrayint new_idom =-1 ;iarray_for_each (pred, preds[idx]) { -if (++work %1024 ==0 ) { -if (signal_pending (current)) -return -EAGAIN ; -cond_resched (); - } +if (bpf_must_abort ()) +return -EINTR ;if (idoms[pred] ==-1 )continue ;
@@ -416,24 +411,15 @@ static int compute_loops_in_subprog(struct bpf_verifier_env *env, struct loops_dint *stack = dfs->stack;int s, h, err, cur, stack_sz;struct bpf_iarray *succ; -u32 i; stack[0 ] = start; state[start].traversed = true; state[start].next_succ =0 ; dfs_pos[start] =1 ; stack_sz =1 ; - i =0 ; do { - /* - * The algorithm should be very fast in practice, - * guard against pathological inputs, just in case. - */ - if ((++i % 1024) == 0) { - if (signal_pending(current)) - return -EAGAIN; - cond_resched(); - } + if (bpf_must_abort()) + return -EINTR; cur = stack[stack_sz - 1]; succ = bpf_insn_successors(env, cur);
kernel/bpf/scev.c +4 -6
@@ -2664,11 +2664,10 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header, i idx = *min_heap_peek_inline (worklist);min_heap_pop_inline (worklist, &worklist_cb, env->cfg.postorder_nums); start = idx; -if (signal_pending (current)) { - err = -EAGAIN ; +if (bpf_must_abort ()) { + err = -EINTR ; goto out; } -cond_resched ();/* join_successor() maps nested-loop entries to their representative header. */ nested_loop = idx != cur_header ? aux[idx].loop :NULL ;
@@ -3265,9 +3264,8 @@ int bpf_compute_scev(struct bpf_verifier_env *env) idx = postorder[i];if (!aux[idx].need_scev)continue ; -if (signal_pending (current)) -return -EAGAIN ; -cond_resched (); +if (bpf_must_abort ()) +return -EINTR ; header =bpf_loop_at_index (env, idx); err = aux[idx].loop ? compute_header_scevs(env, header)
kernel/bpf/syscall.c +8 -1
@@ -6604,7 +6604,14 @@ static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size, SYSCALL_DEFINE5(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size, struct bpf_common_attr __user *, uattr_common, unsigned int, size_common) { -return __sys_bpf (cmd,USER_BPFPTR (uattr), size,USER_BPFPTR (uattr_common), size_common); +int err =__sys_bpf (cmd,USER_BPFPTR (uattr), size,USER_BPFPTR (uattr_common), size_common); + + cmd &= ~BPF_COMMON_ATTRS ; +/* bpf_must_abort() ended the command, nothing of it is left */ +if (err == -EINTR &&task_sigpending (current) && + (cmd ==BPF_PROG_LOAD || cmd ==BPF_BTF_LOAD || cmd ==BPF_MAP_CREATE )) +return -ERESTARTNOINTR ; +return err; } static bool syscall_prog_is_valid_access(int off, int size,
kernel/bpf/verifier.c +7 -7
@@ -21790,11 +21790,8 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)struct bpf_insn_aux_data *insn_aux;int err; -if (signal_pending (current)) -return -EAGAIN ; - -if (need_resched ()) -cond_resched (); +if (bpf_must_abort ()) +return -EINTR ;/* no insn makes as many ids as there are from here to BPF_INHERITED_ID */ if (env->id_gen >=BPF_MAX_ID ) {
@@ -22988,8 +22985,8 @@ static int resolve_func_ptrs(struct bpf_verifier_env *env)continue ;for (off =0 ; off +sizeof (u64) <= map->value_size; off +=sizeof (u64)) { -if (!(off %SZ_64K )) -cond_resched (); +if (bpf_must_abort ()) +return -EINTR ; val = *(u64 *)(unsigned long )(addr + off);if (!val || val %sizeof (struct bpf_insn ) || val /sizeof (struct bpf_insn ) >= insn_cnt)
@@ -25306,6 +25303,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,/* Serialize verification of unprivileged programs. */ if (!is_priv)mutex_lock (&bpf_verifier_lock); + ret = -EINTR ; +if (bpf_must_abort ()) + goto skip_full_check; len = env->insn_aux_data_len = env->prog->len; env->insn_aux_data =
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next v2 01/21] bpf: Stop a load only when the loader is killed or has to freeze
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] bpf: bpf_log_attr_finalize() overwrites -EINTR on bpf_must_abort() - [Medium] bpf: stale map->user…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] bpf: bpf_log_attr_finalize() overwrites -EINTR on bpf_must_abort()
- [Medium] bpf: stale map->user state across restart on blinding abort in bpf_check()
--
commit 595bfc06524fa376713bc6415b648b32cc04152d
Author: Alexei Starovoitov <[email protected]>
bpf: Stop a load only when the loader is killed or has to freeze
This commit replaces signal_pending() and fatal_signal_pending() checks across verifier passes with a unified bpf_must_abort() helper that aborts with -EINTR only when the loader has a fatal signal or needs to freeze, and restarts BPF_PROG_LOAD, BPF_BTF_LOAD, and BPF_MAP_CREATE via -ERESTARTNOINTR.
Quoted 4 lines
kernel/bpf/fixups.c +0
-0
[ ... ]
kernel/bpf/fixups.c struct bpf_insn *bpf_patch_list_add(struct bpf_verifier_env *env, u32 off, · line 180
Quoted 7 lines
kernel/bpf/fixups.c +1
-1@@ -190,7 +176,7 @@ struct bpf_insn *bpf_patch_list_add(struct bpf_verifier_env *env, u32 off,struct bpf_patch_list *pl = &env->patch_list;struct bpf_insn_patch *p = pl->cnt ? &pl->patches[pl->cnt -1 ] :NULL ; -if (bpf_rewrite_must_abort ()) +if (bpf_must_abort ())return ERR_PTR (-EINTR );
[Severity: Medium]
Can aborting on a non-fatal freezer request here leave mutated map state behind when BPF_PROG_LOAD restarts?
For a single-subprog program, bpf_check() runs bpf_fixup_call_args() -> bpf_jit_subprogs() -> resolve_func_ptrs(), which sets BPF_MAP_USER_PATCHED on ptr->map->user and zeroes dead function-pointer slots in the frozen read-only map, and then populates env->prog->aux->used_maps before calling __bpf_prog_select_runtime():
kernel/bpf/verifier.c:bpf_check() {
...
env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);err_release_maps:
err = bpf_log_attr_finalize(attr_log, &env->log);
if (err)
ret = err;
if (ret)
release_insn_arrays(env);
if (!env->prog->aux->used_maps)
release_maps(env);
...
}If constant blinding inside __bpf_prog_select_runtime() -> bpf_prog_jit_compile() -> bpf_jit_blind_constants() hits bpf_must_abort() in bpf_patch_list_add(), it returns -EINTR after the map was already modified and with env->prog->aux->used_maps already set. Synchronous release_maps() is skipped, __bpf_free_used_maps() is deferred to a workqueue (and its cmpxchg(&map->user, (unsigned long)aux, 0) cannot clear BPF_MAP_USER_PATCHED), and when the thawed task restarts BPF_PROG_LOAD via -ERESTARTNOINTR, bpf_map_claim() either fails with -EBUSY or races with the deferred map release work.
[ ... ]
Quoted 8 lines
kernel/bpf/syscall.c +0
-0@@ -6604,7 +6604,14 @@ static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size, SYSCALL_DEFINE5(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size, struct bpf_common_attr __user *, uattr_common, unsigned int, size_common) {
kernel/bpf/syscall.c static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size, · line 6615
Quoted 10 lines
kernel/bpf/syscall.c +8
-1-return __sys_bpf (cmd,USER_BPFPTR (uattr), size,USER_BPFPTR (uattr_common), size_common); +int err =__sys_bpf (cmd,USER_BPFPTR (uattr), size,USER_BPFPTR (uattr_common), size_common); + + cmd &= ~BPF_COMMON_ATTRS ; +/* bpf_must_abort() ended the command, nothing of it is left */ +if (err == -EINTR &&task_sigpending (current) && + (cmd ==BPF_PROG_LOAD || cmd ==BPF_BTF_LOAD || cmd ==BPF_MAP_CREATE )) +return -ERESTARTNOINTR ; +return err; }
[Severity: Medium]
Does bpf_log_attr_finalize() overwrite -EINTR with -ENOSPC and prevent the syscall from restarting after freezing?
When bpf_check() aborts with ret = -EINTR, its cleanup path still finalizes the verifier log:
kernel/bpf/verifier.c:bpf_check() {
...
err_release_maps:
err = bpf_log_attr_finalize(attr_log, &env->log);
if (err)
ret = err;
...
}If the user supplied a log buffer and log->len_max > log->len_total (for example, a rolling log buffer, or under BPF_LOG_LEVEL1 where do_check() calls bpf_flow_print_way() on err == -EINTR and do_check_common() skips bpf_vlog_reset()), bpf_log_attr_finalize() returns -ENOSPC and clobbers ret = -EINTR. SYSCALL_DEFINE5(bpf) then sees err == -ENOSPC instead of -EINTR and returns -ENOSPC to user space after thawing instead of -ERESTARTNOINTR.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v2 2/21 bpf: Fail the load when there is no memory
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The verifier allocates with GFP_KERNEL_ACCOUNT. At the limit of the memory cgroup this wakes up the OOM killer, and the loader dies:
memory.max = 64M, program needs 120M
before: Killed
after: bpf() = -ENOMEM
Use one mask for all allocations of the verifier. Most of the patch is:
sed -i 's/GFP_KERNEL_ACCOUNT/BPF_VERIFIER_GFP/'
The rest:
- BPF_PROG_LOAD passes the flags to bpf_prog_alloc() and friends. Classic BPF does not, except for the patch list of constant blinding.
- -ENOMEM in front of the JIT fails the load. There is no fall back to the interpreter. A failed bpf_prog_alloc() gives -ENOMEM, not -EINVAL.
With __GFP_RETRY_MAYFAIL kvmalloc() may reclaim and compact for a table of up to 4 MB before it uses vmalloc().
--- include/linux/bpf_verifier.h | 4 ++ kernel/bpf/cfg.c | 14 +++---- kernel/bpf/check_btf.c | 6 +-- kernel/bpf/const_fold.c | 4 +- kernel/bpf/core.c | 20 +++++----- kernel/bpf/diagnostics.c | 8 ++-- kernel/bpf/fixups.c | 22 +++++------ kernel/bpf/flow.c | 70 +++++++++++++++++----------------- kernel/bpf/join.c | 2 +- kernel/bpf/liveness.c | 26 ++++++------- kernel/bpf/log.c | 2 +- kernel/bpf/loops.c | 16 ++++---- kernel/bpf/scev.c | 22 +++++------ kernel/bpf/syscall.c | 6 +-- kernel/bpf/verifier.c | 74 ++++++++++++++++++------------------ 15 files changed, 150 insertions(+), 146 deletions(-)
include/linux/bpf_verifier.h +4 -0
@@ -13,6 +13,10 @@#include <linux/freezer.h> #include <linux/sched/signal.h> +/* No memory fails the load. It does not wake up the OOM killer. */ +#define BPF_GFP_MAYFAIL (__GFP_RETRY_MAYFAIL | __GFP_NOWARN) +#define BPF_VERIFIER_GFP (GFP_KERNEL_ACCOUNT | BPF_GFP_MAYFAIL) +/* * For each loop that can run long. The caller returns -EINTR. * killed the task dies
kernel/bpf/cfg.c +7 -7
@@ -188,7 +188,7 @@ struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem)size_t new_size =sizeof (struct bpf_iarray ) + n_elem *sizeof (old->items[0 ]);struct bpf_iarray *new; - new =kvrealloc (old, new_size,GFP_KERNEL_ACCOUNT ); + new =kvrealloc (old, new_size,BPF_VERIFIER_GFP );if (!new) {/* this is what callers always want, so simplify the call site */ kvfree (old);
@@ -663,12 +663,12 @@ int bpf_check_cfg(struct bpf_verifier_env *env)int ex_insn_beg, i, ret =0 ; insn_state = env->cfg.insn_state =kvzalloc_objs (int, insn_cnt, -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP );if (!insn_state)return -ENOMEM ; insn_stack = env->cfg.insn_stack =kvzalloc_objs (int, insn_cnt, -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP );if (!insn_stack) {kvfree (insn_state);return -ENOMEM ;
@@ -771,10 +771,10 @@ int bpf_compute_postorder(struct bpf_verifier_env *env)struct dfs_state *state =NULL ;struct bpf_iarray *succ =NULL ; - postorder_nums =kvzalloc_objs (int, env->prog->len,GFP_KERNEL_ACCOUNT ); - postorder =kvzalloc_objs (int, env->prog->len,GFP_KERNEL_ACCOUNT ); - stack =kvzalloc_objs (int, env->prog->len,GFP_KERNEL_ACCOUNT ); - state = kvzalloc_objs(struct dfs_state, env->prog->len, GFP_KERNEL_ACCOUNT); + postorder_nums =kvzalloc_objs (int, env->prog->len,BPF_VERIFIER_GFP ); + postorder =kvzalloc_objs (int, env->prog->len,BPF_VERIFIER_GFP ); + stack =kvzalloc_objs (int, env->prog->len,BPF_VERIFIER_GFP ); + state = kvzalloc_objs(struct dfs_state, env->prog->len, BPF_VERIFIER_GFP);if (!postorder_nums || !postorder || !stack || !state) {kvfree (postorder_nums);kvfree (postorder);
kernel/bpf/check_btf.c +3 -3
@@ -63,7 +63,7 @@ static int prepare_btf_func(struct bpf_verifier_env *env, urecord =make_bpfptr (attr->func_info, uattr.is_kernel); min_size =min_t (u32, krec_size, urec_size); - krecord =kvcalloc (nfuncs, krec_size,GFP_KERNEL_ACCOUNT | __GFP_NOWARN); + krecord =kvcalloc (nfuncs, krec_size,BPF_VERIFIER_GFP );if (!krecord)return -ENOMEM ;
@@ -164,7 +164,7 @@ static int check_btf_func(struct bpf_verifier_env *env, krecord = prog->aux->func_info; info_aux =kzalloc_objs (*info_aux, nfuncs, -GFP_KERNEL_ACCOUNT | __GFP_NOWARN); +BPF_VERIFIER_GFP );if (!info_aux)return -ENOMEM ;
@@ -242,7 +242,7 @@ static int check_btf_line(struct bpf_verifier_env *env,* pass in a smaller bpf_line_info object. */ linfo = kvzalloc_objs(struct bpf_line_info, nr_linfo, -GFP_KERNEL_ACCOUNT | __GFP_NOWARN); +BPF_VERIFIER_GFP );if (!linfo)return -ENOMEM ;
kernel/bpf/const_fold.c +2 -2
@@ -253,7 +253,7 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)int i, r, t;/* kvzalloc zeroes memory, so all entries start as CONST_ARG_UNVISITED (0) */ - ci_in =kvzalloc_objs (*ci_in, insn_cnt,GFP_KERNEL_ACCOUNT ); + ci_in =kvzalloc_objs (*ci_in, insn_cnt,BPF_VERIFIER_GFP );if (!ci_in)return -ENOMEM ;
@@ -572,7 +572,7 @@ int bpf_compute_leave_conds(struct bpf_verifier_env *env)bool jump;u64 any; - env->leave_conds =kvcalloc (env->prog->len,sizeof (*p),GFP_KERNEL_ACCOUNT ); + env->leave_conds =kvcalloc (env->prog->len,sizeof (*p),BPF_VERIFIER_GFP );if (!env->leave_conds)return -ENOMEM ;for (i =0 ; i < env->cfg.cur_postorder; i++) {
kernel/bpf/core.c +10 -10
@@ -180,7 +180,7 @@ int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog) prog->aux->jited_linfo =kvzalloc_objs (*prog->aux->jited_linfo, prog->aux->nr_linfo, -bpf_memcg_flags (GFP_KERNEL | __GFP_NOWARN)); +bpf_memcg_flags (GFP_KERNEL |BPF_GFP_MAYFAIL ));if (!prog->aux->jited_linfo)return -ENOMEM ;
@@ -309,7 +309,7 @@ int bpf_prog_calc_tag(struct bpf_prog *fp)bool was_ld_map;u32 i; - dst =__vmalloc (size,GFP_KERNEL_ACCOUNT ); + dst =__vmalloc (size,BPF_VERIFIER_GFP );if (!dst)return -ENOMEM ;
@@ -349,7 +349,7 @@ static int patch_list_reserve_patch(struct bpf_patch_list *pl)return 0 ; cap =max (pl->cap *2 ,16U ); - p =kvrealloc (pl->patches,array_size (cap,sizeof (*p)),GFP_KERNEL_ACCOUNT ); + p =kvrealloc (pl->patches,array_size (cap,sizeof (*p)),BPF_VERIFIER_GFP );if (!p)return -ENOMEM ; pl->patches = p;
@@ -366,7 +366,7 @@ static int patch_list_reserve_insns(struct bpf_patch_list *pl, u32 cnt)return 0 ; cap =max3 (pl->insn_cap *2 , pl->insn_cnt + cnt,64U ); - insns =kvrealloc (pl->insns,array_size (cap,sizeof (*insns)),GFP_KERNEL_ACCOUNT ); + insns =kvrealloc (pl->insns,array_size (cap,sizeof (*insns)),BPF_VERIFIER_GFP );if (!insns)return -ENOMEM ; pl->insns = insns;
@@ -619,7 +619,7 @@ static int patch_image_map_linfo(struct bpf_patch_image *img, const struct bpf_pconst struct bpf_line_info *linfo = prog->aux->linfo;u32 i, j, pos, next, nr = prog->aux->nr_linfo; - img->new_linfo =kvmalloc_array (nr +1 ,sizeof (u32),GFP_KERNEL_ACCOUNT ); + img->new_linfo =kvmalloc_array (nr +1 ,sizeof (u32),BPF_VERIFIER_GFP );if (!img->new_linfo)return -ENOMEM ; img->nr_linfo = nr;
@@ -656,8 +656,8 @@ int bpf_patch_list_build(const struct bpf_patch_list *pl, const struct bpf_progmemset (img,0 ,sizeof (*img)); img->cnt = cnt; - img->new_off =kvmalloc_array (cnt +1 ,sizeof (u32),GFP_KERNEL_ACCOUNT ); - img->new_tgt =kvmalloc_array (cnt +1 ,sizeof (u32),GFP_KERNEL_ACCOUNT ); + img->new_off =kvmalloc_array (cnt +1 ,sizeof (u32),BPF_VERIFIER_GFP ); + img->new_tgt =kvmalloc_array (cnt +1 ,sizeof (u32),BPF_VERIFIER_GFP );if (!img->new_off || !img->new_tgt)return -ENOMEM ;
@@ -678,7 +678,7 @@ int bpf_patch_list_build(const struct bpf_patch_list *pl, const struct bpf_progreturn err; } - img->insns =kvmalloc_array (img->new_cnt,sizeof (*img->insns),GFP_KERNEL_ACCOUNT ); + img->insns =kvmalloc_array (img->new_cnt,sizeof (*img->insns),BPF_VERIFIER_GFP );if (!img->insns)return -ENOMEM ;
@@ -3017,10 +3017,10 @@ static struct bpf_prog *bpf_prog_jit_compile(struct bpf_verifier_env *env, struc prog =bpf_jit_blind_constants (env, prog);/* * Fall back to the interpreter after blinding failures, except when -* the loader was killed. +* the load has to stop or has no memory. */ if (IS_ERR (prog)) { -if (PTR_ERR (prog) == -EINTR ) +if (PTR_ERR (prog) == -EINTR || (env &&PTR_ERR (prog) == -ENOMEM ))return prog; goto out_restore; }
kernel/bpf/diagnostics.c +4 -4
@@ -234,7 +234,7 @@ int bpf_diag_init(struct bpf_verifier_env *env)if (!bpf_diag_enabled (env))return 0 ; - env->diag = kzalloc_obj(struct bpf_diag, GFP_KERNEL_ACCOUNT); + env->diag = kzalloc_obj(struct bpf_diag, BPF_VERIFIER_GFP);if (!env->diag)return -ENOMEM ;
@@ -266,7 +266,7 @@ static char *diag_fmt_alloc(struct bpf_verifier_env *env, size_t size) } capacity =max_t (size_t,BPF_DIAG_FMT_CHUNK_SIZE , size); - chunk =kmalloc_flex (*chunk, data, capacity,GFP_KERNEL_ACCOUNT ); + chunk =kmalloc_flex (*chunk, data, capacity,BPF_VERIFIER_GFP );if (!chunk)return NULL ;
@@ -456,7 +456,7 @@ static void diag_append_history(struct bpf_verifier_env *env, goto rotate; cap =min (log->cap ? log->cap *2 :64 , max_events); - events =kvrealloc (log->events,array_size (cap,sizeof (*events)),GFP_KERNEL_ACCOUNT ); + events =kvrealloc (log->events,array_size (cap,sizeof (*events)),BPF_VERIFIER_GFP );if (!events) { log->growth_failed = true; goto rotate;
@@ -542,7 +542,7 @@ static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt,if (!bpf_diag_enabled (env))return ; - buf =kvasprintf (GFP_KERNEL_ACCOUNT , fmt, args); + buf =kvasprintf (BPF_VERIFIER_GFP , fmt, args);if (!buf) {diag_write (env,"%s<failed to allocate diagnostic text>\n" ,BPF_DIAG_TEXT_INDENT );return ;
kernel/bpf/fixups.c +11 -11
@@ -507,11 +507,11 @@ int bpf_patch_list_commit(struct bpf_verifier_env *env) err = -ENOMEM ; data =__vmalloc (array_size (img.new_cnt,sizeof (*data)), -GFP_KERNEL_ACCOUNT | __GFP_ZERO); +BPF_VERIFIER_GFP | __GFP_ZERO);if (!data) goto out; - prog =bpf_prog_realloc (prog,bpf_prog_size (img.new_cnt),GFP_USER ); + prog =bpf_prog_realloc (prog,bpf_prog_size (img.new_cnt),GFP_USER |BPF_GFP_MAYFAIL );if (!prog) goto out; env->prog = prog;
@@ -651,7 +651,7 @@ int bpf_insert_loop_guards(struct bpf_verifier_env *env)* Where the subprog has 'r0 = 0; exit', 0 if it has none. And how far that moved * the subprog: guard_to is from the time before. */ - leave =kvcalloc (2 * env->subprog_cnt,sizeof (int ),GFP_KERNEL_ACCOUNT ); + leave =kvcalloc (2 * env->subprog_cnt,sizeof (int ),BPF_VERIFIER_GFP );if (!leave)return -ENOMEM ; moved = leave + env->subprog_cnt;
@@ -689,9 +689,9 @@ int bpf_insert_loop_guards(struct bpf_verifier_env *env) }/* where the guard of the insn goes */ - target =kvcalloc (len,sizeof (int ),GFP_KERNEL_ACCOUNT ); - zero =kvcalloc (len,sizeof (u16),GFP_KERNEL_ACCOUNT ); - patch =kvcalloc (8 ,sizeof (*patch),GFP_KERNEL_ACCOUNT ); + target =kvcalloc (len,sizeof (int ),BPF_VERIFIER_GFP ); + zero =kvcalloc (len,sizeof (u16),BPF_VERIFIER_GFP ); + patch =kvcalloc (8 ,sizeof (*patch),BPF_VERIFIER_GFP );if (!target || !zero || !patch) { err = -ENOMEM ; goto out;
@@ -1259,7 +1259,7 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env)unsigned long *removed;int i, next, err =0 ; - removed =kvcalloc (BITS_TO_LONGS (insn_cnt),sizeof (long ),GFP_KERNEL_ACCOUNT ); + removed =kvcalloc (BITS_TO_LONGS (insn_cnt),sizeof (long ),BPF_VERIFIER_GFP );if (!removed)return -ENOMEM ;
@@ -1768,7 +1768,7 @@ static u32 *bpf_dup_subprog_starts(struct bpf_verifier_env *env) {u32 *starts =NULL ; - starts =kvmalloc_objs (u32, env->subprog_cnt,GFP_KERNEL_ACCOUNT ); + starts =kvmalloc_objs (u32, env->subprog_cnt,BPF_VERIFIER_GFP );if (starts) {for (int i =0 ; i < env->subprog_cnt; i++) starts[i] = env->subprog_info[i].start;
@@ -1902,7 +1902,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)* subprogs don't have IDs and not reachable via prog_get_next_id * func[i]->stats will never be accessed and stays NULL */ - func[i] =bpf_prog_alloc_no_stats (bpf_prog_size (len),GFP_USER ); + func[i] =bpf_prog_alloc_no_stats (bpf_prog_size (len),GFP_USER |BPF_GFP_MAYFAIL );if (!func[i]) goto out_free; memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
@@ -2215,7 +2215,7 @@ int bpf_fixup_call_args(struct bpf_verifier_env *env) err =bpf_jit_subprogs (env);if (err ==0 )return 0 ; -if (err == -EFAULT || err == -EINTR ) +if (err == -EFAULT || err == -EINTR || err == -ENOMEM )return err; }#ifndef CONFIG_BPF_JIT_ALWAYS_ON
@@ -2859,7 +2859,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) }if (!tmg) { tmg = alloc_percpu_gfp(struct bpf_timed_may_goto, -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP );if (!tmg)return -ENOMEM ; prog->aux->timed_may_goto = tmg;
kernel/bpf/flow.c +35 -35
175 lines not on this page · raw message
kernel/bpf/join.c +1 -1
@@ -46,7 +46,7 @@ struct bpf_join_state {static struct bpf_join_state *join_state (struct bpf_verifier_env *env) {if (!env->join) { - env->join =kvzalloc_obj (*env->join,GFP_KERNEL_ACCOUNT ); + env->join =kvzalloc_obj (*env->join,BPF_VERIFIER_GFP );if (env->join) env->join->env = env; }
kernel/bpf/liveness.c +13 -13
@@ -121,7 +121,7 @@ static struct func_instance *call_instance(struct bpf_verifier_env *env,if (f)return f; - f =kvzalloc_obj (*f,GFP_KERNEL_ACCOUNT ); + f =kvzalloc_obj (*f,BPF_VERIFIER_GFP );if (!f)return ERR_PTR (-ENOMEM ); f->callsite = lookup_key;
@@ -155,7 +155,7 @@ static struct func_instance *lookup_instance(struct bpf_verifier_env *env,int bpf_stack_liveness_init (struct bpf_verifier_env *env) { - env->liveness =kvzalloc_obj (*env->liveness,GFP_KERNEL_ACCOUNT ); + env->liveness =kvzalloc_obj (*env->liveness,BPF_VERIFIER_GFP );if (!env->liveness)return -ENOMEM ;hash_init (env->liveness->func_instances);
@@ -216,7 +216,7 @@ static struct frame_masks *widen_frame_masks(struct func_instance *instance,if (old && old->words >= words)return old; - new =kvzalloc_flex (*new, bits,frame_mask_words (instance, words),GFP_KERNEL_ACCOUNT ); + new =kvzalloc_flex (*new, bits,frame_mask_words (instance, words),BPF_VERIFIER_GFP );if (!new)return NULL ; new->words = words;
@@ -815,7 +815,7 @@ static int print_instances(struct bpf_verifier_env *env) cnt =0 ;hash_for_each (liveness->func_instances, bkt, instance, hl_node) cnt++; - sorted_instances =kvmalloc_objs (*sorted_instances, cnt,GFP_KERNEL_ACCOUNT ); + sorted_instances =kvmalloc_objs (*sorted_instances, cnt,BPF_VERIFIER_GFP );if (!sorted_instances)return -ENOMEM ; cnt =0 ;
@@ -2081,15 +2081,15 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,bool changed;int i, p, r, err = -ENOMEM ; - at_in =kvmalloc_objs (*at_in, len,GFP_KERNEL_ACCOUNT ); + at_in =kvmalloc_objs (*at_in, len,BPF_VERIFIER_GFP );if (!at_in) goto err_free; - at_stack_in =kvmalloc_objs (*at_stack_in, (size_t )len * nslots,GFP_KERNEL_ACCOUNT ); + at_stack_in =kvmalloc_objs (*at_stack_in, (size_t )len * nslots,BPF_VERIFIER_GFP );if (!at_stack_in) goto err_free; - at_stack_out =kvmalloc_objs (*at_stack_out, nslots,GFP_KERNEL_ACCOUNT ); + at_stack_out =kvmalloc_objs (*at_stack_out, nslots,BPF_VERIFIER_GFP );if (!at_stack_out) goto err_free;
@@ -2190,7 +2190,7 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,struct spill_snapshot *snap;kvfree (env->callsite_at_stack[idx]); - env->callsite_at_stack[idx] =kvmalloc_flex (*snap, at, nslots,GFP_KERNEL_ACCOUNT ); + env->callsite_at_stack[idx] =kvmalloc_flex (*snap, at, nslots,BPF_VERIFIER_GFP ); snap = env->callsite_at_stack[idx];if (!snap) { err = -ENOMEM ;
@@ -2321,7 +2321,7 @@ static struct func_instance *fresh_instance(struct func_instance *src) {struct func_instance *f; - f =kvzalloc_obj (*f,GFP_KERNEL_ACCOUNT ); + f =kvzalloc_obj (*f,BPF_VERIFIER_GFP );if (!f)return ERR_PTR (-ENOMEM ); f->callsite = src->callsite;
@@ -2546,15 +2546,15 @@ int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env)struct subprog_at_info *info;int k, err =0 ; - info =kvzalloc_objs (*info, env->subprog_cnt,GFP_KERNEL_ACCOUNT ); + info =kvzalloc_objs (*info, env->subprog_cnt,BPF_VERIFIER_GFP );if (!info)return -ENOMEM ; env->callsite_at_stack =kvzalloc_objs (*env->callsite_at_stack, insn_cnt, -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP ); env->liveness->callee_args =kvcalloc (MAX_CALL_FRAMES *MAX_AT_TRACK_REGS ,sizeof (*env->liveness->callee_args), -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP );if (!env->callsite_at_stack || !env->liveness->callee_args) { err = -ENOMEM ; insn_cnt = env->callsite_at_stack ? insn_cnt :0 ;
@@ -2839,7 +2839,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)* - repeat the computation while {in,out} fields changes for * any instruction. */ - state =kvzalloc_objs (*state, insn_cnt,GFP_KERNEL_ACCOUNT ); + state =kvzalloc_objs (*state, insn_cnt,BPF_VERIFIER_GFP );if (!state) { err = -ENOMEM ; goto out;
kernel/bpf/log.c +1 -1
@@ -195,7 +195,7 @@ int bpf_vlog_stash(struct bpf_verifier_log *log, u64 pos, struct bpf_vlog_stash stash->lost_end = log->end_pos - to; stash->len = to - from;/* as large as the buffer at worst: fail before the OOM killer is called */ - stash->buf =kvzalloc (stash->len,GFP_KERNEL_ACCOUNT | __GFP_NOWARN | __GFP_RETRY_MAYFAIL); + stash->buf =kvzalloc (stash->len,BPF_VERIFIER_GFP );if (!stash->buf)return -ENOMEM ;/* two pieces if it wraps around */
kernel/bpf/loops.c +8 -8
@@ -28,7 +28,7 @@ static struct bpf_iarray **compute_predecessors(struct bpf_verifier_env *env)size_t sz;void *tmp; - num_preds =kvzalloc_objs (u32, prog->len,GFP_KERNEL_ACCOUNT ); + num_preds =kvzalloc_objs (u32, prog->len,BPF_VERIFIER_GFP );if (!num_preds)return NULL ;
@@ -49,7 +49,7 @@ static struct bpf_iarray **compute_predecessors(struct bpf_verifier_env *env) i++; } - result =kvzalloc (sz,GFP_KERNEL_ACCOUNT ); + result =kvzalloc (sz,BPF_VERIFIER_GFP );if (!result) {kvfree (num_preds);return NULL ;
@@ -151,7 +151,7 @@ int bpf_compute_idoms(struct bpf_verifier_env *env)if (!preds)return -ENOMEM ; - idoms =kvzalloc_objs (*idoms, len,GFP_KERNEL_ACCOUNT ); + idoms =kvzalloc_objs (*idoms, len,BPF_VERIFIER_GFP );if (!idoms) {kvfree (preds);return -ENOMEM ;
@@ -212,7 +212,7 @@ static int add_exit(struct bpf_loop *loop, int from, int to) }if (!loop->exits) { loop->exits =kvzalloc_objs (*loop->exits,MAX_LOOP_EXITS , -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP );if (!loop->exits)return -ENOMEM ; }
@@ -229,7 +229,7 @@ static int mark_as_header(struct bpf_verifier_env *env, int h)struct bpf_insn_aux_data *aux = env->insn_aux_data;if (!aux[h].loop) { - aux[h].loop = kvzalloc_obj(struct bpf_loop, GFP_KERNEL_ACCOUNT); + aux[h].loop = kvzalloc_obj(struct bpf_loop, BPF_VERIFIER_GFP);if (!aux[h].loop)return -ENOMEM ; }
@@ -542,9 +542,9 @@ int bpf_compute_loops(struct bpf_verifier_env *env)struct bpf_iarray *succ;struct bpf_loop *loop; - dfs.dfs_pos =kvzalloc_objs (int, len,GFP_KERNEL_ACCOUNT ); - dfs.state = kvzalloc_objs(struct dfs_state, len, GFP_KERNEL_ACCOUNT); - dfs.stack =kvzalloc_objs (int, len,GFP_KERNEL_ACCOUNT ); + dfs.dfs_pos =kvzalloc_objs (int, len,BPF_VERIFIER_GFP ); + dfs.state = kvzalloc_objs(struct dfs_state, len, BPF_VERIFIER_GFP); + dfs.stack =kvzalloc_objs (int, len,BPF_VERIFIER_GFP );if (!dfs.dfs_pos || !dfs.state || !dfs.stack) { err = -ENOMEM ; goto out;
kernel/bpf/scev.c +11 -11
@@ -275,7 +275,7 @@ static void exprs_ht_add(struct scev *scev, u32 id)/* @cap is a power of two. No warning for a size that kvmalloc() rejects. */ static int grow_exprs (struct scev *scev,u32 cap) { -gfp_t gfp =GFP_KERNEL_ACCOUNT | __GFP_NOWARN; +gfp_t gfp =BPF_VERIFIER_GFP ;void *tmp;u32 id;
@@ -957,11 +957,11 @@ static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idxif (e)return e; - e =kzalloc_obj (*e,GFP_KERNEL_ACCOUNT ); + e =kzalloc_obj (*e,BPF_VERIFIER_GFP );if (!e)return NULL ; - tmp =krealloc (envs,struct_size (envs, entries, cnt +1 ),GFP_KERNEL_ACCOUNT | __GFP_ZERO); + tmp =krealloc (envs,struct_size (envs, entries, cnt +1 ),BPF_VERIFIER_GFP | __GFP_ZERO);if (!tmp) {kfree (e);return NULL ;
@@ -1812,7 +1812,7 @@ static int worklist_push(struct bpf_verifier_env *env, int loop_header, int idx)int *data; data =kvrealloc (worklist->data,array_size (size,sizeof (*data)), -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP );if (!data)return -ENOMEM ; worklist->data = data;
@@ -2300,7 +2300,7 @@ static int grow_array(void *p, u32 cnt, u32 *cap, size_t size)if (cnt < *cap)return 0 ; - tmp =kvrealloc (*(void **)p,array_size (new_cap, size),GFP_KERNEL_ACCOUNT ); + tmp =kvrealloc (*(void **)p,array_size (new_cap, size),BPF_VERIFIER_GFP );if (!tmp)return -ENOMEM ; *(void **)p = tmp;
@@ -2567,7 +2567,7 @@ static int find_linked_regs(struct bpf_verifier_env *env, struct env *e, int h, q->refine =test_bit (k, roots); }if (!envs) { - envs =kzalloc (sizeof (*envs),GFP_KERNEL_ACCOUNT ); + envs =kzalloc (sizeof (*envs),BPF_VERIFIER_GFP );if (!envs)return -ENOMEM ; scev->envs[idx] = envs;
@@ -2634,11 +2634,11 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header, iif (!cur_loop && !can_compute_subprog_scev (env, sub))return 0 ; - cur_env =kzalloc_obj (*cur_env,GFP_KERNEL_ACCOUNT ); + cur_env =kzalloc_obj (*cur_env,BPF_VERIFIER_GFP );if (!cur_env) goto nomem;if (log_level2) { - old_env =kzalloc_obj (*old_env,GFP_KERNEL_ACCOUNT ); + old_env =kzalloc_obj (*old_env,BPF_VERIFIER_GFP );if (!old_env) goto nomem; }
@@ -3351,7 +3351,7 @@ int bpf_init_scev(struct bpf_verifier_env *env)struct scev *scev;u32 r; - scev = kzalloc_obj(struct scev, GFP_KERNEL_ACCOUNT); + scev = kzalloc_obj(struct scev, BPF_VERIFIER_GFP);if (!scev)return -ENOMEM ; env->scev = scev;
@@ -3369,9 +3369,9 @@ int bpf_init_scev(struct bpf_verifier_env *env)set_expr_base (scev, &scev->exprs[r], r); scev->exprs_cnt =REG_EXPR_ID (REGS_NUM ); scev->envs =kvzalloc_objs (*scev->envs, env->prog->len, -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP ); scev->discovered =kvzalloc_objs (*scev->discovered, env->prog->len, -GFP_KERNEL_ACCOUNT ); +BPF_VERIFIER_GFP );if (!scev->envs || !scev->discovered) goto nomem;/*
kernel/bpf/syscall.c +3 -3
@@ -3074,13 +3074,13 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at }/* plain bpf_prog allocation */ - prog =bpf_prog_alloc (bpf_prog_size (attr->insn_cnt),GFP_USER ); + prog =bpf_prog_alloc (bpf_prog_size (attr->insn_cnt),GFP_USER |BPF_GFP_MAYFAIL );if (!prog) {if (dst_prog)bpf_prog_put (dst_prog);if (attach_btf)btf_put (attach_btf); - err = -EINVAL ; + err = -ENOMEM ; goto put_token; }
@@ -3103,7 +3103,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at prog->aux->user =get_current_user (); prog->len = attr->insn_cnt; - err =bpf_prog_stream_init (prog,GFP_USER ); + err =bpf_prog_stream_init (prog,GFP_USER |BPF_GFP_MAYFAIL );if (err) goto free_prog;
kernel/bpf/verifier.c +37 -37
287 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next v2 02/21] bpf: Fail the load when there is no memory
TL;DR: - Unconverted CO-RE (bpf_core_apply) allocations may still wake the memcg OOM killer during load - Constant-blinding allocations lack a mayfail flag, so ENOMEM-fails-load may still hit global…
Quoted 1 line
bpf: Fail the load when there is no memory
TL;DR:
- Unconverted CO-RE (bpf_core_apply) allocations may still wake the memcg OOM killer during load
- Constant-blinding allocations lack a mayfail flag, so ENOMEM-fails-load may still hit global OOM
- Commit message overclaims "all allocations"
Quoted 3 lines
kernel/bpf/core.c +0
-0
[ ... ]
kernel/bpf/core.c static struct bpf_prog *bpf_prog_jit_compile(struct bpf_verifier_env *env, struc · line 3026
Quoted 13 lines
kernel/bpf/core.c +2
-2@@ -3017,10 +3017,10 @@ static struct bpf_prog *bpf_prog_jit_compile(struct bpf_verifier_env *env, struc prog =bpf_jit_blind_constants (env, prog);/* * Fall back to the interpreter after blinding failures, except when -* the loader was killed. +* the load has to stop or has no memory. */ if (IS_ERR (prog)) { -if (PTR_ERR (prog) == -EINTR ) +if (PTR_ERR (prog) == -EINTR || (env &&PTR_ERR (prog) == -ENOMEM ))return prog; goto out_restore; }
The commit message says "Use one mask for all allocations of the verifier", and this hunk makes -ENOMEM from bpf_jit_blind_constants() fatal for the load. Are the allocations inside bpf_jit_blind_constants() covered by that rule?
bpf_jit_blind_constants():
linfo_unblinded = kvmalloc_array(nr_linfo, sizeof(*linfo_unblinded),
GFP_USER);
...
clone = bpf_prog_clone_create(prog, GFP_USER); bpf_prog_clone_create():
gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags);Neither call has __GFP_RETRY_MAYFAIL or __GFP_NOWARN, so under global memory pressure they can still reach the OOM killer or print an allocation failure warning before returning the -ENOMEM that now fails the load.
The path is bpf_check() -> __bpf_prog_select_runtime(env, ...) -> bpf_prog_jit_compile() -> bpf_jit_blind_constants() whenever blinding is requested (bpf_jit_harden). bpf_jit_subprogs() reaches the same allocations for programs with subprogs. These allocations are not memcg-charged (bpf_prog_clone_create() does not use bpf_memcg_flags()), so the memcg case from the commit message is not hit.
Other verifier-path allocations that keep a plain mask are bpf_jit_add_poke_descriptor() (krealloc_array(..., GFP_KERNEL), called from bpf_do_misc_fixups()) and the func[] array in jit_subprogs(). The func[] array is converted later in the series by 8aac70a8f47f ("bpf: Remove BPF_MAX_SUBPROGS"); bpf_jit_blind_constants() is not converted anywhere in the series.
Should the env path of bpf_jit_blind_constants() passGFP_USER | BPF_GFP_MAYFAIL, as bpf_patch_list_commit() already does for bpf_prog_realloc()? Otherwise the commit message could limit its claim to the GFP_KERNEL_ACCOUNT sites.
Quoted 7 lines
The verifier allocates with
GFP_KERNEL_ACCOUNT. At the limit of the memory cgroup this wakes up the OOM killer, and the loader dies:
memory.max = 64M, program needs 120M
before: Killed
after:bpf()=-ENOMEM
Use one mask for all allocations of the verifier. Most of the patch is:
sed -i 's/GFP_KERNEL_ACCOUNT/BPF_VERIFIER_GFP/'
Can a CO-RE load at memory.max still be OOM-killed from inside the verifier? The patch does not convert the GFP_KERNEL_ACCOUNT allocations reached through:
bpf_prog_load() -> bpf_check() -> bpf_check_core_relo() ->
bpf_core_apply()
kernel/bpf/btf.c:bpf_core_apply() {
...
specs = kzalloc_objs(*specs, 3, GFP_KERNEL_ACCOUNT);
...
cands.cands = kzalloc_objs(*cands.cands, cc->cnt, GFP_KERNEL_ACCOUNT);
...
}bpf_core_find_cands() also reaches populate_cand_cache() (kmemdup() and kmemdup_nul() with GFP_KERNEL_ACCOUNT) and bpf_core_add_cands() (kmalloc() with GFP_KERNEL_ACCOUNT).
bpf_check_core_relo() runs for every load with attr->core_relo_cnt != 0, which includes light skeletons and loader programs. try_charge_memcg() only skips mem_cgroup_oom() for __GFP_NORETRY or __GFP_RETRY_MAYFAIL:
if (gfp_mask & __GFP_RETRY_MAYFAIL)
goto nomem;
None of these masks carries __GFP_RETRY_MAYFAIL, so the memcg OOM killer can still be woken from the verifier, which is the "Killed" outcome the commit message says is removed. The tree at the end of the series still has GFP_KERNEL_ACCOUNT in bpf_core_apply().
Separately, bpf_prog_verify_signature() converts the "data" kvmalloc() but leaves sig = kvmemdup_bpfptr(usig, attr->signature_size), which allocates with GFP_USER | __GFP_NOWARN. That is not memcg-accounted, so it cannot cause the memcg kill, but it is another verifier allocation that does not use the one mask.
Should the bpf_core_apply() and candidate cache allocations be converted to BPF_VERIFIER_GFP, or should the commit message be narrowed so it does not claim all allocations of the verifier?
---
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/43899902250
PATCH v2 3/21 bpf: Give a syscall program the largest context when it does tail calls
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
BPF_PROG_RUN compares ctx_size_in with max_ctx_offset of the program that it runs. The target of a tail call gets the same context:
first: bpf_tail_call(ctx, ...) max_ctx_offset 0, ctx_size_in 8 target: r0 = *(u32 *)(ctx + 60000) out of bounds
The target is not known before the run. Pad the copy of the context with zeros up to U16_MAX, no program can use more. kern_sys_bpf() makes no copy, so its caller has to pass that much. An extension cannot add tail calls to a program that has none.
The copy is accounted now. It comes from kmalloc-cg or vmalloc, not from the caches of memdup_user().
--- kernel/bpf/syscall.c | 7 +++++++ net/bpf/test_run.c | 20 ++++++++++++++------ 2 files changed, 21 insertions(+), 6 deletions(-)
kernel/bpf/syscall.c +7 -0
@@ -3859,6 +3859,12 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog, err = -EINVAL ; goto out_unlock; } +/* The same for tail calls, see bpf_prog_test_run_syscall(). */ +if (prog->type ==BPF_PROG_TYPE_EXT && tgt_prog->type ==BPF_PROG_TYPE_SYSCALL && + prog->aux->tail_call_reachable && !tgt_prog->aux->tail_call_reachable) { + err = -EINVAL ; + goto out_unlock; + } err =bpf_link_prime (&link->link.link, &link_primer);if (err)
@@ -6669,6 +6675,7 @@ int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)return PTR_ERR (prog);if (attr->test.ctx_size_in < prog->aux->max_ctx_offset || + (prog->aux->tail_call_reachable && attr->test.ctx_size_in <U16_MAX ) || attr->test.ctx_size_in >U16_MAX ) {bpf_prog_put (prog);return -EINVAL ;
net/bpf/test_run.c +14 -6
@@ -1687,8 +1687,8 @@ int bpf_prog_test_run_syscall(struct bpf_prog *prog, {void __user *ctx_in =u64_to_user_ptr (kattr->test.ctx_in);__u32 ctx_size_in = kattr->test.ctx_size_in; +u32 retval, size = ctx_size_in;void *ctx =NULL ; -u32 retval;int err =0 ;/* doesn't support data_in/out, ctx_out, duration, or repeat or flags */
@@ -1702,10 +1702,18 @@ int bpf_prog_test_run_syscall(struct bpf_prog *prog, ctx_size_in > U16_MAX)return -EINVAL ; -if (ctx_size_in) { - ctx =memdup_user (ctx_in, ctx_size_in); -if (IS_ERR (ctx)) -return PTR_ERR (ctx); +/* the target of a tail call can use that much */ +if (prog->aux->tail_call_reachable) + size =max_t (u32, size,U16_MAX ); + +if (size) { + ctx =kvzalloc (size,GFP_KERNEL_ACCOUNT | __GFP_NOWARN); +if (!ctx) +return -ENOMEM ; +if (copy_from_user (ctx, ctx_in, ctx_size_in)) { + err = -EFAULT ; + goto out; + } }rcu_read_lock_trace ();
@@ -1720,7 +1728,7 @@ int bpf_prog_test_run_syscall(struct bpf_prog *prog,if (copy_to_user (ctx_in, ctx, ctx_size_in)) err = -EFAULT ; out: -kfree (ctx); +kvfree (ctx);return err; }
Signature · 1 line
2.55.0
PATCH v2 4/21 bpf: Do not inline bpf_loop() when its callback is dead code
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The main pass does not enter the callback of bpf_loop(0, cb). When cb comes from a table of functions, nothing keeps it and it is removed. The inlined loop still has 'call cb'. The call goes to the next function, or the load fails with 'verifier bug: No program to jit'.
Leave the call of the helper. It does not look at cb.
--- kernel/bpf/fixups.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
kernel/bpf/fixups.c +5 -1
@@ -3610,8 +3610,12 @@ int bpf_optimize_bpf_loop(struct bpf_verifier_env *env)struct bpf_loop_inline_state *inline_state = &env->insn_aux_data[i].loop_inline_state; -/* the callback that takes a stack in arena is not for a call from the program */ +/* +* The callback that takes a stack in arena is not for a call from the program. +* The callback of a loop without iterations is dead code, it goes away. +*/ if (is_bpf_loop_call (insn) && inline_state->fit_for_inline && + env->insn_aux_data[subprogs[inline_state->callback_subprogno].start].seen && !subprogs[inline_state->callback_subprogno].arena_stack_entry) { stack_depth_extra =BPF_REG_SIZE *3 + stack_depth_roundup; err = inline_bpf_loop(env, i,
Signature · 1 line
2.55.0
PATCH v2 5/21 bpf: Dump programs that have more than 524288 insns
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
kmemdup() stops at 4 MB. A program that loads cannot be dumped.
--- kernel/bpf/syscall.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
kernel/bpf/syscall.c +2 -3
@@ -5076,8 +5076,7 @@ static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,u8 code;int i; - insns =kmemdup (prog->insnsi,bpf_prog_insn_size (prog), -GFP_USER ); + insns =kvmemdup (prog->insnsi,bpf_prog_insn_size (prog),GFP_USER | __GFP_NOWARN);if (!insns)return insns;
@@ -5252,7 +5251,7 @@ static int bpf_prog_get_info_by_fd(struct file *file, uinsns =u64_to_user_ptr (info.xlated_prog_insns); ulen =min_t (u32, info.xlated_prog_len, ulen); fault =copy_to_user (uinsns, insns_sanitized, ulen); -kfree (insns_sanitized); +kvfree (insns_sanitized);if (fault)return -EFAULT ; }else {
Signature · 1 line
2.55.0
PATCH v2 6/21 bpf: Resolve BTF structs and arrays first
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
btf_resolve() does not see this loop:
ptr -> typedef -> array -+
^--------------+
The walk from the pointer stops at the array and marks the typedef as resolved. Only the limits of the later walks end the loop. The walk for special fields is going to lose its limit.
Resolve structs and arrays first. Then a type that holds itself is always found. Such BTF does not load any more.
--- kernel/bpf/btf.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
kernel/bpf/btf.c +16 -0
@@ -6015,6 +6015,22 @@ static int btf_check_all_types(struct btf_verifier_env *env)return err; env->phase++; +/* +* Structs and arrays go first. A walk from a pointer stops at them and hides this loop: +* ptr -> typedef -> array -+ +* ^--------------+ +*/ +for (i = btf->base_btf ?0 :1 ; i < btf->nr_types; i++) { + type_id = btf->start_id + i; + t =btf_type_by_id (btf, type_id); + +if ((btf_type_is_struct (t) ||btf_type_is_array (t)) && + !env_type_is_resolved (env, type_id)) { + err =btf_resolve (env, t, type_id); +if (err) +return err; + } + }for (i = btf->base_btf ?0 :1 ; i < btf->nr_types; i++) { type_id = btf->start_id + i; t =btf_type_by_id (btf, type_id);
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next v2 06/21] bpf: Resolve BTF structs and arrays first
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] bpf: missing Fixes trailer for BTF loop detection in btf_check_all_types() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] bpf: missing Fixes trailer for BTF loop detection in btf_check_all_types()
--
commit f2b6216605cc6af96cb5995fe77081d986ad71b1
Author: Alexei Starovoitov <[email protected]>
Quoted 7 lines
bpf: Resolve BTF structs and arrays first
btf_resolve()does not see this loop:ptr -> typedef -> array -+
^--------------+
Quoted 8 lines
The walk from the pointer stops at the array and marks the typedef as resolved. Only the limits of the later walks end the loop. The walk for special fields is going to lose its limit.
Resolve structs and arrays first. Then a type that holds itself is always found. Such BTF does not load any more.
Signed-off-by Alexei Starovoitov <[email protected]>
[Severity: Low]
This fixes a bug in BTF type resolution where resolving a pointer first marks intermediate modifiers as resolved and hides self-referential loops through structs or arrays. Should this include:
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
PATCH v2 7/21 bpf: Remove the limits on maps, BTFs and fd_array of a program
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A program can use 64 maps, 64 BTF objects and 4096 entries of fd_array. Each jump table and each .data.X section is a map. Nothing needs these numbers at run time.
Add two small tools:
bpf_table_next() a table that doubles
bpf_index key -> number of an entry, a hash table
ld_imm64 map --> used_index[address of map] --> used_maps[i]
The program takes the tables from the verifier, there is no copy. The table of fd_array grows with the entries that are read. Unprivileged programs have 4096 insns, they keep 4096 entries.
--- include/linux/bpf_verifier.h | 39 +++++- kernel/bpf/cfg.c | 39 ++++++ kernel/bpf/core.c | 4 +- kernel/bpf/syscall.c | 6 +- kernel/bpf/verifier.c | 119 ++++++------------ .../selftests/bpf/prog_tests/fd_array.c | 36 ++++-- 6 files changed, 137 insertions(+), 106 deletions(-)
include/linux/bpf_verifier.h +33 -6
@@ -742,6 +742,33 @@ struct bpf_iarray {u32 items[]; }; +/* +* Make room for entry 'cnt' of a table that has 'cnt' entries, return the new entry. +* The table doubles: 1, 2, 4, 8, ... It is not a stack: 'cnt' never goes down. +*/ +#define bpf_table_next (tab, cnt) \ + ({ \ + typeof(tab) __tab = (tab); \ + size_t __cap = 2 * (size_t)(cnt) ?: 1; \ + if (!((cnt) & ((cnt) - 1))) \ + __tab = kvrealloc(__tab, array_size(__cap, sizeof(*__tab)), \ + BPF_VERIFIER_GFP); \ + __tab ? &((tab) = __tab)[cnt] : NULL; \ + }) + +/* key -> number of an entry of a table */ +struct bpf_index { +struct bpf_index_slot { +u64 key; +u32 next_val;/* value + 1, 0 if the slot is free */ + } *slots; +u32 cnt; +u8 bits; +}; + +int bpf_index_find (const struct bpf_index *index,u64 key); +int bpf_index_add (struct bpf_index *index,u64 key,u32 val); +#define iarray_for_each (item, arr) \ for (int ___idx = 0; \ ___idx < (arr)->cnt && ({ item = (arr)->items[___idx]; 1; }); \
@@ -970,9 +997,6 @@ struct bpf_insn_aux_data {struct bpf_loop *loop; }; -#define MAX_USED_MAPS 64/* max number of maps accessed by one eBPF program */ -#define MAX_USED_BTFS 64/* max number of BTFs accessed by one BPF program */ -/* * Longest line the verifier log can carry: tmp_str_buf, see * TMP_STR_BUF_LEN, plus its prefix.
@@ -1259,9 +1283,12 @@ struct bpf_verifier_env {u32 *walk_insns;/* the insns that were looked at in each of them */ u32 max_arena_stack_depth;/* of all call chains */ struct bpf_verifier_state *cur_state;/* current verifier state */ -struct bpf_map *used_maps[MAX_USED_MAPS ];/* array of map's used by eBPF program */ -struct btf_mod_pair used_btfs[MAX_USED_BTFS ];/* array of BTF's used by BPF program */ -struct bpf_map *insn_array_maps[MAX_USED_MAPS ];/* array of INSN_ARRAY map's to be relocated */ +struct bpf_map **used_maps;/* array of map's used by eBPF program */ +struct btf_mod_pair *used_btfs;/* array of BTF's used by BPF program */ +struct bpf_index used_index;/* address of a map or BTF -> entry of these two */ +struct bpf_map **insn_array_maps;/* array of INSN_ARRAY map's to be relocated */ +u32 max_key_size;/* of all used maps and their inner maps */ +u32 max_value_size;u32 used_map_cnt;/* number of used maps */ u32 used_btf_cnt;/* number of used BTF objects */ u32 insn_array_map_cnt;/* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */
kernel/bpf/cfg.c +39 -0
@@ -3,6 +3,7 @@#include <linux/bpf.h> #include <linux/bpf_verifier.h> #include <linux/filter.h> +#include <linux/hash.h> #include <linux/sort.h> #include "diagnostics.h"
@@ -199,6 +200,44 @@ struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem)return new; } +static struct bpf_index_slot *index_slot (const struct bpf_index *index,u64 key) +{ +u32 i =hash_64 (key, index->bits); + +while (index->slots[i].next_val && index->slots[i].key != key) + i = (i +1 ) & (BIT (index->bits) -1 ); +return &index->slots[i]; +} + +/* Returns the value of 'key', -1 if there is none */ +int bpf_index_find (const struct bpf_index *index,u64 key) +{ +return index->cnt ?index_slot (index, key)->next_val -1 :-1 ; +} + +/* 'key' is new. At most a half of the slots is taken. */ +int bpf_index_add (struct bpf_index *index,u64 key,u32 val) +{ +struct bpf_index old = *index; +u32 i; + +if (2 * old.cnt >=BIT (old.bits) -1 ) { + index->slots =kvcalloc (BIT (old.bits +2 ),sizeof (*old.slots),BPF_VERIFIER_GFP ); +if (!index->slots) { + index->slots = old.slots; +return -ENOMEM ; + } + index->bits +=2 ; +for (i =0 ; old.cnt && i <BIT (old.bits); i++) +if (old.slots[i].next_val) + *index_slot (index, old.slots[i].key) = old.slots[i]; +kvfree (old.slots); + } + *index_slot (index, key) = (struct bpf_index_slot ){ key, val +1 }; + index->cnt++; +return 0 ; +} +static int copy_insn_array (struct bpf_map *map,u32 start,u32 end,u32 *items) {struct bpf_insn_array_value *value;
kernel/bpf/core.c +2 -2
@@ -3429,7 +3429,7 @@ void __bpf_free_used_maps(struct bpf_prog_aux *aux,static void bpf_free_used_maps (struct bpf_prog_aux *aux) {__bpf_free_used_maps (aux, aux->used_maps, aux->used_map_cnt); -kfree (aux->used_maps); +kvfree (aux->used_maps); }void __bpf_free_used_btfs (struct btf_mod_pair *used_btfs,u32 len)
@@ -3450,7 +3450,7 @@ void __bpf_free_used_btfs(struct btf_mod_pair *used_btfs, u32 len)static void bpf_free_used_btfs (struct bpf_prog_aux *aux) {__bpf_free_used_btfs (aux->used_btfs, aux->used_btf_cnt); -kfree (aux->used_btfs); +kvfree (aux->used_btfs); }static void bpf_prog_free_images (struct work_struct *work)
kernel/bpf/syscall.c +3 -3
@@ -6291,8 +6291,8 @@ static int bpf_prog_bind_map(union bpf_attr *attr) goto out_unlock; } - used_maps_new =kmalloc_objs (used_maps_new[0 ], - prog->aux->used_map_cnt +1 ); + used_maps_new =kvmalloc_objs (used_maps_new[0 ], + prog->aux->used_map_cnt +1 );if (!used_maps_new) { ret = -ENOMEM ; goto out_unlock;
@@ -6310,7 +6310,7 @@ static int bpf_prog_bind_map(union bpf_attr *attr) prog->aux->used_map_cnt++; prog->aux->used_maps = used_maps_new; -kfree (used_maps_old); +kvfree (used_maps_old); out_unlock:mutex_unlock (&prog->aux->used_maps_mutex);
kernel/bpf/verifier.c +37 -82
227 lines not on this page · raw message
tools/testing/selftests/bpf/prog_tests/fd_array.c +23 -13
@@ -376,6 +376,11 @@ static void check_fd_array_cnt__fd_array_with_trash(void)if (!ASSERT_EQ (prog_fd, -EINVAL ,"prog should have been rejected with -EINVAL" )) goto cleanup; +/* trash 3: the table grows with the entries that are read */ + prog_fd =load_test_prog ((int *)8 ,1 <<30 ); +if (!ASSERT_EQ (prog_fd, -EFAULT ,"prog should have been rejected with -EFAULT" )) + goto cleanup; +/* Validate that the prog is ok if trash is removed */ Close (extra_fds[2 ]); extra_fds[2 ] =new_btf ();
@@ -394,22 +399,27 @@ static void check_fd_array_cnt__fd_array_with_trash(void) }/* -* Test that a program with too big fd_array can't be loaded. +* Test that the numbers of maps, BTFs and entries of fd_array are not limited. */ -static void check_fd_array_cnt__fd_array_too_big (void ) +static void check_fd_array_cnt__fd_array_big (void ) { -int extra_fds[65 ]; -int prog_fd =-1 ; -int i; - -for (i =0 ; i <65 ; i++) { - extra_fds[i] =new_map (); -if (!ASSERT_GE (extra_fds[i],0 ,"new_map" )) +static int extra_fds[5000 ]; +const int objs =300 ; +__u32 nr_map_ids =0 ; +int prog_fd, i, j; + +for (i =0 ; i < objs; i++) { + extra_fds[i] = i %2 ?new_map () :new_btf (); +if (!ASSERT_GE (extra_fds[i],0 ,"new_obj" )) goto cleanup_fds; } +for (j = objs; j <ARRAY_SIZE (extra_fds); j++) + extra_fds[j] = extra_fds[j % objs]; - prog_fd =load_test_prog (extra_fds,65 ); -ASSERT_EQ (prog_fd, -E2BIG ,"prog should have been rejected with -E2BIG" ); + prog_fd =load_test_prog (extra_fds,ARRAY_SIZE (extra_fds)); +if (ASSERT_GE (prog_fd,0 ,"prog should have been loaded" )) +check_expected_map_ids (prog_fd, objs /2 +1 ,NULL , &nr_map_ids); +Close (prog_fd); cleanup_fds:while (i-- >0 )
@@ -436,6 +446,6 @@ void test_fd_array_cnt(void)if (test__start_subtest ("fd-array-trash-input" ))check_fd_array_cnt__fd_array_with_trash (); -if (test__start_subtest ("fd-array-2big" )) -check_fd_array_cnt__fd_array_too_big (); +if (test__start_subtest ("fd-array-big" )) +check_fd_array_cnt__fd_array_big (); }
Signature · 1 line
2.55.0
PATCH v2 8/21 bpf: Do not scan all maps for each insn and each subprog
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The number of maps has no limit now.
- The dump of a program looks for the map of each ld_imm64. Put the addresses of the maps into a tree.
- The JIT of each subprog needs the insn arrays only.
- The jump table of a subprog doubles.
--- kernel/bpf/cfg.c | 3 ++- kernel/bpf/fixups.c | 4 +-- kernel/bpf/syscall.c | 64 +++++++++++++++++++++----------------------- 3 files changed, 35 insertions(+), 36 deletions(-)
kernel/bpf/cfg.c +2 -1
@@ -366,13 +366,14 @@ static int __compute_subprog_jts(struct bpf_verifier_env *env) } old_cnt = subprog->jt ? subprog->jt->cnt :0 ; - jt =bpf_iarray_realloc (subprog->jt, old_cnt + jt_cur->cnt); + jt =bpf_iarray_realloc (subprog->jt,roundup_pow_of_two (old_cnt + jt_cur->cnt));if (!jt) { subprog->jt =NULL ;kvfree (jt_cur);return -ENOMEM ; }memcpy (jt->items + old_cnt, jt_cur->items, jt_cur->cnt <<2 ); + jt->cnt = old_cnt + jt_cur->cnt; subprog->jt = jt;kvfree (jt_cur);
kernel/bpf/fixups.c +2 -2
@@ -1950,8 +1950,8 @@ static int jit_subprogs(struct bpf_verifier_env *env) func[i]->aux->arena_stack_size = prog->aux->arena_stack_size; func[i]->aux->arena_stack_entry = env->subprog_info[i].arena_stack_entry; func[i]->aux->uses_arena_insns =bpf_prog_has_arena_insns (func[i]); - func[i]->aux->used_maps = env->used_maps; - func[i]->aux->used_map_cnt = env->used_map_cnt; + func[i]->aux->used_maps = env->insn_array_maps; + func[i]->aux->used_map_cnt = env->insn_array_map_cnt; num_exentries =0 ; insn = func[i]->insnsi;for (j =0 ; j < func[i]->len; j++, insn++) {
kernel/bpf/syscall.c +31 -33
100 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 9/21 bpf: Remove the limits on kfuncs of a program
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A program can call 256 kfuncs from 256 module BTFs. Calls in dead code count too. Each new kfunc sorts the table again.
Append to the tables and find the entries through one index:
(func_id, offset) -> descriptor (func_id, offset, specialized) -> descriptor of the other target (0, offset) -> BTF of the module
What stays is the width of insn->off, where JITs get the number of the descriptor: 65536 of them.
--- include/linux/bpf_verifier.h | 25 ++-- kernel/bpf/core.c | 2 +- kernel/bpf/fixups.c | 4 +- kernel/bpf/syscall.c | 2 +- kernel/bpf/verifier.c | 225 ++++++++++------------------------- 5 files changed, 79 insertions(+), 179 deletions(-)
include/linux/bpf_verifier.h +9 -16
@@ -1286,6 +1286,7 @@ struct bpf_verifier_env {struct bpf_map **used_maps;/* array of map's used by eBPF program */ struct btf_mod_pair *used_btfs;/* array of BTF's used by BPF program */ struct bpf_index used_index;/* address of a map or BTF -> entry of these two */ +struct bpf_index kfunc_index;/* see kfunc_key() */ struct bpf_map **insn_array_maps;/* array of INSN_ARRAY map's to be relocated */ u32 max_key_size;/* of all used maps and their inner maps */ u32 max_value_size;
@@ -2195,11 +2196,6 @@ enum bpf_reg_arg_type {DST_OP_NO_MARK /* same as above, check only, don't mark */ }; -#define MAX_KFUNC_DESCS 256 -/* Each kfunc can have its canonical and one specialized call target. */ -#define MAX_KFUNC_CALL_DESCS (MAX_KFUNC_DESCS * 2) -static_assert (MAX_KFUNC_CALL_DESCS <=S16_MAX +1 ); -struct bpf_kfunc_desc {struct btf_func_model func_model;struct bpf_func_proto proto;
@@ -2209,20 +2205,17 @@ struct bpf_kfunc_desc { };struct bpf_kfunc_desc_tab { +struct bpf_kfunc_desc *descs;u32 nr_descs; -u32 nr_base_descs; -/* Sorted by func_id (BTF ID) and offset (fd_array offset) during -* verification. JITs use the descriptor index stored in the finalized -* call's off field. The first nr_base_descs entries are the canonical -* descriptors used for verifier lookups. Call specialization may append -* immutable descriptors for additional targets. -* -* Grown one entry at a time by bpf_add_kfunc_call() and during -* call specialization. -*/ -struct bpf_kfunc_desc descs[]; }; +static inline void bpf_free_kfunc_tab (struct bpf_kfunc_desc_tab *tab) +{ +if (tab) +kvfree (tab->descs); +kfree (tab); +} +/* Functions exported from verifier.c, used by fixups.c */ void bpf_mark_subprog_exc_cb (struct bpf_verifier_env *env,int subprog);bool bpf_allow_tail_call_in_subprogs (struct bpf_verifier_env *env);
kernel/bpf/core.c +1 -1
@@ -195,7 +195,7 @@ void bpf_prog_jit_attempt_done(struct bpf_prog *prog) prog->aux->jited_linfo =NULL ; } -kfree (prog->aux->kfunc_tab); +bpf_free_kfunc_tab (prog->aux->kfunc_tab); prog->aux->kfunc_tab =NULL ; }
kernel/bpf/fixups.c +2 -2
@@ -122,10 +122,10 @@ bpf_jit_find_kfunc_model(const struct bpf_prog *prog,struct bpf_kfunc_desc_tab *tab; tab = prog->aux->kfunc_tab; -if (insn->off <0 || insn->off >= tab->nr_descs) +if ((u16 )insn->off >= tab->nr_descs)return NULL ; - res = &tab->descs[insn->off]; + res = &tab->descs[(u16 )insn->off];if (bpf_jit_supports_far_kfunc_call ()) {if (res->func_id != insn->imm)return NULL ;
kernel/bpf/syscall.c +1 -1
@@ -2489,7 +2489,7 @@ 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); -kfree (prog->aux->kfunc_tab); +bpf_free_kfunc_tab (prog->aux->kfunc_tab);kfree (prog->aux->ctx_arg_info);if (prog->aux->attach_btf)btf_put (prog->aux->attach_btf);
kernel/bpf/verifier.c +66 -159
363 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 10/21 bpf: Remove the limits on tables of functions
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
4096 sets of functions sets are in a hash table now 1024 targets of one load counted before duplicates were removed 4096 pointers near a load the scan is linear and can be killed 1M pointers in all maps the table grows
Nothing sorts the pointers: walk the maps in the order of their addresses, and collect the targets of a load in a bitmap.
The number of a subprog in a set has 32 bits.
--- include/linux/bpf_verifier.h | 5 +- kernel/bpf/verifier.c | 132 +++++++----------- .../selftests/bpf/progs/verifier_callx_many.c | 31 +++- 3 files changed, 82 insertions(+), 86 deletions(-)
include/linux/bpf_verifier.h +3 -2
@@ -1332,6 +1332,7 @@ struct bpf_verifier_env {/* What a pointer that was read from a table of functions may point to. */ struct bpf_func_set **func_sets;u32 func_set_cnt; +struct bpf_index func_set_index;bool has_callx;/* * Call graph edges created by callx instructions. A bitmap of
@@ -1718,8 +1719,8 @@ static inline bool bpf_register_is_null(struct bpf_reg_state *reg)bool bpf_map_is_rdonly (const struct bpf_map *map);/* Sorted, no function is there twice */ struct bpf_func_set { -u16 cnt; - u16 subprog[] __counted_by(cnt); +u32 cnt; + u32 subprog[] __counted_by(cnt); }; struct bpf_func_ptr *bpf_map_func_ptrs(struct bpf_verifier_env *env,
kernel/bpf/verifier.c +49 -83
247 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_callx_many.c +30 -1
@@ -47,7 +47,7 @@ REP400(MANY_FUNC)#define SETS400 (mask) "r7 = r6; r7 &= " #mask "; r7 += r8;" REP400(SET_LOAD) SEC("socket") -__failure __msg("more than 4096 sets of functions") +__success __retval(11) __naked void callx_rodata_4400_sets(void) { asm volatile (
@@ -65,6 +65,35 @@ __naked void callx_rodata_4400_sets(void) : __clobber_all); } +#define TABLE_5000 (name, last, mask) \ +__naked void name(void) \ +{ \ + asm volatile ( \ + RODATA(tab, ".rept 2500; .quad many000; .quad many001; .endr;" last) \ + "call %[bpf_get_prandom_u32];" \ + "r0 &= 8191;" \ + "if r0 < " #mask " goto +1;" \ + "r0 = 0;" \ + "r0 <<= 3;" \ + "r2 = tab_%= ll;" \ + "r2 += r0;" \ + "r2 = *(u64 *)(r2 + 0);" \ + "r1 = 10;" \ + "callx r2;" \ + "exit;" \ + : \ + : __imm(bpf_get_prandom_u32) \ + : __clobber_all); \ +} + +SEC("socket") +__success __retval(11) +TABLE_5000(callx_rodata_5000_pointers, "", 5000) + +SEC("socket") +__failure __msg("overlaps with a pointer to a function") +TABLE_5000 (callx_rodata_5000_pointers_and_data,".quad 1;" ,5001 ) + /* 3 states that have no join get to a table of 400 functions: 3 states, and not 1200 */ SEC("socket") __success __retval(11)
Signature · 1 line
2.55.0
PATCH v2 11/21 libbpf: Size the tables of the loader program from the object
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
gen_loader mirrors limits of the kernel: 64 maps, 32 programs and 256 kfuncs. The numbers are known before the loader is made.
fd_array: [ maps | copies of maps | unused | BTFs of kfuncs ]
prog_fds: [ programs ] was on the stack of the loader
Use gotol and a register for ctx when an offset needs more than 16 bits. That was an error, so loaders that could be made do not get gotol.
--- tools/lib/bpf/bpf_gen_internal.h | 3 +- tools/lib/bpf/gen_loader.c | 157 +++++++++++++------------------ tools/lib/bpf/libbpf.c | 8 +- 3 files changed, 74 insertions(+), 94 deletions(-)
tools/lib/bpf/bpf_gen_internal.h +2 -1
@@ -50,6 +50,7 @@ struct bpf_gen {struct ksym_desc *ksyms;__u32 nr_ksyms;int fd_array; +int prog_fds;int nr_fd_array;/* * Maps with pointers to functions, that programs get their own copies
@@ -61,7 +62,7 @@ struct bpf_gen { };void bpf_gen__init (struct bpf_gen *gen,int log_level,int nr_progs,int nr_maps, -int max_func_ptr_maps); +int max_func_ptr_maps,int nr_kfuncs);int bpf_gen__finish (struct bpf_gen *gen,int nr_progs,int nr_maps);void bpf_gen__free (struct bpf_gen *gen);void bpf_gen__load_btf (struct bpf_gen *gen,const void *raw_data,__u32 raw_size);
tools/lib/bpf/gen_loader.c +67 -90
284 lines not on this page · raw message
tools/lib/bpf/libbpf.c +5 -3
@@ -9909,7 +9909,7 @@ static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const ch* permit cross-endian creation of "light skeleton". */ if (obj->gen_loader) { -int nr_func_ptr_maps =0 , nr_progs =0 , i; +int nr_func_ptr_maps =0 , nr_progs =0 , nr_entries =0 , i;bool text_has_callx = false;/*
@@ -9929,8 +9929,10 @@ static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const ch !prog_is_subprog (obj, &obj->programs[i]) && (text_has_callx || prog_has_callx(&obj->programs[i]))) nr_progs++; -bpf_gen__init (obj->gen_loader, obj->log_level | extra_log_level, - obj->nr_programs, obj->nr_maps, nr_func_ptr_maps * nr_progs); +for (i =0 ; i < obj->nr_programs; i++) + nr_entries += !prog_is_subprog (obj, &obj->programs[i]); +bpf_gen__init (obj->gen_loader, obj->log_level | extra_log_level, nr_entries, + obj->nr_maps, nr_func_ptr_maps * nr_progs, obj->nr_extern); }else if (!is_native_endianness (obj)) {pr_warn ("object '%s': loading non-native endianness is unsupported\n" , obj->name);return libbpf_err (-LIBBPF_ERRNO__ENDIAN );
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next v2 11/21] libbpf: Size the tables of the loader program from the object
TL;DR: Larger per-program code in the generated loader may push branch offsets past 16 bits, so gotol is emitted; kernels older than v6.4 reject it, so previously loadable light skeletons may now…
Quoted 1 line
libbpf: Size the tables of the loader program from the object
TL;DR: Larger per-program code in the generated loader may push branch offsets past 16 bits, so gotol is emitted; kernels older than v6.4 reject it, so previously loadable light skeletons may now fail to load there.
Quoted 8 lines
gen_loadermirrors limits of the kernel: 64 maps, 32 programs and 256 kfuncs. The numbers are known before the loader is made.
fd_array: [ maps | copies of maps | unused | BTFs of kfuncs ]
prog_fds: [ programs ] was on the stack of the loaderUse gotol and a register for ctx when an offset needs more than 16 bits. That was an error, so loaders that could be made do not get gotol.
Is that last sentence accurate for loaders close to the old 16-bit limit?
The prog fd slots moved from the stack into the blob, which makes the cleanup block and the per-program fd store longer. Every backward branch to cleanup_label from emit_check_err() has to cross that code.
Quoted 3 lines
tools/lib/bpf/gen_loader.c +0
-0
[ ... ]
tools/lib/bpf/gen_loader.c void bpf_gen__init(struct bpf_gen *gen, int log_level, int nr_progs, int nr_maps · line 163
Quoted 11 lines
tools/lib/bpf/gen_loader.c +2
-0@@ -139,27 +141,24 @@ void bpf_gen__init(struct bpf_gen *gen, int log_level, int nr_progs, int nr_mapsfor (i =0 ; i < stack_sz; i +=4 ) {emit (gen,BPF_LDX_MEM (BPF_W ,BPF_REG_1 ,BPF_REG_10 , -stack_sz + i));emit (gen,BPF_JMP_IMM (BPF_JSLE ,BPF_REG_1 ,0 ,1 ));emit (gen,BPF_EMIT_CALL (BPF_FUNC_sys_close)); } +for (i =0 ; i < nr_progs; i++) +emit_sys_close_blob (gen,blob_prog_fd_off (gen, i));for (i =0 ; i < nr_maps; i++)emit_sys_close_blob (gen,blob_fd_array_off (gen, i));
Previously this was 3 insns per stack prog_fd slot. Now each program costs 6 insns here (12 with log_level).
[ ... ]
Quoted 8 lines
tools/lib/bpf/gen_loader.c +2
-1@@ -294,7 +283,8 @@ static void emit_check_err(struct bpf_gen *gen)if (is_simm16 (off)) {emit (gen,BPF_JMP_IMM (BPF_JSLT ,BPF_REG_7 ,0 , off)); }else { - gen->error = -ERANGE ; +emit (gen,BPF_JMP_IMM (BPF_JSGE ,BPF_REG_7 ,0 ,1 )); +emit (gen,BPF_JMP32_A (off -1 )); }
[ ... ]
tools/lib/bpf/gen_loader.c void bpf_gen__prog_load(struct bpf_gen *gen, · line 1123
Quoted 7 lines
tools/lib/bpf/gen_loader.c +4
-0@@ -1136,14 +1116,10 @@ void bpf_gen__prog_load(struct bpf_gen *gen, +/* remember prog_fd in the blob, if successful */ +emit2 (gen,BPF_LD_IMM64_RAW_FULL (BPF_REG_1 ,BPF_PSEUDO_MAP_IDX_VALUE , +0 ,0 ,0 ,blob_prog_fd_off (gen, gen->nr_progs))); +emit (gen,BPF_STX_MEM (BPF_W ,BPF_REG_1 ,BPF_REG_7 ,0 )); gen->nr_progs++;
The store of each prog fd grew from 1 insn (BPF_STX_MEM to the stack) to 3 insns here. emit_relo_ksym_typeless() also adds one insn per typeless ksym.
Take an object with N entry programs and no subprograms, where N <= 32 was allowed before. The backward distance from the last emit_check_err() grows by roughly N * (3 + 2) insns, or N * (9 + 2) with log_level. For N = 32 that is about 160 to 350 insns.
A loader whose last check was within that margin below 32768 insns used to be generated with plain 16-bit BPF_JSLT branches. Now is_simm16(off) fails and emit_check_err() emits BPF_JMP32_A (gotol) instead, which kernels older than v6.4 reject in do_check() ("BPF_JA uses reserved fields").
So a light skeleton that a previous libbpf could build for those kernels could now fail to load there. Should the commit message be reworded, or should the per-program growth be kept out of the backward-branch distance?
---
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/43899902250
PATCH v2 12/21 bpf: Relax jumps that patches push out of range
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A jump has 16 bits. Patches grow the code under it: inlined lookups, checks of divisions, may_goto, guards of loops, constant blinding. A verified program fails with -ERANGE: 2979 lookups under one branch are enough.
Let bpf_patch_list_build() use gotol for such a jump:
if r1 > r2 goto far -> if r1 > r2 goto +1
goto +1
gotol farThe same form works for may_goto and unwind_goto. An image where all jumps fit does not change.
The passes do not compute offsets any more:
- the last insn of a patch stands for the patched insn and keeps its target;
- bpf_patch_list_jump() gives a target in the old image to an insn.
may_goto_off(), bpf_adj_moved_insn() and BPF_GUARD_NEAR go away. All guards that leave a subprog share one 'r0 = 0; exit'.
x86-32, riscv32, parisc and sparc64 have no gotol in the JIT. They fail on the unknown opcode, as they do when gotol is in the program. There a guard that is more than 32K insns away from the end of its subprog had its own exit and was JITed. It is not JITed now.
A jump to itself is a jump like any other. It goes to the start of its
patch: 'nospec; goto -1' in sanitized dead code is 'nospec; goto -2' now.
---
include/linux/bpf_verifier.h | 11 +-
kernel/bpf/core.c | 335 +++++++-----
kernel/bpf/fixups.c | 502 +++++-------------
.../{blinding_log.c => blinding_far_jump.c} | 38 +-
.../selftests/bpf/progs/verifier_and.c | 2 +-
.../selftests/bpf/progs/verifier_bounds.c | 14 +-
.../selftests/bpf/progs/verifier_movsx.c | 4 +-
.../selftests/bpf/progs/verifier_patch_list.c | 146 ++++-
.../selftests/bpf/progs/verifier_unpriv.c | 2 +-
9 files changed, 484 insertions(+), 570 deletions(-)
rename tools/testing/selftests/bpf/prog_tests/{blinding_log.c => blinding_far_jump.c} (51%)include/linux/bpf_verifier.h +10 -1
@@ -1208,6 +1208,10 @@ struct bpf_insn_patch {u32 len;u32 start;/* first insn of the patch in bpf_patch_list.insns */ u32 target;/* insn of the patch that jumps to 'off' land on */ +u32 self;/* insn of the patch that stands for insn 'off' */ +u32 jmp;/* 1 + insn of the patch that goes to insn 'jmp_to', 0 if none */ +u32 jmp_to; +u32 jmp_back;/* or to that many insns in front of the patch of it */ struct bpf_insn orig;/* the replaced insn when the patch was queued */ };
@@ -1230,7 +1234,9 @@ struct bpf_patch_image {u32 *new_off;u32 *new_tgt;u32 *new_linfo; +u32 *relaxed;/* insn before patch_image_relax() -> insn after it */ u32 cnt; +u32 short_cnt;/* insns before patch_image_relax() */ u32 new_cnt;u32 nr_linfo;s32 grow;
@@ -1256,7 +1262,8 @@ struct bpf_insn *__bpf_patch_list_add(struct bpf_patch_list *pl,int __bpf_patch_list_del (struct bpf_patch_list *pl,const struct bpf_prog *prog,u32 off);int __bpf_patch_list_insert (struct bpf_patch_list *pl,const struct bpf_prog *prog, -u32 off,const struct bpf_insn *insns,u32 cnt); +u32 off,const struct bpf_insn *insns,u32 cnt,bool behind); +void bpf_patch_list_jump (struct bpf_patch_list *pl,const struct bpf_insn *insn,u32 to,u32 back);void bpf_patch_list_release (struct bpf_patch_list *pl);int bpf_patch_list_build (const struct bpf_patch_list *pl,const struct bpf_prog *prog,struct bpf_patch_image *img);
@@ -2266,6 +2273,8 @@ static inline void bpf_patch_list_free(struct bpf_verifier_env *env) }#endif int bpf_patch_list_del (struct bpf_verifier_env *env,u32 off); +int bpf_patch_list_append (struct bpf_verifier_env *env,u32 off, +const struct bpf_insn *insns,u32 cnt);int bpf_patch_list_insert (struct bpf_verifier_env *env,u32 off,const struct bpf_insn *insns,u32 cnt);
kernel/bpf/core.c +193 -142
502 lines not on this page · raw message
kernel/bpf/fixups.c +130 -372
693 lines not on this page · raw message
tools/testing/selftests/bpf/prog_tests/blinding_far_jump.c renamed from tools/testing/selftests/bpf/prog_tests/blinding_log.c +15 -23
@@ -1,24 +1,23 @@// SPDX-License-Identifier: GPL-2.0 -/* The verifier log of a prog whose constants are blinded */ +/* A far jump in a prog whose constants are blinded */ #include <test_progs.h> #include <linux/filter.h> #include "sysctl_helpers.h" #define NR_CONSTS 11000 -#define LOG_SIZE 65536/* * A prog of one function gets its constants blinded when its runtime is * selected. Each 'r0 += 1' becomes 3 insns, which pushes the jump over them * out of its 16-bit range. Serial, because it sets bpf_jit_harden. */ -void serial_test_blinding_log (void ) +void serial_test_blinding_far_jump (void ) {const char *harden ="/proc/sys/net/core/bpf_jit_harden" ; -LIBBPF_OPTS (bpf_prog_load_opts, opts); +char old[16 ] = {}, pkt[64 ] = {}; + LIBBPF_OPTS(bpf_test_run_opts, opts, .data_in = pkt, .data_size_in = sizeof(pkt));struct bpf_insn *insns; -char old[16 ] = {}, *log;int i, cnt =0 , fd;if (!is_jit_enabled ()) {
@@ -28,32 +27,25 @@ void serial_test_blinding_log(void) } insns =calloc (NR_CONSTS +3 ,sizeof (*insns)); - log =calloc (1 ,LOG_SIZE ); -if (!ASSERT_OK_PTR (insns,"insns" ) || !ASSERT_OK_PTR (log,"log" )) - goto out; +if (!ASSERT_OK_PTR (insns,"insns" )) +return ; - insns[cnt++] =BPF_EMIT_CALL (BPF_FUNC_get_prandom_u32); - insns[cnt++] =BPF_JMP_IMM (BPF_JEQ ,BPF_REG_0 ,0 ,NR_CONSTS ); +/* mark is 0 */ + insns[cnt++] =BPF_LDX_MEM (BPF_W ,BPF_REG_0 ,BPF_REG_1 , offsetof(struct __sk_buff , mark)); + insns[cnt++] =BPF_JMP_IMM (BPF_JNE ,BPF_REG_0 ,0 ,NR_CONSTS );for (i =0 ; i <NR_CONSTS ; i++) insns[cnt++] =BPF_ALU64_IMM (BPF_ADD ,BPF_REG_0 ,1 ); insns[cnt++] =BPF_EXIT_INSN (); - opts.log_buf = log; - opts.log_size =LOG_SIZE ; -/* log stats only: level 1 logs each insn, which wraps the buffer */ - opts.log_level =4 ;if (sysctl_set_or_fail (harden, old,"2" )) goto out; - fd =bpf_prog_load (BPF_PROG_TYPE_SOCKET_FILTER ,NULL ,"GPL" , insns, cnt, &opts); + fd =bpf_prog_load (BPF_PROG_TYPE_SOCKET_FILTER ,NULL ,"GPL" , insns, cnt,NULL );sysctl_set_or_fail (harden,NULL , old); -/* don't mind whether the interpreter takes the prog or the load fails */ -if (fd >=0 ) -close (fd); - -/* expect the message about the jump in the log and in log_true_size */ -ASSERT_HAS_SUBSTR (log,"cannot be patched due to 16-bit range" ,"log" ); -ASSERT_EQ (opts.log_true_size,strlen (log) +1 ,"log_true_size" ); +if (!ASSERT_OK_FD (fd,"load" )) + goto out; +if (ASSERT_OK (bpf_prog_test_run_opts (fd, &opts),"run" )) +ASSERT_EQ (opts.retval,NR_CONSTS ,"retval" ); +close (fd); out:free (insns); -free (log); }
tools/testing/selftests/bpf/progs/verifier_and.c +1 -1
@@ -90,7 +90,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("if w0 < 0x1 goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R1 !read_ok'` */ -__xlated_unpriv("goto pc-1") /* `r1 = *(u32*)(r1 + 512)`, sanitized dead code */ +__xlated_unpriv("goto pc-2") /* `r1 = *(u32*)(r1 + 512)`, sanitized dead code */ __xlated_unpriv("r0 = 0")#endif __naked void known_subreg_with_unknown_reg (void )
tools/testing/selftests/bpf/progs/verifier_bounds.c +7 -7
@@ -626,7 +626,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R0 invalid mem access 'scalar'` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("exit")#endif __naked void _32bit_and_64bit_arithmetic_test1 (void )
@@ -655,7 +655,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R0 invalid mem access 'scalar'` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("exit")#endif __naked void _32bit_and_64bit_arithmetic_test2 (void )
@@ -709,7 +709,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("if r1 != 0x0 goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R0 min value is outside of the allowed memory range` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("r0 = 0")#endif __naked void reg_0_reg_xor_1 (void )
@@ -742,7 +742,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("if w1 != 0x0 goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R0 min value is outside of the allowed memory range` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("r0 = 0")#endif __naked void reg32_0_reg32_xor_1 (void )
@@ -775,7 +775,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("if r1 > 0x0 goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R0 min value is outside of the allowed memory range` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("r0 = 0")#endif __naked void reg_2_reg_xor_3 (void )
@@ -862,7 +862,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("if r1 >= 0x0 goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R0 min value is outside of the allowed memory range` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("r0 = 0")#endif __naked void reg_0_reg_xor_3 (void )
@@ -896,7 +896,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("if w1 >= 0x0 goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R0 min value is outside of the allowed memory range` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("r0 = 0")#endif __naked void reg32_0_reg32_xor_3 (void )
tools/testing/selftests/bpf/progs/verifier_movsx.c +2 -2
@@ -437,7 +437,7 @@ __success_unpriv __xlated_unpriv("w0 = 0") __xlated_unpriv("exit") __xlated_unpriv("nospec") /* inserted to prevent `frame pointer is read only` */ -__xlated_unpriv("goto pc-1") +__xlated_unpriv("goto pc-2")#endif __naked void mov64sx_s32_varoff_2 (void ) {
@@ -465,7 +465,7 @@ __success_unpriv __xlated_unpriv("w0 = 0") __xlated_unpriv("exit") __xlated_unpriv("nospec") /* inserted to prevent `frame pointer is read only` */ -__xlated_unpriv("goto pc-1") +__xlated_unpriv("goto pc-2")#endif __naked void mov64sx_s32_varoff_3 (void ) {
tools/testing/selftests/bpf/progs/verifier_patch_list.c +125 -21
162 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_unpriv.c +1 -1
@@ -615,7 +615,7 @@ __retval(0)#ifdef SPEC_V1 __xlated_unpriv("if r0 == 0x0 goto pc+2") __xlated_unpriv("nospec") /* inserted to prevent `R7 invalid mem access 'scalar'` */ -__xlated_unpriv("goto pc-1") /* sanitized dead code */ +__xlated_unpriv("goto pc-2") /* sanitized dead code */ __xlated_unpriv("exit")#endif __naked void alu32_mov_u32_const (void )
Signature · 1 line
2.55.0
PATCH v2 13/21 bpf: Keep the call graph in lists of edges
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The call graph is a matrix of bits. Its closure takes O(n^3 / 64) and runs twice. The passes over it repeat until nothing changes.
Keep the edges in lists and sort the graph once, with cycles in a row:
main -> f1 -> f2 -> f3 order: f3 | f2 f1 | main
^ |
+-----+Marks go to callers or to callees in one pass over that order. callx calls one extra node, which calls all functions whose address is taken.
After the main pass only the insns that were seen count. A call, a tail call, LD_ABS or bpf_throw() in dead code rejects nothing. The load of an address is not a call: the main pass records who calls a callback.
--- include/linux/bpf_verifier.h | 40 +- kernel/bpf/cfg.c | 128 +++++ kernel/bpf/verifier.c | 485 +++++++----------- .../bpf/progs/test_global_func_deep_stack.c | 12 +- .../selftests/bpf/progs/verifier_tailcall.c | 4 +- tools/testing/selftests/bpf/verifier/calls.c | 3 +- 6 files changed, 357 insertions(+), 315 deletions(-)
include/linux/bpf_verifier.h +33 -7
@@ -769,6 +769,32 @@ struct bpf_index {int bpf_index_find (const struct bpf_index *index,u64 key);int bpf_index_add (struct bpf_index *index,u64 key,u32 val); +/* A graph of calls. The nodes are subprogs, and behind them what stands for a set of subprogs. */ +struct bpf_call_graph { +u32 cnt;/* nodes */ +u32 edge_cnt; +u32 *callee;/* node s calls callee[first[s]] .. callee[first[s + 1] - 1] */ +u32 *first; +/* see bpf_call_graph_sort() */ +u32 *postorder; +u32 *order; +u32 *cycle; +u16 *marks;/* of the user of the graph */ +u32 next;/* nodes that have 'first' */ +}; + +#define bpf_for_each_callee (cg, s, j) \ + for (u32 ___e = (cg)->first[s]; \ + ___e < (cg)->first[(s) + 1] && ({ j = (cg)->callee[___e]; 1; }); ___e++) + +int bpf_call_graph_init (struct bpf_call_graph *cg,u32 cnt); +int bpf_call_graph_add (struct bpf_call_graph *cg,u32 caller,u32 callee); +void bpf_call_graph_sort (struct bpf_call_graph *cg,u16 skip); +bool bpf_call_graph_recursive (const struct bpf_call_graph *cg,u32 s); +void bpf_call_graph_mark_callees (struct bpf_call_graph *cg,u16 mask); +void bpf_call_graph_mark_callers (struct bpf_call_graph *cg,u16 mask,u16 skip); +void bpf_call_graph_free (struct bpf_call_graph *cg); +#define iarray_for_each (item, arr) \ for (int ___idx = 0; \ ___idx < (arr)->cnt && ({ item = (arr)->items[___idx]; 1; }); \
@@ -1088,6 +1114,7 @@ struct bpf_subprog_info {* U32_MAX when it has none. */ u32 exit_idx; +u32 callx_edge;/* 1 + the first of its env->callx_edges, 0 if none */ struct bpf_iarray *jt;/* jump table shared by all gotox of this subprogram */ u16 stack_depth;/* max. stack depth used by this function */ u16 stack_extra;
@@ -1341,13 +1368,12 @@ struct bpf_verifier_env {u32 func_set_cnt;struct bpf_index func_set_index;bool has_callx; -/* -* Call graph edges created by callx instructions. A bitmap of -* subprog_cnt * subprog_cnt bits, where bit (caller * subprog_cnt + callee) -* is set when the main verification pass sees 'caller' calling 'callee' -* via callx. Allocated when the first such edge is recorded. -*/ -unsigned long *callx_edges; +/* What callx and helpers call, a list for each caller, see record_callx_edge() */ +struct bpf_callx_edge { +u32 callee; +u32 next;/* 1 + the next edge of the caller, 0 if none */ + } *callx_edges; +struct bpf_index callx_index;struct bpf_idmap idmap_scratch;struct {int *insn_state;
kernel/bpf/cfg.c +128 -0
134 lines not on this page · raw message
kernel/bpf/verifier.c +182 -303
757 lines not on this page · raw message
tools/testing/selftests/bpf/progs/test_global_func_deep_stack.c +11 -1
@@ -125,7 +125,8 @@ int global_func_many_chains(void *ctx)/* * r1 is the number of calls that follow, so main -> fs15 .. fs0 and main -> fs31 .. fs16 -* are executed: 17 frames each. main -> fs31 .. fs0 is in the call graph: 33 frames. +* are executed: 17 frames each. With main -> fs16 -> fs15 no call is dead code, and +* main -> fs31 .. fs0 is in the call graph: 33 frames. * libbpf puts fs15() .. fs0() in front of their second caller fs16(). */ #undef F_0
@@ -138,6 +139,15 @@ SEC("syscall") __failure __msg("the call stack of 32 frames is too deep !") __load_if_JITed() __naked int static_func_deep_stack_second_caller(void) +{ + asm volatile ("r1 = 15; call fs15; r1 = 15; call fs31; r1 = 1; call fs16; exit;" + ::: __clobber_all); +} + +SEC("syscall") +__success +__load_if_JITed() +__naked int static_func_deep_stack_dead_call(void) { asm volatile ("r1 = 15; call fs15; r1 = 15; call fs31; exit;" ::: __clobber_all); }
tools/testing/selftests/bpf/progs/verifier_tailcall.c +2 -2
@@ -137,8 +137,8 @@ int exception_cb_tail_call(__u64 cookie) } SEC("tc") -__description("tail call in an async callback that calls nothing") -__failure __msg("cannot tail call within callback") +__description("dead tail call in an async callback") +__success __attribute__((btf_decl_tag ("exception_callback:exception_cb_tail_call" ))) __naked void tail_call_in_async_callback(void) {
tools/testing/selftests/bpf/verifier/calls.c +1 -2
@@ -1526,8 +1526,7 @@ }, .prog_type = BPF_PROG_TYPE_XDP, .flags = F_NEEDS_JIT_ENABLED, - .errstr = "call stack", - .result = REJECT, + .result = ACCEPT, }, { "calls: spill into caller stack frame",
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next v2 13/21] bpf: Keep the call graph in lists of edges
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf: stale recursive flag on dead subprogs in check_recursion() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: stale recursive flag on dead subprogs in check_recursion()
--
commit 539e11dd4eb699b7232e8c0101b8c5c17216cd6e
Author: Alexei Starovoitov <[email protected]>
bpf: Keep the call graph in lists of edges
This commit replaces the bitmap-based call graph with edge lists sorted via Tarjan's algorithm and restricts post-verification call graph analysis to instructions seen during the main pass.
Quoted 4 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 1 line
kernel/bpf/verifier.c +0
-0@@ -5447,122 +5385,75 @@ static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
[ ... ]
Quoted 6 lines
static int
build_call_graph(struct bpf_verifier_env *env, struct bpf_call_graph *cg){kernel/bpf/verifier.c +0
-2struct bpf_subprog_info *si = env->subprog_info;struct bpf_insn *insn = env->prog->insnsi; -int cnt = env->subprog_cnt, words =BITS_TO_LONGS (cnt); -int i, j, s;
[ ... ]
Quoted 6 lines
kernel/bpf/verifier.c +1
-4+ err =bpf_call_graph_init (cg, cnt);for (s =0 ; s < cnt; s++) { -for (i = si[s].start; i < si[s +1 ].start; i++) { -/* the subprog that takes the address of a subprog counts as its caller */ -if (!bpf_pseudo_call (insn + i) && !bpf_pseudo_func (insn + i)) -continue ;
[ ... ]
Quoted 23 lines
kernel/bpf/verifier.c +12
-7- } -/* the callees of callx and the callbacks of helpers, see record_callx_edge() */ -for (j =next_callx_callee (env, s,0 ); j >=0 ; j =next_callx_callee (env, s, j +1 )) -__set_bit (j,subprog_calls (cg, s)); +for (i = si[s].start; i < si[s +1 ].start && !err; i++) +if (bpf_pseudo_call (insn + i) && env->insn_aux_data[i].seen) + err =bpf_call_graph_add (cg, s,bpf_find_subprog (env, + i + insn[i].imm +1 )); +/* the callees of callx and the callbacks of helpers */ +for (i = si[s].callx_edge; i && !err; i = env->callx_edges[i -1 ].next) + err =bpf_call_graph_add (cg, s, env->callx_edges[i -1 ].callee); } -memcpy (cg->reach, cg->calls, cnt * words *sizeof (long )); -close_call_graph (cg->reach, cnt); +if (err) +return err; +bpf_call_graph_sort (cg,0 );for (s =0 ; s < cnt; s++)if (!s || si[s].is_async_cb) -add_reach (cg, cg->live, s); + cg->marks[s] =CG_LIVE ; +bpf_call_graph_mark_callees (cg,CG_LIVE );
[ ... ]
kernel/bpf/verifier.c static int check_recursion(struct bpf_verifier_env *env, struct bpf_call_graph * · line 5505
Quoted 11 lines
kernel/bpf/verifier.c +2
-2@@ -5611,8 +5498,8 @@ static int check_recursion(struct bpf_verifier_env *env, struct bpf_call_graph * {int j, s; -for_each_set_bit (s, cg->live, cg->cnt) { -if (!test_bit (s,subprog_reach (cg, s))) { +for_each_marked_subprog (cg, s,CG_LIVE ) { +if (!bpf_call_graph_recursive (cg, s)) { env->subprog_info[s].recursive = false;continue ; }
[Severity: Medium]
Does check_recursion() leave env->subprog_info[s].recursive set on subprogs that are not marked CG_LIVE?
Before the main pass, mark_recursive_subprogs() builds a conservative call graph over all instructions and sets si[s].recursive = true for every subprog on a cycle. After the main pass, build_call_graph() ignores unseen bpf_pseudo_call instructions and bpf_pseudo_func address loads, so a subprog reachable only from a dead call or an uncalled address load is no longer marked CG_LIVE and check_recursion() skips it without clearing env->subprog_info[s].recursive.
Later, bpf_insert_recursion_checks() runs before bpf_opt_remove_dead_code() and inspects si[s].recursive across all subprogs regardless of CG_LIVE:
kernel/bpf/fixups.c:bpf_insert_recursion_checks() {
...
for (s = 1; s < env->subprog_cnt; s++)
found |= si[s].recursive;
if (!found)
return 0;
env->prog->jit_required = 1;
...
}This patches recursion checks into the dead subprog and sets prog->jit_required = 1, causing bpf_fixup_call_args() to reject valid non-JITed programs with -EINVAL.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
PATCH v2 14/21 bpf: Find the effects of callees on the call graph
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Each load of the address of a table of functions walks all its pointers, again after each function that the walk finds, and again in each round of close_callee_effects(). 1000 loads of a table of 128K pointers take a minute.
Make the map one node of the call graph:
f1: r1 = map ll --+
+--> node of the map --> all functions in the map f2: r1 = map ll --+
The functions that maps point to are roots of the walk of the cfg, like the exception callback.
--- kernel/bpf/cfg.c | 240 +++++++++++++++-------------------------------- 1 file changed, 75 insertions(+), 165 deletions(-)
kernel/bpf/cfg.c +75 -165
@@ -52,54 +52,6 @@ enum { BRANCH = 2, }; -static void mark_subprog_changes_pkt_data (struct bpf_verifier_env *env,int off) -{ -struct bpf_subprog_info *subprog; - - subprog =bpf_find_containing_subprog (env, off); - subprog->changes_pkt_data = true; -} - -static void mark_subprog_might_sleep (struct bpf_verifier_env *env,int off) -{ -struct bpf_subprog_info *subprog; - - subprog =bpf_find_containing_subprog (env, off); - subprog->might_sleep = true; -} - -static void mark_subprog_might_throw (struct bpf_verifier_env *env,int off) -{ -struct bpf_subprog_info *subprog; - - subprog =bpf_find_containing_subprog (env, off); - subprog->might_throw = true; -} - -/* -* 't' is an index of a call-site. -* 'w' is a callee entry point. -* Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED. -* DFS traversal order guarantees that callee's effect marks are correct at that -* moment, unless the callee calls one of its callers: see close_callee_effects(). -* Returns true if the marks of the caller changed. -*/ -static bool merge_callee_effects (struct bpf_verifier_env *env,int t,int w) -{ -struct bpf_subprog_info *caller, *callee; - - caller =bpf_find_containing_subprog (env, t); - callee =bpf_find_containing_subprog (env, w); -if (caller->changes_pkt_data >= callee->changes_pkt_data && - caller->might_sleep >= callee->might_sleep && - caller->might_throw >= callee->might_throw) -return false; - caller->changes_pkt_data |= callee->changes_pkt_data; - caller->might_sleep |= callee->might_sleep; - caller->might_throw |= callee->might_throw; -return true; -} -enum {DONE_EXPLORING =0 ,KEEP_EXPLORING =1 ,
@@ -169,19 +121,13 @@ static int visit_func_call_insn(int t, struct bpf_insn *insns, bool visit_callee) {int ret, insn_sz; -int w; insn_sz =bpf_is_ldimm64 (&insns[t]) ?2 :1 ; ret =push_insn (t, t + insn_sz,FALLTHROUGH , env);if (ret)return ret; -if (visit_callee) { - w = t + insns[t].imm +1 ; -merge_callee_effects (env, t, w); - ret =push_insn (t, w,BRANCH , env); - } -return ret; +return visit_callee ?push_insn (t, t + insns[t].imm +1 ,BRANCH , env) :0 ; }struct bpf_iarray *bpf_iarray_realloc (struct bpf_iarray *old,size_t n_elem)
@@ -628,98 +574,63 @@ static int visit_gotox_insn(int t, struct bpf_verifier_env *env)return keep_exploring ?KEEP_EXPLORING :DONE_EXPLORING ; } -/* -* Return pointers to functions in the read-only map that ld_imm64 instruction -* 't' loads the address of, or of its value, if there are any. -*/ -static struct bpf_func_ptr *insn_func_ptrs (struct bpf_verifier_env *env,int t,u32 *cnt) -{ -struct bpf_insn *insn = &env->prog->insnsi[t]; - - *cnt =0 ; -if (!env->func_ptr_cnt || !bpf_is_ldimm64 (insn)) -return NULL ; -if (insn->src_reg !=BPF_PSEUDO_MAP_VALUE && - insn->src_reg !=BPF_PSEUDO_MAP_IDX_VALUE && - insn->src_reg !=BPF_PSEUDO_MAP_FD && - insn->src_reg !=BPF_PSEUDO_MAP_IDX ) -return NULL ; - -return bpf_map_func_ptrs (env, env->used_maps[env->insn_aux_data[t].map_index], cnt); -} - -/* -* ld_imm64 that loads the address of a map that has pointers to functions -* is similar to ld_imm64 with BPF_PSEUDO_FUNC that loads the address of one -* function: any of them may be read from the map and called via callx later. -* Treat it as a call of all of them. -*/ -static int visit_func_ptrs_insn (int t,struct bpf_verifier_env *env, -struct bpf_func_ptr *ptrs,u32 cnt) -{ -int *insn_stack = env->cfg.insn_stack; -int *insn_state = env->cfg.insn_state; -int ret, w; -u32 i; - - ret =push_insn (t, t +2 ,FALLTHROUGH , env); -if (ret) -return ret; - -/* -* Explore one function at a time like push_insn() does, so that -* DISCOVERED function is a caller of 't' and not the one that waits in -* insn_stack[], which merge_callee_effects() relies on. -*/ -for (i =0 ; i < cnt; i++) { - w = ptrs[i].xlated_off; -if (insn_state[w]) -continue ; - -if (env->cfg.cur_stack >= env->prog->len) -return -E2BIG ; - - insn_stack[env->cfg.cur_stack++] = w; - insn_state[w] =DISCOVERED ; -return KEEP_EXPLORING ; - } - -/* all functions are explored, their effects are known */ -for (i =0 ; i < cnt; i++) { - w = ptrs[i].xlated_off; -merge_callee_effects (env, t, w); - -/* the same mark as push_insn() leaves on a branch target */ -mark_jump_target (env, w); - } -return DONE_EXPLORING ; -} +enum { +CHANGES_PKT_DATA =BIT (0 ), +MIGHT_SLEEP =BIT (1 ), +MIGHT_THROW =BIT (2 ), +};/* -* A subprog that calls one of its callers is EXPLORED before that caller is: it -* took the marks that the caller had so far, and so did everybody who called it -* since. Merge again at every call until nothing changes. +* A subprog does what its callees do. The load of the address of a function counts as a call. +* So does the load of the address of a map with pointers to functions: +* +* f1: r1 = map ll --+ +* +--> node of the map --> all functions in the map +* f2: r1 = map ll --+ */ -static void close_callee_effects (struct bpf_verifier_env *env) +static int merge_callee_effects (struct bpf_verifier_env *env) { +struct bpf_subprog_info *si = env->subprog_info;struct bpf_insn *insn = env->prog->insnsi; -struct bpf_func_ptr *ptrs; -bool changed; -u32 cnt, j; -int t; - -do { - changed = false; -for (t =0 ; t < env->prog->len; t++) { +u32 cnt = env->subprog_cnt, n, s, t; +struct bpf_call_graph cg; +struct bpf_func_ptr *ptr; +int err; + + err =bpf_call_graph_init (&cg, cnt + env->used_map_cnt); +for (s =0 ; s < cnt && !err; s++) { + cg.marks[s] = (si[s].changes_pkt_data ?CHANGES_PKT_DATA :0 ) | + (si[s].might_sleep ?MIGHT_SLEEP :0 ) | + (si[s].might_throw ?MIGHT_THROW :0 ); +for (t = si[s].start; t < si[s +1 ].start && !err; t++) {if (bpf_pseudo_call (&insn[t]) ||bpf_pseudo_func (&insn[t])) - changed |=merge_callee_effects (env, t, t + insn[t].imm +1 ); - ptrs =insn_func_ptrs (env, t, &cnt); -for (j =0 ; j < cnt; j++) - changed |=merge_callee_effects (env, t, ptrs[j].xlated_off); -if (bpf_is_ldimm64 (&insn[t])) - t++; + err =bpf_call_graph_add (&cg, s,bpf_find_subprog (env, + t + insn[t].imm +1 )); +else if (bpf_is_ldimm64 (&insn[t]) && insn[t].src_reg && + insn[t].src_reg !=BPF_PSEUDO_BTF_ID ) + err =bpf_call_graph_add (&cg, s, + cnt + env->insn_aux_data[t].map_index); } - }while (changed); + } +for (s =0 ; s < env->used_map_cnt; s++) { + ptr =bpf_map_func_ptrs (env, env->used_maps[s], &n); +for (; n-- && !err; ptr++) + err =bpf_must_abort () ? -EINTR : +bpf_call_graph_add (&cg, cnt + s, +bpf_find_subprog (env, ptr->xlated_off)); + } +if (err) + goto out; +bpf_call_graph_sort (&cg,0 ); +bpf_call_graph_mark_callers (&cg,U16_MAX ,0 ); +for (s =0 ; s < cnt; s++) { + si[s].changes_pkt_data = cg.marks[s] &CHANGES_PKT_DATA ; + si[s].might_sleep = cg.marks[s] &MIGHT_SLEEP ; + si[s].might_throw = cg.marks[s] &MIGHT_THROW ; + } +out: +bpf_call_graph_free (&cg); +return err; }/* Visits the instruction at index t and returns one of the following:
@@ -730,17 +641,12 @@ static void close_callee_effects(struct bpf_verifier_env *env)static int visit_insn (int t,struct bpf_verifier_env *env) {struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; -struct bpf_func_ptr *ptrs; +struct bpf_subprog_info *sub;int ret, off, insn_sz; -u32 cnt;if (bpf_pseudo_func (insn))return visit_func_call_insn (t, insns, env, true); - ptrs =insn_func_ptrs (env, t, &cnt); -if (ptrs) -return visit_func_ptrs_insn (t, env, ptrs, cnt); -/* All non-branch instructions have a single fall-through edge. */ if (BPF_CLASS (insn->code) !=BPF_JMP &&BPF_CLASS (insn->code) !=BPF_JMP32 ) {
@@ -760,6 +666,7 @@ static int visit_insn(int t, struct bpf_verifier_env *env)*/ if (bpf_is_sync_callback_calling_insn (insn))mark_calls_callback (env, t); + sub =bpf_find_containing_subprog (env, t);if (bpf_helper_call (insn)) {const struct bpf_func_proto *fp;
@@ -770,11 +677,11 @@ static int visit_insn(int t, struct bpf_verifier_env *env)* elimination. */ if (ret ==0 && fp->might_sleep) -mark_subprog_might_sleep (env, t); + sub->might_sleep = true;/* nobody knows yet whether the dynptr is that of an skb */ if (bpf_helper_changes_pkt_data (insn->imm) || insn->imm == BPF_FUNC_dynptr_write) -mark_subprog_changes_pkt_data (env, t); + sub->changes_pkt_data = true; }else if (insn->src_reg ==BPF_PSEUDO_KFUNC_CALL ) {struct bpf_call_arg_meta meta;
@@ -785,11 +692,11 @@ static int visit_insn(int t, struct bpf_verifier_env *env)* dead code elimination. */ if (ret ==0 &&bpf_is_kfunc_sleepable (&meta)) -mark_subprog_might_sleep (env, t); + sub->might_sleep = true;if (ret ==0 &&bpf_is_kfunc_pkt_changing (&meta)) -mark_subprog_changes_pkt_data (env, t); + sub->changes_pkt_data = true;if (ret ==0 &&bpf_is_throw_kfunc (insn)) -mark_subprog_might_throw (env, t); + sub->might_throw = true; }return visit_func_call_insn (t, insns, env, insn->src_reg ==BPF_PSEUDO_CALL );
@@ -828,7 +735,8 @@ int bpf_check_cfg(struct bpf_verifier_env *env) {int insn_cnt = env->prog->len;int *insn_stack, *insn_state; -int ex_insn_beg, i, ret =0 ; +int i, root, ret =0 ; +u32 ptr =0 ; insn_state = env->cfg.insn_state =kvzalloc_objs (int, insn_cnt,BPF_VERIFIER_GFP );
@@ -842,15 +750,12 @@ int bpf_check_cfg(struct bpf_verifier_env *env)return -ENOMEM ; } - ex_insn_beg = env->exception_callback_subprog - ? env->subprog_info[env->exception_callback_subprog].start - :0 ; - - insn_state[0 ] =DISCOVERED ;/* mark 1st insn as discovered */ - insn_stack[0 ] =0 ;/* 0 is the first instruction */ + root =0 ;/* 0 is the first instruction */ +walk_cfg: + insn_state[root] =DISCOVERED ; + insn_stack[0 ] = root; env->cfg.cur_stack =1 ; -walk_cfg:while (env->cfg.cur_stack >0 ) {int t = insn_stack[env->cfg.cur_stack -1 ];
@@ -877,11 +782,16 @@ int bpf_check_cfg(struct bpf_verifier_env *env) goto err_free; } -if (ex_insn_beg && insn_state[ex_insn_beg] !=EXPLORED ) { - insn_state[ex_insn_beg] =DISCOVERED ; - insn_stack[0 ] = ex_insn_beg; - env->cfg.cur_stack =1 ; + root = env->subprog_info[env->exception_callback_subprog].start; +if (insn_state[root] !=EXPLORED ) goto walk_cfg; + +/* callx can call what the maps point to */ +while (ptr < env->func_ptr_cnt) { + root = env->func_ptrs[ptr++].xlated_off; +mark_jump_target (env, root); +if (insn_state[root] !=EXPLORED ) + goto walk_cfg; }for (i =0 ; i < insn_cnt; i++) {
@@ -910,8 +820,8 @@ int bpf_check_cfg(struct bpf_verifier_env *env) i++;/* skip second half of ldimm64 */ } } - ret =0 ;/* cfg looks good */ -close_callee_effects (env); +/* cfg looks good */ + ret =merge_callee_effects (env); env->prog->aux->changes_pkt_data = env->subprog_info[0 ].changes_pkt_data; env->prog->aux->might_sleep = env->subprog_info[0 ].might_sleep;
Signature · 1 line
2.55.0
PATCH v2 15/21 bpf: Link the decl tags of a type
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The search for a tag looks at all types, for each argument of each subprog. That is quadratic when the number of subprogs has no limit.
Link the tags when the BTF is loaded:
next_tag[func] -> tag -> tag -> 0
--- kernel/bpf/btf.c | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-)
kernel/bpf/btf.c +39 -6
@@ -281,6 +281,7 @@ struct btf {char name[MODULE_NAME_LEN ];bool kernel_btf;__u32 *base_id_map;/* map from distilled base BTF -> vmlinux BTF ids */ +u32 *next_tag;/* see btf_link_decl_tags() */ };enum verifier_phase {
@@ -1907,6 +1908,7 @@ static void btf_free(struct btf *btf)if (!btf_is_vmlinux (btf))kvfree (btf->data);kvfree (btf->base_id_map); +kvfree (btf->next_tag);kfree (btf); }
@@ -3636,13 +3638,45 @@ static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,return BTF_FIELD_FOUND ; } +/* For BTF of programs: next_tag[type] -> its first tag, next_tag[tag] -> its next tag, ... 0 */ +static int btf_link_decl_tags (struct btf *btf) +{ +u32 i; + + btf->next_tag =kvcalloc (btf->nr_types,sizeof (u32),GFP_KERNEL | __GFP_NOWARN); +if (!btf->next_tag) +return -ENOMEM ; +for (i = btf->nr_types; --i;) { +if (!btf_type_is_decl_tag (btf->types[i])) +continue ; + btf->next_tag[i] = btf->next_tag[btf->types[i]->type]; + btf->next_tag[btf->types[i]->type] = i; + } +return 0 ; +} + +static int btf_type_ptr_cmp (const void *a,const void *b) +{ +return cmp_int (*(void **)a, *(void **)b); +} + +/* last_id is 0 for the first tag */ int btf_find_next_decl_tag (const struct btf *btf,const struct btf_type *pt,int comp_idx,const char *tag_key,int last_id) { +int i = last_id ?:btf_named_start_id (btf, false) -1 , n =btf_nr_types (btf);int len =strlen (tag_key); -int i, n; +struct btf_type **p; + +if (btf->next_tag && !last_id) { +/* the types are in the order of their ids in btf->data */ + p =bsearch (&pt, btf->types +1 , n -1 ,sizeof (*p), btf_type_ptr_cmp); +if (!p) +return -ENOENT ; + i = p - btf->types; + } -for (i = last_id +1 , n =btf_nr_types (btf); i < n; i++) { +while ((i = btf->next_tag ? btf->next_tag[i] ?: n : i +1 ) < n) {const struct btf_type *t =btf_type_by_id (btf, i);if (!btf_type_is_decl_tag (t))
@@ -3665,8 +3699,7 @@ const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_typeconst struct btf_type *t;int len, id; - id =btf_find_next_decl_tag (btf, pt, comp_idx, tag_key, -btf_named_start_id (btf, false) -1 ); + id =btf_find_next_decl_tag (btf, pt, comp_idx, tag_key,0 );if (id <0 )return ERR_PTR (id);
@@ -6519,7 +6552,7 @@ static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,if (err) goto errout; - err =btf_parse_type_sec (env); + err =btf_parse_type_sec (env) ?:btf_link_decl_tags (btf);if (err) goto errout;
@@ -8677,8 +8710,8 @@ static int btf_scan_decl_tags(struct bpf_verifier_env *env,const struct btf_type *fn_t, u32 arg_idx, bool is_global, u32 *tags) { - int id = btf_named_start_id(btf, false) - 1; const char tag_key[] = "arg:"; +int id =0 ; static const struct { const char *tag_value; enum btf_arg_tag arg_tag;
Signature · 1 line
2.55.0
PATCH v2 16/21 bpf: Remove BPF_MAX_SUBPROGS
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Mark the starts of subprogs in a bitmap, count them, then allocate subprog_info. 180 KB of zeros go away from each load.
The number of the callee was in the 16 bits of insn->off. Put it into imm of the copy of the call that the JIT gets:
main image: call pc+N is not changed, nothing to undo func[i]: call subprog# JIT: bpf_jit_get_func_addr()
x86 and sparc use that function now, like the other JITs. The dump of the program finds the number with a binary search.
Other changes:
- The tags of subprogs that make calls change, and so do their names in kallsyms.
- The loops of the JIT over subprogs can be stopped.
- The limit of 10000 in stack liveness counts chains of calls only.
- Liveness of registers visits callees first. Else a chain of N calls takes N rounds.
What stays: bpf_flow_reset() looks at all insns after each global function. That loop can be stopped between two functions.
--- arch/sparc/net/bpf_jit_comp_64.c | 7 +- arch/x86/net/bpf_jit_comp.c | 12 ++- include/linux/bpf_verifier.h | 7 +- kernel/bpf/cfg.c | 2 +- kernel/bpf/check_btf.c | 5 +- kernel/bpf/core.c | 7 +- kernel/bpf/fixups.c | 152 ++++++++++++------------------- kernel/bpf/liveness.c | 20 +++- kernel/bpf/syscall.c | 25 ++++- kernel/bpf/verifier.c | 76 ++++++++-------- 10 files changed, 151 insertions(+), 162 deletions(-)
arch/sparc/net/bpf_jit_comp_64.c +6 -1
@@ -1213,8 +1213,13 @@ static int build_insn(const struct bpf_insn *insn, struct jit_ctx *ctx)/* function call */ case BPF_JMP |BPF_CALL : { -u8 *func = ((u8 *)__bpf_call_base) + imm; +bool fixed; +u64 func; +int err; + err =bpf_jit_get_func_addr (ctx->prog, insn, ctx->prog->aux->func, &func, &fixed); +if (err) +return err; ctx->saw_call = true;emit_call ((u32 *)func, ctx);
arch/x86/net/bpf_jit_comp.c +9 -3
@@ -3323,16 +3323,22 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int */* call */ case BPF_JMP |BPF_CALL : {const struct btf_func_model *fm =NULL ; -bool arena_sp_args = false; +bool arena_sp_args = false, fixed; +u64 addr; - func = (u8 *) __bpf_call_base + imm32; +/* subprogs have addresses in the last pass */ + err =bpf_jit_get_func_addr (bpf_prog, insn, bpf_prog->aux->func, &addr, + &fixed); +if (err) +return err; + func = (u8 *)addr;if (src_reg ==BPF_PSEUDO_CALL && tail_call_reachable) {u8 *tcc_load = prog;LOAD_TAIL_CALL_CNT_PTR (stack_depth); ip += prog - tcc_load; } -if (!imm32) +if (fixed && !imm32)return -EINVAL ;if (arena_sp &&call_clobbers_arena_sp (insn)) {u8 *start = prog;
include/linux/bpf_verifier.h +2 -5
@@ -901,7 +901,6 @@ struct bpf_insn_aux_data {union {enum bpf_reg_type ptr_type;/* pointer type for load/store insns */ struct bpf_map_ptr_state map_ptr_state; -s32 call_imm;/* saved imm field of call insn */ u32 alu_limit;/* limit for add/sub register with pointer */ struct {u32 map_index;/* index into used_maps[] */
@@ -1078,8 +1077,6 @@ struct bpf_verifier_log *bpf_log_attr_create_vlog(struct bpf_log_attr *attr_log, u32 size);int bpf_log_attr_finalize (struct bpf_log_attr *attr,struct bpf_verifier_log *log); -#define BPF_MAX_SUBPROGS 1024 -/* * A pointer to a static subprog in the value of a frozen read-only array map: * a 64-bit value that is the offset in bytes of the first instruction of
@@ -1354,9 +1351,9 @@ struct bpf_verifier_env {struct bpf_verifier_log log;struct bpf_diag *diag;struct bpf_func_proto bpf_subprog_scratch; -struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS +2 ];/* max + 2 for the fake and exception subprogs */ +struct bpf_subprog_info *subprog_info;/* subprog indices sorted in topological order: leaves first, callers last */ -int subprog_topo_order[BPF_MAX_SUBPROGS +2 ]; +int *subprog_topo_order;/* * Pointers to static subprogs found in frozen read-only maps of the * program, see resolve_func_ptrs(). Sorted by map and map_off.
kernel/bpf/cfg.c +1 -1
@@ -478,7 +478,7 @@ void bpf_free_subprog_jts(struct bpf_verifier_env *env) {int i; -for (i =0 ; i <ARRAY_SIZE (env->subprog_info); i++) { +for (i =0 ; i < env->subprog_cnt; i++) {kvfree (env->subprog_info[i].jt); env->subprog_info[i].jt =NULL ; }
kernel/bpf/check_btf.c +2 -3
@@ -163,8 +163,7 @@ static int check_btf_func(struct bpf_verifier_env *env, urecord =make_bpfptr (attr->func_info, uattr.is_kernel); krecord = prog->aux->func_info; - info_aux =kzalloc_objs (*info_aux, nfuncs, -BPF_VERIFIER_GFP ); + info_aux =kvzalloc_objs (*info_aux, nfuncs,BPF_VERIFIER_GFP );if (!info_aux)return -ENOMEM ;
@@ -207,7 +206,7 @@ static int check_btf_func(struct bpf_verifier_env *env,return 0 ; err_free: -kfree (info_aux); +kvfree (info_aux);return ret; }
kernel/bpf/core.c +3 -4
@@ -1595,7 +1595,6 @@ int bpf_jit_get_func_addr(const struct bpf_prog *prog, const struct bpf_insn *insn, bool extra_pass, u64 *func_addr, bool *func_addr_fixed) { - s16 off = insn->off; s32 imm = insn->imm;u8 *addr;int err;
@@ -1609,8 +1608,8 @@ int bpf_jit_get_func_addr(const struct bpf_prog *prog,if (!extra_pass) addr =NULL ;else if (prog->aux->func && - off >=0 && off < prog->aux->real_func_cnt) - addr = (u8 *)prog->aux->func[off]->bpf_func; + imm >=0 && imm < prog->aux->real_func_cnt) + addr = (u8 *)prog->aux->func[imm]->bpf_func;else return -EINVAL ; } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
@@ -3519,7 +3518,7 @@ static void bpf_prog_free_images(struct work_struct *work)bpf_jit_free (aux->func[i]); }if (aux->real_func_cnt) { -kfree (aux->func); +kvfree (aux->func);bpf_prog_unlock_free (aux->prog); }else {bpf_jit_free (aux->prog);
kernel/bpf/fixups.c +56 -96
231 lines not on this page · raw message
kernel/bpf/liveness.c +16 -4
@@ -2365,7 +2365,8 @@ static int analyze_subprog(struct bpf_verifier_env *env,struct func_instance *prev_instance =NULL ;int j, err; -if (++env->liveness->subprog_calls >10000 ) { +/* a subprog on its own is analyzed once, chains of calls multiply */ +if (depth && ++env->liveness->subprog_calls >10000 ) {verbose (env,"liveness analysis exceeded complexity limit (%d calls)\n" , env->liveness->subprog_calls);return -E2BIG ;
@@ -2817,7 +2818,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)struct bpf_insn *insns = env->prog->insnsi;struct insn_live_regs *state;int insn_cnt = env->prog->len; -int err =0 , i, subprog, start, end; +int err =0 , i, n =0 , subprog, start, end, *order;bool changed, ret_reg_pair;/* Use the following algorithm:
@@ -2840,7 +2841,8 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)* any instruction. */ state =kvzalloc_objs (*state, insn_cnt,BPF_VERIFIER_GFP ); -if (!state) { + order =kvzalloc_objs (*order, insn_cnt,BPF_VERIFIER_GFP ); +if (!state || !order) { err = -ENOMEM ; goto out; }
@@ -2854,6 +2856,15 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)compute_insn_live_regs (env, &insns[i], &state[i], ret_reg_pair); } +/* callees first, so a chain of calls takes one round */ +for (i =0 ; i < env->subprog_cnt; i++) { + subprog = env->subprog_topo_order[i]; + start = env->subprog_info[subprog].postorder_start; + end = env->subprog_info[subprog +1 ].postorder_start; +while (start < end) + order[n++] = env->cfg.insn_postorder[start++]; + } + changed = true;while (changed) {u32 args =mask_widen (GENMASK (BPF_REG_5 ,BPF_REG_1 )), callx_use =0 , declared;
@@ -2882,7 +2893,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env) goto out; }for (i =0 ; i < env->cfg.cur_postorder; ++i) { -int insn_idx = env->cfg.insn_postorder[i]; +int insn_idx = order[i];struct insn_live_regs *live = &state[insn_idx];struct bpf_iarray *succ;u32 new_out =0 ;
@@ -2943,6 +2954,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)*/ err =bpf_compute_subprog_arg_access (env); out: +kvfree (order);kvfree (state);return err; }
kernel/bpf/syscall.c +20 -5
@@ -2465,7 +2465,7 @@ static void __bpf_prog_put_rcu(struct rcu_head *rcu)kvfree (aux->jited_linfo);kvfree (aux->linfo);kvfree (aux->func_info); -kfree (aux->func_info_aux); +kvfree (aux->func_info_aux);free_uid (aux->user);security_bpf_prog_free (aux->prog);bpf_prog_free (aux->prog);
@@ -5035,7 +5035,22 @@ static int bpf_prog_map_addrs(const struct bpf_prog *prog, struct maple_tree *mtreturn err; } -static void prepare_dump_pseudo_call (struct bpf_insn *insn) +/* 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; + +while (r - l >1 ) { + m = (l + r) /2 ; +if (prog->aux->func[m]->aux->subprog_start <= start) + l = m; +else + r = m; + } +return l; +} + +static void prepare_dump_pseudo_call (const struct bpf_prog *prog,struct bpf_insn *insn,u32 idx) {s32 call_off = insn->imm;
@@ -5044,12 +5059,12 @@ static void prepare_dump_pseudo_call(struct bpf_insn *insn)* 1. For interpreter (BPF_CALL_ARGS): insn->off is the index of * interpreters_args array, so here using bpf_call_args_imm() * to get the real address offset. -* 2. For JIT (BPF_CALL): insn->off is the subprog id. +* 2. For JIT (BPF_CALL): the subprog id. */ if (insn->code == (BPF_JMP |BPF_CALL_ARGS )) insn->imm =bpf_call_args_imm (insn->off);else - insn->imm = insn->off; + insn->imm =bpf_prog_find_func (prog, idx + call_off +1 );/* Avoid dumping a truncated and misleading pc-relative offset. */ if (call_off >S16_MAX || call_off <S16_MIN )
@@ -5093,7 +5108,7 @@ static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog, code == (BPF_JMP | BPF_CALL_ARGS)) {/* Restore the legacy xlated dump layout. */ if (insns[i].src_reg ==BPF_PSEUDO_CALL ) -prepare_dump_pseudo_call (&insns[i]); +prepare_dump_pseudo_call (prog, &insns[i], i);if (code == (BPF_JMP |BPF_CALL_ARGS )) insns[i].code =BPF_JMP |BPF_CALL ;if (!bpf_dump_raw_ok (f_cred))
kernel/bpf/verifier.c +36 -40
125 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 17/21 bpf: Walk each type once when looking for special fields
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The walk enters a struct again for each member of that type. With three members on each level it takes 3^depth steps, in recursion, and cannot be killed. Only the limit of 32 levels ends it.
Enter a struct once and copy the fields that were found:
struct in { kptr p; };
struct out { struct in a; long x; struct in b[2]; };
enter 'in' copy from a, twice
The walk has its own stack, so the depth is free. The table of fields grows, so BTF_FIELDS_MAX goes away. Fields are found in order and do not
overlap: look them up with a binary search.
A map value with 12 kptrs had no record at all. It has one now, so the rules for special fields apply: the map needs CAP_BPF, and it cannot be mmaped or BPF_F_RDONLY_PROG.
The size of a record is bounded by the size of what it describes. For a map it is value_size. An allocated object has 4096 bytes, that is 512 fields. A struct with more gets no record when the BTF is loaded.
--- include/linux/bpf.h | 5 - include/linux/bpf_verifier.h | 15 + kernel/bpf/btf.c | 334 ++++++++---------- kernel/bpf/syscall.c | 6 +- kernel/bpf/verifier.c | 67 ++-- .../selftests/bpf/progs/cpumask_common.h | 3 - .../selftests/bpf/progs/cpumask_failure.c | 5 +- 7 files changed, 197 insertions(+), 238 deletions(-)
include/linux/bpf.h +0 -5
@@ -193,11 +193,6 @@ struct bpf_map_ops {const struct bpf_iter_seq_info *iter_seq_info; }; -enum { -/* Support at most 11 fields in a BTF type */ -BTF_FIELDS_MAX =11 , -}; -enum btf_field_type {BPF_SPIN_LOCK = (1 <<0 ),BPF_TIMER = (1 <<1 ),
include/linux/bpf_verifier.h +15 -0
@@ -1975,6 +1975,21 @@ static inline int bpf_head_guard_target(const struct bpf_verifier_env *env, int }bool bpf_subprog_is_global (const struct bpf_verifier_env *env,int subprog); +/* The first field that ends behind 'off'. The fields are sorted and do not overlap. */ +static inline u32 btf_record_first_field (const struct btf_record *rec,s64 off) +{ +u32 l =0 , r = rec->cnt, m; + +while (l < r) { + m = (l + r) /2 ; +if (rec->fields[m].offset + rec->fields[m].size <= off) + l = m +1 ; +else + r = m; + } +return l; +} +/* Kinds of member a by-value struct or union may be composed of. */ enum btf_member_kind {BTF_MEMBER_SCALAR =BIT (0 ),/* an int or an enum */
kernel/bpf/btf.c +145 -189
462 lines not on this page · raw message
kernel/bpf/syscall.c +4 -2
@@ -703,7 +703,7 @@ void btf_record_free(struct btf_record *rec)continue ; } } -kfree (rec); +kvfree (rec); }void bpf_map_free_record (struct bpf_map *map)
@@ -721,7 +721,7 @@ struct btf_record *btf_record_dup(const struct btf_record *rec)if (IS_ERR_OR_NULL (rec))return NULL ; size =struct_size (rec, fields, rec->cnt); - new_rec =kmemdup (rec, size,GFP_KERNEL | __GFP_NOWARN); + new_rec =kvmemdup (rec, size,BPF_VERIFIER_GFP );if (!new_rec)return ERR_PTR (-ENOMEM );/* Do a deep copy of the btf_record */
@@ -1293,6 +1293,8 @@ static int map_check_btf(struct bpf_map *map, struct bpf_token *token,BPF_RB_ROOT |BPF_REFCOUNT |BPF_WORKQUEUE |BPF_UPTR |BPF_TASK_WORK |BPF_RCU_HEAD , map->value_size); +if (map->record ==ERR_PTR (-ENOMEM ) || map->record ==ERR_PTR (-EINTR )) +return PTR_ERR (map->record);if (!IS_ERR_OR_NULL (map->record)) {int i;
kernel/bpf/verifier.c +31 -36
79 lines not on this page · raw message
tools/testing/selftests/bpf/progs/cpumask_common.h +0 -3
@@ -7,9 +7,6 @@#include "errno.h" #include <stdbool.h> -/* Should use BTF_FIELDS_MAX, but it is not always available in vmlinux.h, -* so use the hard-coded number as a workaround. -*/ #define CPUMASK_KPTR_FIELDS_MAX 11int err;
tools/testing/selftests/bpf/progs/cpumask_failure.c +2 -3
@@ -15,7 +15,6 @@ struct kptr_nested_array_2 { };struct kptr_nested_array_1 { -/* Make btf_parse_fields() in map_create() return -E2BIG */ struct kptr_nested_array_2 d_2[CPUMASK_KPTR_FIELDS_MAX +1 ]; };
@@ -213,8 +212,8 @@ int BPF_PROG(test_global_mask_rcu_no_null_check, struct task_struct *task, u64 c } SEC("tp_btf/task_newtask") -__failure __msg("has no valid kptr") -int BPF_PROG(test_invalid_nested_array, struct task_struct *task, u64 clone_flags) +__success +int BPF_PROG (test_big_nested_array ,struct task_struct *task,u64 clone_flags) {struct bpf_cpumask *local, *prev;
Signature · 1 line
2.55.0
PATCH v2 18/21 bpf: Raise the limit on the length of BTF names
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A name of 513 bytes refuses the whole BTF. Mangled names can be longer. The users that copy a name use snprintf(). Raise the limit to 4096. It cannot go away: a search by name takes types x length, and so does the log. The search can be stopped now.
Many types can point into one long string. Look at each byte once and keep a bit for each offset:
strings: f o o \0 b \7 r \0
names: 1 1 1 0 0 0 1 0
--- kernel/bpf/btf.c | 108 +++++++++++++++++++++++------------------------ 1 file changed, 52 insertions(+), 56 deletions(-)
kernel/bpf/btf.c +52 -56
@@ -309,6 +309,9 @@ enum resolve_mode {*/ }; +/* It bounds the time of the loops that compare or print names */ +#define BTF_MAX_NAME_LEN 4096 +#define MAX_RESOLVE_DEPTH 32struct btf_sec_info {
@@ -320,6 +323,7 @@ struct btf_verifier_env {struct btf *btf;u8 *visit_states;struct resolve_vertex stack[MAX_RESOLVE_DEPTH ]; +unsigned long *names;/* offsets of the strings that can be names */ struct bpf_verifier_log log;u32 log_type_id;u32 top_stack;
@@ -685,10 +689,15 @@ s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)return id; } }else { +/* only the tags in BTF of a program have long names */ +bool slow = !btf->kernel_btf &&strlen (name) >KSYM_NAME_LEN ; +for (id =btf_start_id (btf); id < total; id++) { t =btf_type_by_id (btf, id);if (BTF_INFO_KIND (t->info) != kind)continue ; +if (slow &&bpf_must_abort ()) +return -EINTR ; tname =btf_name_by_offset (btf, t->name_off);if (strcmp (tname, name) ==0 )return id;
@@ -915,49 +924,6 @@ const char *btf_str_by_offset(const struct btf *btf, u32 offset)return NULL ; } -/* Names in BTF of Rust are not C identifiers. Allow any printable character */ -static bool btf_name_valid_identifier (const struct btf *btf,u32 offset) -{ -/* offset must be valid */ -const char *src =btf_str_by_offset (btf, offset); -const char *src_limit; - -if (!isprint (*src)) -return false; - -/* set a limit on identifier length */ - src_limit = src +KSYM_NAME_LEN ; - src++; -while (*src && src < src_limit) { -if (!isprint (*src)) -return false; - src++; - } - -return !*src; -} - -/* Allow any printable character in DATASEC names */ -static bool btf_name_valid_section (const struct btf *btf,u32 offset) -{ -/* offset must be valid */ -const char *src =btf_str_by_offset (btf, offset); -const char *src_limit; - -if (!*src) -return false; - -/* set a limit on identifier length */ - src_limit = src +KSYM_NAME_LEN ; -while (*src && src < src_limit) { -if (!isprint (*src)) -return false; - src++; - } - -return !*src; -} -static const char *__btf_name_by_offset (const struct btf *btf,u32 offset) {const char *name;
@@ -1993,9 +1959,21 @@ static int env_resolve_init(struct btf_verifier_env *env)static void btf_verifier_env_free (struct btf_verifier_env *env) {kvfree (env->visit_states); +kvfree (env->names);kfree (env); } +/* Names in BTF of Rust are not C identifiers. Allow any printable character */ +static bool btf_name_valid (const struct btf_verifier_env *env,u32 offset) +{ +const struct btf *btf = env->btf; + +/* offset must be valid */ +if (offset < btf->start_str_off) +return *btf_str_by_offset (btf, offset); +return test_bit (offset - btf->start_str_off, env->names); +} +static bool env_type_is_resolve_sink (const struct btf_verifier_env *env,const struct btf_type *next_type) {
@@ -2768,7 +2746,7 @@ static int btf_ref_type_check_meta(struct btf_verifier_env *env,*/ if (BTF_INFO_KIND (t->info) ==BTF_KIND_TYPEDEF ) {if (!t->name_off || - !btf_name_valid_identifier (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -3030,7 +3008,7 @@ static s32 btf_fwd_check_meta(struct btf_verifier_env *env,/* fwd type must have a valid name */ if (!t->name_off || - !btf_name_valid_identifier (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -3353,7 +3331,7 @@ static s32 btf_struct_check_meta(struct btf_verifier_env *env,/* struct type either no name or a valid one */ if (t->name_off && - !btf_name_valid_identifier (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -3371,7 +3349,7 @@ static s32 btf_struct_check_meta(struct btf_verifier_env *env,/* struct member either no name or a valid one */ if (member->name_off && - !btf_name_valid_identifier (btf, member->name_off)) { + !btf_name_valid (env, member->name_off)) {btf_verifier_log_member (env, t, member,"Invalid name" );return -EINVAL ; }
@@ -4162,6 +4140,8 @@ static int btf_parse_graph_root(const struct btf *btf,* verify its type. */ for_each_member (i, t, member) { +if (bpf_must_abort ()) +return -EINTR ;if (strcmp (info->graph_root.node_name,__btf_name_by_offset (btf, member->name_off)))continue ;
@@ -4640,7 +4620,7 @@ static s32 btf_enum_check_meta(struct btf_verifier_env *env,/* enum type either no name or a valid one */ if (t->name_off && - !btf_name_valid_identifier (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -4656,7 +4636,7 @@ static s32 btf_enum_check_meta(struct btf_verifier_env *env,/* enum member must have a valid name */ if (!enums[i].name_off || - !btf_name_valid_identifier (btf, enums[i].name_off)) { + !btf_name_valid (env, enums[i].name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -4748,7 +4728,7 @@ static s32 btf_enum64_check_meta(struct btf_verifier_env *env,/* enum type either no name or a valid one */ if (t->name_off && - !btf_name_valid_identifier (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -4764,7 +4744,7 @@ static s32 btf_enum64_check_meta(struct btf_verifier_env *env,/* enum member must have a valid name */ if (!enums[i].name_off || - !btf_name_valid_identifier (btf, enums[i].name_off)) { + !btf_name_valid (env, enums[i].name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -5054,7 +5034,7 @@ static s32 btf_locsec_check_meta(struct btf_verifier_env *env, }if (!t->name_off || - !btf_name_valid_section (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -5246,7 +5226,7 @@ static s32 btf_func_check_meta(struct btf_verifier_env *env, u32 meta_left) {if (!t->name_off || - !btf_name_valid_identifier (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -5315,7 +5295,7 @@ static s32 btf_var_check_meta(struct btf_verifier_env *env, }if (!t->name_off || - !btf_name_valid_identifier (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -5381,7 +5361,7 @@ static s32 btf_datasec_check_meta(struct btf_verifier_env *env, }if (!t->name_off || - !btf_name_valid_section (env->btf, t->name_off)) { + !btf_name_valid (env, t->name_off)) {btf_verifier_log_type (env, t,"Invalid name" );return -EINVAL ; }
@@ -5768,7 +5748,7 @@ static int btf_func_proto_check(struct btf_verifier_env *env,if (args[i].name_off && (!btf_name_offset_valid (btf, args[i].name_off) || - !btf_name_valid_identifier (btf, args[i].name_off))) { + !btf_name_valid (env, args[i].name_off))) {btf_verifier_log_type (env, t,"Invalid arg#%u" , i +1 );return -EINVAL ;
@@ -6067,6 +6047,7 @@ static int btf_parse_str_sec(struct btf_verifier_env *env)const struct btf_header *hdr;struct btf *btf = env->btf;const char *start, *end; +u32 i, len =0 ; hdr = &btf->hdr; start = btf->nohdr_data + hdr->str_off;
@@ -6091,6 +6072,21 @@ static int btf_parse_str_sec(struct btf_verifier_env *env)return -EINVAL ; } +/* many names can share one long string: look at each byte once */ +kvfree (env->names); + env->names =kvcalloc (BITS_TO_LONGS (hdr->str_len),sizeof (long ), +GFP_KERNEL | __GFP_NOWARN); +if (!env->names) +return -ENOMEM ; +for (i = hdr->str_len; i--;) { +if (!start[i]) + len =0 ; +else if (!isprint (start[i])) + len =BTF_MAX_NAME_LEN ; +else if (len++ <BTF_MAX_NAME_LEN ) +__set_bit (i, env->names); + } +return 0 ; }
Signature · 1 line
2.55.0
PATCH v2 19/21 bpf: Find dominators in O(n log n)
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The intersection walks up the dominator tree for each predecessor. Many edges to one insn make it quadratic:
if ... goto out 30000 of them take 13 s, 100000 do not finish
if ... goto out
...
out:
Use the algorithm of Lengauer and Tarjan, with path compression.
--- kernel/bpf/loops.c | 157 ++++++++++++++++++++++++++++----------------- 1 file changed, 98 insertions(+), 59 deletions(-)
kernel/bpf/loops.c +98 -59
@@ -96,78 +96,117 @@ static int idoms_intersect(struct bpf_verifier_env *env, int a, int b)return a; } -/* See "A Simple, Fast Dominance Algorithm" by Cooper et al. for details. */ -static int compute_subprog_idoms (struct bpf_verifier_env *env,struct bpf_iarray **preds, -int subprog_idx) -{ -struct bpf_subprog_info *subprog = &env->subprog_info[subprog_idx]; -int start = subprog->start; -int po_first = subprog->postorder_start; -int po_last = (subprog +1 )->postorder_start -1 ; -int *idoms = env->idoms; -int po_num, pred; -bool changed; +/* An insn. The nodes are in the order of a depth-first walk, node 0 is none. */ +struct idom_node { +u32 insn; +u32 parent;/* in the walk */ +u32 semi;/* semidominator */ +u32 idom; +u32 up;/* a parent, or a parent of it, once the node is done */ +u32 min;/* the node with the lowest 'semi' on the way to 'up' */ +u32 bucket;/* list of the nodes whose 'semi' this node is */ +u32 next;/* in that list. Before that the next successor for the walk */ +}; - idoms[start] = start; - changed = true; -do { - changed = false; -/* -* Iterate in reverse postorder, skipping the subprog entry: -* insn_postorder[po_last] is the subprogram entry. -*/ -for (po_num = po_last -1 ; po_num >= po_first; po_num--) { -int idx = env->cfg.insn_postorder[po_num]; -int new_idom =-1 ; - -iarray_for_each (pred, preds[idx]) { -if (bpf_must_abort ()) -return -EINTR ; - -if (idoms[pred] ==-1 ) -continue ; -if (new_idom ==-1 ) - new_idom = pred; -else - new_idom =idoms_intersect (env, pred, new_idom); - } -if (new_idom !=-1 && idoms[idx] != new_idom) { - idoms[idx] = new_idom; - changed = true; - } - } - }while (changed); - idoms[start] =-1 ; -return 0 ; +/* The node with the lowest 'semi' on the way up from node 'id'. Makes the way short. */ +static u32 idom_eval (struct idom_node *nodes,u32 *path,u32 id) +{ +struct idom_node *node, *up; +u32 cnt =0 , cur; + +for (cur = id; nodes[nodes[cur].up].up; cur = nodes[cur].up) + path[cnt++] = cur; +while (cnt--) { + node = &nodes[path[cnt]]; + up = &nodes[node->up]; +if (nodes[up->min].semi < nodes[node->min].semi) + node->min = up->min; + node->up = up->up; + } +return nodes[id].min; } +/* +* See "A Fast Algorithm for Finding Dominators in a Flowgraph" by Lengauer and Tarjan. +* +* 1 -> 2 -> 3 -> 4 walk: parent[4] = 3 +* | ^ from the end: semi[4] = 1 +* +-> 5 ---------+ from the top: idom[4] = 1 +*/ int bpf_compute_idoms (struct bpf_verifier_env *env) { -struct bpf_iarray **preds; -u32 len = env->prog->len; -int *idoms, i, err =0 ; +u32 len = env->prog->len, cnt =0 , i, insn, id, cur, best, *num, *path; +struct bpf_iarray **preds, *succ; +struct idom_node *nodes, *node; +int err = -ENOMEM ; preds =compute_predecessors (env); -if (!preds) -return -ENOMEM ; + env->idoms =kvmalloc_objs (*env->idoms, len,BPF_VERIFIER_GFP ); + nodes =kvzalloc_objs (*nodes, len +1 ,BPF_VERIFIER_GFP ); +/* insn -> node */ + num =kvzalloc_objs (*num,2 * (size_t )len,BPF_VERIFIER_GFP ); + path = num + len; +if (!preds || !env->idoms || !nodes || !num) + goto out; +memset (env->idoms,0xff , len *sizeof (*env->idoms)); - idoms =kvzalloc_objs (*idoms, len,BPF_VERIFIER_GFP ); -if (!idoms) { -kvfree (preds); -return -ENOMEM ; + err = -EINTR ; +for (i =0 ; i < env->subprog_cnt; i++) { + insn = env->subprog_info[i].start; +for (cur =0 ;; insn = succ->items[nodes[cur].next++]) { +if (!num[insn]) { + num[insn] = ++cnt; + nodes[cnt] = (struct idom_node ){ insn, cur, cnt, .min = cnt }; + cur = cnt; + } +if (bpf_must_abort ()) + goto out; +/* go back to a node that has a successor left */ +for (; cur; cur = nodes[cur].parent) { + succ =bpf_insn_successors (env, nodes[cur].insn); +if (nodes[cur].next < succ->cnt) +break ; + } +if (!cur) +break ; + } } - env->idoms = idoms; -for (i =0 ; i < len; i++) - idoms[i] =-1 ; - -for (i =0 ; i < env->subprog_cnt; i++) { - err =compute_subprog_idoms (env, preds, i); -if (err) -break ; +for (id = cnt; id; id--) { + node = &nodes[id]; +if (!node->parent) +continue ; +iarray_for_each (insn, preds[node->insn]) { +if (bpf_must_abort ()) + goto out; +if (!num[insn]) +continue ; + best =idom_eval (nodes, path, num[insn]); + node->semi =min (node->semi, nodes[best].semi); + } + node->next = nodes[node->semi].bucket; + nodes[node->semi].bucket = id; + node->up = node->parent; +for (cur = nodes[node->parent].bucket; cur; cur = nodes[cur].next) { + best =idom_eval (nodes, path, cur); + nodes[cur].idom = nodes[best].semi < nodes[cur].semi ? best : node->parent; + } + nodes[node->parent].bucket =0 ; } +for (id =1 ; id <= cnt; id++) { + node = &nodes[id]; +if (!node->parent) +continue ; +if (node->idom != node->semi) + node->idom = nodes[node->idom].idom; + env->idoms[node->insn] = nodes[node->idom].insn; + } + err =0 ; +out:kvfree (preds); +kvfree (nodes); +kvfree (num);return err; }
Signature · 1 line
2.55.0
PATCH v2 20/21 selftests/bpf: Test programs above the old limits
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
100 maps, 1100 subprogs, calls in dead code, 1000 kptrs, far cleanup pads, bpf_loop() with a dead callback. Unsafe twins must fail.
--- .../selftests/bpf/prog_tests/verifier.c | 4 + .../bpf/progs/verifier_callx_dead_cb.c | 60 +++++ .../selftests/bpf/progs/verifier_no_limits.c | 224 ++++++++++++++++++ .../selftests/bpf/progs/verifier_unwind.c | 32 +++ 4 files changed, 320 insertions(+) create mode 100644 tools/testing/selftests/bpf/progs/verifier_callx_dead_cb.c create mode 100644 tools/testing/selftests/bpf/progs/verifier_no_limits.c
tools/testing/selftests/bpf/prog_tests/verifier.c +4 -0
@@ -39,6 +39,7 @@#include "verifier_call_large_imm.skel.h" #include "verifier_calls_in_a_row.skel.h" #include "verifier_callx.skel.h" +#include "verifier_callx_dead_cb.skel.h" #include "verifier_callx_many.skel.h" #include "verifier_callx_rodata.skel.h" #include "verifier_cfg.skel.h"
@@ -110,6 +111,7 @@#include "verifier_netfilter_retcode.skel.h" #include "verifier_bpf_fastcall.skel.h" #include "verifier_or_jmp32_k.skel.h" +#include "verifier_no_limits.skel.h" #include "verifier_patch_list.skel.h" #include "verifier_percpu_addr.skel.h" #include "verifier_precision.skel.h"
@@ -248,6 +250,7 @@ void test_verifier_btf_unreliable_prog(void) { RUN(verifier_btf_unreliable_progvoid test_verifier_call_large_imm (void ) {RUN (verifier_call_large_imm); }void test_verifier_calls_in_a_row (void ) {RUN (verifier_calls_in_a_row); }void test_verifier_callx (void ) {RUN_JITED (verifier_callx); } +void test_verifier_callx_dead_cb (void ) {RUN_JITED (verifier_callx_dead_cb); }void test_verifier_callx_many (void ) {RUN_JITED (verifier_callx_many); }void test_verifier_callx_rodata (void ) {RUN_JITED (verifier_callx_rodata); }void test_verifier_cfg (void ) {RUN (verifier_cfg); }
@@ -317,6 +320,7 @@ void test_verifier_mul(void) { RUN(verifier_mul); }void test_verifier_netfilter_ctx (void ) {RUN (verifier_netfilter_ctx); }void test_verifier_netfilter_retcode (void ) {RUN (verifier_netfilter_retcode); }void test_verifier_bpf_fastcall (void ) {RUN (verifier_bpf_fastcall); } +void test_verifier_no_limits (void ) {RUN_JITED (verifier_no_limits); }void test_verifier_or_jmp32_k (void ) {RUN (verifier_or_jmp32_k); }/* * Run serially with bpf_jit_harden at 0: blinding changes the xlated insns that
tools/testing/selftests/bpf/progs/verifier_callx_dead_cb.c new file +60 -0
60 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_no_limits.c new file +224 -0
224 lines not on this page · raw message
tools/testing/selftests/bpf/progs/verifier_unwind.c +32 -0
@@ -69,6 +69,38 @@ static unsigned long may_unwind(void) ); } +/* The patches of the divisions push the pad out of the 16-bit range */ +#define FAR_PAD (name, sub) \ +__naked void name(void) \ +{ \ + asm volatile ( \ + "r6 = *(u32 *)(r1 + 0);" \ + "r1 = r6;" \ + "r1 -= " #sub ";" \ + "call may_unwind;" \ + unwind_goto(8202) \ + "r7 = 1;" \ + ".rept 8200; r7 /= r6; .endr;" \ + "exit;" \ + "r0 += 100;" \ + "exit;" \ + : \ + : __imm_unwind_goto(8202) \ + : __clobber_all); \ +} + +SEC("tc") +__arch_x86_64 __arch_arm64 +__success __retval(7) +__load_if_JITed() +FAR_PAD(far_pad_returns, 64) + +SEC("tc") +__arch_x86_64 __arch_arm64 +__success __retval(105) +__load_if_JITed() +FAR_PAD (far_pad_unwinds,0 ) + /* owns nothing: its pad only carries on */__naked __noinline __used static unsigned long passes_on(void)
Signature · 1 line
2.55.0
PATCH v2 21/21 selftests/bpf: Test limits of the load with raw programs
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A load under a timer signal, under the freezer and in a small memory cgroup, the context of a syscall program, 33000 subprogs, a dump of more than 4 MB, 300 kfuncs, loops of BTF types, long BTF names, a light skeleton with 600 maps and 601 programs.
--- tools/testing/selftests/bpf/Makefile.skel | 2 +- .../selftests/bpf/prog_tests/no_limits.c | 465 ++++++++++++++++++ .../testing/selftests/bpf/progs/many_progs.c | 36 ++ 3 files changed, 502 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/no_limits.c create mode 100644 tools/testing/selftests/bpf/progs/many_progs.c
tools/testing/selftests/bpf/Makefile.skel +1 -1
@@ -34,7 +34,7 @@ LINKED_SKELS := test_static_linked.skel.h linked_funcs.skel.h \ LSKELS := fexit_sleep.c trace_printk.c trace_vprintk.c map_ptr_kern.c \ core_kern.c core_kern_overflow.c test_ringbuf.c \ test_ringbuf_n.c test_ringbuf_map_key.c test_ringbuf_write.c \ - test_ringbuf_overwrite.c callx_rodata.c + test_ringbuf_overwrite.c callx_rodata.c many_progs.c LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c
tools/testing/selftests/bpf/prog_tests/no_limits.c new file +465 -0
465 lines not on this page · raw message
tools/testing/selftests/bpf/progs/many_progs.c new file +36 -0
@@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0 +#include <vmlinux.h> +#include <bpf/bpf_helpers.h> + +#define REP10 (M , p) M(p##0) M(p##1) M(p##2) M(p##3) M(p##4) M(p##5) M(p##6) M(p##7) M(p##8) M(p##9) +#define REP100 (M , p) REP10(M, p##0) REP10(M, p##1) REP10(M, p##2) REP10(M, p##3) REP10(M, p##4) \ + REP10(M, p##5) REP10(M, p##6) REP10(M, p##7) REP10(M, p##8) REP10(M, p##9) + +#define PROG (n) \ +struct { \ + __uint(type, BPF_MAP_TYPE_ARRAY); \ + __uint(max_entries, 1); \ + __type(key, int); \ + __type(value, int); \ +} map##n SEC(".maps"); \ + \ +SEC("tc") \ +int prog##n(void *ctx) \ +{ \ + int *v = bpf_map_lookup_elem(&map##n, &(int){ 0 }); \ + \ + return v ? *v + n : 0; \ +} + +REP100(PROG, 1) REP100(PROG, 2) REP100(PROG, 3) REP100(PROG, 4) REP100(PROG, 5) REP100(PROG, 6) + +extern const void no_such_symbol __ksym __weak; + +/* The loader is more than 32768 insns away from its cleanup code */ +SEC("tc") +int last (void *ctx) +{ +return &no_such_symbol ?1 :2 ; +} + +char _license[] SEC("license") = "GPL";
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf-next v2 21/21] selftests/bpf: Test limits of the load with raw programs
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] selftests/bpf: unguarded JIT-only xlated imm check in test_subprogs() - [Low] selftests/bpf: pipe…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] selftests/bpf: unguarded JIT-only xlated imm check in test_subprogs()
- [Low] selftests/bpf: pipe write fd leak on error path in test_freezer()
- [Low] selftests/bpf: unchecked fork() in no_limits reads uninitialized status
--
commit 3c35bcd7e95d13e7559756b6f54585ddac4df9c1
Author: Alexei Starovoitov <[email protected]>
selftests/bpf: Test limits of the load with raw programs
This commit adds BPF selftests covering program loading under signals, the cgroup freezer, and memory cgroup limits, as well as tests for syscall program context, large subprogram counts, xlated dumps, kfuncs, BTF type chains, and a light skeleton with many maps and programs.
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/no_limits.c new file +0
-0@@ -0,0 +1,465 @@
[ ... ]
tools/testing/selftests/bpf/prog_tests/no_limits.c line 62
Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/no_limits.c new file +9
-0+static int exit_code (pid_t pid) +{ +int status; + +if (!ASSERT_EQ (waitpid (pid, &status,0 ), pid,"wait" ) || + !ASSERT_TRUE (WIFEXITED (status),"exited" )) +return -1 ; +return WEXITSTATUS (status); +}
[Severity: Low]
Can exit_code() read an uninitialized status if fork() fails in test_freezer() or load_in_memcg()? When pid is -1, waitpid(-1, &status,
0) fails with ECHILD and returns -1 without writing status, which passes ASSERT_EQ(-1, -1) and then evaluates WIFEXITED(status) and WEXITSTATUS(status) on uninitialized stack memory.
Quoted 43 lines
tools/testing/selftests/bpf/prog_tests/no_limits.c new file +43
-0+ +/* The freezer does not wait for the end of the load. The load starts again after it. */ +static void test_freezer (int flag) +{ +struct bpf_insn *insns =straight_code (200000 ); +struct bpf_common_attr common = {}; +union bpf_attr attr = { + .prog_type =BPF_PROG_TYPE_SCHED_CLS , + .insns =ptr_to_u64 (insns), + .insn_cnt =200000 , + .license =ptr_to_u64 ("GPL" ), + }; +int cg =-1 , pipes[2 ] = {-1 ,-1 }, fd; +char buf[64 ] ="" ; +pid_t pid; + +if (!insns || !ASSERT_OK (setup_cgroup_environment (),"setup" ) || + !ASSERT_OK (pipe (pipes),"pipe" )) + goto out; + cg =create_and_get_cgroup ("/no_limits" ); +if (!ASSERT_OK_FD (cg,"cgroup" )) + goto out; + pid =fork (); +if (!pid) { +/* the fd that the prog gets */ +if (join_parent_cgroup ("/no_limits" )) +_exit (1 ); + fd =dup (pipes[0 ]); +close (fd); +if (write (pipes[1 ], &fd,sizeof (fd)) !=sizeof (fd)) +_exit (2 ); +_exit (syscall (__NR_bpf,BPF_PROG_LOAD | flag, &attr,sizeof (attr), &common, +sizeof (common)) != fd ?3 :0 ); + } +close (pipes[1 ]); +if (ASSERT_EQ (read (pipes[0 ], &fd,sizeof (fd)),sizeof (fd),"read" )) { +usleep (10000 ); +ASSERT_OK (write_cgroup_file ("/no_limits" ,"cgroup.freeze" ,"1" ),"freeze" ); +while (!strstr (buf,"frozen 1" ) && + !read_cgroup_file ("/no_limits" ,"cgroup.events" , buf,sizeof (buf))) +usleep (1000 ); +snprintf (buf,sizeof (buf),"/proc/%d/fd/%d" , pid, fd); +ASSERT_ERR (faccessat (AT_FDCWD , buf,F_OK ,AT_SYMLINK_NOFOLLOW ),"no prog yet" );
tools/testing/selftests/bpf/prog_tests/no_limits.c line 115
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/no_limits.c new file +10
-0+ASSERT_OK (write_cgroup_file ("/no_limits" ,"cgroup.freeze" ,"0" ),"thaw" ); + } +ASSERT_OK (exit_code (pid),"load" ); +out: +close (pipes[0 ]); +if (cg >=0 ) +close (cg); +cleanup_cgroup_environment (); +free (insns); +}
[Severity: Low]
Does the out path leak pipes[1] if create_and_get_cgroup() fails after pipe(pipes) succeeds? Also, if an earlier check jumps to out before pipe(pipes) succeeds, close(pipes[0]) calls close(-1).
[ ... ]
Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/no_limits.c new file +9
-0+/* The number of a subprog does not fit into s16 */ +static void test_subprogs (void ) +{ +const int funcs =33000 , cnt =4 * funcs +1 ; +struct bpf_insn *insns =many_funcs (funcs); +struct bpf_prog_info info = {}; +__u32 len =sizeof (info); +int fd; +
tools/testing/selftests/bpf/prog_tests/no_limits.c line 245
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/no_limits.c new file +10
-0+if (!insns) +return ; + fd =load (insns, cnt); +if (!ASSERT_OK_FD (fd,"load" )) + goto out; +ASSERT_EQ (run (fd), funcs -1 ,"retval" ); + info.xlated_prog_len = cnt *sizeof (*insns); + info.xlated_prog_insns =ptr_to_u64 (insns); +if (ASSERT_OK (bpf_prog_get_info_by_fd (fd, &info, &len),"dump" )) +ASSERT_EQ (insns[funcs -1 ].imm, funcs,"subprog" );
[Severity: Medium]
Will this assertion fail when BPF JIT is disabled?
When a program is interpreted rather than JIT-compiled, bpf_fixup_call_args() rewrites pseudo-calls to BPF_JMP | BPF_CALL_ARGS, and prepare_dump_pseudo_call() dumps bpf_call_args_imm(insn->off) into insn->imm instead of the target subprogram index:
kernel/bpf/syscall.c:prepare_dump_pseudo_call() {
...
if (insn->code == (BPF_JMP | BPF_CALL_ARGS))
insn->imm = bpf_call_args_imm(insn->off);
else
insn->imm = bpf_prog_find_func(prog, idx + call_off + 1);
...
}Should test_subprogs() check info.jited_prog_len (or env.jit_enabled) before asserting that insns[funcs - 1].imm equals funcs?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:
Hello:
This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:
Quoted 9 lines · On Mon, 16 Nov 2026 15:26:05 +0000 you wrote:
From: Alexei Starovoitov <[email protected]>
In short: the verifier keeps the maps, kfuncs, subprogs and special fields of a program in arrays of a fixed size. A safe program that needs one more entry is rejected. With this series the arrays grow with the program. What was quadratic or worse below a limit is linear or n log n now. Outside of
tools/the kernel loses 300 lines.[...]
Here is the summary with links:
- [bpf-next,v2,01/21] bpf: Stop a load only when the loader is killed or has to freeze
https://git.kernel.org/bpf/bpf-next/c/3a05f3d3c0bc - [bpf-next,v2,02/21] bpf: Fail the load when there is no memory https://git.kernel.org/bpf/bpf-next/c/4599bf12bb4f - [bpf-next,v2,03/21] bpf: Give a syscall program the largest context when it does tail calls https://git.kernel.org/bpf/bpf-next/c/08c987904970 - [bpf-next,v2,04/21] bpf: Do not inline bpf_loop() when its callback is dead code https://git.kernel.org/bpf/bpf-next/c/55bb28777e3a - [bpf-next,v2,05/21] bpf: Dump programs that have more than 524288 insns https://git.kernel.org/bpf/bpf-next/c/97d3a5d19de6 - [bpf-next,v2,06/21] bpf: Resolve BTF structs and arrays first https://git.kernel.org/bpf/bpf-next/c/9867cc99fb19 - [bpf-next,v2,07/21] bpf: Remove the limits on maps, BTFs and fd_array of a program https://git.kernel.org/bpf/bpf-next/c/1ec779c99e72 - [bpf-next,v2,08/21] bpf: Do not scan all maps for each insn and each subprog https://git.kernel.org/bpf/bpf-next/c/8aeba721ce8c - [bpf-next,v2,09/21] bpf: Remove the limits on kfuncs of a program https://git.kernel.org/bpf/bpf-next/c/dba6e823dc9a - [bpf-next,v2,10/21] bpf: Remove the limits on tables of functions https://git.kernel.org/bpf/bpf-next/c/66b31f31139e - [bpf-next,v2,11/21] libbpf: Size the tables of the loader program from the object https://git.kernel.org/bpf/bpf-next/c/cf46f59c622f - [bpf-next,v2,12/21] bpf: Relax jumps that patches push out of range https://git.kernel.org/bpf/bpf-next/c/80ab9d3a5e45 - [bpf-next,v2,13/21] bpf: Keep the call graph in lists of edges https://git.kernel.org/bpf/bpf-next/c/0073adc796bd - [bpf-next,v2,14/21] bpf: Find the effects of callees on the call graph https://git.kernel.org/bpf/bpf-next/c/8a7567b57874 - [bpf-next,v2,15/21] bpf: Link the decl tags of a type https://git.kernel.org/bpf/bpf-next/c/d01bec4218c7 - [bpf-next,v2,16/21] bpf: Remove BPF_MAX_SUBPROGS https://git.kernel.org/bpf/bpf-next/c/f7e93aa4a34f - [bpf-next,v2,17/21] bpf: Walk each type once when looking for special fields https://git.kernel.org/bpf/bpf-next/c/ca4395aade31 - [bpf-next,v2,18/21] bpf: Raise the limit on the length of BTF names https://git.kernel.org/bpf/bpf-next/c/00b7fccc41c7 - [bpf-next,v2,19/21] bpf: Find dominators in O(n log n) https://git.kernel.org/bpf/bpf-next/c/c424815cd9a1 - [bpf-next,v2,20/21] selftests/bpf: Test programs above the old limits https://git.kernel.org/bpf/bpf-next/c/eda0d4a09944 - [bpf-next,v2,21/21] selftests/bpf: Test limits of the load with raw programs https://git.kernel.org/bpf/bpf-next/c/633c547b1dab
You are awesome, thank you!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html