bpf: Share subprogs between programs
Subsystems (8)
v2 cover bpf: Share subprogs between programs
From: Alexei Starovoitov <[email protected]>
A scheduler or a datapath is many programs that call the same functions. Each program gets a copy of them, so they are verified and JITed N times. Load such programs together, with one copy.
before after
prog1: main1 | f | g entry1: main1 --+ prog2: main2 | f | g entry2: main2 --+--> owner: f | g prog3: main3 | f | g entry3: main3 --+
3 x BPF_PROG_LOAD, 3 fds 1 x BPF_PROG_LOAD, 3 fds
An entry is a program with its own fd, id, name, stats and streams. It's attached, pinned and closed like any other program. The owner has the code and goes away with the last entry.
libbpf does it by default for programs of one type and attach type, or of one struct_ops map, that call the same functions. It makes copies when the kernel has no entries or rejects the load. Light skeletons, signed or not, do the same.
It works on x86-64 and arm64. Tracing, LSM and extension programs, and programs with tail calls keep their copies. See patch 2 for the full list.
32 tc programs that call the same 65 global functions:
insns verified x86-64 code load copies 1056831 991295 4547452 bytes 1.60 s one copy 33118 31070 143034 bytes 0.12 s
sched_ext schedulers:
x86-64 code, bytes verified insns
progs copies shared copies shared
scx_qmap 26 109732 50129 36855 36855 scx_lavd 36 118101 68345 51763 54574 scx_rusty 14 42107 25912 12697 12697 scx_chaos 24 76758 57123 16299 16342 scx_p2dq 23 56888 48299 12531 12531 scx_layered 24 58401 52662 26795 26626
One copy takes less cache. 32 pairs of tasks ping-pong over pipes on 8 cpus. To evict the scheduler from the caches each task jumps through 1 MB or 2 MB of code per message, L2 is 1 MB. For hot cache it spins as long as 1 MB takes. run_time_ns of all struct_ops programs per round trip, copies -> shared:
hot cache 1 MB of code 2 MB of code scx_lavd 2326 -> 2332 0 % 2940 -> 2812 -4 % 10075 -> 9133 -9 % scx_rusty 1476 -> 1469 0 % 1741 -> 1731 -1 % 5936 -> 5530 -7 % scx_p2dq 2014 -> 2006 0 % 2354 -> 2308 -2 % 7054 -> 6551 -7 %
Round trips per second change from 0 % to +2.8 %, noise is 3 %.
v1 -> v2:
- Rebase on cancellations. Patch 3 is new: landing pads for many main programs.
- bpf_jit_supports_exceptions() is gone, use bpf_jit_supports_unwind().
- The limit on cost is for each main program, not for the load.
- libbpf shares when a log level is set too, and prints the verifier log of a rejected load.
- Fix the build of the selftest on s390.
v1: https://lore.kernel.org/bpf/[email protected]/
Alexei Starovoitov (7):
bpf: Prepare for many main programs in one load
bpf: Check many main programs in one set of insns
bpf: Generate landing pads for many main programs
bpf: Take entries at BPF_PROG_LOAD libbpf, bpftool: Share subprogs between programs
libbpf: Share subprogs in light skeletons selftests/bpf: Test programs that share subprogs
Documentation/bpf/verifier.rst | 47 +- include/linux/bpf.h | 89 +-- include/linux/bpf_verifier.h | 55 +- include/uapi/linux/bpf.h | 32 +- kernel/bpf/arena.c | 2 +- kernel/bpf/bpf_struct_ops.c | 64 ++- kernel/bpf/btf.c | 10 +- kernel/bpf/cfg.c | 8 +- kernel/bpf/core.c | 50 +- kernel/bpf/failing_path.c | 6 +- kernel/bpf/fixups.c | 115 ++-- kernel/bpf/flow.c | 48 +- kernel/bpf/pads.c | 63 ++- kernel/bpf/precision.c | 2 + kernel/bpf/stream.c | 33 +- kernel/bpf/syscall.c | 302 ++++++++-- kernel/bpf/verifier.c | 534 +++++++++++++++--- net/ipv4/bpf_tcp_ops.c | 3 +- tools/bpf/bpftool/cfg.c | 4 + tools/bpf/bpftool/common.c | 26 +- tools/bpf/bpftool/prog.c | 37 ++ tools/include/uapi/linux/bpf.h | 32 +- tools/lib/bpf/bpf.c | 40 +- tools/lib/bpf/bpf.h | 9 +- tools/lib/bpf/bpf_gen_internal.h | 3 +- tools/lib/bpf/gen_loader.c | 83 ++- tools/lib/bpf/libbpf.c | 349 +++++++++++- tools/testing/selftests/bpf/Makefile.skel | 2 +- .../selftests/bpf/prog_tests/bpf_attr_size.c | 2 +- .../selftests/bpf/prog_tests/call_rcu.c | 2 +- .../selftests/bpf/prog_tests/share_subprogs.c | 190 +++++++ .../selftests/bpf/prog_tests/unwind_attach.c | 4 +- .../selftests/bpf/progs/pro_epilogue.c | 4 +- .../selftests/bpf/progs/share_subprogs.c | 245 ++++++++ .../bpf/progs/share_subprogs_arena.c | 41 ++ .../bpf/progs/share_subprogs_signed.c | 87 +++ 36 files changed, 2324 insertions(+), 299 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/share_subprogs.c create mode 100644 tools/testing/selftests/bpf/progs/share_subprogs.c create mode 100644 tools/testing/selftests/bpf/progs/share_subprogs_arena.c create mode 100644 tools/testing/selftests/bpf/progs/share_subprogs_signed.c
base-commit: f7d8db28387ba2732c541caae20b5362b7dd5b7c
Signature · 1 line
2.55.0
PATCH v2 1/7 bpf: Prepare for many main programs in one load
From: Alexei Starovoitov <[email protected]>
The next patch lets one BPF_PROG_LOAD have many main programs that share the functions that they call. Today the verifier assumes that subprog 0 is the only main program. Remove the assumption:
- Mark the main program in subprog_info and test the mark.
- Group the fields of struct bpf_prog_aux that describe the attach point, and the fields that the verifier computes for attach and run. The first group will be swapped, the second one copied. It's not struct_group(), since that is a union, and a pointer that a tracing program reads from a union is not trusted.
- Split bpf_prog_alloc_attr() out of bpf_prog_load().
- Emit prologue, epilogue and the setup of the stack in arena for a given subprog.
No functional change.
--- include/linux/bpf.h | 66 ++++++++++++--------- include/linux/bpf_verifier.h | 30 ++++++++-- kernel/bpf/btf.c | 10 ++-- kernel/bpf/failing_path.c | 2 +- kernel/bpf/fixups.c | 107 ++++++++++++++++++++++------------- kernel/bpf/pads.c | 6 +- kernel/bpf/syscall.c | 42 +++++++++----- kernel/bpf/verifier.c | 74 ++++++++++++++---------- 8 files changed, 213 insertions(+), 124 deletions(-)
include/linux/bpf.h +38 -28
@@ -295,6 +295,7 @@ struct bpf_map_owner {enum bpf_prog_type type;bool jited;bool xdp_has_frags; +bool has_prologue;bool sleepable;u64 storage_cookie[MAX_BPF_CGROUP_STORAGE_TYPE ];const struct btf_type *attach_func_proto;
@@ -1913,25 +1914,54 @@ struct bpf_prog_aux {atomic64_t refcnt;u32 used_map_cnt;u32 used_btf_cnt; -u32 max_ctx_offset; -u32 max_pkt_offset; -u32 max_tp_access; -u32 stack_depth;u32 id;u32 func_cnt;/* used by non-func prog as the number of func progs */ u32 exception_callback_subprog;/* index in func[], 0 if there is none */ u32 func_idx;/* 0 for non-func prog, the index in func array for func prog */ +u32 subprog_start; +/* +* Up to recursion_detected: where the prog is attached, all that check_attach_btf_id() +* writes for types that can have entries. Each entry has its own, see enter_main(). +*/ u32 attach_btf_id;/* in-kernel BTF type id to attach to */ u32 attach_st_ops_member_off;u32 ctx_arg_info_size; +bool attach_btf_trace;/* true if attaching to BTF-enabled raw tp */ +bool priv_stack_requested; +struct btf *attach_btf; +struct bpf_ctx_arg_aux *ctx_arg_info; +/* BTF_KIND_FUNC_PROTO for valid attach_btf_id */ +const struct btf_type *attach_func_proto; +/* function name for valid attach_btf_id */ +const char *attach_func_name; +const struct bpf_struct_ops *st_ops; +/* callback if recursion is detected */ +void (*recursion_detected)(struct bpf_prog *prog); +/* +* Up to cgroup_storage: what the verifier has found in the insns, for those who attach +* and run the prog. An entry gets it from its owner, see finish_entry(). +*/ +u32 max_ctx_offset; +u32 max_pkt_offset; +u32 max_tp_access;u32 max_rdonly_access;u32 max_rdwr_access;/* [min, max): the bytes of a rdwr buffer that may be written */ u32 min_rdwr_write;u32 max_rdwr_write; -u32 subprog_start; -struct btf *attach_btf; -struct bpf_ctx_arg_aux *ctx_arg_info; +u32 stack_depth; +/* +* The size of the stack in arena that the program needs, a multiple of +* the page size. 0 when r12 is not used. +*/ +u32 arena_stack_size; +bool sleepable_async_cb;/* has a bpf_wq or bpf_task_work callback */ +bool tail_call_reachable; +bool jits_use_priv_stack; +bool changes_pkt_data; +bool might_sleep; +bool kprobe_write_ctx; +struct bpf_map *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE ];void __percpu *priv_stack_ptr;struct mutex dst_mutex;/* protects dst_* pointers below, *after* prog becomes visible */ struct bpf_prog *dst_prog;
@@ -1942,22 +1972,14 @@ struct bpf_prog_aux {bool verifier_zext;/* Zero extensions has been inserted by verifier. */ bool dev_bound;/* Program is bound to the netdev. */ bool offload_requested;/* Program is bound and offloaded to the netdev. */ -bool attach_btf_trace;/* true if attaching to BTF-enabled raw tp */ bool attach_tracing_prog;/* true if tracing another tracing program */ bool tramp_linked;/* true if it was ever linked to a trampoline */ -bool sleepable_async_cb;/* has a bpf_wq or bpf_task_work callback */ bool func_proto_unreliable; -bool tail_call_reachable;bool xdp_has_frags; -bool jits_use_priv_stack; -bool priv_stack_requested; -bool changes_pkt_data;bool has_prologue; -bool might_sleep;bool can_unwind;/* frames of recursive subprogs can be on the stack when it is called */ bool in_recursion; -bool kprobe_write_ctx;/* has insns that work with the arena base, see bpf_prog_has_arena_insns() */ bool uses_arena_insns;struct {
@@ -1968,18 +1990,8 @@ struct bpf_prog_aux {u64 prog_array_member_cnt;/* counts how many times as member of prog_array */ struct mutex ext_mutex;/* mutex for freplace_link_cnt and prog_array_member_cnt */ struct bpf_arena *arena; -/* -* The size of the stack in arena that the program needs, a multiple of -* the page size. 0 when r12 is not used. -*/ -u32 arena_stack_size; -/* a callback that takes a stack in arena, like the main program does */ +/* the main program or a callback, it takes a stack in arena */ bool arena_stack_entry; -void (*recursion_detected)(struct bpf_prog *prog);/* callback if recursion is detected */ -/* BTF_KIND_FUNC_PROTO for valid attach_btf_id */ -const struct btf_type *attach_func_proto; -/* function name for valid attach_btf_id */ -const char *attach_func_name;struct bpf_prog **func;struct bpf_prog_aux *main_prog_aux;/* main prog: there when the prog has timed may_goto */
@@ -1994,7 +2006,6 @@ struct bpf_prog_aux {#endif struct bpf_ksym ksym;const struct bpf_prog_ops *ops; -const struct bpf_struct_ops *st_ops;struct bpf_map **used_maps;struct mutex used_maps_mutex;/* mutex for used_maps and used_map_cnt */ struct btf_mod_pair *used_btfs;
@@ -2003,7 +2014,6 @@ struct bpf_prog_aux {u64 load_time;/* ns since boottime */ u32 verified_insns;int cgroup_atype;/* enum cgroup_bpf_attach_type */ -struct bpf_map *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE ];char name[BPF_OBJ_NAME_LEN ];u16 freplace_link_cnt;/* counts freplace links extending this prog */ #ifdef CONFIG_SECURITY
include/linux/bpf_verifier.h +26 -4
@@ -1523,6 +1523,9 @@ struct bpf_subprog_info {struct bpf_iarray *jt;/* jump table shared by all gotox of this subprogram */ u32 deepest_insn;/* the insn that set stack_depth */ u32 first_exit;/* see bpf_flow_exit() */ +u32 main;/* 1 + index in env->mains, 0 if it's not a main prog */ +u8 prologue_len; + bool has_epilogue: 1;u16 stack_depth;/* max. stack depth used by this function */ u16 stack_extra;u16 arena_stack_depth;/* size of the frame in the stack in arena */
@@ -1547,7 +1550,7 @@ struct bpf_subprog_info { bool might_throw: 1; /* it calls bpf_throw(), or what it calls does, see may_not_return() *//* * It has an unwind_exit, or a landing pad of it leaves with one, see -* bpf_mark_subprogs_that_unwind(). Subprog 0 has the bit for such a site, for freplace. +* bpf_mark_subprogs_that_unwind(). A main prog has the bit for such a site, for freplace. */ bool can_unwind: 1;/* the same for cancel_exit: it has a site at which the kernel cancels it */
@@ -1581,7 +1584,7 @@ struct bpf_subprog_info { bool changes_pkt_data: 1; bool might_sleep: 1; bool uses_arena_sp: 1; -/* a callback that takes a stack in arena, like the main program does */ +/* the main program or a callback, it takes a stack in arena */ bool arena_stack_entry: 1; u8 arg_slot_cnt:4;
@@ -1737,6 +1740,11 @@ static inline u32 bpf_stack_depth_of_prog(const struct bpf_subprog_info *sub)return sub->stack_depth - sub->hidden_words *BPF_REG_SIZE ; } +struct bpf_main_prog { +struct bpf_prog *prog; +u32 subprog;/* until dead code is removed */ +}; +static inline u16 bpf_in_stack_arg_cnt (const struct bpf_subprog_info *sub) {if (sub->stack_args_from_code)
@@ -1885,6 +1893,8 @@ struct bpf_verifier_env {struct bpf_prog *prog;/* eBPF program being verified */ const struct bpf_verifier_ops *ops;struct module *attach_btf_mod;/* The owner module of prog->aux->attach_btf */ +struct bpf_main_prog *mains; +u32 main_cnt;struct bpf_verifier_stack_elem *head;/* stack of verifier states to be processed */ bool strict_alignment;/* perform strict pointer alignment checks */ bool test_reg_invariants;/* fail verification on register invariants violations */
@@ -2437,7 +2447,7 @@ static inline bool bpf_pad_rethrows(const struct bpf_verifier_env *env, int subp {const struct bpf_subprog_info *sub = &env->subprog_info[subprog]; -return kind ==BPF_SITE_CALL && subprog && !sub->is_exception_cb && sub->bail_unwinds; +return kind ==BPF_SITE_CALL && !sub->main && !sub->is_exception_cb && sub->bail_unwinds; }/*
@@ -2472,7 +2482,9 @@ static inline bool bpf_site_has_value(const struct bpf_verifier_env *env, int sustatic inline bool bpf_pad_cancel_exits (const struct bpf_verifier_env *env,int subprog,enum bpf_site_kind kind) { -return bpf_site_is_cancel (kind) && subprog && env->subprog_info[subprog].bail_unwinds; +const struct bpf_subprog_info *sub = &env->subprog_info[subprog]; + +return bpf_site_is_cancel (kind) && !sub->main && sub->bail_unwinds; }/* The register that has the value when the landing pad of a site of @kind is entered */
@@ -2863,6 +2875,16 @@ bool bpf_obj_free_runs_dtor(const struct btf *btf, u32 btf_id);int bpf_iter_slots_valid_init (const struct bpf_func_state *state,int spi,const struct btf *btf,u32 btf_id,int nr_slots); +static inline bool bpf_subprog_is_main (const struct bpf_verifier_env *env,int subprog) +{ +return env->subprog_info[subprog].main; +} + +static inline struct bpf_prog *bpf_subprog_main_prog (struct bpf_verifier_env *env,int subprog) +{ +return env->main_cnt >1 ? env->mains[env->subprog_info[subprog].main -1 ].prog : env->prog; +} +/* 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) {
kernel/bpf/btf.c +6 -4
@@ -8795,6 +8795,8 @@ static void btf_scan_type_tags(const struct btf *btf, u32 type_id, u32 *tags)static int btf_validate_return_type (struct bpf_verifier_env *env,struct btf *btf,const struct btf_type *t,int subprog,bool is_global) { +bool main =bpf_subprog_is_main (env, subprog); + t =btf_type_skip_modifiers (btf, t->type,NULL );/*
@@ -8802,7 +8804,7 @@ static int btf_validate_return_type(struct bpf_verifier_env *env, struct btf *bt* General arena variables are not allowed, since it makes no sense to return by value * a variable that's on the heap in the first place. */ -if (subprog &&btf_type_is_arena_ptr (btf, t)) +if (!main &&btf_type_is_arena_ptr (btf, t))return 0 ;/* We always accept void or scalars. */
@@ -8822,10 +8824,10 @@ static int btf_validate_return_type(struct bpf_verifier_env *env, struct btf *bt* back into. A local function is verified inline, so its caller * receives the real register state and any member is fine. */ -bool local_func = subprog && !is_global; +bool local_func = !main && !is_global;u32 member_kinds =BTF_MEMBER_SCALAR ; -if (subprog) +if (!main) member_kinds |=BTF_MEMBER_ARENA_PTR ;if (local_func ||btf_struct_is_composed_of (env, btf, t, member_kinds))
@@ -8931,7 +8933,7 @@ int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)if (err) {if (is_global) {/* Only a subprogram may return arena pointers. */ -const char *supported = subprog ? +const char *supported = !bpf_subprog_is_main (env, subprog) ?"void, scalar, arena pointer, or a struct/union of " "scalars and arena pointers" :"void, scalar, or a scalar-only struct/union" ;
kernel/bpf/failing_path.c +1 -1
@@ -189,7 +189,7 @@ static bool selects_path_again(struct bpf_verifier_env *env, int idx)if (env->insn_aux_data[idx].calls_callback)return true; -if (idx < env->subprog_info[1 ].start &&bpf_loop_at_index (env, idx) <0 ) +if (bpf_find_containing_subprog (env, idx)->main &&bpf_loop_at_index (env, idx) <0 )return false;return bpf_insn_is_cond_jump (insn->code) ||insn_is_gotox (insn) || (bpf_calls_function (env, idx) && !bpf_pseudo_call (insn));
kernel/bpf/fixups.c +68 -39
226 lines not on this page · raw message
kernel/bpf/pads.c +3 -3
@@ -2315,7 +2315,7 @@ static bool pad_reports(const struct bpf_verifier_env *env, int subprog)if (!st_ops || !st_ops->cancelled || sub->is_exception_cb)return false; -return !subprog || (sub->is_async_cb && !sub->bail_unwinds); +return sub->main || (sub->is_async_cb && !sub->bail_unwinds); }/*
@@ -2354,7 +2354,7 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,int class, i, n =0 ;/* the main program hands the value to the exception callback */ -if (!subprog && env->exception_callback_subprog) +if (bpf_subprog_is_main (env, subprog) && env->exception_callback_subprog) dst =BPF_REG_1 ;if (plan_saves_value (env, plan, subprog)) { buf[n++] =BPF_STX_MEM (BPF_DW ,BPF_REG_FP , src, value_off);
@@ -2573,7 +2573,7 @@ static int sites_of_subprogs(struct bpf_verifier_env *env)for (s =0 ; s < env->subprog_cnt; s++) { sub = &env->subprog_info[s]; - sub->left_at = sub->can_unwind && s ?LEFT_AT_UNWIND_EXIT :0 ; + sub->left_at = sub->can_unwind && !sub->main ?LEFT_AT_UNWIND_EXIT :0 ; } do { changed = false;
kernel/bpf/syscall.c +27 -15
78 lines not on this page · raw message
kernel/bpf/verifier.c +44 -30
251 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load
TL;DR: Comments in struct bpf_prog_aux refer to enter_main() and finish_entry(), which only exist in the next patch. Can they be reworded or moved so this commit stands alone? Comment-only issue.
Quoted 1 line
bpf: Prepare for many main programs in one load
TL;DR: Comments in struct bpf_prog_aux refer to enter_main() and finish_entry(), which only exist in the next patch. Can they be reworded or moved so this commit stands alone? Comment-only issue.
Quoted 3 lines
include/linux/bpf.h +0
-0
[ ... ]
Quoted 1 line
include/linux/bpf.h +0
-0@@ -1913,25 +1914,54 @@ struct bpf_prog_aux {
[ ... ]
Quoted 6 lines
include/linux/bpf.h +5
-0+u32 subprog_start; +/* +* Up to recursion_detected: where the prog is attached, all that check_attach_btf_id() +* writes for types that can have entries. Each entry has its own, see enter_main(). +*/ u32 attach_btf_id;/* in-kernel BTF type id to attach to */
[ ... ]
include/linux/bpf.h struct bpf_prog_aux { · line 1944
Quoted 5 lines
include/linux/bpf.h +5
-0+/* +* Up to cgroup_storage: what the verifier has found in the insns, for those who attach +* and run the prog. An entry gets it from its owner, see finish_entry(). +*/ +u32 max_ctx_offset;
These two comments refer to enter_main() and finish_entry(), and to the notion of "entries". Neither function exists at this commit:
git grep 'enter_main\|finish_entry' aeaa4ea2846f -- kernel include
finds only these two comment lines. Both functions are added by the next commit in the series, "bpf: Check many main programs in one set of insns".
Can the comments be written in terms of what this commit does, or can the grouping explanation move to the commit that adds the code relying on it, so that this commit can be read or bisected on its own?
---
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/46979206999
PATCH v2 2/7 bpf: Check many main programs in one set of insns
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A scheduler or a datapath is many programs that call the same functions. Each program gets a copy of them, so they are verified and JITed N times. 32 tc programs that call the same 65 global functions:
insns verified x86-64 code load copies 1056831 991295 4547452 bytes 1.60 s one copy 33118 31070 143034 bytes 0.12 s
One copy takes less cache. 32 pairs of tasks ping-pong over pipes on 8 cpus. To evict the scheduler from the caches each task jumps through 1 MB or 2 MB of code per message, L2 is 1 MB. For hot cache it spins as long as 1 MB takes. run_time_ns of all struct_ops programs per round trip, copies -> shared:
hot cache 1 MB of code 2 MB of code scx_lavd 2326 -> 2332 0 % 2940 -> 2812 -4 % 10075 -> 9133 -9 % scx_rusty 1476 -> 1469 0 % 1741 -> 1731 -1 % 5936 -> 5530 -7 % scx_p2dq 2014 -> 2006 0 % 2354 -> 2308 -2 % 7054 -> 6551 -7 %
Round trips per second change from 0 % to +2.8 %, noise is 3 %.
Let a load have entries: functions that are main programs too. Each entry is a struct bpf_prog of one function. The program that is verified is the owner of the code:
insns: main | f | g | entry1 | entry2 | h
| ^ ^ | | ^
+----+ +-----+--------+------+All have one type, attach type and flags. For struct_ops it's one struct and any member, sleepable or not. Each main program has passes of its own, while env->prog answers for its attach point, see enter_main(). What it calls is checked like this:
static function for each main program global function of struct_ops, kprobe.. for each main program global function of tc, XDP.. once
Main programs of a type that converts ctx access are the same to a global function. For other types the ctx, the kfuncs and the valid results depend on the attach point. A helper has to have one proto for all.
The private stack has one frame of a function, and main programs can run on top of each other, so they use the kernel stack. They have one cgroup storage and one count of may_goto, each of them resets it at entry. When one has percpu_state all have it.
Each main program has the full limit on cost, as its copy would have.
An insn has one rewrite, so programs that are valid on their own can be rejected together. A main program that is proven is not checked again. So reject the load when a loop needs may_goto for one program, and another one did not take its edges.
Not supported: tracing, LSM, extension and device bound programs, tail calls, exclusive maps, callx through a table in a map, tstamp_type, writes to pt_regs, exception callbacks, bpf_tcp_ops_set_rcvlowat(), a signature on the load itself. A signed loader can load programs with entries. The next patches take care of landing pads and add the UAPI.
--- include/linux/bpf.h | 11 +- include/linux/bpf_verifier.h | 18 +- kernel/bpf/cfg.c | 8 +- kernel/bpf/failing_path.c | 4 +- kernel/bpf/fixups.c | 7 +- kernel/bpf/flow.c | 48 ++++- kernel/bpf/precision.c | 2 + kernel/bpf/verifier.c | 394 ++++++++++++++++++++++++++++++++--- net/ipv4/bpf_tcp_ops.c | 3 +- 9 files changed, 452 insertions(+), 43 deletions(-)
include/linux/bpf.h +8 -3
@@ -1811,8 +1811,9 @@ struct bpf_func_info_aux {bool ret_reg_pair;/* The code of a static function loads stack arguments */ bool stack_args; -bool called[BPF_FUNC_CTX_CNT ]; -bool verified[BPF_FUNC_CTX_CNT ]; +/* by and for which main prog, see subprog_caller() */ +u32 called[BPF_FUNC_CTX_CNT ]; +u32 verified[BPF_FUNC_CTX_CNT ];bool called_with_pkt_ptrs;/* what the callers of a global function are checked against */ struct bpf_subprog_arg_info args[MAX_BPF_FUNC_REG_ARGS ];
@@ -1919,6 +1920,8 @@ struct bpf_prog_aux {u32 exception_callback_subprog;/* index in func[], 0 if there is none */ u32 func_idx;/* 0 for non-func prog, the index in func array for func prog */ u32 subprog_start; +u32 entry_cnt;/* main progs whose code it has, see struct bpf_prog_entry */ +struct bpf_prog **entries;/* while they are loaded */ /* * Up to recursion_detected: where the prog is attached, all that check_attach_btf_id() * writes for types that can have entries. Each entry has its own, see enter_main().
@@ -1982,6 +1985,8 @@ struct bpf_prog_aux {bool in_recursion;/* has insns that work with the arena base, see bpf_prog_has_arena_insns() */ bool uses_arena_insns; +/* one of the entries of main_prog_aux, or the func that has its code */ +bool is_entry;struct {s32 keyring_serial;u8 keyring_type;
@@ -4574,7 +4579,7 @@ static inline gfp_t bpf_memcg_flags(gfp_t flags)static inline bool bpf_is_subprog (const struct bpf_prog *prog) { -return prog->aux->func_idx !=0 ; +return prog->aux->func_idx !=0 && !prog->aux->is_entry; }const struct bpf_line_info *bpf_find_linfo (const struct bpf_prog *prog,u32 insn_off);
include/linux/bpf_verifier.h +15 -3
@@ -1223,7 +1223,7 @@ struct bpf_loop {/* insns in the loop, nested loops included */ u32 nr_insns; -/* What one pass gives to the next pass */ +/* What one pass gives to the next pass. Up to @steps: see flow_reset_loop() */ struct_group_tagged(bpf_loop_precision, precision, u32 peel_cnt; /* trips before the leftover */ /* while bpf_loop_per_pass.cost is not above @budget: */
@@ -1324,6 +1324,8 @@ struct bpf_insn_aux_data { u64 cast_arena:1; /* addr_space_cast of an address in arena */ u64 cast_mov:1; /* addr_space_cast of a pointer that is not in arena, it's a move */ u64 loop_guard:1; /* may_goto is added in front of this instruction */ + u64 needs_guard:1; /* these two: of the loop header, see bpf_flow_note_guards() */ + u64 no_guard_edges:1; u64 speculative_first:1; /* a speculative state came to it first */ u64 call_recorded:1; /* see record_call_fixup() */ u64 pessimized:1; /* see bpf_partition_for_pessimized() */
@@ -1526,6 +1528,9 @@ struct bpf_subprog_info {u32 main;/* 1 + index in env->mains, 0 if it's not a main prog */ u8 prologue_len; bool has_epilogue: 1; +/* what a main prog asks of the place where it is attached */ +u32 max_ctx_offset; +u32 max_tp_access;u16 stack_depth;/* max. stack depth used by this function */ u16 stack_extra;u16 arena_stack_depth;/* size of the frame in the stack in arena */
@@ -1740,6 +1745,7 @@ static inline u32 bpf_stack_depth_of_prog(const struct bpf_subprog_info *sub)return sub->stack_depth - sub->hidden_words *BPF_REG_SIZE ; } +/* An entry of env->prog, which is attached like the first one, but see enter_main() */ struct bpf_main_prog {struct bpf_prog *prog;u32 subprog;/* until dead code is removed */
@@ -1894,7 +1900,7 @@ struct bpf_verifier_env {const struct bpf_verifier_ops *ops;struct module *attach_btf_mod;/* The owner module of prog->aux->attach_btf */ struct bpf_main_prog *mains; -u32 main_cnt; +u32 main_cnt, cur_main;struct bpf_verifier_stack_elem *head;/* stack of verifier states to be processed */ bool strict_alignment;/* perform strict pointer alignment checks */ bool test_reg_invariants;/* fail verification on register invariants violations */
@@ -1923,6 +1929,7 @@ struct bpf_verifier_env {u32 failing_path_budget_shift;/* see func_failing_path_budget() */ u32 failing_path_max_trips;/* see failing_path_trip() */ u32 pass;/* number of the pass, see do_check_all() */ +u32 pass_main;/* the main prog that it checks */ struct bpf_precision *precision;u64 cost, mem;/* see bpf_check_limits() */ u64 max_cost, max_mem;
@@ -1952,6 +1959,7 @@ struct bpf_verifier_env {bool calls_joined;/* see flow_may_add_instance() */ bool extra_values;/* a state can have constants that no run has */ bool new_linear_xreg;/* see bpf_same_insns_unproven() */ +/* from here on: of all main progs */ bool seen_direct_write;/* a register may point to the stack and is not PTR_TO_STACK, see bpf_reg_state::buf */ bool seen_stack_slice;
@@ -2014,7 +2022,8 @@ struct bpf_verifier_env {u32 callee;u32 next;/* 1 + the next edge of the caller, 0 if none */ } *callx_edges; -struct bpf_index callx_index; +u32 callx_cnt; +struct bpf_index callx_index;/* of the pass */ struct bpf_idmap idmap_scratch;struct bpf_pkt_pair *pkt_pairs;/* of the two states that are compared or joined */ u32 pkt_pair_cnt, pkt_pair_cap;
@@ -2414,6 +2423,8 @@ int bpf_flow_exit(struct bpf_verifier_env *env, struct bpf_verifier_state *st, ivoid bpf_flow_next_is_no_bound (struct bpf_verifier_env *env,int insn_idx,int h);bool bpf_flow_loops_lost_bound (struct bpf_verifier_env *env);void bpf_flow_new_pass (struct bpf_verifier_env *env); +void bpf_flow_new_main (struct bpf_verifier_env *env); +void bpf_flow_note_guards (struct bpf_verifier_env *env);void bpf_flow_drop_guards (struct bpf_verifier_env *env);bool bpf_flow_guard_is_guess (struct bpf_verifier_env *env,int idx);int bpf_flow_place_guards (struct bpf_verifier_env *env);
@@ -2880,6 +2891,7 @@ static inline bool bpf_subprog_is_main(const struct bpf_verifier_env *env, int sreturn env->subprog_info[subprog].main; } +/* Not for the main pass, see enter_main() */ static inline struct bpf_prog *bpf_subprog_main_prog (struct bpf_verifier_env *env,int subprog) {return env->main_cnt >1 ? env->mains[env->subprog_info[subprog].main -1 ].prog : env->prog;
kernel/bpf/cfg.c +7 -1
@@ -736,7 +736,7 @@ int bpf_check_cfg(struct bpf_verifier_env *env)int insn_cnt = env->prog->len;int *insn_stack, *insn_state;int i, root, ret =0 ; -u32 ptr =0 ; +u32 ptr =0 , main =1 ; insn_state = env->cfg.insn_state =kvzalloc_objs (int, insn_cnt,BPF_VERIFIER_GFP );
@@ -786,6 +786,12 @@ int bpf_check_cfg(struct bpf_verifier_env *env)if (insn_state[root] !=EXPLORED ) goto walk_cfg; +while (main < env->main_cnt) { + root = env->subprog_info[env->mains[main++].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;
kernel/bpf/failing_path.c +2 -2
@@ -114,11 +114,11 @@ static u64 hash_value(const struct bpf_reg_state *reg, u64 hash)return bpf_hash64 (reg, offsetof(struct bpf_reg_state , grew_once), hash); } -/* The join_key, the values of the deps, and which of them have one sym */ +/* The main prog, the join_key, the values of the deps, and which of them have one sym */ static u64 hash_state (struct bpf_verifier_env *env,const struct bpf_verifier_state *st) {unsigned long all[XREG_WORDS ], control_deps[XREG_WORDS ]; -u64 hash =bpf_hash_join_key (env, st); +u64 hash =bpf_hash64 (&env->cur_main,sizeof (env->cur_main),bpf_hash_join_key (env, st));const struct bpf_reg_state *reg;const struct bpf_func_state *f;struct bpf_reg_state tmp;
kernel/bpf/fixups.c +6 -1
@@ -2222,6 +2222,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)struct bpf_insn *insn;void *old_bpf_func;int err, num_exentries; +bool main; err =bpf_prog_alloc_jited_linfo (prog);if (err)
@@ -2248,6 +2249,7 @@ static int jit_subprogs(struct bpf_verifier_env *env) goto out_free;memcpy (func[i]->insnsi, &prog->insnsi[subprog_start], len *sizeof (struct bpf_insn )); + main = env->subprog_info[i].main; func[i]->type = prog->type; func[i]->len = len;for (j =0 , insn = func[i]->insnsi; j < len; j++, insn++) {
@@ -2276,12 +2278,15 @@ static int jit_subprogs(struct bpf_verifier_env *env) insn[1 ].imm = addr >>32 ; } } -if (bpf_prog_calc_tag (func[i])) +if (i && main) +memcpy (func[i]->digest, prog->digest,sizeof (prog->digest)); +else if (bpf_prog_calc_tag (func[i])) goto out_free; func[i]->is_func =1 ; func[i]->sleepable = prog->sleepable; func[i]->blinded = prog->blinded; func[i]->aux->func_idx = i; + func[i]->aux->is_entry = i && main;/* Below members will be freed only at prog->aux */ func[i]->aux->btf = prog->aux->btf; func[i]->aux->subprog_start = subprog_start;
kernel/bpf/flow.c +44 -4
78 lines not on this page · raw message
kernel/bpf/precision.c +2 -0
@@ -1826,6 +1826,8 @@ void bpf_precision_free(struct bpf_verifier_env *env)if (!prec)return ; +if (prec->data_deps) + env->mem -=18 * prec->words *sizeof (long ) +5 * env->prog->len *sizeof (u16);kvfree (prec->func);kvfree (prec->loops);kvfree (prec->hops_to_err);
kernel/bpf/verifier.c +366 -28
650 lines not on this page · raw message
net/ipv4/bpf_tcp_ops.c +2 -1
@@ -406,7 +406,8 @@ static int bpf_tcp_ops_set_rcvlowat_kfunc_filter(const struct bpf_prog *prog,if (!btf_id_set8_contains (&bpf_tcp_ops_set_rcvlowat_kfunc_set, kfunc_id))return 0 ; -if (prog->aux->st_ops != &bpf_tcp_ops) +/* it would get aux of the owner, with the member of the first entry */ +if (prog->aux->st_ops != &bpf_tcp_ops || prog->aux->entry_cnt)return -EACCES ; moff = prog->aux->attach_st_ops_member_off;
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] bpf: missing sleepable_async_cb propagation in mark_sleepable_async_cb() - [Low] bpf: unreturned…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] bpf: missing sleepable_async_cb propagation in mark_sleepable_async_cb()
- [Low] bpf: unreturned env->mem charges in bpf_precision_free() across main progs
--
commit e92d07122046139421d58da32ed44b43dd2f289e
Author: Alexei Starovoitov <[email protected]>
bpf: Check many main programs in one set of insns
This commit extends the BPF verifier to verify multiple main program entry points within a single shared instruction image.
kernel/bpf/precision.c void bpf_precision_free(struct bpf_verifier_env *env) · line 1833
Quoted 13 lines
kernel/bpf/precision.c +2
-0@@ -1826,6 +1826,8 @@ void bpf_precision_free(struct bpf_verifier_env *env)if (!prec)return ; +if (prec->data_deps) + env->mem -=18 * prec->words *sizeof (long ) +5 * env->prog->len *sizeof (u16);kvfree (prec->func);kvfree (prec->loops);kvfree (prec->hops_to_err);
[Severity: Low]
As reported by [email protected] on v1 [1], does bpf_precision_free() leave bytes charged to env->mem across main programs when prec->seen is allocated or when alloc_masks() fails before setting prec->data_deps?
In bpf_failing_path_was_here(), growing prec->seen charges env->mem += size * sizeof(*set), and alloc_masks() leaves 5 * env->prog->len * sizeof(u16) charged for prec->hops_to_err when bpf_check_limits() or kvcalloc() fails with prec->data_deps still NULL. Because do_check_mains() carries env->mem across entries, these unreturned charges can accumulate and cause later main programs in the load to fail with -E2BIG.
Quoted 4 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 39 lines
kernel/bpf/verifier.c +27
-2@@ -25328,14 +25478,50 @@ static int do_check_all(struct bpf_verifier_env *env)restart_log (env, &log);if (err && (!path_err || guess) && (limit || (env->for_log && !env->err)))verbose (env,"the limit on cost or memory ended pass %u\n" , env->pass); -if (!err && env->sleepable_async_cb) -mark_sleepable_async_cb (env);bpf_precision_free (env);free_snapshot (env, initial);free_snapshot (env, good_pass);return err; } +/* +* A main prog that is proven is not checked again. The ones after it must not add a site that its +* states went past, or take away a site at which they were cancelled. +*/ +static int check_proven_mains (struct bpf_verifier_env *env) +{ +struct bpf_insn_aux_data *aux = env->insn_aux_data; +int i; + +for (i =0 ; i < env->prog->len; i++) { +if (aux[i].needs_guard && aux[i].no_guard_edges) { +verbose (env,"loop at insn %d needs may_goto for some programs only\n" , i); +return -EINVAL ; + } + } +return 0 ; +} + +/* Each main prog has passes of its own. They start from what the progs before it wrote. */ +static int do_check_mains (struct bpf_verifier_env *env) +{ +u64 cost = env->cost, max_cost = env->max_cost, max_mem = env->max_mem; +int err =0 ; + +for (; env->pass_main < env->main_cnt && !err; env->pass_main++) { + env->cost = cost; + env->max_cost = max_cost;
kernel/bpf/verifier.c static int do_check_all(struct bpf_verifier_env *env) · line 25523
Quoted 10 lines
kernel/bpf/verifier.c +10
-0+ env->max_mem = max_mem; +bpf_flow_new_main (env); + err =do_check_all (env); +if (!err && env->main_cnt >1 ) + err =check_proven_mains (env); + } +if (!err && env->sleepable_async_cb) +mark_sleepable_async_cb (env); +return err; +}
[Severity: Medium]
Can a non-sleepable struct_ops entry miss sleepable_async_cb and map sleepable_refcnt increments when the first entry is sleepable?
can_share_subprogs() allows a struct_ops load to mix sleepable and non-sleepable entries. When the first entry is sleepable (env->prog->sleepable is true) and the load schedules a sleepable async callback, mark_sleepable_async_cb() returns early before setting env->prog->aux->sleepable_async_cb = true:
kernel/bpf/verifier.c:mark_sleepable_async_cb() {
if (bpf_prog_runs_sleepable(env->prog))
return;
env->prog->aux->sleepable_async_cb = true;
...
}finish_entry() then copies from->sleepable_async_cb (false) into each entry's aux, so for any non-sleepable entry bpf_prog_runs_sleepable(entry) is false. As a result, finish_entry() skips incrementing map->sleepable_refcnt for that entry's used_maps and the entry is freed via call_rcu() instead of call_rcu_tasks_trace(), allowing map->sleepable_refcnt to drop to zero and skip RCU Tasks Trace synchronization while the non-sleepable entry and its sleepable async callback remain active.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns
In reply to Alexei StarovoitovTL;DR: Possible wrong behaviour in verifier.c: a restarted verifier pass may leave a stale no_guard_edges bit, so check_proven_mains() could reject a valid multi-main load with -EINVAL, though the…
Quoted 1 line
bpf: Check many main programs in one set of insns
TL;DR: Possible wrong behaviour in verifier.c: a restarted verifier pass may leave a stale no_guard_edges bit, so check_proven_mains() could reject a valid multi-main load with -EINVAL, though the same program loads with one main.
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
kernel/bpf/verifier.c static int check_loop_guard(struct bpf_verifier_env *env) · line 22453
Quoted 9 lines
kernel/bpf/verifier.c +3
-1@@ -22327,8 +22447,10 @@ static int check_loop_guard(struct bpf_verifier_env *env)if (!aux->guard_place ||cur_func (env)->callback_depth)return 0 ; loop = env->insn_aux_data[bpf_loop_at_index (env, env->insn_idx)].loop; -if (loop->rt_bounded) +if (loop->rt_bounded) { + loop->this_pass.no_guard_edges = true;return 0 ; + }
Can a single main program be rejected here with "loop at insn %d needs may_goto for some programs only" because of a pass that was restarted?
rt_bounded is an assumption for the whole pass. iter_stops_loops() -> bpf_flow_next_is_no_bound() can find out mid-pass that it is wrong and set env->restart, while the pass carries on. If that pass has no error, check_pass() returns 0 because pass_needs_restart() is true, and do_check_all() does:
} else if (!ret) {
bpf_flow_note_guards(env);
if (pass_needs_restart(env)) {
env->pass_again = true;
continue;
}bpf_flow_note_guards() ORs this_pass.no_guard_edges into insn_aux_data[h].no_guard_edges before the restart is decided, and nothing clears that bit afterwards. The snapshot only covers insn_aux_data[].fixups.
In the next pass bpf_flow_new_pass() recomputes rt_bounded as false. If the loop has no trip count (always the case without CAP_PERFMON), flow_check_trip_counts() -> bpf_flow_needs_guard() sets needs_guard, and bpf_flow_note_guards() ORs it into insn_aux_data[h].needs_guard. Then check_proven_mains() sees:
if (aux[i].needs_guard && aux[i].no_guard_edges)
and fails the load with -EINVAL.
The pattern in the iter_stops_loops() comment triggers it, for example while (v->x) { bpf_for(i, 0, 10) ...; }. With main_cnt == 1 the same program loads, because check_proven_mains() is not called. The pass that set the bit was restarted and the final pass took the may_goto edges, so no main program was proven without the guard.
The same applies to the guards_late restart and the pre-existing no_guard_edges assignment in guess_loop_guard().
Should bpf_flow_note_guards() only note passes that are not restarted, or should the per-pass bits be kept apart until the last pass of the main program?
[ ... ]
---
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/46979206999
PATCH v2 3/7 bpf: Generate landing pads for many main programs
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A function that main programs share has one landing pad per site, and it has to be right for all of them:
static int f(bool lock) prog1: f(false)
{ prog2: f(true)
if (lock)
bpf_rcu_read_lock();
while (...) <- cancelled here
;
if (lock)
bpf_rcu_read_unlock();
}Each pass starts with no records of the sites, so the pad would be for the last main program only. Start the passes of a main program with a copy of what the ones before it recorded. Settle the pads after each main program, so that its passes can fix its errors, and undo that until the last one.
A main program that is proven is not checked again. Reject the load when a later one changes a site that it went through:
- a global function can be cancelled, and its call did not expect that
- an access to arena where nothing was held needs a pad that releases
- a function cannot be cancelled any more, so its may_goto jumps For the same reason don't change what is handed over to its functions.
The pad of a main program returns the value of its struct_ops member and passes the entry to ->cancelled(). An async callback passes the owner. With bpf_throw() pads pass on the value that a shared function leaves with, so reject main programs that have different values.
--- include/linux/bpf_verifier.h | 9 +++++- kernel/bpf/pads.c | 59 ++++++++++++++++++++++++++------- kernel/bpf/verifier.c | 63 ++++++++++++++++++++++++++++++++---- 3 files changed, 112 insertions(+), 19 deletions(-)
include/linux/bpf_verifier.h +8 -1
@@ -1614,6 +1614,12 @@ struct bpf_subprog_info { bool bail_unwinds: 1;/* bail_unwinds as it was before the first pass, see check_funcs() */ bool bail_unwinds_at_first: 1; +/* a main prog that is not checked again gets to it, see check_proven_mains() */ + bool proven: 1; +/* a call of the global subprog took it for one that does not unwind, or is not cancelled */ + bool call_skips_unwind: 1; + bool call_skips_cancel: 1; + bool leaves_unexpected: 1; /* and it does *//* * It has an unwind_exit, or a state left it with unwind_exit in this pass, or is expected * to, see mark_unwind_above(). For a global subprog the bit goes to the next pass.
@@ -1749,6 +1755,7 @@ static inline u32 bpf_stack_depth_of_prog(const struct bpf_subprog_info *sub)struct bpf_main_prog {struct bpf_prog *prog;u32 subprog;/* until dead code is removed */ +int cancelled_retval; };static inline u16 bpf_in_stack_arg_cnt (const struct bpf_subprog_info *sub)
@@ -2526,7 +2533,7 @@ void bpf_pad_note_section(struct bpf_verifier_env *env, enum bpf_pad_class classvoid bpf_pad_note_return (struct bpf_verifier_env *env,const struct bpf_verifier_state *st,const struct bpf_func_state *caller,int call_idx,bool plain);size_t bpf_pad_plans_free (struct bpf_insn_aux_data *aux); -void bpf_pads_new_round (struct bpf_verifier_env *env); +void bpf_pads_keep (struct bpf_verifier_env *env,struct bpf_pads_moved *kept);void bpf_pads_move (struct bpf_verifier_env *env,struct bpf_pads_moved *moved,bool save);size_t bpf_pads_free_moved (struct bpf_pads_moved *moved,u32 cnt); struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
kernel/bpf/pads.c +47 -12
87 lines not on this page · raw message
kernel/bpf/verifier.c +57 -6
142 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 bpf-next 3/7] bpf: Generate landing pads for many main programs
TL;DR: Comment only: the try_more() comment saying step 3 runs once per load looks out of date, since handed_back is now reset per main program; the commit message may also need to mention it.
Quoted 1 line
bpf: Generate landing pads for many main programs
TL;DR: Comment only: the try_more() comment saying step 3 runs once per load looks out of date, since handed_back is now reset per main program; the commit message may also need to mention it.
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 9 lines
kernel/bpf/verifier.c +2
-0@@ -25286,6 +25312,8 @@ static bool try_more(struct bpf_verifier_env *env, struct bpf_snapshot *initial)return false; env->handed_back = true;for (s =1 ; s < env->subprog_cnt; s++) { +if (initial->subprogs[s].proven) +continue ; owned |= initial->subprogs[s].owns_args; initial->subprogs[s].owns_args =0 ; }
[ ... ]
kernel/bpf/verifier.c static int do_check_mains(struct bpf_verifier_env *env) · line 25568
Quoted 8 lines
kernel/bpf/verifier.c +1
-0@@ -25513,6 +25562,7 @@ static int do_check_mains(struct bpf_verifier_env *env) env->max_cost = max_cost; env->max_mem = max_mem;bpf_flow_new_main (env); + env->handed_back = false; err =do_check_all (env);if (!err && env->main_cnt >1 ) err =check_proven_mains (env);
This isn't a bug, but the comment above try_more() now looks out of date:
* Steps 2 and 3 happen once per load. They need a callee that released a
* reference which its call had in a register ('could_take_refs'), ...
With env->handed_back reset for every main program in do_check_mains(), the guard in try_more() no longer limits step 3 to one time per load:
if (!env->ref_conflict || env->handed_back) return false; env->handed_back = true;
Step 3 can now run once per main program, and only for subprograms that are not already proven. The do_check_all() shortcut that is gated on !env->handed_back is also re-enabled for each main program.
Step 2 is still once per load, since env->takes_refs is never cleared.
Should the comment say that step 3 happens once per main program and skips proven functions, and should the commit message mention the handed_back reset?
---
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/46979206999
PATCH v2 4/7 bpf: Take entries at BPF_PROG_LOAD
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Let user space load many main programs with one copy of the functions that they call. Add an array of struct bpf_prog_entry to the attributes. A record names a function, its type, flags, attach point and name. The other attributes hold for all. The syscall returns the fd of the main program at insn 0 and writes the other fds to the records. All get an fd, or none. It takes CAP_BPF.
A load of N main programs creates N + 1 struct bpf_prog:
- N entries, the one at insn 0 too. User space attaches, pins and runs them like any other program. An entry points to its function in the JITed code of the owner.
- One owner of the JITed code. It has no name and cannot be attached, pinned or run. The load returns no fd for it. Its id is in bpf_prog_info.owner_prog_id, so tools can get an fd by id to dump the code. It's freed with the last entry.
Each entry passes the token and LSM checks like a load of its own. For now only the member of a struct_ops and BPF_F_SLEEPABLE can differ between entries. The rest is in the record to allow more later.
Shared code has aux of the owner:
- Prints and reports walk the stack to find the entry that runs. Async callbacks have none below them. They use the streams of the owner, which are the streams of the first entry.
- Kfuncs get the struct_ops map of the entries, or none if there are two.
- A tracing program names a shared function through the fd of any entry and sees the calls from all of them.
For bpf_sys_bpf() the verifier checks only attr_size bytes at attr, so the records have to follow the attributes there.
The first entry is made from the attributes, so don't overwrite them with the ids that bpf_struct_ops_resolve_attach() finds.
It works where bpf_throw() does, on x86-64 and arm64. On x86-64 the walk of the stack needs ORC. Others get -EOPNOTSUPP.
--- Documentation/bpf/verifier.rst | 47 +++- include/linux/bpf.h | 12 +- include/uapi/linux/bpf.h | 32 ++- kernel/bpf/arena.c | 2 +- kernel/bpf/bpf_struct_ops.c | 64 +++-- kernel/bpf/core.c | 50 +++- kernel/bpf/fixups.c | 1 + kernel/bpf/stream.c | 33 ++- kernel/bpf/syscall.c | 260 ++++++++++++++++-- kernel/bpf/verifier.c | 5 + tools/include/uapi/linux/bpf.h | 32 ++- .../selftests/bpf/prog_tests/bpf_attr_size.c | 2 +- 12 files changed, 472 insertions(+), 68 deletions(-)
Documentation/bpf/verifier.rst +45 -2
@@ -292,7 +292,8 @@ gets below ``min_len``, ``r`` is at least ``min_len``:: A pass ====== -A pass checks the main function, then each global function that is called. +A pass checks the main function, then each global function that is called. See +`Entries`_ for more than one main function. The states move through the program like this:: +---------+ next +-------------------+
@@ -1134,6 +1135,47 @@ A global function is different because its callers are checked without it and only see a number as its return value. A compiler that wants an object to get through a global function gives the call there a landing pad of its own. +Entries +======= + +The function at insn 0 is the main program. A load can name more main +programs, see ``struct bpf_prog_entry``. Then each main program, the first one +too, becomes a program of one function with its own fd, an *entry*. It holds the +*owner*, which has the code of all functions and cannot be attached or run:: + + insns: main | f | g | entry1 | entry2 | h + | ^ ^ | | ^ + +----+ +-----+--------+------+ + +All have one type, attach type and flags. For struct_ops it is one struct and +any member, sleepable or not. + +Each main program has passes of its own and the full limit on cost, see +``do_check_mains()``. The passes start with no precision, and with the fixups of +the programs before it. ``enter_main()`` makes ``env->prog`` answer for the +attach point of the main program. What it calls is checked like this: + +============================================= =================================== +function checked +============================================= =================================== +static for each main program that calls it +global, the type does not convert ctx access the same +global, the type converts ctx access once +============================================= =================================== + +Main programs of a type that converts ctx access, like tc and XDP, are the same +to a function. For other types, like struct_ops and tracepoints, the ctx, the +kfuncs and the valid results depend on the attach point. + +An insn has one fixup, a loop has one ``may_goto`` and a site has one landing +pad for the states of all main programs. A main program that is proven is not +checked again. So the load is rejected when a later one changes a site that it +went through, see ``check_proven_mains()``. Programs that are valid on their own +can be rejected together, the loader then loads them with copies. + +What is not tracked for each main program holds for all of them, as if they were +one program. What cannot hold for all, like a tail call, is rejected. + After an error ==============
@@ -1711,7 +1753,7 @@ correlated two branches: one tests a result that the other one stored cost the work that is done data_deps xregs whose value flows into an operand of an unproven insn deps data_deps and control_deps -entry a state that enters a loop +entry a state that enters a loop; in a load: one more main program equation how two or three numbers are related failing path a path without joins on which the check of an unproven insn fails; it is the result of a path-sensitive run
@@ -1747,6 +1789,7 @@ live read later, before it is written location a register or a stack slot that holds a pointer at a site may_goto a jump that is taken when the program has looped too long on its own a function is checked without the frames of its callers +owner the program that has the code of entries partition keep more states apart in the next pass pass one run of the main analysis over all functions path with a guess the failing path of a run that made a guess; it can be false
include/linux/bpf.h +9 -3
@@ -295,6 +295,7 @@ struct bpf_map_owner {enum bpf_prog_type type;bool jited;bool xdp_has_frags; +bool async_cb;bool has_prologue;bool sleepable;u64 storage_cookie[MAX_BPF_CGROUP_STORAGE_TYPE ];
@@ -1922,6 +1923,7 @@ struct bpf_prog_aux {u32 subprog_start;u32 entry_cnt;/* main progs whose code it has, see struct bpf_prog_entry */ struct bpf_prog **entries;/* while they are loaded */ +struct bpf_prog *entry;/* what the symbol of this prog or func is the code of */ /* * Up to recursion_detected: where the prog is attached, all that check_attach_btf_id() * writes for types that can have entries. Each entry has its own, see enter_main().
@@ -1979,6 +1981,7 @@ struct bpf_prog_aux {bool tramp_linked;/* true if it was ever linked to a trampoline */ bool func_proto_unreliable;bool xdp_has_frags; +bool async_cb;bool has_prologue;bool can_unwind;/* frames of recursive subprogs can be on the stack when it is called */
@@ -2070,6 +2073,7 @@ struct bpf_prog_aux {struct bpf_stream *stream[2 ];spinlock_t st_ops_assoc_lock;/* protects st_ops_assoc */ struct bpf_map __rcu *st_ops_assoc; +u32 st_ops_links;/* of entries in st_ops_assoc */ };struct bpf_prog_stats {
@@ -2457,7 +2461,7 @@ int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff);int bpf_struct_ops_map_sys_lookup_elem (struct bpf_map *map,void *key,void *value);u32 bpf_struct_ops_map_update_size (const struct bpf_map *map); -int bpf_struct_ops_resolve_attach (struct btf **btf,union bpf_attr *attr); +int bpf_struct_ops_resolve_attach (struct btf **btf,u32 *id,u32 *member_idx); int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, struct bpf_tramp_node *node, const struct btf_func_model *model,
@@ -2542,8 +2546,7 @@ static inline u32 bpf_struct_ops_map_update_size(const struct bpf_map *map)return map->value_size; } -static inline int bpf_struct_ops_resolve_attach (struct btf **btf, -union bpf_attr *attr) +static inline int bpf_struct_ops_resolve_attach (struct btf **btf,u32 *id,u32 *member_idx) {return -EOPNOTSUPP ; }
@@ -3454,6 +3457,7 @@ int bpf_check_uarg_tail_zero(bpfptr_t uaddr, size_t expected_size,struct bpf_log_attr ;int bpf_check (struct bpf_prog **fp,union bpf_attr *attr,bpfptr_t uattr,struct bpf_log_attr *attr_log); +int bpf_prog_alloc_entries (struct bpf_prog *prog,union bpf_attr *attr,bpfptr_t uattr);#ifndef CONFIG_BPF_JIT_ALWAYS_ON int bpf_patch_call_args (struct bpf_insn *insn,u32 stack_depth);
@@ -4533,6 +4537,7 @@ int bpf_try_get_buffers(struct bpf_bprintf_buffers **bufs);void bpf_put_buffers (void );int bpf_prog_stream_init (struct bpf_prog *prog,gfp_t gfp_extra_flags); +void bpf_prog_stream_share (struct bpf_prog *entry,struct bpf_prog *owner);void bpf_prog_stream_free (struct bpf_prog *prog);int bpf_prog_stream_read (struct bpf_prog *prog,enum bpf_stream_id stream_id,void __user *buf,u32 len);int bpf_prog_stream_new_fd (struct bpf_prog *prog,enum bpf_stream_id stream_id,u32 flags);
@@ -4596,6 +4601,7 @@ void bpf_get_linfo_source(struct btf *btf, const struct bpf_line_info *linfo,int bpf_prog_get_file_line (struct bpf_prog *prog,unsigned long ip,const char **filep,const char **linep,int *nump);struct bpf_prog *bpf_prog_find_from_stack (void ); +struct bpf_prog *bpf_prog_find_main (const struct bpf_prog *prog);int bpf_insn_array_init (struct bpf_map *map,const struct bpf_prog *prog);int bpf_insn_array_ready (struct bpf_map *map);
include/uapi/linux/bpf.h +31 -1
@@ -289,6 +289,10 @@ union bpf_iter_link_info {* The close-on-exec file descriptor flag (see **fcntl**\ (2)) is * automatically enabled for the new file descriptor. * +* Each of the *entries* names a function of *insns* that is +* loaded as one more program. Its file descriptor is returned in +* *prog_fd* of the entry. +* * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately).
@@ -1568,6 +1572,25 @@ struct bpf_common_attr {#define BPF_OBJ_NAME_LEN 16U +/* +* A function of the insns of BPF_PROG_LOAD that is a main program too. It becomes +* a program of its own, like the function at insn 0, and they share the other +* functions. The other attributes of the load hold for it as well. +* +* Type, flags and attach point have to be those of the load, but for the member and +* BPF_F_SLEEPABLE of a struct_ops. It takes CAP_BPF and func_info. All get an fd, or none. +*/ +struct bpf_prog_entry { +__u32 insn_off; +__u32 prog_type; +__u32 prog_flags; +__u32 expected_attach_type; +__u32 attach_btf_id; +__u32 attach_btf_obj_fd; +__u32 prog_fd;/* output */ +char prog_name[BPF_OBJ_NAME_LEN ]; +}; +enum {BPF_STREAM_STDOUT =1 ,BPF_STREAM_STDERR =2 ,
@@ -1738,6 +1761,10 @@ union bpf_attr {* verification. */ __s32 keyring_id; +/* More main programs in the same insns, see struct bpf_prog_entry. */ +__aligned_u64 entries; +__u32 entry_cnt; +__u32 entry_rec_size; };struct {/* anonymous struct used by BPF_OBJ_* commands */
@@ -5457,6 +5484,9 @@ union bpf_attr {* long bpf_sys_bpf(u32 cmd, void *attr, u32 attr_size) * Description * Execute bpf syscall with given arguments. +* +* The *entries* of **BPF_PROG_LOAD** have to follow the attributes, +* *attr_size* covers both. * Return * A syscall result. *
@@ -6887,7 +6917,7 @@ struct bpf_prog_info {__u32 verified_insns;__u32 attach_btf_obj_id;__u32 attach_btf_id; - __u32 :32 ; +__u32 owner_prog_id;/* the program that has the code, see struct bpf_prog_entry */ } __attribute__((aligned(8)));struct bpf_map_info {
kernel/bpf/arena.c +1 -1
@@ -1406,7 +1406,7 @@ static void __bpf_prog_report_arena_violation(struct bpf_prog *prog, bool write,u64 user_vm_start;/* Use main prog for stream access */ - prog = prog->aux->main_prog_aux->prog; + prog =bpf_prog_find_main (prog); user_vm_start =bpf_arena_get_user_vm_start (prog->aux->arena); addr +=clear_lo32 (user_vm_start);
kernel/bpf/bpf_struct_ops.c +48 -16
134 lines not on this page · raw message
kernel/bpf/core.c +44 -6
93 lines not on this page · raw message
kernel/bpf/fixups.c +1 -0
@@ -2287,6 +2287,7 @@ static int jit_subprogs(struct bpf_verifier_env *env) func[i]->blinded = prog->blinded; func[i]->aux->func_idx = i; func[i]->aux->is_entry = i && main; + func[i]->aux->async_cb = env->subprog_info[i].is_async_cb;/* Below members will be freed only at prog->aux */ func[i]->aux->btf = prog->aux->btf; func[i]->aux->subprog_start = subprog_start;
kernel/bpf/stream.c +24 -9
@@ -403,7 +403,7 @@ __bpf_kfunc int bpf_stream_vprintk(int stream_id, const char *fmt__str, const vou32 data_len = len__sz;int ret, num_args; - stream =bpf_stream_get (stream_id, aux); + stream =bpf_stream_get (stream_id,bpf_prog_find_main (aux->prog)->aux);if (!stream)return -ENOENT ;
@@ -439,7 +439,7 @@ __bpf_kfunc int bpf_stream_print_stack(int stream_id, struct bpf_prog_aux *aux)if (!bpf_stream_get (stream_id, aux))return -ENOENT ; - prog = aux->main_prog_aux->prog; + prog =bpf_prog_find_main (aux->prog); bpf_stream_stage(ss, prog, stream_id, ({ bpf_stream_dump_stack(ss);
@@ -475,8 +475,21 @@ int bpf_prog_stream_init(struct bpf_prog *prog, gfp_t gfp_extra_flags)return 0 ; } +/* The loader gets no fd of the owner. The first entry has its streams */ +void bpf_prog_stream_share (struct bpf_prog *entry,struct bpf_prog *owner) +{ +int i; + +bpf_prog_stream_free (entry); +for (i =0 ; i <ARRAY_SIZE (owner->aux->stream); i++) { +refcount_inc (&owner->aux->stream[i]->refcnt); + entry->aux->stream[i] = owner->aux->stream[i]; + } +} +void bpf_prog_stream_free (struct bpf_prog *prog) { +bool shared = prog->aux->is_entry && !prog->aux->subprog_start;int i;for (i =0 ; i <ARRAY_SIZE (prog->aux->stream); i++) {
@@ -484,13 +497,15 @@ void bpf_prog_stream_free(struct bpf_prog *prog)if (!stream)continue ; -/* -* Pairs with smp_load_acquire() in bpf_stream_file_read(): every -* publication precedes the dead flag, so a reader that observes -* it also observes all buffered data. -*/ -smp_store_release (&stream->dead, true); -wake_up_interruptible_poll (&stream->waitq,EPOLLHUP ); +if (!shared) { +/* +* Pairs with smp_load_acquire() in bpf_stream_file_read(): every +* publication precedes the dead flag, so a reader that observes +* it also observes all buffered data. +*/ +smp_store_release (&stream->dead, true); +wake_up_interruptible_poll (&stream->waitq,EPOLLHUP ); + }bpf_stream_put (stream); prog->aux->stream[i] =NULL ; }
kernel/bpf/syscall.c +232 -28
409 lines not on this page · raw message
kernel/bpf/verifier.c +5 -0
@@ -26789,6 +26789,7 @@ static int finish_entry(struct bpf_verifier_env *env, int s)if (!entry)return -ENOMEM ; from->entries[sub->main -1 ] = entry; + (s ? func->aux : from)->entry = entry; aux = entry->aux; entry->len = func->len;
@@ -27637,6 +27638,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,if (ret) goto err_prep; + ret =bpf_prog_alloc_entries (env->prog, attr, uattr); +if (ret) + goto err_prep; +bpf_get_btf_vmlinux ();/* Serialize verification of unprivileged programs. */
tools/include/uapi/linux/bpf.h +31 -1
@@ -289,6 +289,10 @@ union bpf_iter_link_info {* The close-on-exec file descriptor flag (see **fcntl**\ (2)) is * automatically enabled for the new file descriptor. * +* Each of the *entries* names a function of *insns* that is +* loaded as one more program. Its file descriptor is returned in +* *prog_fd* of the entry. +* * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately).
@@ -1568,6 +1572,25 @@ struct bpf_common_attr {#define BPF_OBJ_NAME_LEN 16U +/* +* A function of the insns of BPF_PROG_LOAD that is a main program too. It becomes +* a program of its own, like the function at insn 0, and they share the other +* functions. The other attributes of the load hold for it as well. +* +* Type, flags and attach point have to be those of the load, but for the member and +* BPF_F_SLEEPABLE of a struct_ops. It takes CAP_BPF and func_info. All get an fd, or none. +*/ +struct bpf_prog_entry { +__u32 insn_off; +__u32 prog_type; +__u32 prog_flags; +__u32 expected_attach_type; +__u32 attach_btf_id; +__u32 attach_btf_obj_fd; +__u32 prog_fd;/* output */ +char prog_name[BPF_OBJ_NAME_LEN ]; +}; +enum {BPF_STREAM_STDOUT =1 ,BPF_STREAM_STDERR =2 ,
@@ -1738,6 +1761,10 @@ union bpf_attr {* verification. */ __s32 keyring_id; +/* More main programs in the same insns, see struct bpf_prog_entry. */ +__aligned_u64 entries; +__u32 entry_cnt; +__u32 entry_rec_size; };struct {/* anonymous struct used by BPF_OBJ_* commands */
@@ -5457,6 +5484,9 @@ union bpf_attr {* long bpf_sys_bpf(u32 cmd, void *attr, u32 attr_size) * Description * Execute bpf syscall with given arguments. +* +* The *entries* of **BPF_PROG_LOAD** have to follow the attributes, +* *attr_size* covers both. * Return * A syscall result. *
@@ -6887,7 +6917,7 @@ struct bpf_prog_info {__u32 verified_insns;__u32 attach_btf_obj_id;__u32 attach_btf_id; - __u32 :32 ; +__u32 owner_prog_id;/* the program that has the code, see struct bpf_prog_entry */ } __attribute__((aligned(8)));struct bpf_map_info {
tools/testing/selftests/bpf/prog_tests/bpf_attr_size.c +1 -1
@@ -93,7 +93,7 @@ static void test_prog_info_tail_zero(void) BPF_EXIT_INSN(), };struct bpf_prog_info_fake { - __u8 info[offsetofend(struct bpf_prog_info, attach_btf_id)]; + __u8 info[offsetofend(struct bpf_prog_info, owner_prog_id)];__u32 pad; } info = { .pad =1 ,
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 bpf-next 4/7] bpf: Take entries at BPF_PROG_LOAD
TL;DR: Nit: the new bpf_map_owner::async_cb field in include/linux/bpf.h appears unused, since nothing seems to set or compare it. Was it only meant for struct bpf_prog_aux?
Quoted 1 line
bpf: Take entries at
BPF_PROG_LOAD
TL;DR: Nit: the new bpf_map_owner::async_cb field in include/linux/bpf.h appears unused, since nothing seems to set or compare it. Was it only meant for struct bpf_prog_aux?
Quoted 3 lines
include/linux/bpf.h +0
-0
[ ... ]
include/linux/bpf.h struct bpf_map_owner { · line 301
Quoted 8 lines
include/linux/bpf.h +1
-0@@ -295,6 +295,7 @@ struct bpf_map_owner {enum bpf_prog_type type;bool jited;bool xdp_has_frags; +bool async_cb;bool has_prologue;bool sleepable;u64 storage_cookie[MAX_BPF_CGROUP_STORAGE_TYPE ];
This isn't a bug, but is bpf_map_owner::async_cb meant to be set and compared in __bpf_prog_map_compatible()?
Nothing in the series seems to read or write map->owner->async_cb (or map->owner->has_prologue), and only the bpf_prog_aux copy is used, by find_from_stack_cb(). Did this field only need adding to struct bpf_prog_aux?
---
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/46979206999
PATCH v2 5/7 libbpf, bpftool: Share subprogs between programs
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
libbpf appends a copy of each called function to each main program. Load the programs of one type and attach type, or of one struct_ops map, that call the same functions together, with one copy. It's on by default. A program with BPF_PROG_LOAD_STRATEGY_MANUAL keeps its copies.
Each program is relocated with its copies as before. At load time merge the images and try that first. When the kernel has no entries, or rejects the load, load the programs one by one. When a log level is set, print the verifier log of the rejected load as a debug message.
What users can see: an extension cannot replace a shared function, and a tracing program sees the calls of it from all programs. Programs that share hold the maps of each other, have one associated struct_ops map and one tag. Adjust three selftests that depend on copies.
A map that holds a program and is used by its sibling would never be freed. So keep copies for cpumap and devmap programs, and for objects with a BPF_F_PRESERVE_ELEMS map.
x86-64 code, bytes verified insns
progs copies shared copies shared
scx_qmap 26 109732 50129 36855 36855 scx_lavd 36 118101 68345 51763 54574 scx_rusty 14 42107 25912 12697 12697 scx_chaos 24 76758 57123 16299 16342 scx_p2dq 23 56888 48299 12531 12531 scx_layered 24 58401 52662 26795 26626
One copy takes less cache. 32 pairs of tasks ping-pong over pipes on 8 cpus. To evict the scheduler from the caches each task jumps through 1 MB or 2 MB of code per message, L2 is 1 MB. For hot cache it spins as long as 1 MB takes. run_time_ns of all struct_ops programs per round trip, copies -> shared:
hot cache 1 MB of code 2 MB of code scx_lavd 2326 -> 2332 0 % 2940 -> 2812 -4 % 10075 -> 9133 -9 % scx_rusty 1476 -> 1469 0 % 1741 -> 1731 -1 % 5936 -> 5530 -7 % scx_p2dq 2014 -> 2006 0 % 2354 -> 2308 -2 % 7054 -> 6551 -7 %
Round trips per second change from 0 % to +2.8 %, noise is 3 %.
bpftool prints owner_prog_id, and finds the calls of an entry in dumps.
--- tools/bpf/bpftool/cfg.c | 4 + tools/bpf/bpftool/common.c | 26 +- tools/bpf/bpftool/prog.c | 37 +++ tools/lib/bpf/bpf.c | 40 ++- tools/lib/bpf/bpf.h | 9 +- tools/lib/bpf/libbpf.c | 305 +++++++++++++++++- .../selftests/bpf/prog_tests/call_rcu.c | 2 +- .../selftests/bpf/prog_tests/unwind_attach.c | 4 +- .../selftests/bpf/progs/pro_epilogue.c | 4 +- 9 files changed, 406 insertions(+), 25 deletions(-)
tools/bpf/bpftool/cfg.c +4 -0
@@ -132,6 +132,7 @@ static bool cfg_partition_funcs(struct cfg *cfg, struct bpf_insn *cur, struct bpf_insn *end) {struct func_node *func, *last_func; +struct bpf_insn *start = cur; func =cfg_append_func (cfg, cur);if (!func)
@@ -142,6 +143,9 @@ static bool cfg_partition_funcs(struct cfg *cfg, struct bpf_insn *cur,continue ;if (cur->src_reg !=BPF_PSEUDO_CALL )continue ; +/* an entry calls functions of its owner */ +if (cur + cur->off +1 < start || cur + cur->off +1 >= end) +continue ; func =cfg_append_func (cfg, cur + cur->off +1 );if (!func)return true;
tools/bpf/bpftool/common.c +25 -1
@@ -860,6 +860,30 @@ print_all_levels(__maybe_unused enum libbpf_print_level level,return vfprintf (stderr, format, args); } +/* The owner of entries has their tag. Only the entries can be used. */ +static int drop_prog_owners (int *fds,int nb_fds) +{ +struct bpf_prog_info a, b; +__u32 len =sizeof (a); +int i, j; + +for (i =0 ; i < nb_fds; i++) { +memset (&a,0 ,sizeof (a)); +if (bpf_prog_get_info_by_fd (fds[i], &a, &len) || !a.owner_prog_id) +continue ; +for (j =0 ; j < nb_fds; j++) { +memset (&b,0 ,sizeof (b)); +if (bpf_prog_get_info_by_fd (fds[j], &b, &len) || b.id != a.owner_prog_id) +continue ; +close (fds[j]); +memmove (fds + j, fds + j +1 , (--nb_fds - j) *sizeof (*fds)); + i -= j < i; +break ; + } + } +return nb_fds; +} +static int prog_fd_by_nametag (void *nametag,int **fds,bool tag) {char prog_name[MAX_PROG_FULL_NAME ];
@@ -878,7 +902,7 @@ static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)p_err ("%s" ,strerror (errno)); goto err_close_fds; } -return nb_fds; +return drop_prog_owners (*fds, nb_fds); } fd =bpf_prog_get_fd_by_id (id);
tools/bpf/bpftool/prog.c +37 -0
@@ -483,6 +483,9 @@ static void print_prog_json(struct bpf_prog_info *info, int fd, bool orphaned)if (info->btf_id)jsonw_int_field (json_wtr,"btf_id" , info->btf_id); +if (info->owner_prog_id) +jsonw_uint_field (json_wtr,"owner_prog_id" , info->owner_prog_id); +if (!hashmap__empty (prog_table)) {struct hashmap_entry *entry;
@@ -572,6 +575,9 @@ static void print_prog_plain(struct bpf_prog_info *info, int fd, bool orphaned)if (info->btf_id)printf ("\n\tbtf_id %u" , info->btf_id); +if (info->owner_prog_id) +printf ("\n\towner_prog_id %u" , info->owner_prog_id); +emit_obj_refs_plain (refs_table, info->id,"\n\tpids " );printf ("\n" );
@@ -698,6 +704,28 @@ static int do_show(int argc, char **argv)return err; } +static int get_owner_info (__u32 id,struct bpf_prog_info *info,void **data) +{ +__u32 len =sizeof (*info), cnt; +int fd, err; + + fd =bpf_prog_get_fd_by_id (id); +if (fd <0 ) +return -1 ; + + err =bpf_prog_get_info_by_fd (fd, info, &len); + cnt = info->nr_jited_ksyms; + *data = err ?NULL :calloc (cnt,sizeof (__u64)); +if (*data) { +memset (info,0 ,sizeof (*info)); + info->nr_jited_ksyms = cnt; + info->jited_ksyms =ptr_to_u64 (*data); + err =bpf_prog_get_info_by_fd (fd, info, &len); + } +close (fd); +return *data ? err :-1 ; +} +static int prog_dump (struct bpf_prog_info *info,enum dump_mode mode,char *filepath,bool opcodes,bool visual,bool linum)
@@ -853,9 +881,17 @@ prog_dump(struct bpf_prog_info *info, enum dump_mode mode, goto exit_free; } }else { +struct bpf_prog_info owner = {}; +void *data =NULL ; +kernel_syms_load (&dd); dd.nr_jited_ksyms = info->nr_jited_ksyms; dd.jited_ksyms =u64_to_ptr (info->jited_ksyms); +/* it calls functions of its owner */ +if (info->owner_prog_id && !get_owner_info (info->owner_prog_id, &owner, &data)) { + dd.nr_jited_ksyms = owner.nr_jited_ksyms; + dd.jited_ksyms =u64_to_ptr (owner.jited_ksyms); + } dd.btf = btf; dd.func_info = func_info; dd.finfo_rec_size = info->func_info_rec_size;
@@ -868,6 +904,7 @@ prog_dump(struct bpf_prog_info *info, enum dump_mode mode,else dump_xlated_plain (&dd, buf, member_len, opcodes, linum);kernel_syms_destroy (&dd); +free (data); } err =0 ;
tools/lib/bpf/bpf.c +37 -3
@@ -122,15 +122,45 @@ static inline int sys_bpf_fd(enum bpf_cmd cmd, union bpf_attr *attr,return ensure_good_fd (fd); } +/* All FDs of a load are good, or none is left */ +static int ensure_good_prog_fds (int fd,void *entries,__u32 cnt,size_t rec_size) +{ +struct bpf_prog_entry *entry; +int err; +__u32 i; + + fd =ensure_good_fd (fd); + err = fd <0 ? errno :0 ; +for (i =0 ; i < cnt && !err; i++) { + entry = entries + i * rec_size; + entry->prog_fd =ensure_good_fd (entry->prog_fd); +if ((int )entry->prog_fd <0 ) + err = errno; + } +if (!err) +return fd; + +for (i =0 ; i < cnt; i++) { + entry = entries + i * rec_size; +close (entry->prog_fd); + } +close (fd); + errno = err; +return -1 ; +} +int sys_bpf_prog_load (union bpf_attr *attr,unsigned int size,int attempts) {int fd;do { - fd =sys_bpf_fd (BPF_PROG_LOAD , attr, size); + fd =sys_bpf (BPF_PROG_LOAD , attr, size); }while (fd <0 && errno ==EAGAIN && --attempts >0 ); -return fd; + if (fd < 0 || size < offsetofend(union bpf_attr, entry_rec_size)) +return ensure_good_fd (fd); +return ensure_good_prog_fds (fd, (void *)(unsigned long )attr->entries, attr->entry_cnt, + attr->entry_rec_size); }/* Probe whether kernel switched from memlock-based (RLIMIT_MEMLOCK) to
@@ -304,7 +334,7 @@ int bpf_prog_load(enum bpf_prog_type prog_type, const struct bpf_insn *insns, size_t insn_cnt, struct bpf_prog_load_opts *opts) { - const size_t attr_sz = offsetofend(union bpf_attr, keyring_id); + const size_t attr_sz = offsetofend(union bpf_attr, entry_rec_size);void *finfo =NULL , *linfo =NULL ;const char *func_info, *line_info;__u32 log_size, log_level, attach_prog_fd, attach_btf_obj_fd;
@@ -379,6 +409,10 @@ int bpf_prog_load(enum bpf_prog_type prog_type, attr.fd_array =ptr_to_u64 (OPTS_GET (opts, fd_array,NULL )); attr.fd_array_cnt =OPTS_GET (opts, fd_array_cnt,0 ); + attr.entries =ptr_to_u64 (OPTS_GET (opts, entries,NULL )); + attr.entry_cnt =OPTS_GET (opts, entry_cnt,0 ); + attr.entry_rec_size =OPTS_GET (opts, entry_rec_size,0 ); +if (log_level) { attr.log_buf =ptr_to_u64 (log_buf); attr.log_size = log_size;
tools/lib/bpf/bpf.h +8 -1
@@ -83,6 +83,8 @@ LIBBPF_API int bpf_map_create(enum bpf_map_type map_type,__u32 max_entries, const struct bpf_map_create_opts *opts); +struct bpf_prog_entry ; +struct bpf_prog_load_opts {size_t sz;/* size of this struct for forward/backward compatibility */
@@ -128,9 +130,14 @@ struct bpf_prog_load_opts {/* if set, provides the length of fd_array */ __u32 fd_array_cnt; + +/* more main programs in the same insns, the kernel sets their prog_fd */ +struct bpf_prog_entry *entries; +__u32 entry_cnt; +__u32 entry_rec_size; size_t :0; }; -#define bpf_prog_load_opts__last_field fd_array_cnt +#define bpf_prog_load_opts__last_field entry_rec_size LIBBPF_API int bpf_prog_load(enum bpf_prog_type prog_type, const char *prog_name, const char *license,
tools/lib/bpf/libbpf.c +289 -16
365 lines not on this page · raw message
tools/testing/selftests/bpf/prog_tests/call_rcu.c +1 -1
@@ -115,7 +115,7 @@ static void test_call_rcu_teardown(void)if (!ASSERT_OK (bpf_prog_get_info_by_fd (bpf_program__fd (skel->progs.arm), &pinfo, &len),"prog_info" )) goto out; - prog_id = pinfo.id; + prog_id = pinfo.owner_prog_id ?: pinfo.id; len =sizeof (minfo); if (!ASSERT_OK(bpf_map_get_info_by_fd(bpf_map__fd(skel->maps.bss), &minfo, &len),
tools/testing/selftests/bpf/prog_tests/unwind_attach.c +3 -1
@@ -83,7 +83,9 @@ void test_unwind_attach(void) prog == tgt->progs.shared_pad || prog == tgt->progs.tail_call_in_subprog || prog == tgt->progs.exception_callback_unwinds); - err =verifier_unwind__load (tgt); +/* an extension cannot replace a shared function */ +bpf_program__set_load_strategy (tgt->progs.shared_pad,BPF_PROG_LOAD_STRATEGY_MANUAL ); + err =verifier_unwind__load (tgt) ?:bpf_program__load (tgt->progs.shared_pad);if (err == -ENOTSUPP ) {printf ("%s:SKIP:JIT does not support unwinding\n" , __func__);test__skip ();
tools/testing/selftests/bpf/progs/pro_epilogue.c +2 -2
@@ -56,7 +56,7 @@ __xlated("1: r1 = *(u64 *)(r1 +0)") __xlated("2: r6 = r1") __xlated("3: call kernel-function") __xlated("4: r1 = r6") -__xlated ("5: call pc+" ) +__xlated ("5: call pc" ) /* epilogue */ __xlated("6: r1 = *(u64 *)(r10 -8)")__xlated ("7: r1 = *(u64 *)(r1 +0)" )
@@ -94,7 +94,7 @@ __xlated("5: r1 = *(u64 *)(r1 +0)") __xlated("6: r6 = r1") __xlated("7: call kernel-function") __xlated("8: r1 = r6") -__xlated ("9: call pc+" ) +__xlated ("9: call pc" ) /* epilogue */ __xlated("10: r1 = *(u64 *)(r10 -8)")__xlated ("11: r1 = *(u64 *)(r1 +0)" )
Signature · 1 line
2.55.0
PATCH v2 6/7 libbpf: Share subprogs in light skeletons
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A light skeleton has a copy of each called function in each program, and so do signed programs, because their loader is a light skeleton.
The kernel is not known when the loader is generated. So emit the load with entries first, and keep the loads of the copies. The loader skips them when the programs have their fds already.
The records of the entries are in the blob, so the signature of the loader covers them. The blob has the merged image on top of the copies. For 172 objects of public projects:
x86-64 code blob, bytes
copies 9131554 48438960 shared 5917044 56340432
--- tools/lib/bpf/bpf_gen_internal.h | 3 +- tools/lib/bpf/gen_loader.c | 83 +++++++++++++++++++++++++++++--- tools/lib/bpf/libbpf.c | 50 ++++++++++++------- 3 files changed, 111 insertions(+), 25 deletions(-)
tools/lib/bpf/bpf_gen_internal.h +2 -1
@@ -51,6 +51,7 @@ struct bpf_gen {__u32 nr_ksyms;int fd_array;int prog_fds; +bool has_entries;int nr_fd_array;/* * Maps with pointers to functions, that programs get their own copies
@@ -73,7 +74,7 @@ void bpf_gen__map_create(struct bpf_gen *gen,void bpf_gen__prog_load (struct bpf_gen *gen,enum bpf_prog_type prog_type,const char *prog_name,const char *license,struct bpf_insn *insns,size_t insn_cnt, -struct bpf_prog_load_opts *load_attr,int prog_idx); +struct bpf_prog_load_opts *load_attr);void bpf_gen__map_update_elem (struct bpf_gen *gen,int map_idx,void *value,__u32 value_size,__u64 flags); void bpf_gen__struct_ops_update_elem(struct bpf_gen *gen, int map_idx, void *value,
tools/lib/bpf/gen_loader.c +77 -6
132 lines not on this page · raw message
tools/lib/bpf/libbpf.c +32 -18
121 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 7/7 selftests/bpf: Test programs that share subprogs
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Run entries that call, print, throw and are cancelled. Check that a function is not shared when it's not valid for one of the entries. Load entries from a signed light skeleton.
--- tools/testing/selftests/bpf/Makefile.skel | 2 +- .../selftests/bpf/prog_tests/share_subprogs.c | 190 ++++++++++++++ .../selftests/bpf/progs/share_subprogs.c | 245 ++++++++++++++++++ .../bpf/progs/share_subprogs_arena.c | 41 +++ .../bpf/progs/share_subprogs_signed.c | 87 +++++++ 5 files changed, 564 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/share_subprogs.c create mode 100644 tools/testing/selftests/bpf/progs/share_subprogs.c create mode 100644 tools/testing/selftests/bpf/progs/share_subprogs_arena.c create mode 100644 tools/testing/selftests/bpf/progs/share_subprogs_signed.c
tools/testing/selftests/bpf/Makefile.skel +1 -1
@@ -37,7 +37,7 @@ LSKELS := fexit_sleep.c trace_printk.c trace_vprintk.c map_ptr_kern.c \ test_ringbuf_overwrite.c callx_rodata.c many_progs.c \ struct_ops_vmlinux.c struct_ops_mod.c -LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c +LSKELS_SIGNED := fentry_test.c fexit_test.c share_subprogs_signed.c atomics.c # Generate both light skeleton and libbpf skeleton for these LSKELS_EXTRA := test_ksyms_module.c test_ksyms_weak.c kfunc_call_test.c \
tools/testing/selftests/bpf/prog_tests/share_subprogs.c new file +190 -0
190 lines not on this page · raw message
tools/testing/selftests/bpf/progs/share_subprogs.c new file +245 -0
245 lines not on this page · raw message
tools/testing/selftests/bpf/progs/share_subprogs_arena.c new file +41 -0
41 lines not on this page · raw message
tools/testing/selftests/bpf/progs/share_subprogs_signed.c new file +87 -0
87 lines not on this page · raw message
Signature · 1 line
2.55.0
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 Wed, 2 Dec 2026 21:27:36 +0000 you wrote:
From: Alexei Starovoitov <[email protected]>
A scheduler or a datapath is many programs that call the same functions. Each program gets a copy of them, so they are verified and JITed N times. Load such programs together, with one copy.
before after
[...]
Here is the summary with links:
- [v2,bpf-next,1/7] bpf: Prepare for many main programs in one load
https://git.kernel.org/bpf/bpf-next/c/8021b5d6fe0b - [v2,bpf-next,2/7] bpf: Check many main programs in one set of insns https://git.kernel.org/bpf/bpf-next/c/e14a1b797c3c - [v2,bpf-next,3/7] bpf: Generate landing pads for many main programs https://git.kernel.org/bpf/bpf-next/c/2d59b3a8d6df - [v2,bpf-next,4/7] bpf: Take entries at BPF_PROG_LOAD https://git.kernel.org/bpf/bpf-next/c/7851161035ca - [v2,bpf-next,5/7] libbpf, bpftool: Share subprogs between programs https://git.kernel.org/bpf/bpf-next/c/d47d7a8b0502 - [v2,bpf-next,6/7] libbpf: Share subprogs in light skeletons https://git.kernel.org/bpf/bpf-next/c/91f8054f506c - [v2,bpf-next,7/7] selftests/bpf: Test programs that share subprogs https://git.kernel.org/bpf/bpf-next/c/11002df10384
You are awesome, thank you!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html