* [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs
@ 2026-12-02 21:27 Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load Alexei Starovoitov
` (6 more replies)
0 siblings, 7 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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/20261202001639.2301557-1-alexei.starovoitov@gmail.com/
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
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
--
2.55.0
^ permalink raw reply [flat|nested] 13+ messages in thread
* [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
@ 2026-12-02 21:27 ` Alexei Starovoitov
2026-12-02 22:20 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns Alexei Starovoitov
` (5 subsequent siblings)
6 siblings, 1 reply; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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.
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
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(-)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 0e21ecbc43e8..9eccf86ea6e7 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 975a746c7f46..f6d54ca7cfed 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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 su
static 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)
{
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 104f936e28f4..3597ba1b5594 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -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";
diff --git a/kernel/bpf/failing_path.c b/kernel/bpf/failing_path.c
index 1d5a5782835d..cac1ed2f8331 100644
--- a/kernel/bpf/failing_path.c
+++ b/kernel/bpf/failing_path.c
@@ -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));
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 7a913f5b5df6..fd297b475576 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -633,7 +633,7 @@ static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_pl
int n = 0;
n += bpf_pad_insns(env, plan, s, buf + n, aux + n);
- if (!s && cb) {
+ if (bpf_subprog_is_main(env, s) && cb) {
bool cancels = bpf_subprog_cancels(&env->subprog_info[cb]);
buf[n++] = BPF_CALL_REL(0);
@@ -715,7 +715,8 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
for (k = 0; k < env->subprog_cnt; k++) {
s = env->subprog_topo_order[k];
sub = &env->subprog_info[s];
- if ((sub->can_unwind && sub->can_cancel) || (s && !sub->bail_unwinds))
+ if ((sub->can_unwind && sub->can_cancel) ||
+ (!sub->main && !sub->bail_unwinds))
continue;
unwinds = sub->can_unwind;
cancels = sub->can_cancel;
@@ -1490,16 +1491,18 @@ static struct bpf_insn *emit_arena_stack_percpu(struct bpf_verifier_env *env,
*/
static int insert_arena_stack_get(struct bpf_verifier_env *env, int s)
{
- struct bpf_insn ld_aux[2] = { BPF_LD_IMM64(BPF_REG_1, (long)env->prog->aux) };
int local = bpf_jit_supports_local_atomics() ? BPF_ATOMIC_LOCAL : 0;
- int ptr = s ? BPF_REG_6 : BPF_REG_2, cnt = s ? BPF_REG_7 : BPF_REG_3;
- int size = s ? BPF_REG_8 : BPF_REG_4;
struct bpf_subprog_info *sub = &env->subprog_info[s];
+ bool cb = !sub->main;
+ struct bpf_prog *prog = cb ? env->prog : bpf_subprog_main_prog(env, s);
+ struct bpf_insn ld_aux[2] = { BPF_LD_IMM64(BPF_REG_1, (long)prog->aux) };
+ int ptr = cb ? BPF_REG_6 : BPF_REG_2, cnt = cb ? BPF_REG_7 : BPF_REG_3;
+ int size = cb ? BPF_REG_8 : BPF_REG_4;
struct bpf_insn *buf = env->insn_buf, *patch;
int jfree, jdone, jslow, slow, free, done, i;
/* the arguments wait in the frame, nothing is there yet */
- if (s)
+ if (cb)
sub->stack_depth = max(sub->stack_depth, MAX_BPF_FUNC_REG_ARGS * BPF_REG_SIZE);
patch = emit_arena_stack_percpu(env, buf, ptr);
@@ -1508,18 +1511,18 @@ static int insert_arena_stack_get(struct bpf_verifier_env *env, int s)
CPU_STACK_OFF(busy));
jfree = patch++ - buf;
slow = patch - buf;
- if (!s)
+ if (!cb)
*patch++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
- for (i = BPF_REG_1; s && i <= BPF_REG_5; i++)
+ for (i = BPF_REG_1; cb && i <= BPF_REG_5; i++)
*patch++ = BPF_STX_MEM(BPF_DW, BPF_REG_FP, i, -i * BPF_REG_SIZE);
*patch++ = ld_aux[0];
*patch++ = ld_aux[1];
*patch++ = BPF_MOV64_REG(BPF_REG_2, cnt);
*patch++ = BPF_EMIT_KERNEL_CALL(bpf_arena_stack_get);
*patch++ = BPF_MOV32_REG(BPF_REG_ARENA_SP, BPF_REG_0);
- if (!s)
+ if (!cb)
*patch++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
- for (i = BPF_REG_1; s && i <= BPF_REG_5; i++)
+ for (i = BPF_REG_1; cb && i <= BPF_REG_5; i++)
*patch++ = BPF_LDX_MEM(BPF_DW, i, BPF_REG_FP, -i * BPF_REG_SIZE);
jdone = patch++ - buf;
*patch++ = BPF_MOV64_IMM(BPF_REG_0, 0);
@@ -1577,7 +1580,7 @@ int bpf_insert_arena_stack(struct bpf_verifier_env *env)
if (subprogs[cur].arena_stack_depth)
*patch++ = BPF_ALU32_IMM(BPF_ADD, BPF_REG_ARENA_SP,
-(int)subprogs[cur].arena_stack_depth);
- if (!cur || subprogs[cur].arena_stack_entry) {
+ if (subprogs[cur].arena_stack_entry) {
/*
* r1-r5 are free, except R2 before cancel_exit: it is 0 there, see
* bpf_pad_insns(), and stays 0 on both paths.
@@ -1607,7 +1610,7 @@ int bpf_insert_arena_stack(struct bpf_verifier_env *env)
return PTR_ERR(insn);
}
/* Not before the insn is rewritten: the list takes a copy of it. */
- if (subprogs[cur].start == i && (!cur || subprogs[cur].arena_stack_entry)) {
+ if (subprogs[cur].start == i && subprogs[cur].arena_stack_entry) {
err = insert_arena_stack_get(env, cur);
if (err)
return err;
@@ -1786,35 +1789,31 @@ static int arena_member_fixup(struct bpf_verifier_env *env, int idx, struct bpf_
return cnt;
}
-int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
+static int insert_prologue(struct bpf_verifier_env *env, int s)
{
- struct bpf_subprog_info *subprogs = env->subprog_info;
+ struct bpf_subprog_info *sub = &env->subprog_info[s];
+ struct bpf_prog *prog = bpf_subprog_main_prog(env, s);
const struct bpf_verifier_ops *ops = env->ops;
- int i, cnt, size, ctx_field_size, ret, epilogue_cnt = 0, first = 0;
struct bpf_insn *epilogue_buf = env->epilogue_buf;
struct bpf_insn *insn_buf = env->insn_buf;
- bool nospec, nospec_next = false;
- struct bpf_insn *insn;
- u32 target_size, size_default, off;
- enum bpf_access_type type;
- bool is_narrower_load;
- int epilogue_idx = 0;
+ int cnt, ret, epilogue_cnt;
+
+ prog->insnsi[0] = env->prog->insnsi[sub->start];
if (ops->gen_epilogue) {
- epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
- -(subprogs[0].stack_depth + 8));
+ epilogue_cnt = ops->gen_epilogue(epilogue_buf, prog, -(sub->stack_depth + 8));
if (epilogue_cnt >= INSN_BUF_SIZE) {
verifier_bug(env, "epilogue is too long");
return -EFAULT;
} else if (epilogue_cnt) {
/* Save the ARG_PTR_TO_CTX for the epilogue to use */
- subprogs[0].stack_depth += 8;
- insn_buf[0] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
- -subprogs[0].stack_depth);
- ret = bpf_patch_list_insert(env, 0, insn_buf, 1);
+ sub->stack_depth += 8;
+ insn_buf[0] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, -sub->stack_depth);
+ ret = bpf_patch_list_insert(env, sub->start, insn_buf, 1);
if (ret)
return ret;
- first++;
+ sub->prologue_len++;
+ sub->has_epilogue = true;
ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
if (ret < 0)
@@ -1827,28 +1826,49 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
verifier_bug(env, "gen_prologue is null");
return -EFAULT;
}
- cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
- env->prog);
+ cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, prog);
if (cnt >= INSN_BUF_SIZE) {
verifier_bug(env, "prologue is too long");
return -EFAULT;
} else if (cnt) {
- env->prog->aux->has_prologue = true;
+ prog->aux->has_prologue = true;
/* the prologue ends with the first insn of the program */
- if (verifier_bug_if(memcmp(&insn_buf[cnt - 1], env->prog->insnsi,
+ if (verifier_bug_if(memcmp(&insn_buf[cnt - 1], prog->insnsi,
sizeof(*insn_buf)), env,
"prologue doesn't end with the first insn"))
return -EFAULT;
- ret = bpf_patch_list_insert(env, 0, insn_buf, cnt - 1);
+ ret = bpf_patch_list_insert(env, sub->start, insn_buf, cnt - 1);
if (ret)
return ret;
- first += cnt - 1;
+ sub->prologue_len += cnt - 1;
ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
if (ret < 0)
return ret;
}
}
+ return 0;
+}
+
+int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
+{
+ struct bpf_subprog_info *subprogs = env->subprog_info;
+ const struct bpf_verifier_ops *ops = env->ops;
+ int i, s, cnt, size, ctx_field_size, ret, epilogue_cnt = 0;
+ struct bpf_insn *epilogue_buf = env->epilogue_buf;
+ struct bpf_insn *insn_buf = env->insn_buf;
+ bool nospec, nospec_next = false;
+ struct bpf_insn *insn;
+ u32 target_size, size_default, off;
+ enum bpf_access_type type;
+ bool is_narrower_load;
+ int epilogue_idx = 0;
+
+ for (s = 0; s < env->subprog_cnt; s++) {
+ ret = subprogs[s].main ? insert_prologue(env, s) : 0;
+ if (ret)
+ return ret;
+ }
/*
* The loop below rewrites some insns in place. No insn may have a queued
@@ -1861,11 +1881,21 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
if (bpf_prog_is_offloaded(env->prog->aux))
return 0;
- for (i = first; i < env->prog->len; i++) {
+ for (i = 0, s = 0; i < env->prog->len; i++) {
bpf_convert_ctx_access_t convert_ctx_access;
enum bpf_reg_type ptr_type;
u8 mode;
+ if (i == subprogs[s].start) {
+ i += subprogs[s].prologue_len;
+ epilogue_cnt = epilogue_idx = 0;
+ if (subprogs[s].has_epilogue)
+ epilogue_cnt = ops->gen_epilogue(epilogue_buf,
+ bpf_subprog_main_prog(env, s),
+ -subprogs[s].stack_depth);
+ s++;
+ }
+
insn = &env->prog->insnsi[i];
/* A call or an atomic gets its nospec in front of the next insn */
@@ -1930,8 +1960,7 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
return PTR_ERR(insn);
continue;
} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
- epilogue_cnt &&
- i < subprogs[1].start) {
+ epilogue_cnt) {
/* Generate epilogue for the main prog */
if (epilogue_idx) {
/* jump back to the earlier generated epilogue */
@@ -2575,7 +2604,7 @@ int bpf_check_unwind_gotos(struct bpf_verifier_env *env)
"cancel_goto at insn %d follows no call", i))
return -EFAULT;
if (bpf_is_cancel_exit(insn) &&
- verifier_bug_if(i < env->subprog_info[1].start, env,
+ verifier_bug_if(bpf_find_containing_subprog(env, i)->main, env,
"cancel_exit at insn %d of the main program", i))
return -EFAULT;
if (env->insn_aux_data[i].unwind_goto_follows && can_have_unwind_goto(insn) &&
@@ -3706,7 +3735,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
for (i = 0; i < env->subprog_cnt; i++) {
int stack_slots = subprogs[i].stack_extra / 8;
/* an invocation begins, see bpf_timed_may_goto_save() for async callbacks */
- bool main_prog = tmg && !i;
+ bool main_prog = tmg && subprogs[i].main;
/* only a helper calls it, in a loop that ends when it returns 1 */
bool loop_cb = tmg && i && subprogs[i].is_loop_cb && !subprogs[i].is_called &&
!subprogs[i].is_other_cb && !subprogs[i].is_async_cb;
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 7ff259811a62..70a972716385 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -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;
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index f090a7ab72ba..2bff30bb3669 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -2958,7 +2958,7 @@ BTF_ID_LIST_GLOBAL_SINGLE(bpf_multi_func_btf_id, func, bpf_multi_func)
/* last field in 'union bpf_attr' used by this command */
#define BPF_PROG_LOAD_LAST_FIELD keyring_id
-static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
+static struct bpf_prog *bpf_prog_alloc_attr(union bpf_attr *attr, bpfptr_t uattr)
{
enum bpf_prog_type type = attr->prog_type;
struct bpf_prog *prog, *dst_prog = NULL;
@@ -2969,9 +2969,6 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
char license[128];
bool multi_func;
- if (CHECK_ATTR(BPF_PROG_LOAD))
- return -EINVAL;
-
if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
BPF_F_ANY_ALIGNMENT |
BPF_F_TEST_STATE_FREQ |
@@ -2981,14 +2978,14 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
BPF_F_XDP_DEV_BOUND_ONLY |
BPF_F_TEST_REG_INVARIANTS |
BPF_F_TOKEN_FD))
- return -EINVAL;
+ return ERR_PTR(-EINVAL);
bpf_prog_load_fixup_attach_type(attr);
if (attr->prog_flags & BPF_F_TOKEN_FD) {
token = bpf_token_get_from_fd(attr->prog_token_fd);
if (IS_ERR(token))
- return PTR_ERR(token);
+ return ERR_CAST(token);
/* if current token doesn't grant prog loading permissions,
* then we can't use this token, so ignore it and rely on
* system-wide capabilities checks
@@ -3181,6 +3178,30 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
if (err < 0)
goto free_prog;
+ return prog;
+
+free_prog:
+ free_uid(prog->aux->user);
+ if (prog->aux->attach_btf)
+ btf_put(prog->aux->attach_btf);
+ bpf_prog_free(prog);
+put_token:
+ bpf_token_put(token);
+ return ERR_PTR(err);
+}
+
+static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
+{
+ struct bpf_prog *prog;
+ int err;
+
+ if (CHECK_ATTR(BPF_PROG_LOAD))
+ return -EINVAL;
+
+ prog = bpf_prog_alloc_attr(attr, uattr);
+ if (IS_ERR(prog))
+ return PTR_ERR(prog);
+
/* run eBPF verifier */
err = bpf_check(&prog, attr, uattr, attr_log);
if (err < 0)
@@ -3226,15 +3247,6 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
*/
__bpf_prog_put_noref(prog, prog->aux->func_cnt);
return err;
-
-free_prog:
- free_uid(prog->aux->user);
- if (prog->aux->attach_btf)
- btf_put(prog->aux->attach_btf);
- bpf_prog_free(prog);
-put_token:
- bpf_token_put(token);
- return err;
}
#define BPF_OBJ_LAST_FIELD path_fd
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 8021afe783b6..b753d6c7a00b 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -459,7 +459,7 @@ static int bpf_compute_subprog_ret_regs(struct bpf_verifier_env *env)
*/
for (subprog = 1; subprog < env->subprog_cnt; subprog++) {
type = subprog_ret_type(env, subprog);
- if (!type || btf_type_is_void(type))
+ if (!type || btf_type_is_void(type) || bpf_subprog_is_main(env, subprog))
continue;
if (verifier_bug_if(IS_ERR(btf_resolve_size(btf, type, &size)), env,
"cannot size return type of subprog %d", subprog))
@@ -3240,6 +3240,11 @@ static int add_subprogs(struct bpf_verifier_env *env)
*/
subprog[cnt].start = insn_cnt;
+ env->mains = kvzalloc_objs(*env->mains, 1, BPF_VERIFIER_GFP);
+ if (!env->mains)
+ return -ENOMEM;
+ subprog[0].main = env->main_cnt = 1;
+
if (ex_cb_insn) {
env->exception_callback_subprog = bpf_find_subprog(env, ex_cb_insn);
mark_subprog_exc_cb(env, env->exception_callback_subprog);
@@ -5761,7 +5766,7 @@ static int build_call_graph(struct bpf_verifier_env *env, struct bpf_call_graph
bpf_call_graph_sort(cg, 0);
for (s = 0; s < cnt; s++)
- if (!s || si[s].is_async_cb)
+ if (si[s].main || si[s].is_async_cb)
cg->marks[s] = CG_LIVE;
bpf_call_graph_mark_callees(cg, CG_LIVE);
for_each_marked_subprog(cg, s, CG_LIVE)
@@ -5953,6 +5958,10 @@ static void mark_arena_stack_entries(struct bpf_verifier_env *env, struct bpf_ca
bpf_call_graph_mark_callers(cg, CG_ARENA_SP, CG_CB);
for_each_marked_subprog(cg, s, CG_CB)
env->subprog_info[s].arena_stack_entry = cg->marks[s] & CG_ARENA_SP;
+ for (s = 0; s < env->subprog_cnt; s++)
+ if (bpf_subprog_is_main(env, s))
+ env->subprog_info[s].arena_stack_entry =
+ env->main_cnt == 1 || (cg->marks[s] & CG_ARENA_SP);
}
/* temporary state used for call frame depth calculation */
@@ -6244,7 +6253,7 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
* The first insns of the main prog are for the kernel. A call from
* an async callback is on no cycle.
*/
- if (!j && bpf_pseudo_call(&insn[i])) {
+ if (si[j].main && bpf_pseudo_call(&insn[i])) {
verbose(env, "recursive call of the main program\n");
err = -EINVAL;
goto out;
@@ -6296,7 +6305,8 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
*/
for (s = 0; s < cnt; s++) {
si[s].bail_unwinds = si[s].can_unwind ||
- (s && env->prog->jit_requested && bpf_jit_supports_unwind() &&
+ (!si[s].main && env->prog->jit_requested &&
+ bpf_jit_supports_unwind() &&
!bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
(cg.marks[s] & CALLED));
si[s].bail_unwinds_at_first = si[s].bail_unwinds;
@@ -6316,7 +6326,7 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
if (!bpf_call_graph_recursive(&cg, s))
continue;
err = -EINVAL;
- if (!s) {
+ if (si[s].main) {
verbose(env, "recursive call of the main program\n");
break;
}
@@ -12538,7 +12548,8 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
* while it is verified.
*/
if (!env->subprog_info[subprog].changes_pkt_data &&
- (state->frame[0]->subprogno || holds_pkt_pointers(env)))
+ (!bpf_subprog_is_main(env, state->frame[0]->subprogno) ||
+ holds_pkt_pointers(env)))
sub_aux->called_with_pkt_ptrs = true;
/*
@@ -13345,11 +13356,11 @@ static bool st_ops_returns_ptr(const struct bpf_prog *prog)
}
/* What leaves frame 0 gets to the caller of the program */
-static bool returns_to_kernel(const struct bpf_verifier_state *state)
+static bool returns_to_kernel(const struct bpf_verifier_env *env)
{
- const struct bpf_func_state *frame = state->frame[0];
+ const struct bpf_func_state *frame = env->cur_state->frame[0];
- return !frame->subprogno || frame->in_exception_callback_fn;
+ return bpf_subprog_is_main(env, frame->subprogno) || frame->in_exception_callback_fn;
}
static int check_reference_leak(struct bpf_verifier_env *env)
@@ -13370,7 +13381,7 @@ static int check_reference_leak(struct bpf_verifier_env *env)
*/
if (reg->id == state->refs[i].id &&
env->prog->insnsi[env->insn_idx].code == (BPF_JMP | BPF_EXIT) &&
- st_ops_returns_ptr(env->prog) && returns_to_kernel(state))
+ st_ops_returns_ptr(env->prog) && returns_to_kernel(env))
continue;
verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
state->refs[i].id, state->refs[i].insn_idx);
@@ -14142,7 +14153,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
}
/* It can return a reference. The caller of a subprog takes r0 for a scalar. */
if (st_ops_returns_ptr(env->prog) &&
- (env->cur_state->curframe || !returns_to_kernel(env->cur_state))) {
+ (env->cur_state->curframe || !returns_to_kernel(env))) {
verbose(env, "tail_call in a subprog would lead to reference leak\n");
return -EINVAL;
}
@@ -16200,6 +16211,8 @@ static void prepare_subprog_args(struct bpf_verifier_env *env)
for (i = 1; i < env->subprog_cnt; i++) {
sub = &env->subprog_info[i];
+ if (sub->main)
+ continue;
if (!try_btf_prepare_func_args(env, i) && bpf_subprog_is_global(env, i))
/* Keep all argument registers live if the prototype is unavailable. */
sub->arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS;
@@ -20327,7 +20340,7 @@ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
* to hold a real function address. Assume that no usable program
* combines e.g. main and timer callback and just reject here.
*/
- if (subprogno == 0) {
+ if (bpf_subprog_is_main(env, subprogno)) {
verbose(env, "callback function cannot be the main program\n");
return -EINVAL;
}
@@ -21289,7 +21302,7 @@ static int process_bpf_exit_full(struct bpf_verifier_env *env, bool *do_print_st
* Exit from async callback implies return code restrictions
* that depend on async scheduling mechanism.
*/
- if (cur_frame->subprogno &&
+ if (!bpf_subprog_is_main(env, cur_frame->subprogno) &&
!cur_frame->in_async_callback_fn &&
!cur_frame->in_exception_callback_fn)
err = check_global_subprog_return_code(env);
@@ -22195,13 +22208,13 @@ int bpf_cancelled_retval(struct bpf_verifier_env *env)
* The kernel called the current frame of @st, or it is the main program of an extension or the
* exception callback. The program ends when this frame leaves.
*/
-static bool frame_is_top(const struct bpf_verifier_state *st)
+static bool frame_is_top(const struct bpf_verifier_env *env, const struct bpf_verifier_state *st)
{
const struct bpf_func_state *frame = st->frame[st->curframe];
if (st->curframe)
return false;
- return !frame->subprogno || frame->in_async_callback_fn ||
+ return bpf_subprog_is_main(env, frame->subprogno) || frame->in_async_callback_fn ||
frame->in_exception_callback_fn;
}
@@ -22236,7 +22249,7 @@ static enum bpf_pad_conflict frame_cannot_unwind(struct bpf_verifier_env *env,
/* A landing pad has no nospec barrier, so only a loader with CAP_PERFMON gets one. */
if (!bpf_may_unwind(env))
return BPF_CONFLICT_NO_PERFMON;
- if (!frame_is_top(st) && !sub->bail_unwinds)
+ if (!frame_is_top(env, st) && !sub->bail_unwinds)
return BPF_CONFLICT_CANNOT_UNWIND;
return BPF_NO_CONFLICT;
}
@@ -22256,7 +22269,7 @@ static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog)
if (sub->stuck)
return;
- if (!frame_cannot_unwind(env, st) && (!caller->stuck || frame_is_top(st))) {
+ if (!frame_cannot_unwind(env, st) && (!caller->stuck || frame_is_top(env, st))) {
caller->made_calls = true;
return;
}
@@ -22289,8 +22302,8 @@ static int guess_loop_guard(struct bpf_verifier_env *env, struct bpf_loop *loop)
{
const struct bpf_verifier_state *st = env->cur_state;
- if (env->path_sensitive || bpf_prog_is_offloaded(env->prog->aux) || !frame_is_top(st) ||
- frame_holds_resources(st) || frame_cannot_unwind(env, st)) {
+ if (env->path_sensitive || bpf_prog_is_offloaded(env->prog->aux) ||
+ !frame_is_top(env, st) || frame_holds_resources(st) || frame_cannot_unwind(env, st)) {
loop->this_pass.no_guard_edges = true;
return 0;
}
@@ -22338,7 +22351,7 @@ static int check_loop_guard(struct bpf_verifier_env *env)
* The state on that edge leaves the function and never gets to the code after the loop.
* So the state that stays carries the loop as a suspect for errors in that code.
*/
- if (!err && env->head && !frame_is_top(env->cur_state))
+ if (!err && env->head && !frame_is_top(env, env->cur_state))
env->cur_state->suspect_loops |= loop->suspect_bit;
return err;
}
@@ -22636,7 +22649,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
}
st->unwound = 0;
- if (sub->bail_unwinds && !frame_is_top(st))
+ if (sub->bail_unwinds && !frame_is_top(env, st))
st->unwound = bpf_unwound_mark(kernel, false);
/*
* The callers of a global subprog were verified before it. Mark them, and start the pass
@@ -22668,7 +22681,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
verbose(env, "from %d to %s of func#%d\n", insn_idx,
!st->unwound ? "exit" : kernel ? "cancel_exit" : "unwind_exit",
frame->subprogno);
- if (frame_is_top(st)) {
+ if (frame_is_top(env, st)) {
err = PROCESS_BPF_EXIT;
} else if (!st->curframe && st->instance_id) {
/*
@@ -24439,7 +24452,7 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
state->last_insn_idx = -1;
regs = state->frame[state->curframe]->regs;
- if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
+ if (!sub->main || env->prog->type == BPF_PROG_TYPE_EXT) {
const char *sub_name = bpf_subprog_name(env, subprog);
struct bpf_subprog_arg_info *arg;
struct bpf_reg_state *reg;
@@ -24531,11 +24544,11 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
* it's matching expected signature, and otherwise mark BTF
* info for main program as unreliable
*/
- if (env->prog->aux->func_info_aux && !env->prog->aux->func_info_aux[0].unreliable) {
- ret = btf_prepare_func_args(env, 0);
+ if (aux->func_info_aux && !aux->func_info_aux[subprog].unreliable) {
+ ret = btf_prepare_func_args(env, subprog);
if (ret || sub->arg_slot_cnt != 1 ||
sub->args[0].arg_type != ARG_PTR_TO_CTX) {
- env->prog->aux->func_info_aux[0].unreliable = true;
+ aux->func_info_aux[subprog].unreliable = true;
sub->arg_slot_cnt = 1;
}
}
@@ -24546,7 +24559,7 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
}
/* Acquire references for struct_ops program arguments tagged with "__ref" */
- if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
+ if (sub->main && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
for (i = 0; i < aux->ctx_arg_info_size; i++) {
ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0;
if (ret < 0)
@@ -24799,7 +24812,7 @@ static int check_after_pass(struct bpf_verifier_env *env)
return err;
for (i = 0; i < env->subprog_cnt; i++, sub++) {
/* the caller would get r12 of the callee back */
- if (env->uses_arena_sp && (!i || sub->arena_stack_entry) && sub->is_called) {
+ if (env->uses_arena_sp && (sub->main || sub->arena_stack_entry) && sub->is_called) {
verbose(env, "%s() uses R%d and is both called and a callback\n",
bpf_subprog_name(env, i), BPF_REG_ARENA_SP);
return -EINVAL;
@@ -25339,7 +25352,7 @@ static void add_insns_of_callees(struct bpf_verifier_env *env)
/* callees first */
for (i = 0; i < env->subprog_cnt; i++) {
s = env->subprog_topo_order[i];
- if (!s || bpf_subprog_is_global(env, s))
+ if (si[s].main || bpf_subprog_is_global(env, s))
continue;
for (j = si[s].start; j < si[s + 1].start; j++) {
if (!bpf_pseudo_call(&insn[j]))
@@ -25368,7 +25381,7 @@ static void print_verification_stats(struct bpf_verifier_env *env)
if (!name || !name[0])
name = "<unknown>";
- kind = i == 0 ? "main" :
+ kind = bpf_subprog_is_main(env, i) ? "main" :
bpf_subprog_is_global(env, i) ? "global" : "static";
verbose(env, "subprog %d (%s) %s insns_self %d insns_total %d stack %d\n",
i, name, kind, env->subprog_info[i].insns_self,
@@ -27568,6 +27581,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
kvfree(env->idoms);
kvfree(env->subprog_info);
kvfree(env->subprog_topo_order);
+ kvfree(env->mains);
kvfree(env);
return ret;
}
--
2.55.0
^ permalink raw reply related [flat|nested] 13+ messages in thread
* [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load Alexei Starovoitov
@ 2026-12-02 21:27 ` Alexei Starovoitov
2026-12-02 22:15 ` sashiko-bot
2026-12-02 22:35 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 3/7] bpf: Generate landing pads for many main programs Alexei Starovoitov
` (4 subsequent siblings)
6 siblings, 2 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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.
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
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(-)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 9eccf86ea6e7..28280e2db1e6 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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);
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index f6d54ca7cfed..e0eb2cce3180 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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, i
void 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 s
return 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;
diff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c
index 71ec6063dce6..123afe96e329 100644
--- a/kernel/bpf/cfg.c
+++ b/kernel/bpf/cfg.c
@@ -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;
diff --git a/kernel/bpf/failing_path.c b/kernel/bpf/failing_path.c
index cac1ed2f8331..aaae4711d3c3 100644
--- a/kernel/bpf/failing_path.c
+++ b/kernel/bpf/failing_path.c
@@ -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;
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index fd297b475576..247eb6372f69 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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;
diff --git a/kernel/bpf/flow.c b/kernel/bpf/flow.c
index d0e708a94f0a..30758913c0a0 100644
--- a/kernel/bpf/flow.c
+++ b/kernel/bpf/flow.c
@@ -412,6 +412,19 @@ void bpf_flow_new_pass(struct bpf_verifier_env *env)
flow_forget_loop(env, aux->loop);
if (aux->loop->rt_bounded)
aux->loop->rt_bounded = flow_loop_is_bounded(env, i);
+ aux->loop->guarded |= aux->needs_guard;
+ }
+}
+
+/* The pass has no error. Add what it found to what the main progs before this one found. */
+void bpf_flow_note_guards(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++, aux++) {
+ aux->needs_guard |= aux->loop && aux->loop->this_pass.needs_guard;
+ aux->no_guard_edges |= aux->loop && aux->loop->this_pass.no_guard_edges;
}
}
@@ -424,7 +437,8 @@ void bpf_flow_drop_guards(struct bpf_verifier_env *env)
for (i = 0; i < env->prog->len; i++) {
h = bpf_loop_at_index(env, i);
if (h >= 0)
- aux[i].loop_guard &= aux[h].loop->this_pass.needs_guard;
+ aux[i].loop_guard &= aux[h].needs_guard |
+ aux[h].loop->this_pass.needs_guard;
}
}
@@ -439,7 +453,7 @@ bool bpf_flow_guard_is_guess(struct bpf_verifier_env *env, int idx)
{
int h = bpf_loop_at_index(env, idx);
- return !env->path_sensitive && h >= 0 &&
+ return !env->path_sensitive && h >= 0 && !env->insn_aux_data[h].needs_guard &&
!env->insn_aux_data[h].loop->this_pass.needs_guard;
}
@@ -467,8 +481,6 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env)
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);
- /* pass 0 does not know the trip count before it ends */
- loop->guarded = !bpf_prog_is_offloaded(env->prog->aux);
}
return err;
}
@@ -502,6 +514,34 @@ int bpf_check_limits(struct bpf_verifier_env *env)
return -E2BIG;
}
+static void flow_reset_loop(struct bpf_verifier_env *env, struct bpf_loop *loop)
+{
+ size_t from = offsetof(struct bpf_loop, precision);
+
+ if (!loop)
+ return;
+ memset((void *)loop + from, 0, offsetof(struct bpf_loop, steps) - from);
+ loop->suspect_bit = loop->exit_trip = 0;
+ /* pass 0 does not know the trip count before it ends */
+ loop->guarded = !bpf_prog_is_offloaded(env->prog->aux);
+}
+
+/* The passes of a main prog start with no precision */
+void bpf_flow_new_main(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int i;
+
+ env->flow->start_cnt = 0;
+ memset(&env->per_pass, 0, offsetof(struct bpf_env_per_pass, seen_direct_write));
+ for (i = 0; i < env->prog->len; i++, aux++) {
+ aux->pessimized = false;
+ flow_reset_loop(env, aux->loop);
+ flow_reset_loop(env, aux->callback_loop);
+ flow_reset_loop(env, aux->recursion_loop);
+ }
+}
+
static struct bpf_loop *flow_new_call_loop(struct bpf_verifier_env *env, enum bpf_loop_kind kind,
int header, int func)
{
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index 0a2923505308..725de358f5ca 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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);
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index b753d6c7a00b..2c6dc44f4e74 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -408,6 +408,41 @@ bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)
return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
}
+/* Not struct_group(): what a tracing prog reads from a union is not trusted */
+#define aux_fields(aux, first) ((void *)(aux) + offsetof(struct bpf_prog_aux, first))
+#define aux_fields_size(first, last) \
+ (offsetofend(struct bpf_prog_aux, last) - offsetof(struct bpf_prog_aux, first))
+
+#define attach_point(aux) aux_fields(aux, attach_btf_id)
+#define ATTACH_POINT_SIZE aux_fields_size(attach_btf_id, recursion_detected)
+
+static void swap_attach_point(struct bpf_verifier_env *env, struct bpf_main_prog *main)
+{
+ struct bpf_prog *a = env->prog, *b = main->prog;
+ bool sleepable = a->sleepable;
+ u8 tmp[ATTACH_POINT_SIZE];
+
+ a->sleepable = b->sleepable;
+ b->sleepable = sleepable;
+ swap(a->expected_attach_type, b->expected_attach_type);
+ memcpy(tmp, attach_point(a->aux), sizeof(tmp));
+ memcpy(attach_point(a->aux), attach_point(b->aux), sizeof(tmp));
+ memcpy(attach_point(b->aux), tmp, sizeof(tmp));
+}
+
+/*
+ * The checks of insns ask env->prog where the program is attached.
+ * Let it answer for main prog @idx. It has to be undone with @idx 0.
+ */
+static void enter_main(struct bpf_verifier_env *env, u32 idx)
+{
+ if (env->cur_main)
+ swap_attach_point(env, &env->mains[env->cur_main]);
+ env->cur_main = idx;
+ if (idx)
+ swap_attach_point(env, &env->mains[idx]);
+}
+
static const struct btf_type *subprog_ret_type(struct bpf_verifier_env *env, int subprog)
{
const struct btf_type *func, *func_proto;
@@ -3240,7 +3275,7 @@ static int add_subprogs(struct bpf_verifier_env *env)
*/
subprog[cnt].start = insn_cnt;
- env->mains = kvzalloc_objs(*env->mains, 1, BPF_VERIFIER_GFP);
+ env->mains = kvzalloc_objs(*env->mains, env->prog->aux->entry_cnt ?: 1, BPF_VERIFIER_GFP);
if (!env->mains)
return -ENOMEM;
subprog[0].main = env->main_cnt = 1;
@@ -3257,6 +3292,65 @@ static int add_subprogs(struct bpf_verifier_env *env)
return 0;
}
+/* func_info has been checked: it describes all subprogs */
+static int add_entries(struct bpf_verifier_env *env)
+{
+ struct bpf_prog *prog = env->prog, *entry;
+ struct bpf_prog_aux *aux = prog->aux;
+ const char *what = NULL;
+ int i, s, off;
+
+ if (!aux->entry_cnt)
+ return 0;
+ if (bpf_prog_is_dev_bound(aux))
+ what = "device bound programs";
+ else if (env->signature)
+ what = "signed programs";
+ else if (!aux->func_info)
+ what = "programs without BTF";
+ else if (!prog->jit_requested)
+ what = "programs that are not JITed";
+ else if (!bpf_jit_supports_unwind() ||
+ (IS_ENABLED(CONFIG_X86) && !IS_ENABLED(CONFIG_UNWINDER_ORC)))
+ what = "programs for a JIT that cannot walk the stack";
+ else if (env->exception_callback_subprog)
+ what = "programs with an exception callback";
+ for (s = 0; s < env->subprog_cnt; s++)
+ if (env->subprog_info[s].has_tail_call)
+ what = "programs with tail calls";
+ for (i = 0; i < aux->entry_cnt; i++)
+ if (aux->entries[i]->type == BPF_PROG_TYPE_TRACING ||
+ aux->entries[i]->type == BPF_PROG_TYPE_LSM ||
+ aux->entries[i]->type == BPF_PROG_TYPE_EXT)
+ what = "tracing, LSM and extension programs";
+ if (what) {
+ verbose(env, "%s cannot have entries\n", what);
+ return -EOPNOTSUPP;
+ }
+ prog->jit_required = 1;
+
+ for (i = 0; i < aux->entry_cnt; i++) {
+ if (bpf_must_abort())
+ return -EINTR;
+ entry = aux->entries[i];
+ off = entry->aux->subprog_start;
+ s = off >= 0 && off < prog->len ? bpf_find_subprog(env, off) : -ENOENT;
+ if (s < 0 || (i && bpf_subprog_is_main(env, s))) {
+ verbose(env, "entry %s: invalid insn_off %u\n", entry->aux->name, off);
+ return -EINVAL;
+ }
+ if (entry->aux->token != aux->token) {
+ verbose(env, "entry %s: token is not that of %s\n",
+ entry->aux->name, aux->name);
+ return -EPERM;
+ }
+ env->mains[i].prog = entry;
+ env->mains[i].subprog = s;
+ env->subprog_info[s].main = env->main_cnt = i + 1;
+ }
+ return 0;
+}
+
static int add_kfuncs(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
@@ -3390,7 +3484,7 @@ static int check_subprogs(struct bpf_verifier_env *env)
*/
static int record_callx_edge(struct bpf_verifier_env *env, int caller, int callee)
{
- u32 *first = &env->subprog_info[caller].callx_edge, cnt = env->callx_index.cnt;
+ u32 *first = &env->subprog_info[caller].callx_edge, cnt = env->callx_cnt;
u64 key = (u64)caller << 32 | callee;
if (bpf_index_find(&env->callx_index, key) >= 0)
@@ -3398,7 +3492,7 @@ static int record_callx_edge(struct bpf_verifier_env *env, int caller, int calle
if (!bpf_table_next(env->callx_edges, cnt) || bpf_index_add(&env->callx_index, key, cnt))
return -ENOMEM;
env->callx_edges[cnt] = (struct bpf_callx_edge){ callee, *first };
- *first = cnt + 1;
+ *first = ++env->callx_cnt;
return 0;
}
@@ -6254,7 +6348,8 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
* an async callback is on no cycle.
*/
if (si[j].main && bpf_pseudo_call(&insn[i])) {
- verbose(env, "recursive call of the main program\n");
+ verbose(env, "%scall of the main program\n",
+ j ? "" : "recursive ");
err = -EINVAL;
goto out;
}
@@ -6403,6 +6498,9 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
/* x86 JIT has one register for both */
if (env->uses_arena_sp)
priv_stack_mode = NO_PRIV_STACK;
+ /* it has one frame of a subprog, and main progs run on top of each other */
+ if (env->main_cnt > 1)
+ priv_stack_mode = NO_PRIV_STACK;
if (priv_stack_mode == PRIV_STACK_UNKNOWN)
priv_stack_mode = bpf_enable_priv_stack(env->prog);
@@ -10944,6 +11042,11 @@ static int check_map_func_compatibility(struct bpf_verifier_env *env,
if (!map)
return 0;
+ if (env->main_cnt > 1 && env->prog->sleepable && !map_needs_no_rcu(map)) {
+ verbose(env, "sleepable entry cannot use map '%s'\n", map->name);
+ return -EINVAL;
+ }
+
/*
* check_map_prog_compatibility() asks the program. That misses the
* sleepable callback of another program, and an inner map. They may
@@ -12469,6 +12572,15 @@ static int check_static_func_call(struct bpf_verifier_env *env, int subprog,
return 0;
}
+/*
+ * Where ctx accesses are converted all main progs are the same to a global subprog.
+ * Otherwise the ctx, helpers and kfuncs depend on the attach point, so check it for each.
+ */
+static u32 subprog_caller(struct bpf_verifier_env *env)
+{
+ return 1 + (env->ops->convert_ctx_access ? 0 : env->cur_main);
+}
+
static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
int *insn_idx)
{
@@ -12529,11 +12641,11 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
subprog, sub_name);
if (in_sleepable_context(env))
- sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] = true;
+ sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] = subprog_caller(env);
else if (has_rcu_read_lock(env))
- sub_aux->called[BPF_FUNC_CTX_NON_SLEEPABLE] = true;
+ sub_aux->called[BPF_FUNC_CTX_NON_SLEEPABLE] = subprog_caller(env);
else
- sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK] = true;
+ sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK] = subprog_caller(env);
returns_void = subprog_returns_void(env, subprog);
if (env->subprog_info[subprog].changes_pkt_data)
clear_all_pkt_pointers(env);
@@ -13558,7 +13670,9 @@ int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
if (!env->ops->get_func_proto)
return -EINVAL;
- *ptr = env->ops->get_func_proto(func_id, env->prog);
+ /* An insn has one proto: that of the first main prog, see enter_main() */
+ *ptr = env->ops->get_func_proto(func_id, env->cur_main ? env->mains[env->cur_main].prog :
+ env->prog);
return *ptr && (*ptr)->func ? 0 : -EINVAL;
}
@@ -13637,6 +13751,8 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
return -EINVAL;
}
+ if (!err && env->cur_main && fn != env->ops->get_func_proto(func_id, env->prog))
+ err = -EINVAL;
if (err) {
verbose(env, "program of this type cannot use helper %s#%d\n",
func_id_name(func_id), func_id);
@@ -15954,7 +16070,9 @@ int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
meta->func_proto = kfunc.proto;
meta->func_name = kfunc.name;
- if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
+ /* The analyses of the code are for all main progs. check_kfunc_call() asks for each. */
+ if (!kfunc.flags ||
+ (env->main_cnt == 1 && !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)))
return -EACCES;
meta->kfunc_flags = *kfunc.flags;
@@ -16503,6 +16621,8 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
}
err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
+ if (!err && env->main_cnt > 1 && !btf_kfunc_is_allowed(meta.btf, meta.func_id, env->prog))
+ err = -EACCES;
if (err == -EACCES && meta.func_name) {
verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
operation = bpf_diag_fmt(env, "kfunc %s", meta.func_name);
@@ -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;
+ }
if (!(env->path_sensitive ? loop->infinite : loop->guarded))
return guess_loop_guard(env, loop);
@@ -23569,7 +23691,8 @@ static int check_map_prog_compatibility(struct bpf_verifier_env *env,
return -EINVAL;
}
- if (prog->sleepable && !map_needs_no_rcu(map)) {
+ /* the map can be for another entry, see check_map_func_compatibility() */
+ if (prog->sleepable && !prog->aux->entry_cnt && !map_needs_no_rcu(map)) {
verbose(env,
"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
return -EINVAL;
@@ -23647,6 +23770,11 @@ static int check_excl_maps(struct bpf_verifier_env *env)
for (i = 0; i < env->used_map_cnt; i++) {
struct bpf_map *map = env->used_maps[i];
+ /* the digest doesn't say which functions are main programs */
+ if (map->excl_prog_sha && env->main_cnt > 1) {
+ verbose(env, "programs with exclusive maps cannot have entries\n");
+ return -EOPNOTSUPP;
+ }
if (map->excl_prog_sha &&
memcmp(map->excl_prog_sha, env->prog->digest, SHA256_DIGEST_SIZE)) {
verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
@@ -24283,6 +24411,8 @@ static int cmp_maps(const void *a, const void *b)
*
* The program reads the addresses of its functions from there like any other
* data, so it has to be allowed to leak pointers.
+ *
+ * Not with entries: a number of one main program can match a function of another one.
*/
static int resolve_func_ptrs(struct bpf_verifier_env *env)
{
@@ -24292,7 +24422,7 @@ static int resolve_func_ptrs(struct bpf_verifier_env *env)
u64 addr, val;
u32 off;
- if (!env->has_callx || !env->allow_ptr_leaks || !env->used_map_cnt)
+ if (!env->has_callx || !env->allow_ptr_leaks || !env->used_map_cnt || env->main_cnt > 1)
return 0;
/* with the maps in order the pointers are in order */
@@ -24544,6 +24674,8 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
* it's matching expected signature, and otherwise mark BTF
* info for main program as unreliable
*/
+ if (subprog && (env->log.level & BPF_LOG_LEVEL))
+ verbose(env, "Validating entry %s() func#%d...\n", sub->name, subprog);
if (aux->func_info_aux && !aux->func_info_aux[subprog].unreliable) {
ret = btf_prepare_func_args(env, subprog);
if (ret || sub->arg_slot_cnt != 1 ||
@@ -24647,7 +24779,7 @@ static int do_check_subprogs(struct bpf_verifier_env *env)
sub_aux = subprog_aux(env, i);
for (context = 0; context < ARRAY_SIZE(sub_aux->called); context++) {
- if (!sub_aux->called[context] || sub_aux->verified[context])
+ if (sub_aux->called[context] == sub_aux->verified[context])
continue;
env->insn_idx = env->subprog_info[i].start;
@@ -24660,7 +24792,7 @@ static int do_check_subprogs(struct bpf_verifier_env *env)
"that match its prototype\n",
i, bpf_subprog_name(env, i));
- sub_aux->verified[context] = true;
+ sub_aux->verified[context] = sub_aux->called[context];
new_cnt++;
}
}
@@ -24677,12 +24809,22 @@ static int do_check_subprogs(struct bpf_verifier_env *env)
static int do_check_main(struct bpf_verifier_env *env)
{
+ struct bpf_subprog_info *sub = &env->subprog_info[env->mains[env->pass_main].subprog];
+ struct bpf_prog_aux *aux = env->prog->aux;
int ret;
- env->insn_idx = 0;
- ret = do_check_common(env, 0, env->prog->sleepable);
+ enter_main(env, env->pass_main);
+ env->insn_idx = sub->start;
+ ret = do_check_common(env, sub - env->subprog_info, env->prog->sleepable) ?:
+ do_check_subprogs(env);
+ enter_main(env, 0);
+ if (env->main_cnt > 1) {
+ /* these come from insns that have the ctx */
+ swap(sub->max_ctx_offset, aux->max_ctx_offset);
+ swap(sub->max_tp_access, aux->max_tp_access);
+ }
if (!ret)
- env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
+ aux->stack_depth = env->subprog_info[0].stack_depth;
return ret;
}
@@ -24694,6 +24836,7 @@ struct bpf_snapshot {
struct bpf_pads_moved *pads; /* per insn, see bpf_pads_move() */
struct bpf_subprog_info *subprogs;
struct bpf_func_info_aux *funcs;
+ size_t bytes;
struct bpf_prog prog;
};
@@ -24751,7 +24894,7 @@ static struct bpf_snapshot *save_snapshot(struct bpf_verifier_env *env,
BPF_VERIFIER_GFP);
if (!snapshot)
return NULL;
- env->mem += insns + pads + subprogs;
+ env->mem += snapshot->bytes = insns + pads + subprogs;
snapshot->insns = (void *)(snapshot + 1);
snapshot->pads = (void *)snapshot->insns + insns;
memset(snapshot->pads, 0, pads);
@@ -24766,7 +24909,7 @@ static void free_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *sna
{
if (!snapshot)
return;
- env->mem -= bpf_pads_free_moved(snapshot->pads, env->prog->len);
+ env->mem -= snapshot->bytes + bpf_pads_free_moved(snapshot->pads, env->prog->len);
kvfree(snapshot);
}
@@ -24807,6 +24950,11 @@ static int check_after_pass(struct bpf_verifier_env *env)
u16 outgoing;
int i, err;
+ if (env->main_cnt > 1 && (env->prog->tstamp_type_access || env->prog->kprobe_override ||
+ env->prog->aux->kprobe_write_ctx)) {
+ verbose(env, "programs that read tstamp_type or change pt_regs cannot have entries\n");
+ return -EOPNOTSUPP;
+ }
err = check_max_stack_depth(env) ?: check_ext_takes_prologue(env);
if (err)
return err;
@@ -24916,13 +25064,11 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
}
env->pass_again = false;
restore_snapshot(env, initial);
- kvfree(env->callx_edges);
kvfree(env->callx_index.slots);
- env->callx_edges = NULL;
env->callx_index = (struct bpf_index){};
bpf_flow_new_pass(env);
bpf_pads_new_round(env);
- ret = do_check_main(env) ?: do_check_subprogs(env) ?: bpf_check_limits(env);
+ ret = do_check_main(env) ?: bpf_check_limits(env);
if (env->pads_late) {
err = settle_late_unwinds(env, initial);
ret = ret ?: err;
@@ -24934,6 +25080,7 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
{
+ bool last = env->pass_main + 1 == env->main_cnt;
int ret;
if (env->pass && (env->log.level & BPF_LOG_LEVEL2))
@@ -24956,6 +25103,9 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
/* bpf_pads_settle() found what a pass has to know from its start: repeat the pass. */
if (!ret && pass_needs_restart(env))
return 0;
+ /* the call graph is checked once */
+ if (!ret && !last)
+ return 0;
ret = ret ?: check_after_pass(env);
if (ret) {
bpf_find_unproven_after_pass(env);
@@ -25199,7 +25349,7 @@ static int do_check_all(struct bpf_verifier_env *env)
}
env->max_mem = min(env->max_mem, env->mem + BPF_PASS_MEM_BASE +
(u64)BPF_PASS_MEM_PER_INSN * env->prog->len);
- for (;; env->pass += !env->for_log) {
+ for (env->pass = 0;; env->pass += !env->for_log) {
if (!env->pass || !quiet)
restart_log(env, &log);
ret = check_pass(env, initial);
@@ -25236,7 +25386,7 @@ static int do_check_all(struct bpf_verifier_env *env)
break;
bpf_restore_precision(env);
} else if (!ret) {
- bpf_flow_drop_guards(env);
+ bpf_flow_note_guards(env);
if (pass_needs_restart(env)) {
env->pass_again = true;
continue;
@@ -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;
+ 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;
+}
+
/*
* What it took to verify a static subprog on its own is not in insns_total of its callers.
* Add it, once per caller. The main prog and global subprogs have all of it already.
@@ -25936,6 +26122,15 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
BPF_REG_ARENA_SP);
return -EOPNOTSUPP;
}
+ if (aux->entry_cnt && (!subprog || aux->func[subprog]->aux->is_entry)) {
+ bpf_log(log, "%s is a program of its own\n", tname);
+ return -EINVAL;
+ }
+ /* The extension is checked for one main prog */
+ if (aux->entry_cnt && prog_extension) {
+ bpf_log(log, "Cannot replace a function of a program with entries\n");
+ return -EOPNOTSUPP;
+ }
if (subprog && subprog == aux->exception_callback_subprog) {
bpf_log(log,
"%s programs cannot attach to exception callback\n",
@@ -26479,6 +26674,138 @@ static int check_attach_btf_id(struct bpf_verifier_env *env)
return 0;
}
+static bool can_share_subprogs(struct bpf_verifier_env *env, const struct bpf_main_prog *main)
+{
+ const struct bpf_prog *prog = env->prog, *entry = main->prog;
+
+ if (entry->type != prog->type)
+ return false;
+ if (entry->type == BPF_PROG_TYPE_STRUCT_OPS)
+ return entry->aux->st_ops == prog->aux->st_ops;
+ return entry->expected_attach_type == prog->expected_attach_type &&
+ entry->sleepable == prog->sleepable;
+}
+
+static int check_attach_entry(struct bpf_verifier_env *env, struct bpf_main_prog *main)
+{
+ struct bpf_prog_aux *aux = main->prog->aux;
+ const struct bpf_verifier_ops *ops = env->ops;
+ struct module *mod = env->attach_btf_mod;
+ struct bpf_prog *prog = env->prog;
+ int err;
+
+ aux->arena = prog->aux->arena;
+
+ env->attach_btf_mod = NULL;
+ env->prog = main->prog;
+ err = check_attach_btf_id(env);
+ env->prog = prog;
+ env->ops = ops;
+ if (!err && !can_share_subprogs(env, main)) {
+ verbose(env, "entry %s: type, attach type or flags are not those of %s\n",
+ aux->name, prog->aux->name);
+ err = -EINVAL;
+ }
+ /* it's one struct for all */
+ swap(env->attach_btf_mod, mod);
+ module_put(mod);
+ return err;
+}
+
+static int check_attach_entries(struct bpf_verifier_env *env)
+{
+ int m, err = 0;
+
+ for (m = 0; m < env->prog->aux->entry_cnt && !err; m++) {
+ /* it gets a copy, see finish_entry() */
+ env->mem += env->used_map_cnt * sizeof(*env->used_maps);
+ err = bpf_check_limits(env) ?: check_attach_entry(env, &env->mains[m]);
+ }
+ return err;
+}
+
+/* An entry is a prog of one function. The code belongs to @prog. */
+static int finish_entry(struct bpf_verifier_env *env, int s)
+{
+ struct bpf_subprog_info *sub = &env->subprog_info[s];
+ struct bpf_prog *prog = env->prog, *entry, *func = prog->aux->func[s];
+ struct bpf_prog_aux *aux, *from = prog->aux;
+ u32 i, start = func->aux->subprog_start;
+
+ if (bpf_must_abort())
+ return -EINTR;
+ entry = bpf_prog_realloc(from->entries[sub->main - 1], bpf_prog_size(func->len),
+ GFP_USER | BPF_GFP_MAYFAIL);
+ if (!entry)
+ return -ENOMEM;
+ from->entries[sub->main - 1] = entry;
+ aux = entry->aux;
+
+ entry->len = func->len;
+ memcpy(entry->insnsi, prog->insnsi + start, bpf_prog_insn_size(entry));
+ entry->jited = entry->jit_requested = entry->jit_required = 1;
+ entry->blinded = prog->blinded;
+ entry->bpf_func = func->bpf_func;
+ entry->jited_len = func->jited_len;
+ memcpy(entry->digest, prog->digest, sizeof(prog->digest));
+ /* of all main progs, but for what is known of each one */
+ entry->cb_access = prog->cb_access;
+ entry->dst_needed = prog->dst_needed;
+ entry->call_get_func_ip = prog->call_get_func_ip;
+ entry->call_session_cookie = prog->call_session_cookie;
+ entry->call_get_stack = prog->call_get_stack;
+ entry->percpu_state = prog->percpu_state;
+ entry->enforce_expected_attach_type = prog->enforce_expected_attach_type;
+ memcpy(aux_fields(aux, max_ctx_offset), aux_fields(from, max_ctx_offset),
+ aux_fields_size(max_ctx_offset, cgroup_storage));
+ aux->max_ctx_offset = sub->max_ctx_offset;
+ aux->max_tp_access = sub->max_tp_access;
+ aux->changes_pkt_data = sub->changes_pkt_data;
+ aux->might_sleep = sub->might_sleep;
+ aux->stack_depth = sub->stack_depth;
+ aux->verified_insns = sub->insns_total;
+ aux->subprog_start = start;
+
+ btf_get(from->btf);
+ aux->btf = from->btf;
+ aux->func_info = kmemdup(&from->func_info[s], sizeof(*aux->func_info), BPF_VERIFIER_GFP);
+ aux->func_info_aux = kmemdup(&from->func_info_aux[s], sizeof(*aux->func_info_aux),
+ BPF_VERIFIER_GFP);
+ if (!aux->func_info || !aux->func_info_aux)
+ return -ENOMEM;
+ aux->func_info->insn_off = 0;
+ aux->func_info_cnt = 1;
+
+ for (i = sub->linfo_idx; i < from->nr_linfo; i++, aux->nr_linfo++)
+ if (from->linfo[i].insn_off >= start + func->len)
+ break;
+ if (aux->nr_linfo) {
+ aux->linfo = kvmemdup(&from->linfo[sub->linfo_idx],
+ aux->nr_linfo * sizeof(*aux->linfo), BPF_VERIFIER_GFP);
+ aux->jited_linfo = kvmemdup(&from->jited_linfo[sub->linfo_idx],
+ aux->nr_linfo * sizeof(void *), BPF_VERIFIER_GFP);
+ if (!aux->linfo || !aux->jited_linfo)
+ return -ENOMEM;
+ for (i = 0; i < aux->nr_linfo; i++)
+ aux->linfo[i].insn_off -= start;
+ }
+
+ if (from->used_map_cnt) {
+ aux->used_maps = kvmemdup(from->used_maps, from->used_map_cnt * sizeof(void *),
+ BPF_VERIFIER_GFP);
+ if (!aux->used_maps)
+ return -ENOMEM;
+ }
+ for (; aux->used_map_cnt < from->used_map_cnt; aux->used_map_cnt++) {
+ if (bpf_prog_runs_sleepable(entry))
+ atomic64_inc(&aux->used_maps[aux->used_map_cnt]->sleepable_refcnt);
+ bpf_map_inc(aux->used_maps[aux->used_map_cnt]);
+ }
+
+ /* Maps of progs were compared with the owner. Nothing here does tail calls. */
+ return bpf_prog_lock_ro(entry);
+}
+
int bpf_check_attach_btf_id_multi(struct bpf_verifier_log *log, struct btf *btf,
struct bpf_prog *prog, u32 btf_id,
struct bpf_attach_target_info *tgt_info)
@@ -27327,6 +27654,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
+ ret = add_entries(env);
+ if (ret < 0)
+ goto skip_full_check;
+
/* Validate instructions and resolve the program's referenced resources. */
ret = check_and_resolve_insns(env);
if (ret < 0)
@@ -27362,7 +27693,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret)
goto skip_full_check;
- ret = check_attach_btf_id(env);
+ ret = check_attach_btf_id(env) ?: check_attach_entries(env);
if (ret)
goto skip_full_check;
@@ -27427,7 +27758,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
- ret = do_check_all(env);
+ ret = do_check_mains(env);
bpf_free_subprog_jts(env);
/* while the calls are what they are in the program */
if (env->log.level & BPF_LOG_STATS)
@@ -27438,6 +27769,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
ret = bpf_prog_offload_finalize(env);
skip_full_check:
+ if (ret && env->has_callx && env->main_cnt > 1)
+ verbose(env, "programs with entries have no tables of functions\n");
+
/* instruction rewrites happen after this point */
if (ret == 0)
ret = bpf_remove_fastcall_spills_fills(env);
@@ -27520,6 +27854,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
+ for (i = 0; i < env->subprog_cnt && env->main_cnt > 1 && !ret; i++)
+ if (bpf_subprog_is_main(env, i))
+ ret = finish_entry(env, i);
+
err_release_maps:
/*
* Finalize the log after the runtime is selected, which blinds the
diff --git a/net/ipv4/bpf_tcp_ops.c b/net/ipv4/bpf_tcp_ops.c
index 6b8ad08fa54d..97a5c24d9a89 100644
--- a/net/ipv4/bpf_tcp_ops.c
+++ b/net/ipv4/bpf_tcp_ops.c
@@ -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;
--
2.55.0
^ permalink raw reply related [flat|nested] 13+ messages in thread
* [PATCH v2 bpf-next 3/7] bpf: Generate landing pads for many main programs
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns Alexei Starovoitov
@ 2026-12-02 21:27 ` Alexei Starovoitov
2026-12-02 22:21 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 4/7] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
` (3 subsequent siblings)
6 siblings, 1 reply; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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.
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
include/linux/bpf_verifier.h | 9 +++++-
kernel/bpf/pads.c | 59 ++++++++++++++++++++++++++-------
kernel/bpf/verifier.c | 63 ++++++++++++++++++++++++++++++++----
3 files changed, 112 insertions(+), 19 deletions(-)
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index e0eb2cce3180..619df34f0ced 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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 class
void 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,
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 70a972716385..befe9a729115 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -492,19 +492,52 @@ size_t bpf_pad_note_free(struct bpf_pad_note *note)
return bytes;
}
-/* A pass or a path-sensitive run begins */
-void bpf_pads_new_round(struct bpf_verifier_env *env)
+static int copy_plans(struct bpf_verifier_env *env, struct bpf_pad_plan **to,
+ const struct bpf_pad_plan *plan)
+{
+ for (; plan; plan = plan->next, to = &(*to)->next) {
+ *to = kmemdup(plan, sizeof(*plan), BPF_VERIFIER_GFP);
+ if (!*to)
+ return -ENOMEM;
+ env->mem += plan->bytes;
+ (*to)->next = NULL;
+ (*to)->ents = !plan->ents ? NULL :
+ kmemdup_array(plan->ents, BPF_PAD_MAX_ENTS, sizeof(*plan->ents),
+ BPF_VERIFIER_GFP);
+ (*to)->callee = !plan->callee ? NULL :
+ kmemdup_array(plan->callee, roundup_pow_of_two(plan->nr_callees),
+ sizeof(*plan->callee), BPF_VERIFIER_GFP);
+ if (!(*to)->ents != !plan->ents || !(*to)->callee != !plan->callee)
+ return -ENOMEM;
+ }
+ return 0;
+}
+
+static int copy_notes(struct bpf_verifier_env *env, struct bpf_pad_note **to,
+ const struct bpf_pad_note *note)
+{
+ for (; note; note = note->next, to = &(*to)->next) {
+ *to = kmemdup(note, sizeof(*note), BPF_VERIFIER_GFP);
+ if (!*to)
+ return -ENOMEM;
+ env->mem += sizeof(*note);
+ (*to)->next = NULL;
+ }
+ return 0;
+}
+
+/*
+ * A pass adds to what the main progs before this one recorded: a pad is for the states of all of
+ * them. The records have just moved out of @kept. Put a copy back for the next pass.
+ */
+void bpf_pads_keep(struct bpf_verifier_env *env, struct bpf_pads_moved *kept)
{
struct bpf_insn_aux_data *aux = env->insn_aux_data;
int i;
- env->pads_late = false;
- env->pad_skip_gen++;
- for (i = 0; i < env->prog->len; i++, aux++) {
- env->mem -= bpf_pad_plans_free(aux);
- env->mem -= bpf_pad_note_free(aux->pad_note);
- aux->pad_note = NULL;
- }
+ for (i = 0; i < env->prog->len && !env->no_mem; i++, aux++, kept++)
+ env->no_mem = copy_plans(env, &kept->plans, aux->pad_plans) ||
+ copy_notes(env, &kept->note, aux->pad_note);
}
/*
@@ -2346,7 +2379,9 @@ static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_
int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan, int subprog,
struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
{
- struct bpf_insn ld_aux[2] = { BPF_LD_IMM64(BPF_REG_1, (long)env->prog->aux) };
+ u32 main = env->subprog_info[subprog].main;
+ struct bpf_prog *prog = main ? bpf_subprog_main_prog(env, subprog) : env->prog;
+ struct bpf_insn ld_aux[2] = { BPF_LD_IMM64(BPF_REG_1, (long)prog->aux) };
int value_off = env->subprog_info[subprog].value_off;
int src = bpf_site_value_reg(plan->kind), dst = BPF_REG_0;
bool passes_on = bpf_pad_passes_on(env, subprog, plan->kind);
@@ -2354,7 +2389,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 (bpf_subprog_is_main(env, subprog) && env->exception_callback_subprog)
+ if (main && 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);
@@ -2385,7 +2420,7 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
} else if (passes_on) {
/* no call: R0 and R2 are what unwind_exit left */
} else if (!bpf_site_has_value(env, subprog, plan->kind)) {
- buf[n++] = BPF_MOV64_IMM(dst, bpf_cancelled_retval(env));
+ buf[n++] = BPF_MOV64_IMM(dst, env->mains[main ? main - 1 : 0].cancelled_retval);
} else if (src != dst) {
buf[n++] = BPF_MOV64_REG(dst, src);
}
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 2c6dc44f4e74..f6fda89be3e6 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -12685,10 +12685,12 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
* known to leave without returning: with unwind_exit and with cancel_exit.
*/
for (i = 0; i < 2; i++) {
- const struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+ struct bpf_subprog_info *sub = &env->subprog_info[subprog];
struct bpf_verifier_state *branch;
bool kernel = i;
+ sub->call_skips_unwind |= !sub->did_unwind;
+ sub->call_skips_cancel |= !sub->did_cancel;
if (!(kernel ? sub->did_cancel : sub->did_unwind) || !sub->bail_unwinds)
continue;
err = check_unwound_return(env, *insn_idx, subprog, kernel);
@@ -24814,6 +24816,7 @@ static int do_check_main(struct bpf_verifier_env *env)
int ret;
enter_main(env, env->pass_main);
+ env->mains[env->pass_main].cancelled_retval = bpf_cancelled_retval(env);
env->insn_idx = sub->start;
ret = do_check_common(env, sub - env->subprog_info, env->prog->sleepable) ?:
do_check_subprogs(env);
@@ -25016,18 +25019,39 @@ static int settle_late_unwinds(struct bpf_verifier_env *env, const struct bpf_sn
*/
static int mark_used_sites(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)
{
+ struct bpf_subprog_info *sub = env->subprog_info;
int s, err;
bpf_flow_drop_guards(env);
err = bpf_mark_subprogs_that_unwind(env, true);
bpf_pads_mark_used(env);
- for (s = 0; s < env->subprog_cnt; s++) {
- env->subprog_info[s].can_unwind = initial->subprogs[s].can_unwind;
- env->subprog_info[s].can_cancel = initial->subprogs[s].can_cancel;
+ for (s = 0; s < env->subprog_cnt; s++, sub++) {
+ sub->leaves_unexpected = (sub->can_unwind && sub->call_skips_unwind) ||
+ (sub->can_cancel && sub->call_skips_cancel);
+ sub->can_unwind = initial->subprogs[s].can_unwind;
+ sub->can_cancel = initial->subprogs[s].can_cancel;
}
return err;
}
+/* The next main prog adds to the records. See if they can be settled, and put them back. */
+static int try_pads_settle(struct bpf_verifier_env *env)
+{
+ struct bpf_snapshot *unsettled = save_snapshot(env, NULL);
+ int err;
+
+ env->no_mem |= !unsettled;
+ if (!unsettled)
+ return -ENOMEM;
+ restore_snapshot(env, unsettled);
+ bpf_pads_keep(env, unsettled->pads);
+ err = bpf_check_limits(env) ?: bpf_pads_settle(env);
+ if (!err && !pass_needs_restart(env))
+ restore_snapshot(env, unsettled);
+ free_snapshot(env, unsettled);
+ return err;
+}
+
/* Returns the first error */
static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
{
@@ -25067,7 +25091,7 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
kvfree(env->callx_index.slots);
env->callx_index = (struct bpf_index){};
bpf_flow_new_pass(env);
- bpf_pads_new_round(env);
+ bpf_pads_keep(env, initial->pads);
ret = do_check_main(env) ?: bpf_check_limits(env);
if (env->pads_late) {
err = settle_late_unwinds(env, initial);
@@ -25096,7 +25120,7 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
* Only the sites that the program keeps count. Hidden slots add to the stack of a
* function, so the landing pads are settled before the stack is checked.
*/
- ret = mark_used_sites(env, initial) ?: bpf_pads_settle(env);
+ ret = mark_used_sites(env, initial) ?: last ? bpf_pads_settle(env) : try_pads_settle(env);
/* The limit on cost or a signal is no error of the program, see do_check_all(). */
if (ret == -EINTR || (ret && env->over_limit))
return ret;
@@ -25243,6 +25267,8 @@ static bool hand_over_more(struct bpf_verifier_env *env, struct bpf_snapshot *in
int s;
for (s = 1; s < env->subprog_cnt; s++) {
+ if (initial->subprogs[s].proven)
+ continue;
args = env->subprog_info[s].asks_args & ~initial->subprogs[s].owns_args;
initial->subprogs[s].owns_args |= args;
more |= args;
@@ -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;
}
@@ -25491,13 +25519,34 @@ static int do_check_all(struct bpf_verifier_env *env)
static int check_proven_mains(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_subprog_info *sub = env->subprog_info;
int i;
+ /* the pads of the callers pass on the value that a shared function leaves with */
+ if (env->has_throw &&
+ env->mains[env->pass_main].cancelled_retval != env->mains[0].cancelled_retval) {
+ verbose(env, "programs with bpf_throw return different values when cancelled\n");
+ return -EINVAL;
+ }
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;
}
+ if (aux[i].fault_empty && bpf_pad_plan(&aux[i], BPF_SITE_FAULT)) {
+ verbose(env, "insn %d needs a landing pad for some programs only\n", i);
+ return -EINVAL;
+ }
+ }
+ for (i = 0; i < env->subprog_cnt; i++, sub++) {
+ if (sub->leaves_unexpected || (sub->stuck && sub->soft_unwinds) ||
+ (sub->proven && sub->bail_unwinds != sub->bail_unwinds_at_first)) {
+ verbose(env, "%s() can be cancelled for some programs only\n",
+ bpf_subprog_name(env, i));
+ return -EINVAL;
+ }
+ sub->bail_unwinds_at_first = sub->bail_unwinds;
+ sub->proven = aux[sub->start].seen;
}
return 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);
@@ -26762,6 +26812,7 @@ static int finish_entry(struct bpf_verifier_env *env, int s)
aux->max_tp_access = sub->max_tp_access;
aux->changes_pkt_data = sub->changes_pkt_data;
aux->might_sleep = sub->might_sleep;
+ aux->can_unwind = func->aux->can_unwind;
aux->stack_depth = sub->stack_depth;
aux->verified_insns = sub->insns_total;
aux->subprog_start = start;
--
2.55.0
^ permalink raw reply related [flat|nested] 13+ messages in thread
* [PATCH v2 bpf-next 4/7] bpf: Take entries at BPF_PROG_LOAD
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
` (2 preceding siblings ...)
2026-12-02 21:27 ` [PATCH v2 bpf-next 3/7] bpf: Generate landing pads for many main programs Alexei Starovoitov
@ 2026-12-02 21:27 ` Alexei Starovoitov
2026-12-02 22:20 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 5/7] libbpf, bpftool: Share subprogs between programs Alexei Starovoitov
` (2 subsequent siblings)
6 siblings, 1 reply; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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.
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
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(-)
diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index dfb5048a3054..aba25fefb4f5 100644
--- a/Documentation/bpf/verifier.rst
+++ b/Documentation/bpf/verifier.rst
@@ -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
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 28280e2db1e6..340d66a523d8 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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);
diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h
index ce8de1302f7f..9f41c63f1831 100644
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -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 {
diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c
index ebe4ac74f219..c0c431124a13 100644
--- a/kernel/bpf/arena.c
+++ b/kernel/bpf/arena.c
@@ -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);
diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c
index e3608ec9da09..6ac596c156c2 100644
--- a/kernel/bpf/bpf_struct_ops.c
+++ b/kernel/bpf/bpf_struct_ops.c
@@ -580,14 +580,40 @@ static void bpf_struct_ops_map_put_progs(struct bpf_struct_ops_map *st_map)
}
}
+/* Kfuncs get aux of the owner. It knows the map of its entries until they are in two maps. */
+static void entry_assoc(struct bpf_prog_aux *aux, struct bpf_map *map)
+{
+ guard(spinlock_irqsave)(&aux->st_ops_assoc_lock);
+
+ if (!aux->st_ops_links)
+ rcu_assign_pointer(aux->st_ops_assoc, map);
+ if (rcu_access_pointer(aux->st_ops_assoc) == map)
+ aux->st_ops_links++;
+ else
+ rcu_assign_pointer(aux->st_ops_assoc, BPF_PTR_POISON);
+}
+
+static void entry_disassoc(struct bpf_prog_aux *aux, struct bpf_map *map)
+{
+ guard(spinlock_irqsave)(&aux->st_ops_assoc_lock);
+
+ if (rcu_access_pointer(aux->st_ops_assoc) == map && !--aux->st_ops_links)
+ RCU_INIT_POINTER(aux->st_ops_assoc, NULL);
+}
+
static void bpf_struct_ops_map_dissoc_progs(struct bpf_struct_ops_map *st_map)
{
+ struct bpf_prog *prog;
u32 i;
for (i = 0; i < st_map->funcs_cnt; i++) {
if (!st_map->links[i])
break;
- bpf_prog_disassoc_struct_ops(st_map->links[i]->prog);
+ prog = st_map->links[i]->prog;
+ if (prog->aux->is_entry)
+ entry_disassoc(prog->aux->main_prog_aux, &st_map->map);
+ else
+ bpf_prog_disassoc_struct_ops(prog);
}
}
@@ -795,10 +821,10 @@ find_desc_by_local_type(const struct btf *btf, u32 id,
}
/*
- * attach_btf_id is a local struct and expected_attach_type is the index of its
- * member. Replace them, and the BTF, with what the kernel has under the same names.
+ * 'id' is a local struct and 'member_idx' is the index of its member.
+ * Replace them, and the BTF, with what the kernel has under the same names.
*/
-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)
{
const struct bpf_struct_ops_desc *st_ops_desc;
const struct btf_member *member;
@@ -807,23 +833,23 @@ int bpf_struct_ops_resolve_attach(struct btf **btf, union bpf_attr *attr)
struct module *mod;
int err = 0;
- st_ops_desc = find_desc_by_local_type(*btf, attr->attach_btf_id, &kern_btf, &mod);
+ st_ops_desc = find_desc_by_local_type(*btf, *id, &kern_btf, &mod);
if (IS_ERR(st_ops_desc))
return PTR_ERR(st_ops_desc);
- t = btf_type_by_id(*btf, attr->attach_btf_id);
- if (attr->expected_attach_type >= btf_type_vlen(t)) {
+ t = btf_type_by_id(*btf, *id);
+ if (*member_idx >= btf_type_vlen(t)) {
err = -EINVAL;
goto out;
}
- member = btf_type_member(t) + attr->expected_attach_type;
+ member = btf_type_member(t) + *member_idx;
member = find_member(kern_btf, st_ops_desc->type,
btf_name_by_offset(*btf, member->name_off));
if (!member) {
err = -ENOENT;
goto out;
}
- attr->attach_btf_id = st_ops_desc->type_id;
- attr->expected_attach_type = member - btf_type_member(st_ops_desc->type);
+ *id = st_ops_desc->type_id;
+ *member_idx = member - btf_type_member(st_ops_desc->type);
btf_put(*btf);
*btf = kern_btf;
out:
@@ -1055,7 +1081,10 @@ static long __bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key,
*plink++ = &link->link;
/* Poison pointer on error instead of return for backward compatibility */
- bpf_prog_assoc_struct_ops(prog, &st_map->map);
+ if (prog->aux->is_entry)
+ entry_assoc(prog->aux->main_prog_aux, &st_map->map);
+ else
+ bpf_prog_assoc_struct_ops(prog, &st_map->map);
ksym = kzalloc_obj(*ksym, GFP_USER);
if (!ksym) {
@@ -1800,12 +1829,13 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map)
{
+ struct bpf_prog_aux *aux = prog->aux->main_prog_aux;
struct bpf_map *st_ops_assoc;
- guard(spinlock_irqsave)(&prog->aux->st_ops_assoc_lock);
+ guard(spinlock_irqsave)(&aux->st_ops_assoc_lock);
- st_ops_assoc = rcu_dereference_protected(prog->aux->st_ops_assoc,
- lockdep_is_held(&prog->aux->st_ops_assoc_lock));
+ st_ops_assoc = rcu_dereference_protected(aux->st_ops_assoc,
+ lockdep_is_held(&aux->st_ops_assoc_lock));
if (st_ops_assoc && st_ops_assoc == map)
return 0;
@@ -1813,7 +1843,7 @@ int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map)
if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
return -EBUSY;
- rcu_assign_pointer(prog->aux->st_ops_assoc, BPF_PTR_POISON);
+ rcu_assign_pointer(aux->st_ops_assoc, BPF_PTR_POISON);
} else {
/*
* struct_ops map does not track associated non-struct_ops programs.
@@ -1822,7 +1852,7 @@ int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map)
if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
bpf_map_inc(map);
- rcu_assign_pointer(prog->aux->st_ops_assoc, map);
+ rcu_assign_pointer(aux->st_ops_assoc, map);
}
return 0;
@@ -1862,6 +1892,8 @@ void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux,
struct bpf_struct_ops_map *st_map;
struct bpf_map *st_ops_assoc;
+ /* ->recursion_detected() gets the entry */
+ aux = aux->main_prog_aux;
st_ops_assoc = rcu_dereference_check(aux->st_ops_assoc, bpf_rcu_lock_held());
if (!st_ops_assoc || st_ops_assoc == BPF_PTR_POISON)
return NULL;
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 3653a2ecf5b7..8230dcdf14f4 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -958,7 +958,7 @@ void bpf_ksym_add(struct bpf_ksym *ksym)
static void __bpf_ksym_del(struct bpf_ksym *ksym)
{
- if (list_empty(&ksym->lnode))
+ if (list_empty(&ksym->lnode) || ksym->lnode.prev == LIST_POISON2)
return;
latch_tree_erase(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
@@ -3593,11 +3593,29 @@ static void bpf_prog_free_images(struct work_struct *work)
if (aux->func_cnt) {
kvfree(aux->func);
bpf_prog_unlock_free(aux->prog);
+ } else if (aux->is_entry) {
+ if (aux->main_prog_aux != aux)
+ bpf_prog_put(aux->main_prog_aux->prog);
+ bpf_prog_unlock_free(aux->prog);
} else {
bpf_jit_free(aux->prog);
}
}
+/* Nobody calls the function any more. The image goes with the owner */
+static void bpf_prog_kallsyms_del_entry(struct bpf_prog *entry)
+{
+ struct bpf_prog *code;
+
+ guard(rcu)();
+ /* ksym_prefix ends at the first byte */
+ code = bpf_prog_ksym_find((unsigned long)entry->bpf_func + 1);
+ if (!code)
+ return;
+ WRITE_ONCE(code->aux->entry, NULL);
+ bpf_prog_kallsyms_del(code);
+}
+
static void bpf_prog_free_deferred(struct work_struct *work)
{
struct bpf_prog_aux *aux;
@@ -3610,6 +3628,8 @@ static void bpf_prog_free_deferred(struct work_struct *work)
*/
ksyms = aux->func_cnt || !list_empty(&aux->ksym.lnode);
bpf_prog_kallsyms_del_all(aux->prog);
+ if (aux->is_entry && aux->main_prog_aux != aux)
+ bpf_prog_kallsyms_del_entry(aux->prog);
#ifdef CONFIG_BPF_SYSCALL
bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab);
#endif
@@ -4385,6 +4405,7 @@ int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char *
struct walk_stack_ctx {
struct bpf_prog *prog;
+ bool async_cb;
};
static bool find_from_stack_cb(void *cookie, u64 ip, u64 sp, u64 bp)
@@ -4400,19 +4421,36 @@ static bool find_from_stack_cb(void *cookie, u64 ip, u64 sp, u64 bp)
rcu_read_lock();
prog = bpf_prog_ksym_find(ip);
rcu_read_unlock();
+ /* What an async callback has interrupted did not call it */
if (!prog)
- return true;
+ return !ctxp->async_cb;
+ if (ctxp->prog && ctxp->prog->aux != prog->aux->main_prog_aux)
+ return false;
/* Make sure we return the main prog if we found a subprog */
- ctxp->prog = prog->aux->main_prog_aux->prog;
- return false;
+ ctxp->prog = READ_ONCE(prog->aux->entry) ?: prog->aux->main_prog_aux->prog;
+ ctxp->async_cb = prog->aux->async_cb;
+ return ctxp->prog->aux->entry_cnt;
}
-struct bpf_prog *bpf_prog_find_from_stack(void)
+static struct bpf_prog *find_from_stack(struct bpf_prog *prog)
{
- struct walk_stack_ctx ctx = {};
+ struct walk_stack_ctx ctx = { prog };
arch_bpf_stack_walk(find_from_stack_cb, &ctx);
return ctx.prog;
}
+struct bpf_prog *bpf_prog_find_from_stack(void)
+{
+ return find_from_stack(NULL);
+}
+
+/* The code of @prog runs. For which entry? It's the owner if there is none in the stack */
+struct bpf_prog *bpf_prog_find_main(const struct bpf_prog *prog)
+{
+ struct bpf_prog *owner = prog->aux->main_prog_aux->prog;
+
+ return owner->aux->entry_cnt ? find_from_stack(owner) : owner;
+}
+
#endif
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 247eb6372f69..4d76b9a83b39 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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;
diff --git a/kernel/bpf/stream.c b/kernel/bpf/stream.c
index 53519a17bf26..c726e54a63c0 100644
--- a/kernel/bpf/stream.c
+++ b/kernel/bpf/stream.c
@@ -403,7 +403,7 @@ __bpf_kfunc int bpf_stream_vprintk(int stream_id, const char *fmt__str, const vo
u32 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;
}
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 2bff30bb3669..b9cd3d50dee5 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -2694,6 +2694,10 @@ EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
bool bpf_prog_get_ok(struct bpf_prog *prog,
enum bpf_prog_type *attach_type, bool attach_drv)
{
+ /* it has the code of its entries, and that's all */
+ if (prog->aux->entry_cnt)
+ return false;
+
/* not an attachment, just a refcount inc, always allow */
if (!attach_type)
return true;
@@ -2706,18 +2710,23 @@ bool bpf_prog_get_ok(struct bpf_prog *prog,
return true;
}
-static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
- bool attach_drv)
+static struct bpf_prog *bpf_prog_of_fd(struct fd f)
{
- CLASS(fd, f)(ufd);
- struct bpf_prog *prog;
-
if (fd_empty(f))
return ERR_PTR(-EBADF);
if (fd_file(f)->f_op != &bpf_prog_fops)
return ERR_PTR(-EINVAL);
+ return fd_file(f)->private_data;
+}
+
+static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
+ bool attach_drv)
+{
+ CLASS(fd, f)(ufd);
+ struct bpf_prog *prog = bpf_prog_of_fd(f);
- prog = fd_file(f)->private_data;
+ if (IS_ERR(prog))
+ return prog;
if (!bpf_prog_get_ok(prog, attach_type, attach_drv))
return ERR_PTR(-EINVAL);
@@ -2956,11 +2965,12 @@ int __init __used bpf_multi_func(void) { return 0; }
BTF_ID_LIST_GLOBAL_SINGLE(bpf_multi_func_btf_id, func, bpf_multi_func)
/* last field in 'union bpf_attr' used by this command */
-#define BPF_PROG_LOAD_LAST_FIELD keyring_id
+#define BPF_PROG_LOAD_LAST_FIELD entry_rec_size
static struct bpf_prog *bpf_prog_alloc_attr(union bpf_attr *attr, bpfptr_t uattr)
{
enum bpf_prog_type type = attr->prog_type;
+ u32 attach_type, attach_btf_id = attr->attach_btf_id;
struct bpf_prog *prog, *dst_prog = NULL;
struct btf *attach_btf = NULL;
struct bpf_token *token = NULL;
@@ -2981,6 +2991,7 @@ static struct bpf_prog *bpf_prog_alloc_attr(union bpf_attr *attr, bpfptr_t uattr
return ERR_PTR(-EINVAL);
bpf_prog_load_fixup_attach_type(attr);
+ attach_type = attr->expected_attach_type;
if (attr->prog_flags & BPF_F_TOKEN_FD) {
token = bpf_token_get_from_fd(attr->prog_token_fd);
@@ -3050,12 +3061,21 @@ static struct bpf_prog *bpf_prog_alloc_attr(union bpf_attr *attr, bpfptr_t uattr
/* only struct_ops can name its target in the BTF of the object */
err = -ENOTSUPP;
if (type == BPF_PROG_TYPE_STRUCT_OPS)
- err = bpf_struct_ops_resolve_attach(&attach_btf, attr);
+ err = bpf_struct_ops_resolve_attach(&attach_btf,
+ &attach_btf_id,
+ &attach_type);
if (err) {
btf_put(attach_btf);
goto put_token;
}
}
+ } else if (dst_prog->aux->is_entry &&
+ dst_prog->aux->func_info[0].type_id != attr->attach_btf_id) {
+ /* what an entry calls is a function of its owner */
+ prog = dst_prog;
+ dst_prog = prog->aux->main_prog_aux->prog;
+ bpf_prog_inc(dst_prog);
+ bpf_prog_put(prog);
}
} else if (attr->attach_btf_id || multi_func) {
/* fall back to vmlinux BTF, if BTF type ID is specified */
@@ -3071,8 +3091,7 @@ static struct bpf_prog *bpf_prog_alloc_attr(union bpf_attr *attr, bpfptr_t uattr
btf_get(attach_btf);
}
- if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
- attach_btf, attr->attach_btf_id,
+ if (bpf_prog_load_check_attach(type, attach_type, attach_btf, attach_btf_id,
dst_prog, multi_func)) {
if (dst_prog)
bpf_prog_put(dst_prog);
@@ -3093,10 +3112,10 @@ static struct bpf_prog *bpf_prog_alloc_attr(union bpf_attr *attr, bpfptr_t uattr
goto put_token;
}
- prog->expected_attach_type = attr->expected_attach_type;
+ prog->expected_attach_type = attach_type;
prog->sleepable = !!(attr->prog_flags & BPF_F_SLEEPABLE);
prog->aux->attach_btf = attach_btf;
- prog->aux->attach_btf_id = multi_func ? bpf_multi_func_btf_id[0] : attr->attach_btf_id;
+ prog->aux->attach_btf_id = multi_func ? bpf_multi_func_btf_id[0] : attach_btf_id;
prog->aux->dst_prog = dst_prog;
if (dst_prog) {
prog->aux->saved_dst_ctx_type = resolve_prog_type(dst_prog);
@@ -3190,6 +3209,152 @@ static struct bpf_prog *bpf_prog_alloc_attr(union bpf_attr *attr, bpfptr_t uattr
return ERR_PTR(err);
}
+/*
+ * An entry is checked like a load of its own. It gets its insns from the verifier.
+ * The first one is for the function at insn 0.
+ */
+int bpf_prog_alloc_entries(struct bpf_prog *prog, union bpf_attr *attr, bpfptr_t uattr)
+{
+ bpfptr_t urec = make_bpfptr(attr->entries, uattr.is_kernel);
+ struct bpf_prog_aux *aux = prog->aux;
+ union bpf_attr eattr = *attr;
+ struct bpf_prog_entry rec = {};
+ struct bpf_prog *entry;
+ int err;
+
+ if (!attr->entry_cnt)
+ return attr->entries || attr->entry_rec_size ? -EINVAL : 0;
+ if (!bpf_token_capable(aux->token, CAP_BPF))
+ return -EPERM;
+ if (attr->entry_cnt >= attr->insn_cnt ||
+ attr->entry_rec_size < sizeof(rec) || attr->entry_rec_size > PAGE_SIZE ||
+ attr->entry_rec_size % sizeof(u32))
+ return -EINVAL;
+ aux->entries = kvzalloc_objs(*aux->entries, attr->entry_cnt + 1, GFP_KERNEL_ACCOUNT);
+ if (!aux->entries)
+ return -ENOMEM;
+
+ for (;;) {
+ if (bpf_must_abort())
+ return -EINTR;
+ eattr.insn_cnt = 1;
+ entry = bpf_prog_alloc_attr(&eattr, uattr);
+ if (IS_ERR(entry))
+ return PTR_ERR(entry);
+ /* the license can be another one when it's read again */
+ entry->gpl_compatible = prog->gpl_compatible;
+ if (!aux->entry_cnt)
+ bpf_prog_stream_share(entry, prog);
+ entry->aux->is_entry = true;
+ entry->aux->subprog_start = rec.insn_off;
+ aux->entries[aux->entry_cnt++] = entry;
+
+ eattr.insn_cnt = attr->insn_cnt;
+ err = security_bpf_prog_load(entry, &eattr, entry->aux->token, uattr.is_kernel);
+ if (err)
+ return err < 0 ? err : -EPERM;
+ if (aux->entry_cnt > attr->entry_cnt)
+ return 0;
+
+ err = bpf_check_uarg_tail_zero(urec, sizeof(rec), attr->entry_rec_size);
+ if (err)
+ return err;
+ if (copy_from_bpfptr(&rec, urec, sizeof(rec)))
+ return -EFAULT;
+ bpfptr_add(&urec, attr->entry_rec_size);
+ if ((rec.prog_flags ^ attr->prog_flags) & ~BPF_F_SLEEPABLE)
+ return -EINVAL;
+ eattr.prog_type = rec.prog_type;
+ eattr.prog_flags = rec.prog_flags;
+ eattr.expected_attach_type = rec.expected_attach_type;
+ eattr.attach_btf_id = rec.attach_btf_id;
+ eattr.attach_btf_obj_fd = rec.attach_btf_obj_fd;
+ memcpy(eattr.prog_name, rec.prog_name, sizeof(rec.prog_name));
+ }
+}
+
+/* Those that have no id */
+static void bpf_prog_free_entries(struct bpf_prog *prog)
+{
+ struct bpf_prog_aux *aux = prog->aux;
+ u32 i;
+
+ for (i = 0; i < aux->entry_cnt; i++)
+ if (aux->entries[i])
+ __bpf_prog_put_noref(aux->entries[i], false);
+ kvfree(aux->entries);
+ aux->entries = NULL;
+}
+
+static void bpf_prog_announce(struct bpf_prog *prog)
+{
+ perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
+ bpf_audit_prog(prog, BPF_AUDIT_LOAD);
+}
+
+/* All entries get an fd, or none. Returns the fd of the first one. */
+static int bpf_prog_entries_new_fds(struct bpf_prog *prog, union bpf_attr *attr, bpfptr_t uattr)
+{
+ bpfptr_t urec = make_bpfptr(attr->entries, uattr.is_kernel);
+ u32 i, n, cnt = prog->aux->entry_cnt;
+ struct bpf_prog *entry;
+ struct {
+ struct file *file;
+ int fd;
+ } *fds;
+ int err = 0;
+
+ bpf_prog_add(prog, cnt);
+ for (n = 0; n < cnt; n++)
+ prog->aux->entries[n]->aux->main_prog_aux = prog->aux;
+
+ fds = kvmalloc_objs(*fds, cnt, GFP_KERNEL_ACCOUNT);
+ if (!fds)
+ return -ENOMEM;
+ for (n = 0; n < cnt; n++) {
+ entry = prog->aux->entries[n];
+ err = bpf_prog_alloc_id(entry);
+ if (err)
+ break;
+ prog->aux->entries[n] = NULL;
+ bpf_prog_announce(entry);
+
+ fds[n].fd = security_bpf_prog(entry);
+ if (fds[n].fd >= 0)
+ fds[n].fd = get_unused_fd_flags(O_CLOEXEC);
+ if (fds[n].fd < 0) {
+ err = fds[n].fd;
+ bpf_prog_put(entry);
+ break;
+ }
+ fds[n].file = anon_inode_getfile("bpf-prog", &bpf_prog_fops, entry,
+ O_RDWR | O_CLOEXEC);
+ if (IS_ERR(fds[n].file)) {
+ err = PTR_ERR(fds[n].file);
+ put_unused_fd(fds[n].fd);
+ bpf_prog_put(entry);
+ break;
+ }
+ }
+ for (i = 1; i < n && !err; i++) {
+ if (copy_to_bpfptr_offset(urec, offsetof(struct bpf_prog_entry, prog_fd),
+ &fds[i].fd, sizeof(u32)))
+ err = -EFAULT;
+ bpfptr_add(&urec, attr->entry_rec_size);
+ }
+ for (i = 0; i < n; i++) {
+ if (err) {
+ put_unused_fd(fds[i].fd);
+ fput(fds[i].file);
+ } else {
+ fd_install(fds[i].fd, fds[i].file);
+ }
+ }
+ err = err ?: fds[0].fd;
+ kvfree(fds);
+ return err;
+}
+
static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
{
struct bpf_prog *prog;
@@ -3211,6 +3376,10 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
if (err < 0)
goto free_used_maps;
+ /* it is the name of the first entry */
+ if (prog->aux->entry_cnt)
+ memset(prog->aux->name, 0, sizeof(prog->aux->name));
+
/* bpf_throw() and faults look for the symbol. The prog can run once it has the id. */
bpf_prog_kallsyms_add(prog);
@@ -3232,8 +3401,14 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
* Also, any failure handling from this point onwards must
* be using bpf_prog_put() given the program is exposed.
*/
- perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
- bpf_audit_prog(prog, BPF_AUDIT_LOAD);
+ bpf_prog_announce(prog);
+
+ if (prog->aux->entry_cnt) {
+ err = bpf_prog_entries_new_fds(prog, attr, uattr);
+ bpf_prog_free_entries(prog);
+ bpf_prog_put(prog);
+ return err;
+ }
err = bpf_prog_new_fd(prog);
if (err < 0)
@@ -3241,6 +3416,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
return err;
free_used_maps:
+ bpf_prog_free_entries(prog);
/* In case we have subprogs, we need to wait for a grace
* period before we can tear down JIT memory since symbols
* are already exposed under kallsyms.
@@ -5132,7 +5308,8 @@ static void prepare_dump_pseudo_call(const struct bpf_prog *prog, struct bpf_ins
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);
+ insn->imm = bpf_prog_find_func(prog->aux->main_prog_aux->prog,
+ prog->aux->subprog_start + idx + call_off + 1);
/* Avoid dumping a truncated and misleading pc-relative offset. */
if (call_off > S16_MAX || call_off < S16_MIN)
@@ -5258,7 +5435,7 @@ static int bpf_prog_get_info_by_fd(struct file *file,
u32 ulen, len;
int err;
- len = offsetofend(struct bpf_prog_info, attach_btf_id);
+ len = offsetofend(struct bpf_prog_info, owner_prog_id);
err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), len, info_len);
if (err)
return err;
@@ -5274,6 +5451,7 @@ static int bpf_prog_get_info_by_fd(struct file *file,
info.created_by_uid = from_kuid_munged(current_user_ns(),
prog->aux->user->uid);
info.gpl_compatible = prog->gpl_compatible;
+ info.owner_prog_id = prog->aux->is_entry ? prog->aux->main_prog_aux->id : 0;
memcpy(info.tag, prog->tag, sizeof(prog->tag));
memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
@@ -6427,20 +6605,18 @@ static int prog_stream_read(union bpf_attr *attr)
{
char __user *buf = u64_to_user_ptr(attr->prog_stream_read.stream_buf);
u32 len = attr->prog_stream_read.stream_buf_len;
+ CLASS(fd, f)(attr->prog_stream_read.prog_fd);
struct bpf_prog *prog;
- int ret;
if (CHECK_ATTR(BPF_PROG_STREAM_READ_BY_FD))
return -EINVAL;
- prog = bpf_prog_get(attr->prog_stream_read.prog_fd);
+ /* the owner of entries has streams too */
+ prog = bpf_prog_of_fd(f);
if (IS_ERR(prog))
return PTR_ERR(prog);
- ret = bpf_prog_stream_read(prog, attr->prog_stream_read.stream_id, buf, len);
- bpf_prog_put(prog);
-
- return ret;
+ return bpf_prog_stream_read(prog, attr->prog_stream_read.stream_id, buf, len);
}
#define BPF_PROG_ASSOC_STRUCT_OPS_LAST_FIELD prog_assoc_struct_ops.flags
@@ -6490,22 +6666,20 @@ static int prog_assoc_struct_ops(union bpf_attr *attr)
static int prog_stream_open(union bpf_attr *attr)
{
+ CLASS(fd, f)(attr->prog_stream_open.prog_fd);
struct bpf_prog *prog;
u32 flags = attr->prog_stream_open.flags;
- int ret;
if (CHECK_ATTR(BPF_PROG_STREAM_OPEN))
return -EINVAL;
if (flags & ~BPF_F_STREAM_NONBLOCK)
return -EINVAL;
- prog = bpf_prog_get(attr->prog_stream_open.prog_fd);
+ prog = bpf_prog_of_fd(f);
if (IS_ERR(prog))
return PTR_ERR(prog);
- ret = bpf_prog_stream_new_fd(prog, attr->prog_stream_open.stream_id, flags);
- bpf_prog_put(prog);
- return ret;
+ return bpf_prog_stream_new_fd(prog, attr->prog_stream_open.stream_id, flags);
}
static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size,
@@ -6715,18 +6889,48 @@ static bool syscall_prog_is_valid_access(int off, int size,
return true;
}
+/*
+ * The kernel writes fds to the entries, and all that the caller is known to own
+ * are @size bytes at @uattr. So that's where they have to be, after the attr.
+ */
+static int sys_bpf_prog_load(union bpf_attr *uattr, u32 size)
+{
+ union bpf_attr attr = {};
+ u64 off;
+ int ret;
+
+ memcpy(&attr, uattr, min_t(u32, size, sizeof(attr)));
+ if (attr.entry_cnt) {
+ off = attr.entries - (unsigned long)uattr;
+ if (off < offsetofend(union bpf_attr, entry_rec_size) || off > size ||
+ (u64)attr.entry_cnt * attr.entry_rec_size > size - off)
+ return -EFAULT;
+ size = off;
+ }
+ ret = bpf_check_uarg_tail_zero(KERNEL_BPFPTR(uattr), sizeof(attr), size);
+ if (ret)
+ return ret;
+ size = min_t(u32, size, sizeof(attr));
+
+ /* what was checked can't change */
+ ret = __sys_bpf(BPF_PROG_LOAD, KERNEL_BPFPTR(&attr), size, KERNEL_BPFPTR(NULL), 0);
+ memcpy(uattr, &attr, size);
+ return ret;
+}
+
BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
{
if (bpf_in_async_cb())
return -EPERM;
switch (cmd) {
+ case BPF_PROG_LOAD:
+ return sys_bpf_prog_load(attr, attr_size);
case BPF_MAP_CREATE:
case BPF_MAP_DELETE_ELEM:
case BPF_MAP_UPDATE_ELEM:
case BPF_MAP_FREEZE:
case BPF_MAP_GET_FD_BY_ID:
- case BPF_PROG_LOAD:
case BPF_BTF_LOAD:
case BPF_LINK_CREATE:
case BPF_RAW_TRACEPOINT_OPEN:
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index f6fda89be3e6..cc5a39abe9a7 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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. */
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index ce8de1302f7f..9f41c63f1831 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -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 {
diff --git a/tools/testing/selftests/bpf/prog_tests/bpf_attr_size.c b/tools/testing/selftests/bpf/prog_tests/bpf_attr_size.c
index 87842c4347a6..559e4aa5f56d 100644
--- a/tools/testing/selftests/bpf/prog_tests/bpf_attr_size.c
+++ b/tools/testing/selftests/bpf/prog_tests/bpf_attr_size.c
@@ -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,
--
2.55.0
^ permalink raw reply related [flat|nested] 13+ messages in thread
* [PATCH v2 bpf-next 5/7] libbpf, bpftool: Share subprogs between programs
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
` (3 preceding siblings ...)
2026-12-02 21:27 ` [PATCH v2 bpf-next 4/7] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
@ 2026-12-02 21:27 ` Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 6/7] libbpf: Share subprogs in light skeletons Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 7/7] selftests/bpf: Test programs that share subprogs Alexei Starovoitov
6 siblings, 0 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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.
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
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(-)
diff --git a/tools/bpf/bpftool/cfg.c b/tools/bpf/bpftool/cfg.c
index e3785f9a697d..788109113d64 100644
--- a/tools/bpf/bpftool/cfg.c
+++ b/tools/bpf/bpftool/cfg.c
@@ -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;
diff --git a/tools/bpf/bpftool/common.c b/tools/bpf/bpftool/common.c
index ca5fa2f0bf9b..8af3e0b2ae91 100644
--- a/tools/bpf/bpftool/common.c
+++ b/tools/bpf/bpftool/common.c
@@ -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);
diff --git a/tools/bpf/bpftool/prog.c b/tools/bpf/bpftool/prog.c
index 15efc6eebffb..1d048f194ba0 100644
--- a/tools/bpf/bpftool/prog.c
+++ b/tools/bpf/bpftool/prog.c
@@ -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;
diff --git a/tools/lib/bpf/bpf.c b/tools/lib/bpf/bpf.c
index ad6b356cc48c..d61f1cd0585d 100644
--- a/tools/lib/bpf/bpf.c
+++ b/tools/lib/bpf/bpf.c
@@ -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;
diff --git a/tools/lib/bpf/bpf.h b/tools/lib/bpf/bpf.h
index 2ac143fd1102..afad5f491b05 100644
--- a/tools/lib/bpf/bpf.h
+++ b/tools/lib/bpf/bpf.h
@@ -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,
diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index e66e848eb463..54bebd9215c3 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -521,6 +521,11 @@ struct bpf_program {
struct bpf_light_subprog *subprogs;
__u32 subprog_cnt;
+
+ bool can_share;
+ /* only in the image of many programs, see bpf_object_load_shared() */
+ struct bpf_prog_entry *entries;
+ __u32 entry_cnt;
};
struct bpf_struct_ops {
@@ -8688,6 +8693,25 @@ static int bpf_object__bind_arena(struct bpf_object *obj, struct bpf_program *pr
return 0;
}
+static void bpf_object__bind_rodata(struct bpf_object *obj, struct bpf_program *prog, int prog_fd)
+{
+ struct bpf_map *map;
+
+ if (!obj->has_rodata || !kernel_supports(obj, FEAT_PROG_BIND_MAP))
+ return;
+
+ bpf_object__for_each_map(map, obj) {
+ if (map->libbpf_type != LIBBPF_MAP_RODATA)
+ continue;
+
+ if (bpf_prog_bind_map(prog_fd, map->fd, NULL)) {
+ pr_warn("prog '%s': failed to bind map '%s': %s\n",
+ prog->name, map->real_name, errstr(errno));
+ /* Don't fail hard if can't bind rodata. */
+ }
+ }
+}
+
static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
struct bpf_insn *insns, int insns_cnt,
const char *license, __u32 kern_version, int *prog_fd)
@@ -8747,6 +8771,9 @@ static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog
}
load_attr.log_level = log_level;
load_attr.prog_flags = prog->prog_flags;
+ load_attr.entries = prog->entries;
+ load_attr.entry_cnt = prog->entry_cnt;
+ load_attr.entry_rec_size = prog->entry_cnt ? sizeof(*prog->entries) : 0;
load_attr.fd_array = obj->fd_array;
err = bpf_object__bind_arena(obj, prog, &load_attr);
if (err)
@@ -8815,28 +8842,16 @@ static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog
prog->name, log_buf);
}
- if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
- struct bpf_map *map;
- int i;
-
- for (i = 0; i < obj->nr_maps; i++) {
- map = &prog->obj->maps[i];
- if (map->libbpf_type != LIBBPF_MAP_RODATA)
- continue;
-
- if (bpf_prog_bind_map(ret, map->fd, NULL)) {
- pr_warn("prog '%s': failed to bind map '%s': %s\n",
- prog->name, map->real_name, errstr(errno));
- /* Don't fail hard if can't bind rodata. */
- }
- }
- }
+ bpf_object__bind_rodata(obj, prog, ret);
*prog_fd = ret;
ret = 0;
goto out;
}
+ if (prog->entry_cnt && !load_attr.log_true_size)
+ goto out;
+
if (log_level == 0) {
log_level = 1;
goto retry_load;
@@ -8856,6 +8871,13 @@ static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog
/* post-process verifier log to improve error descriptions */
fixup_verifier_log(prog, log_buf, log_buf_size);
+ /* the loads of the copies overwrite it */
+ if (prog->entry_cnt) {
+ pr_debug("prog '%s': -- BEGIN SHARED LOAD LOG --\n%s-- END SHARED LOAD LOG --\n",
+ prog->name, log_buf);
+ goto out;
+ }
+
pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
pr_perm_msg(ret);
@@ -9119,6 +9141,248 @@ static int bpf_program_record_relos(struct bpf_program *prog)
return 0;
}
+/* The struct_ops map that has the program. NULL if there is none, or more than one. */
+static struct bpf_map *find_prog_st_ops_map(struct bpf_object *obj, struct bpf_program *prog)
+{
+ struct bpf_map *map, *found = NULL;
+ int i, vlen;
+
+ bpf_object__for_each_map(map, obj) {
+ if (!bpf_map__is_struct_ops(map) || !map->autocreate)
+ continue;
+ vlen = btf_vlen(btf__type_by_id(obj->btf, map->st_ops->type_id));
+ for (i = 0; i < vlen; i++) {
+ if (map->st_ops->progs[i] != prog)
+ continue;
+ if (found)
+ return NULL;
+ found = map;
+ }
+ }
+ return found;
+}
+
+static bool prog_can_share(struct bpf_object *obj, struct bpf_program *prog)
+{
+ const struct bpf_sec_def *def = prog->sec_def;
+ LIBBPF_OPTS(bpf_prog_load_opts, opts);
+ struct bpf_insn *insn = prog->insns;
+ struct reloc_desc *relo;
+ struct bpf_map *map;
+ size_t i;
+
+ if (!prog->subprog_cnt || !prog->func_info || prog->prog_ifindex ||
+ prog->load_strategy != BPF_PROG_LOAD_STRATEGY_AUTO || prog->exception_cb_idx >= 0)
+ return false;
+ if (prog->type == BPF_PROG_TYPE_TRACING || prog->type == BPF_PROG_TYPE_LSM ||
+ prog->type == BPF_PROG_TYPE_EXT)
+ return false;
+ if (prog->type == BPF_PROG_TYPE_STRUCT_OPS && !find_prog_st_ops_map(obj, prog))
+ return false;
+ /* It would hold the maps of all. A map that holds it until it's freed would never go. */
+ if (prog->type == BPF_PROG_TYPE_XDP && (prog->expected_attach_type == BPF_XDP_CPUMAP ||
+ prog->expected_attach_type == BPF_XDP_DEVMAP))
+ return false;
+ bpf_object__for_each_map(map, obj)
+ if (map->excl_prog == prog || (map->def.map_flags & BPF_F_PRESERVE_ELEMS))
+ return false;
+ for (i = 0; i < prog->insns_cnt; i++, insn++)
+ if (insn->code == (BPF_JMP | BPF_CALL) && !insn->src_reg &&
+ (insn->imm == BPF_FUNC_tail_call || insn->imm == BPF_FUNC_override_return))
+ return false;
+ /* it has its own copy of the map with pointers to functions */
+ for (i = 0, relo = prog->reloc_desc; i < prog->nr_reloc && prog->has_callx; i++, relo++)
+ if (relo->type == RELO_DATA && obj->maps[relo->map_idx].func_ptr_cnt)
+ return false;
+ if (!def || !def->prog_prepare_load_fn)
+ return true;
+ /* Another callback can change anything. This one sets the attach type of USDT. */
+ return def->prog_prepare_load_fn == libbpf_prepare_prog_load &&
+ !libbpf_prepare_prog_load(prog, &opts, def->cookie);
+}
+
+static struct bpf_program *prog_subprog(struct bpf_program *prog, int idx)
+{
+ return find_prog_by_sec_insn(prog->obj, prog->obj->efile.text_shndx,
+ prog->subprogs[idx].sec_insn_off);
+}
+
+static bool prog_can_be_entry(struct bpf_program *first, struct bpf_program *prog)
+{
+ __u32 i, flags = prog->prog_flags ^ first->prog_flags;
+ struct bpf_object *obj = prog->obj;
+
+ if (prog->type != first->type || prog->log_level != first->log_level ||
+ (prog->log_level && prog->log_buf != first->log_buf))
+ return false;
+ if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
+ if ((flags & ~BPF_F_SLEEPABLE) ||
+ find_prog_st_ops_map(obj, prog) != find_prog_st_ops_map(obj, first))
+ return false;
+ } else if (flags || prog->expected_attach_type != first->expected_attach_type) {
+ return false;
+ }
+ for (i = 0; i < prog->subprog_cnt; i++)
+ if (prog_subprog(prog, i)->sub_insn_off)
+ return true;
+ return false;
+}
+
+/* Records of func_info and line_info start with insn_off */
+static int append_btf_ext_info(void **dst, __u32 *dst_cnt, const void *src, __u32 src_cnt,
+ __u32 rec_sz, __u32 from, __u32 to, __u32 off)
+{
+ __u32 i, cnt = 0, *rec;
+ void *tmp;
+
+ for (; src_cnt && *(__u32 *)src < from; src_cnt--)
+ src += rec_sz;
+ while (cnt < src_cnt && *(__u32 *)(src + cnt * rec_sz) < to)
+ cnt++;
+ if (!cnt)
+ return 0;
+ tmp = libbpf_reallocarray(*dst, *dst_cnt + cnt, rec_sz);
+ if (!tmp)
+ return -ENOMEM;
+ *dst = tmp;
+ rec = memcpy(tmp + *dst_cnt * rec_sz, src, cnt * rec_sz);
+ for (i = 0; i < cnt; i++, rec = (void *)rec + rec_sz)
+ *rec += off - from;
+ *dst_cnt += cnt;
+ return 0;
+}
+
+/* Copies function @func, insns [from, to) of @prog, to func->sub_insn_off of @img */
+static int append_shared_func(struct bpf_program *img, struct bpf_program *prog,
+ struct bpf_program *func, size_t from, size_t to)
+{
+ size_t i, off = func->sub_insn_off;
+ struct bpf_insn *insn = img->insns + off;
+ struct reloc_desc relo;
+ int idx, tgt, err;
+
+ memcpy(insn, prog->insns + from, (to - from) * sizeof(*insn));
+ for (i = from; i < to; i++, insn++) {
+ if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
+ continue;
+ tgt = i + insn->imm + 1;
+ idx = find_subprog_idx(prog, tgt);
+ if (idx < 0)
+ return -EINVAL;
+ tgt += prog_subprog(prog, idx)->sub_insn_off - prog->subprogs[idx].sub_insn_off;
+ insn->imm = tgt - (insn - img->insns) - 1;
+ }
+ err = save_subprog_offsets(img, func);
+ for (i = 0; i < prog->nr_reloc && !err; i++) {
+ relo = prog->reloc_desc[i];
+ if (relo.type != RELO_INSN_ARRAY || relo.insn_idx < from || relo.insn_idx >= to)
+ continue;
+ relo.insn_idx += off - from;
+ err = create_jt_map(prog->obj, img, &relo);
+ img->insns[relo.insn_idx].imm = err;
+ err = min(err, 0);
+ }
+ err = err ?: append_btf_ext_info(&img->func_info, &img->func_info_cnt,
+ prog->func_info, prog->func_info_cnt,
+ prog->func_info_rec_size, from, to, off);
+ return err ?: append_btf_ext_info(&img->line_info, &img->line_info_cnt,
+ prog->line_info, prog->line_info_cnt,
+ prog->line_info_rec_size, from, to, off);
+}
+
+/* Appends @prog and the subprogs that @img does not have yet */
+static int append_shared_prog(struct bpf_program *img, struct bpf_program *prog)
+{
+ size_t old_cnt = img->insns_cnt, cnt = old_cnt + prog->subprogs[0].sub_insn_off, end;
+ struct bpf_program *subprog;
+ struct bpf_insn *insns;
+ int i, err;
+
+ prog->sub_insn_off = old_cnt;
+ for (i = 0; i < prog->subprog_cnt; i++) {
+ subprog = prog_subprog(prog, i);
+ if (subprog->sub_insn_off)
+ continue;
+ subprog->sub_insn_off = cnt;
+ cnt += subprog->insns_cnt;
+ }
+ insns = libbpf_reallocarray(img->insns, cnt, sizeof(*insns));
+ if (!insns)
+ return -ENOMEM;
+ img->insns = insns;
+ img->insns_cnt = cnt;
+
+ err = append_shared_func(img, prog, prog, 0, prog->subprogs[0].sub_insn_off);
+ for (i = 0; i < prog->subprog_cnt && !err; i++) {
+ subprog = prog_subprog(prog, i);
+ end = prog->subprogs[i].sub_insn_off + subprog->insns_cnt;
+ if (subprog->sub_insn_off > old_cnt)
+ err = append_shared_func(img, prog, subprog, end - subprog->insns_cnt, end);
+ }
+ return err;
+}
+
+/*
+ * Load @first and the programs that call the same functions with one copy of them.
+ * When it fails they are loaded one by one, each of them has all its code.
+ */
+static void bpf_object_load_shared(struct bpf_object *obj, struct bpf_program *first)
+{
+ struct bpf_program img = *first, *prog, **progs = NULL;
+ struct bpf_prog_entry *entry;
+ size_t jt_cnt = obj->jumptable_map_cnt;
+ __u32 i, cnt;
+ int err;
+
+ if (!first->can_share)
+ return;
+ first->can_share = false;
+ img.insns = img.func_info = img.line_info = img.subprogs = NULL;
+ img.insns_cnt = img.func_info_cnt = img.line_info_cnt = img.subprog_cnt = 0;
+ for (i = 0; i < obj->nr_programs; i++)
+ obj->programs[i].sub_insn_off = 0;
+
+ progs = calloc(obj->nr_programs, sizeof(*progs));
+ img.entries = calloc(obj->nr_programs, sizeof(*img.entries));
+ err = progs && img.entries ? append_shared_prog(&img, first) : -ENOMEM;
+ do {
+ cnt = img.entry_cnt;
+ bpf_object__for_each_program(prog, obj) {
+ if (err || !prog->can_share || !prog_can_be_entry(first, prog))
+ continue;
+ prog->can_share = false;
+ err = append_shared_prog(&img, prog);
+ progs[img.entry_cnt] = prog;
+ entry = &img.entries[img.entry_cnt++];
+ entry->insn_off = prog->sub_insn_off;
+ entry->prog_type = prog->type;
+ entry->prog_flags = prog->prog_flags | (obj->token_fd ? BPF_F_TOKEN_FD : 0);
+ entry->expected_attach_type = prog->expected_attach_type;
+ entry->attach_btf_id = prog->attach_btf_id;
+ entry->attach_btf_obj_fd = prog->attach_btf_obj_fd;
+ libbpf_strlcpy(entry->prog_name, prog->name, sizeof(entry->prog_name));
+ }
+ } while (cnt != img.entry_cnt);
+
+ if (!err && cnt)
+ err = bpf_object_load_prog(obj, &img, img.insns, img.insns_cnt,
+ obj->license, obj->kern_version, &first->fd);
+ if (cnt)
+ pr_debug("prog '%s': load with %u entries: %s\n", first->name, cnt, errstr(err));
+ for (i = 0; i < cnt && !err; i++) {
+ progs[i]->fd = img.entries[i].prog_fd;
+ bpf_object__bind_rodata(obj, progs[i], progs[i]->fd);
+ }
+ while (obj->jumptable_map_cnt > jt_cnt)
+ close(obj->jumptable_maps[--obj->jumptable_map_cnt].fd);
+ free(progs);
+ free(img.entries);
+ free(img.insns);
+ free(img.func_info);
+ free(img.line_info);
+ free(img.subprogs);
+}
+
static int
bpf_object__load_progs(struct bpf_object *obj, int log_level)
{
@@ -9126,6 +9390,9 @@ bpf_object__load_progs(struct bpf_object *obj, int log_level)
size_t i;
int err;
+ bpf_object__for_each_program(prog, obj)
+ prog->can_share = !obj->gen_loader && !log_level && prog_can_share(obj, prog);
+
for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i];
if (prog_is_subprog(obj, prog))
@@ -9136,6 +9403,10 @@ bpf_object__load_progs(struct bpf_object *obj, int log_level)
}
prog->log_level |= log_level;
+ bpf_object_load_shared(obj, prog);
+ if (prog->fd >= 0)
+ continue;
+
if (obj->gen_loader)
bpf_program_record_relos(prog);
@@ -10767,6 +11038,8 @@ int bpf_program__set_insns(struct bpf_program *prog,
prog->insns = insns;
prog->insns_cnt = new_insn_cnt;
+ /* it's not known any more where they are */
+ prog->subprog_cnt = 0;
return 0;
}
diff --git a/tools/testing/selftests/bpf/prog_tests/call_rcu.c b/tools/testing/selftests/bpf/prog_tests/call_rcu.c
index e4d271d43d87..fbd967ae63ed 100644
--- a/tools/testing/selftests/bpf/prog_tests/call_rcu.c
+++ b/tools/testing/selftests/bpf/prog_tests/call_rcu.c
@@ -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),
diff --git a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
index 6e3733aef105..376f3a5709e4 100644
--- a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
+++ b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
@@ -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();
diff --git a/tools/testing/selftests/bpf/progs/pro_epilogue.c b/tools/testing/selftests/bpf/progs/pro_epilogue.c
index d97d6e07ef5c..6050f975623f 100644
--- a/tools/testing/selftests/bpf/progs/pro_epilogue.c
+++ b/tools/testing/selftests/bpf/progs/pro_epilogue.c
@@ -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)")
--
2.55.0
^ permalink raw reply related [flat|nested] 13+ messages in thread
* [PATCH v2 bpf-next 6/7] libbpf: Share subprogs in light skeletons
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
` (4 preceding siblings ...)
2026-12-02 21:27 ` [PATCH v2 bpf-next 5/7] libbpf, bpftool: Share subprogs between programs Alexei Starovoitov
@ 2026-12-02 21:27 ` Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 7/7] selftests/bpf: Test programs that share subprogs Alexei Starovoitov
6 siblings, 0 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
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(-)
diff --git a/tools/lib/bpf/bpf_gen_internal.h b/tools/lib/bpf/bpf_gen_internal.h
index 6fc3eb02f173..50e260b17651 100644
--- a/tools/lib/bpf/bpf_gen_internal.h
+++ b/tools/lib/bpf/bpf_gen_internal.h
@@ -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,
diff --git a/tools/lib/bpf/gen_loader.c b/tools/lib/bpf/gen_loader.c
index 749a86c43e7f..a0e399e0d1ab 100644
--- a/tools/lib/bpf/gen_loader.c
+++ b/tools/lib/bpf/gen_loader.c
@@ -995,10 +995,51 @@ static void info_blob_bswap(struct bpf_gen *gen, int func_info, int line_info,
bpf_core_relo_bswap(cr++);
}
+/* if (!(reg op 0)) goto label */
+static int emit_goto_unless(struct bpf_gen *gen, int op, int reg)
+{
+ emit(gen, BPF_JMP_IMM(op, reg, 0, 1));
+ emit(gen, BPF_JMP_A(0));
+ return gen->insn_cur - gen->insn_start;
+}
+
+static void emit_label(struct bpf_gen *gen, int from)
+{
+ struct bpf_insn *insn = gen->insn_start + from;
+ int off = (gen->insn_cur - gen->insn_start - from) / 8;
+
+ if (!gen->error)
+ insn[-1] = is_simm16(off) ? BPF_JMP_A(off) : BPF_JMP32_A(off);
+}
+
+/* The kernel wants them right after the attr */
+static int add_entries(struct bpf_gen *gen, struct bpf_prog_load_opts *load_attr)
+{
+ struct bpf_prog_entry *e, *src = load_attr->entries;
+ int i, off = add_data(gen, src, load_attr->entry_cnt * sizeof(*e));
+
+ for (i = 0, e = gen->data_start + off; i < load_attr->entry_cnt && !gen->error; i++, e++) {
+ e->insn_off = tgt_endian(e->insn_off);
+ e->prog_type = tgt_endian(e->prog_type);
+ e->prog_flags = tgt_endian(e->prog_flags);
+ e->expected_attach_type = tgt_endian(e->expected_attach_type);
+ e->attach_btf_id = tgt_endian(e->attach_btf_id);
+ e->prog_fd = 0;
+ }
+ return off;
+}
+
+#define entry_field(entries, i, field) \
+ (entries + i * sizeof(struct bpf_prog_entry) + offsetof(struct bpf_prog_entry, field))
+
+/*
+ * A load with entries is for the next program and for those with the indexes in
+ * prog_fd of the entries. It can fail. Their own loads are skipped when it does not.
+ */
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)
{
int func_info_tot_sz = load_attr->func_info_cnt *
load_attr->func_info_rec_size;
@@ -1008,20 +1049,29 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
sizeof(struct bpf_core_relo);
int prog_load_attr, license_off, insns_off, func_info, line_info, core_relos;
int attr_size = offsetofend(union bpf_attr, core_relo_rec_size);
+ int i, entries = 0, entry_cnt = load_attr->entry_cnt, out = 0;
union bpf_attr attr;
+ if (entry_cnt) {
+ attr_size = offsetofend(union bpf_attr, entry_rec_size);
+ } else if (gen->has_entries) {
+ emit2(gen, BPF_LD_IMM64_RAW_FULL(BPF_REG_0, BPF_PSEUDO_MAP_IDX_VALUE,
+ 0, 0, 0, blob_prog_fd_off(gen, gen->nr_progs)));
+ emit(gen, BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0));
+ out = emit_goto_unless(gen, BPF_JEQ, BPF_REG_0);
+ }
+
memset(&attr, 0, attr_size);
/* add license string to blob of bytes */
license_off = add_data(gen, license, strlen(license) + 1);
/* add insns to blob of bytes */
insns_off = add_data(gen, insns, insn_cnt * sizeof(struct bpf_insn));
- pr_debug("gen: prog_load: prog_idx %d type %u insn off %d insns_cnt %zu license off %d\n",
- prog_idx, prog_type, insns_off, insn_cnt, license_off);
+ pr_debug("gen: prog_load: prog_idx %u type %u insn off %d insns_cnt %zu license off %d\n",
+ gen->nr_progs, prog_type, insns_off, insn_cnt, license_off);
/* convert blob insns to target endianness */
if (gen->swapped_endian && !gen->error) {
struct bpf_insn *insn = gen->data_start + insns_off;
- int i;
for (i = 0; i < insn_cnt; i++, insn++)
bpf_insn_bswap(insn);
@@ -1061,7 +1111,14 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
info_blob_bswap(gen, func_info, line_info, core_relos, load_attr);
libbpf_strlcpy(attr.prog_name, prog_name, sizeof(attr.prog_name));
+ attr.entry_cnt = tgt_endian(load_attr->entry_cnt);
+ attr.entry_rec_size = tgt_endian(load_attr->entry_rec_size);
prog_load_attr = add_data(gen, &attr, attr_size);
+ if (entry_cnt) {
+ entries = add_entries(gen, load_attr);
+ attr_size = gen->data_cur - gen->data_start - prog_load_attr;
+ emit_rel_store(gen, attr_field(prog_load_attr, entries), entries);
+ }
pr_debug("gen: prog_load: attr: off %d size %d\n",
prog_load_attr, attr_size);
@@ -1097,6 +1154,9 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
/* attach_btf_id is a struct in the BTF of the object */
move_stack2blob(gen, attr_field(prog_load_attr, attach_btf_obj_fd), 4,
stack_off(btf_fd));
+ for (i = 0; i < entry_cnt && prog_type == BPF_PROG_TYPE_STRUCT_OPS; i++)
+ move_stack2blob(gen, entry_field(entries, i, attach_btf_obj_fd), 4,
+ stack_off(btf_fd));
if (gen->attach_kind) {
emit_find_attach_target(gen);
/* populate union bpf_attr with btf_id and btf_obj_fd found by helper */
@@ -1119,12 +1179,23 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
attr_field(prog_load_attr, attach_btf_obj_fd));
gen->attach_kind = 0;
}
- emit_check_err(gen);
+ if (entry_cnt)
+ out = emit_goto_unless(gen, BPF_JSGE, BPF_REG_7);
+ else
+ emit_check_err(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++;
+ for (i = 0; i < entry_cnt; i++)
+ move_blob2blob(gen, blob_prog_fd_off(gen, load_attr->entries[i].prog_fd), 4,
+ entry_field(entries, i, prog_fd));
+ if (out)
+ emit_label(gen, out);
+ if (entry_cnt)
+ gen->has_entries = true;
+ else
+ gen->nr_progs++;
}
/*
diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index 54bebd9215c3..1ab2d2817049 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -8797,8 +8797,7 @@ static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog
if (obj->gen_loader) {
bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
- license, insns, insns_cnt, &load_attr,
- prog - obj->programs);
+ license, insns, insns_cnt, &load_attr);
*prog_fd = -1;
return 0;
}
@@ -9141,6 +9140,19 @@ static int bpf_program_record_relos(struct bpf_program *prog)
return 0;
}
+/* The loader keeps the fds of the programs in the order of bpf_object__load_progs() */
+static int bpf_program_gen_idx(const struct bpf_program *prog)
+{
+ const struct bpf_program *p;
+ int idx = 0;
+
+ for (p = prog->obj->programs; p != prog; p++)
+ if (!prog_is_subprog(prog->obj, p) &&
+ p->load_strategy == BPF_PROG_LOAD_STRATEGY_AUTO)
+ idx++;
+ return idx;
+}
+
/* The struct_ops map that has the program. NULL if there is none, or more than one. */
static struct bpf_map *find_prog_st_ops_map(struct bpf_object *obj, struct bpf_program *prog)
{
@@ -9275,9 +9287,12 @@ static int append_shared_func(struct bpf_program *img, struct bpf_program *prog,
err = save_subprog_offsets(img, func);
for (i = 0; i < prog->nr_reloc && !err; i++) {
relo = prog->reloc_desc[i];
- if (relo.type != RELO_INSN_ARRAY || relo.insn_idx < from || relo.insn_idx >= to)
+ if (relo.insn_idx < from || relo.insn_idx >= to)
continue;
relo.insn_idx += off - from;
+ img->reloc_desc[img->nr_reloc++] = relo;
+ if (relo.type != RELO_INSN_ARRAY)
+ continue;
err = create_jt_map(prog->obj, img, &relo);
img->insns[relo.insn_idx].imm = err;
err = min(err, 0);
@@ -9295,6 +9310,7 @@ static int append_shared_prog(struct bpf_program *img, struct bpf_program *prog)
{
size_t old_cnt = img->insns_cnt, cnt = old_cnt + prog->subprogs[0].sub_insn_off, end;
struct bpf_program *subprog;
+ struct reloc_desc *relos;
struct bpf_insn *insns;
int i, err;
@@ -9311,6 +9327,11 @@ static int append_shared_prog(struct bpf_program *img, struct bpf_program *prog)
return -ENOMEM;
img->insns = insns;
img->insns_cnt = cnt;
+ relos = libbpf_reallocarray(img->reloc_desc, img->nr_reloc + prog->nr_reloc,
+ sizeof(*relos));
+ if (!relos)
+ return -ENOMEM;
+ img->reloc_desc = relos;
err = append_shared_func(img, prog, prog, 0, prog->subprogs[0].sub_insn_off);
for (i = 0; i < prog->subprog_cnt && !err; i++) {
@@ -9339,6 +9360,8 @@ static void bpf_object_load_shared(struct bpf_object *obj, struct bpf_program *f
first->can_share = false;
img.insns = img.func_info = img.line_info = img.subprogs = NULL;
img.insns_cnt = img.func_info_cnt = img.line_info_cnt = img.subprog_cnt = 0;
+ img.reloc_desc = NULL;
+ img.nr_reloc = 0;
for (i = 0; i < obj->nr_programs; i++)
obj->programs[i].sub_insn_off = 0;
@@ -9360,16 +9383,19 @@ static void bpf_object_load_shared(struct bpf_object *obj, struct bpf_program *f
entry->expected_attach_type = prog->expected_attach_type;
entry->attach_btf_id = prog->attach_btf_id;
entry->attach_btf_obj_fd = prog->attach_btf_obj_fd;
+ entry->prog_fd = obj->gen_loader ? bpf_program_gen_idx(prog) : 0;
libbpf_strlcpy(entry->prog_name, prog->name, sizeof(entry->prog_name));
}
} while (cnt != img.entry_cnt);
+ if (!err && cnt && obj->gen_loader)
+ bpf_program_record_relos(&img);
if (!err && cnt)
err = bpf_object_load_prog(obj, &img, img.insns, img.insns_cnt,
obj->license, obj->kern_version, &first->fd);
if (cnt)
pr_debug("prog '%s': load with %u entries: %s\n", first->name, cnt, errstr(err));
- for (i = 0; i < cnt && !err; i++) {
+ for (i = 0; i < cnt && !err && !obj->gen_loader; i++) {
progs[i]->fd = img.entries[i].prog_fd;
bpf_object__bind_rodata(obj, progs[i], progs[i]->fd);
}
@@ -9381,6 +9407,7 @@ static void bpf_object_load_shared(struct bpf_object *obj, struct bpf_program *f
free(img.func_info);
free(img.line_info);
free(img.subprogs);
+ free(img.reloc_desc);
}
static int
@@ -9391,7 +9418,7 @@ bpf_object__load_progs(struct bpf_object *obj, int log_level)
int err;
bpf_object__for_each_program(prog, obj)
- prog->can_share = !obj->gen_loader && !log_level && prog_can_share(obj, prog);
+ prog->can_share = !log_level && prog_can_share(obj, prog);
for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i];
@@ -10099,19 +10126,6 @@ static int bpf_map_prepare_vdata(const struct bpf_map *map)
return 0;
}
-/* The loader keeps the fds of the programs in the order of bpf_object__load_progs() */
-static int bpf_program_gen_idx(const struct bpf_program *prog)
-{
- const struct bpf_program *p;
- int idx = 0;
-
- for (p = prog->obj->programs; p != prog; p++)
- if (!prog_is_subprog(prog->obj, p) &&
- p->load_strategy == BPF_PROG_LOAD_STRATEGY_AUTO)
- idx++;
- return idx;
-}
-
static int bpf_map_gen_struct_ops_update(struct bpf_map *map)
{
struct bpf_struct_ops *st_ops = map->st_ops;
--
2.55.0
^ permalink raw reply related [flat|nested] 13+ messages in thread
* [PATCH v2 bpf-next 7/7] selftests/bpf: Test programs that share subprogs
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
` (5 preceding siblings ...)
2026-12-02 21:27 ` [PATCH v2 bpf-next 6/7] libbpf: Share subprogs in light skeletons Alexei Starovoitov
@ 2026-12-02 21:27 ` Alexei Starovoitov
6 siblings, 0 replies; 13+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 21:27 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
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.
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
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
diff --git a/tools/testing/selftests/bpf/Makefile.skel b/tools/testing/selftests/bpf/Makefile.skel
index 334342928d01..582a52a34a6f 100644
--- a/tools/testing/selftests/bpf/Makefile.skel
+++ b/tools/testing/selftests/bpf/Makefile.skel
@@ -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 \
diff --git a/tools/testing/selftests/bpf/prog_tests/share_subprogs.c b/tools/testing/selftests/bpf/prog_tests/share_subprogs.c
new file mode 100644
index 000000000000..d3382d40a118
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/share_subprogs.c
@@ -0,0 +1,190 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <network_helpers.h>
+#include <linux/pkt_cls.h>
+#include "share_subprogs.skel.h"
+#include "share_subprogs_arena.skel.h"
+#include "share_subprogs_signed.lskel.h"
+
+static int run(int fd)
+{
+ LIBBPF_OPTS(bpf_test_run_opts, opts, .data_in = &pkt_v4, .data_size_in = sizeof(pkt_v4));
+
+ return bpf_prog_test_run_opts(fd, &opts) ?: opts.retval;
+}
+
+static __u32 owner_of(int fd)
+{
+ struct bpf_prog_info info = {};
+ __u32 len = sizeof(info);
+
+ ASSERT_OK(bpf_prog_get_info_by_fd(fd, &info, &len), "info");
+ return info.owner_prog_id;
+}
+
+static const char *stdout_of(int fd)
+{
+ static char buf[16];
+
+ memset(buf, 0, sizeof(buf));
+ bpf_prog_stream_read(fd, BPF_STREAM_STDOUT, buf, sizeof(buf) - 1, NULL);
+ return buf;
+}
+
+static void test_calls(struct share_subprogs *skel)
+{
+ int first = bpf_program__fd(skel->progs.first);
+ int second = bpf_program__fd(skel->progs.second);
+ struct share_subprogs *tracer;
+ int owner;
+
+ ASSERT_EQ(owner_of(first), owner_of(second), "one owner");
+ owner = bpf_prog_get_fd_by_id(owner_of(first));
+ if (ASSERT_OK_FD(owner, "owner")) {
+ ASSERT_EQ(run(owner), -EINVAL, "run of the owner");
+ close(owner);
+ }
+
+ tracer = share_subprogs__open();
+ if (!ASSERT_OK_PTR(tracer, "open"))
+ return;
+ bpf_program__set_autoload(tracer->progs.tracer, true);
+ bpf_program__set_attach_target(tracer->progs.tracer, second, "add_up");
+ if (!ASSERT_OK(share_subprogs__load(tracer), "load"))
+ goto out;
+ tracer->links.tracer = bpf_program__attach(tracer->progs.tracer);
+ ASSERT_EQ(run(first), 4, "first");
+ ASSERT_EQ(run(second), 32, "second");
+ ASSERT_EQ(run(bpf_program__fd(skel->progs.third)), 5, "third");
+ ASSERT_EQ(tracer->bss->traced, 2, "traced");
+ ASSERT_STREQ(stdout_of(first), "1", "stream of first");
+ ASSERT_STREQ(stdout_of(second), "10", "stream of second");
+out:
+ share_subprogs__destroy(tracer);
+}
+
+static void test_cancel(struct share_subprogs *skel)
+{
+ int refs = run(bpf_program__fd(skel->progs.refs));
+
+ ASSERT_NEQ(owner_of(bpf_program__fd(skel->progs.keeps)), 0, "shared");
+ ASSERT_EQ(run(bpf_program__fd(skel->progs.keeps)), TC_ACT_SHOT, "keeps");
+ ASSERT_EQ(run(bpf_program__fd(skel->progs.gives)), TC_ACT_SHOT, "gives");
+ ASSERT_EQ(run(bpf_program__fd(skel->progs.refs)), refs, "refs");
+}
+
+static void test_arena(void)
+{
+ struct share_subprogs_arena *skel = share_subprogs_arena__open_and_load();
+
+ if (ASSERT_OK_PTR(skel, "load"))
+ ASSERT_EQ(owner_of(bpf_program__fd(skel->progs.arena_1)), 0, "copies");
+ share_subprogs_arena__destroy(skel);
+}
+
+static void test_value(void)
+{
+ struct share_subprogs *skel = share_subprogs__open();
+ struct bpf_insn *insns = NULL;
+ __u32 cnt;
+ int fd;
+
+ if (!ASSERT_OK_PTR(skel, "open"))
+ return;
+ bpf_map__set_autocreate(skel->maps.value, true);
+ bpf_map__set_autocreate(skel->maps.thrown, true);
+ if (!ASSERT_OK(share_subprogs__load(skel), "load"))
+ goto out;
+ ASSERT_EQ(owner_of(bpf_program__fd(skel->progs.thrown_1)), 0, "copies");
+ fd = bpf_program__fd(skel->progs.value_2);
+ ASSERT_NEQ(owner_of(fd), 0, "shared");
+ /* the landing pad is 'r0 = 1; exit' */
+ if (ASSERT_OK(get_xlated_program(fd, &insns, &cnt), "xlated"))
+ ASSERT_EQ(insns[cnt - 2].imm, 1, "value");
+ free(insns);
+out:
+ share_subprogs__destroy(skel);
+}
+
+static int run_tp(int fd)
+{
+ LIBBPF_OPTS(bpf_test_run_opts, opts);
+
+ return bpf_prog_test_run_opts(fd, &opts) ?: opts.retval;
+}
+
+static void test_signed(void)
+{
+ struct share_subprogs_signed_lskel *skel = share_subprogs_signed_lskel__open();
+
+ if (!ASSERT_OK_PTR(skel, "open"))
+ return;
+ skel->keyring_id = KEY_SPEC_SESSION_KEYRING;
+ if (!ASSERT_OK(share_subprogs_signed_lskel__load(skel), "load"))
+ goto out;
+ ASSERT_NEQ(owner_of(skel->progs.test_2.prog_fd), 0, "struct_ops");
+ ASSERT_GT(share_subprogs_signed_lskel__ops__attach(skel), 0, "attach");
+ ASSERT_EQ(skel->bss->sum, 18, "sum");
+ ASSERT_NEQ(owner_of(skel->progs.tp_2.prog_fd), 0, "raw_tp");
+ ASSERT_EQ(run_tp(skel->progs.tp_2.prog_fd), run_tp(skel->progs.tp_alone.prog_fd), "count");
+ ASSERT_EQ(owner_of(skel->progs.invalid_together.prog_fd), 0, "copies");
+out:
+ share_subprogs_signed_lskel__destroy(skel);
+}
+
+static void test_pair(const char *name)
+{
+ struct share_subprogs *skel = share_subprogs__open();
+
+ if (!ASSERT_OK_PTR(skel, "open"))
+ return;
+ bpf_map__set_autocreate(bpf_object__find_map_by_name(skel->obj, name), true);
+ ASSERT_ERR(share_subprogs__load(skel), "load");
+ share_subprogs__destroy(skel);
+}
+
+void serial_test_share_subprogs(void)
+{
+ static const char * const pairs[] = {
+ "helper", "kfunc", "context", "cookie", "sleep", "rcu",
+ };
+ struct share_subprogs *skel;
+ int i, fd;
+
+ skel = share_subprogs__open_and_load();
+ if (skel ? skel->kconfig->CONFIG_UNWINDER_FRAME_POINTER : errno == ENOTSUPP) {
+ share_subprogs__destroy(skel);
+ test__skip();
+ return;
+ }
+ if (!ASSERT_OK_PTR(skel, "load"))
+ return;
+ if (test__start_subtest("calls"))
+ test_calls(skel);
+ if (test__start_subtest("cancel"))
+ test_cancel(skel);
+ if (test__start_subtest("may_goto"))
+ ASSERT_EQ(owner_of(bpf_program__fd(skel->progs.may_goto_1)), 0, "copies");
+ if (test__start_subtest("global"))
+ ASSERT_EQ(owner_of(bpf_program__fd(skel->progs.global_1)), 0, "copies");
+ if (test__start_subtest("stuck"))
+ ASSERT_EQ(owner_of(bpf_program__fd(skel->progs.stuck_1)), 0, "copies");
+ if (test__start_subtest("arena"))
+ test_arena();
+ if (test__start_subtest("value"))
+ test_value();
+
+ fd = dup(bpf_program__fd(skel->progs.second));
+ share_subprogs__destroy(skel);
+ if (test__start_subtest("last_entry")) {
+ kern_sync_rcu();
+ ASSERT_EQ(run(fd), 32, "run");
+ }
+ close(fd);
+
+ if (test__start_subtest("signed"))
+ test_signed();
+ for (i = 0; i < ARRAY_SIZE(pairs); i++)
+ if (test__start_subtest(pairs[i]))
+ test_pair(pairs[i]);
+}
diff --git a/tools/testing/selftests/bpf/progs/share_subprogs.c b/tools/testing/selftests/bpf/progs/share_subprogs.c
new file mode 100644
index 000000000000..7382b9499370
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/share_subprogs.c
@@ -0,0 +1,245 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "bpf_tracing_net.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_experimental.h"
+#include "../test_kmods/bpf_testmod.h"
+
+char _license[] SEC("license") = "GPL";
+
+extern bool CONFIG_UNWINDER_FRAME_POINTER __kconfig __weak;
+int zero, traced;
+
+static __noinline int inc(int x)
+{
+ return x + 1;
+}
+
+__noinline int add_up(int x, int y)
+{
+ bpf_stream_printk(BPF_STDOUT, "%d", x);
+ return inc(x) + y;
+}
+
+__noinline int throws(int x)
+{
+ if (x)
+ bpf_throw(5);
+ return 0;
+}
+
+SEC("tc")
+int first(struct __sk_buff *skb)
+{
+ return add_up(1, 2);
+}
+
+SEC("tc")
+int second(struct __sk_buff *skb)
+{
+ return inc(zero) + add_up(10, 20);
+}
+
+SEC("tc")
+int third(struct __sk_buff *skb)
+{
+ return throws(inc(CONFIG_UNWINDER_FRAME_POINTER));
+}
+
+#define TC(name, expr) SEC("tc") int name(struct __sk_buff *skb) { return expr; }
+#define DOWN(name, to) \
+ static __noinline __u64 name(__u64 n) \
+ { \
+ while (n > to) { \
+ n--; \
+ barrier_var(n); \
+ } \
+ return n; \
+ }
+
+__u64 big = -1, buf[8];
+
+/* may_goto_1 is checked twice for spin(), the second time without may_goto in down1() */
+DOWN(down1, 1)
+
+__noinline int spin(void)
+{
+ while (*(volatile __u64 *)&big == 1)
+ ;
+ return 0;
+}
+
+TC(may_goto_1, spin() + down1(skb->len & 0xffff))
+TC(may_goto_2, down1(big))
+
+/* The call in global_1 has no landing pad */
+DOWN(down2, 2)
+
+__noinline int bounded(int n)
+{
+ return down2(n & 0xffff);
+}
+
+TC(global_1, bounded(skb->len))
+TC(global_2, down2(big))
+
+/* may_goto jumps below a comparator that cannot be cancelled. It's out of bounds for stuck_1. */
+struct tree_node {
+ struct bpf_rb_node rb;
+ struct task_struct __kptr *task;
+};
+
+struct bpf_spin_lock lock SEC(".data.tree") __hidden;
+struct bpf_rb_root root SEC(".data.tree") __hidden __contains(tree_node, rb);
+
+static __noinline __u64 idx(void)
+{
+ while (can_loop)
+ if (*(volatile __u64 *)&big == 1)
+ return 1;
+ return 1 << 24;
+}
+
+static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+ return idx() < zero;
+}
+
+TC(stuck_1, buf[idx()])
+
+SEC("tc")
+int stuck_2(struct __sk_buff *skb)
+{
+ struct tree_node *n = bpf_obj_new(typeof(*n));
+
+ if (!n)
+ return 0;
+ bpf_spin_lock(&lock);
+ bpf_rbtree_add(&root, &n->rb, less);
+ bpf_spin_unlock(&lock);
+ return 0;
+}
+
+/* One landing pad in put() is right for both */
+static __noinline int put(struct task_struct *task, int release)
+{
+ struct task_struct *own = release ? NULL : bpf_task_acquire(task);
+
+ while (*(volatile __u64 *)&big)
+ ;
+ if (own)
+ bpf_task_release(own);
+ if (release)
+ bpf_task_release(task);
+ return 0;
+}
+
+SEC("tc")
+int keeps(struct __sk_buff *skb)
+{
+ struct task_struct *task = bpf_task_from_pid(1);
+
+ if (!task)
+ return 0;
+ put(task, 0);
+ bpf_task_release(task);
+ return 0;
+}
+
+SEC("tc")
+int gives(struct __sk_buff *skb)
+{
+ struct task_struct *task = bpf_task_from_pid(1);
+
+ return task ? put(task, 1) : 0;
+}
+
+SEC("tc")
+int refs(struct __sk_buff *skb)
+{
+ struct task_struct *task = bpf_task_from_pid(1);
+ int cnt;
+
+ if (!task)
+ return 0;
+ cnt = task->rcu_users.refs.counter;
+ bpf_task_release(task);
+ return cnt;
+}
+
+SEC("?fentry")
+int BPF_PROG(tracer)
+{
+ traced++;
+ return 0;
+}
+
+/* The shared function is valid for one member, and not for the other one */
+#define PAIR(test, s, ops, member1, member2, func, arg) \
+ SEC("?struct_ops" s) long test##_1(__u64 *ctx) \
+ { \
+ func(arg); \
+ return 0; \
+ } \
+ SEC("?struct_ops") long test##_2(__u64 *ctx) \
+ { \
+ func(arg); \
+ return 0; \
+ } \
+ SEC("?.struct_ops") struct ops test = { \
+ .member1 = (void *)test##_1, \
+ .member2 = (void *)test##_2, \
+ }
+
+__noinline int set_opt(struct sock *sk __arg_trusted)
+{
+ int one = 1;
+
+ return bpf_setsockopt(sk, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
+}
+
+void bpf_qdisc_watchdog_schedule(struct Qdisc *sch, u64 expire, u64 delta_ns) __ksym;
+
+__noinline int watchdog(struct Qdisc *sch __arg_trusted)
+{
+ bpf_qdisc_watchdog_schedule(sch, 0, 0);
+ return 0;
+}
+
+__noinline int pid(__u64 *ctx __arg_ctx)
+{
+ struct task_struct *task = (void *)ctx[1];
+
+ return traced = task ? task->pid : 0;
+}
+
+static __noinline int sleeps(int *p)
+{
+ return bpf_copy_from_user(p, sizeof(*p), NULL);
+}
+
+struct {
+ __uint(type, BPF_MAP_TYPE_DEVMAP);
+ __uint(max_entries, 1);
+ __type(key, int);
+ __type(value, int);
+} devmap SEC(".maps");
+
+static __noinline int lookup(int *key)
+{
+ bpf_rcu_read_lock();
+ traced = !bpf_map_lookup_elem(&devmap, key);
+ bpf_rcu_read_unlock();
+ return 0;
+}
+
+PAIR(sleep, ".s", bpf_testmod_ops3, test_2, test_1, sleeps, &traced);
+PAIR(rcu, ".s", bpf_testmod_ops3, test_2, test_1, lookup, &zero);
+PAIR(helper, "", tcp_congestion_ops, init, release, set_opt, (void *)ctx[0]);
+PAIR(kfunc, "", Qdisc_ops, dequeue, reset, watchdog, (void *)ctx[0]);
+PAIR(context, "", bpf_testmod_ops, test_maybe_null, test_2, pid, ctx);
+PAIR(cookie, "", Qdisc_ops, reset, dequeue, throws, zero);
+
+/* They return 2 and 1 when they are cancelled. What throws() leaves with is passed on. */
+PAIR(value, "", tcp_congestion_ops, ssthresh, undo_cwnd, down1, big);
+PAIR(thrown, "", tcp_congestion_ops, ssthresh, undo_cwnd, throws, zero);
diff --git a/tools/testing/selftests/bpf/progs/share_subprogs_arena.c b/tools/testing/selftests/bpf/progs/share_subprogs_arena.c
new file mode 100644
index 000000000000..88917e438dde
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/share_subprogs_arena.c
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_experimental.h"
+
+char _license[] SEC("license") = "GPL";
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARENA);
+ __uint(map_flags, BPF_F_MMAPABLE);
+ __uint(max_entries, 1);
+} arena SEC(".maps");
+
+/* Only arena_2 has something to release when the load faults */
+static __noinline int peek(int locks)
+{
+ int *p = NULL, v;
+
+ asm volatile ("" :: "r"(&arena));
+ bpf_addr_space_cast(p, 0, 1);
+ if (locks)
+ bpf_rcu_read_lock();
+ barrier_var(locks);
+ v = *(volatile int *)p;
+ barrier_var(locks);
+ if (locks)
+ bpf_rcu_read_unlock();
+ return v;
+}
+
+SEC("tc")
+int arena_1(struct __sk_buff *skb)
+{
+ return peek(0);
+}
+
+SEC("tc")
+int arena_2(struct __sk_buff *skb)
+{
+ return peek(1);
+}
diff --git a/tools/testing/selftests/bpf/progs/share_subprogs_signed.c b/tools/testing/selftests/bpf/progs/share_subprogs_signed.c
new file mode 100644
index 000000000000..caf630c57cff
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/share_subprogs_signed.c
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_experimental.h"
+#include "../test_kmods/bpf_testmod.h"
+
+char _license[] SEC("license") = "GPL";
+
+int sum;
+
+static __noinline int add_up(int x)
+{
+ bpf_rcu_read_lock();
+ sum += x;
+ bpf_rcu_read_unlock();
+ return 0;
+}
+
+SEC("struct_ops")
+int BPF_PROG(test_1)
+{
+ return add_up(1);
+}
+
+SEC("struct_ops")
+void BPF_PROG(test_2, int a, int b)
+{
+ add_up(a + b);
+}
+
+/* The kernel has the members in another order */
+struct bpf_testmod_ops___local {
+ int data;
+ void (*test_2)(int a, int b);
+ int (*test_1)(void);
+};
+
+SEC(".struct_ops.link")
+struct bpf_testmod_ops___local ops = {
+ .data = 13,
+ .test_2 = (void *)test_2,
+ .test_1 = (void *)test_1,
+};
+
+/* A program that asks for the cpu runs with preemption disabled */
+#define preempt_count() (bpf_get_smp_processor_id(), get_preempt_count() & 0xff)
+
+static __noinline int count(void)
+{
+ return preempt_count();
+}
+
+SEC("raw_tp/sys_enter")
+int tp_1(void *ctx)
+{
+ return count();
+}
+
+SEC("raw_tp/sys_enter")
+int tp_2(void *ctx)
+{
+ return count();
+}
+
+SEC("raw_tp/sys_enter")
+int tp_alone(void *ctx)
+{
+ return preempt_count();
+}
+
+static __noinline __u32 tstamp_type(struct __sk_buff *skb)
+{
+ return skb->tstamp_type;
+}
+
+SEC("tc")
+int valid_alone(struct __sk_buff *skb)
+{
+ return tstamp_type(skb);
+}
+
+SEC("tc")
+int invalid_together(struct __sk_buff *skb)
+{
+ return tstamp_type(skb);
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 13+ messages in thread
* Re: [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns
2026-12-02 21:27 ` [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns Alexei Starovoitov
@ 2026-12-02 22:15 ` sashiko-bot
2026-12-02 22:35 ` bot+bpf-ci
1 sibling, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-12-02 22:15 UTC (permalink / raw)
To: Alexei Starovoitov, bpf
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 <ast@kernel.org>
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.
> diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
> index 0a2923505308b..725de358f5ca8 100644
> --- a/kernel/bpf/precision.c
> +++ b/kernel/bpf/precision.c
> @@ -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 bot+bpf-ci@kernel.org 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.
> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> index b753d6c7a00b5..2c6dc44f4e74e 100644
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c
[ ... ]
> @@ -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;
> + 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.
[1] https://lore.kernel.org/r/a0639de449fd4f8ca45a82936271218bb746b417c8aeeefa92cdd3258174303f@mail.kernel.org
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261202212743.647706-1-alexei.starovoitov@gmail.com?part=2
^ permalink raw reply [flat|nested] 13+ messages in thread
* Re: [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load
2026-12-02 21:27 ` [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load Alexei Starovoitov
@ 2026-12-02 22:20 ` bot+bpf-ci
0 siblings, 0 replies; 13+ messages in thread
From: bot+bpf-ci @ 2026-12-02 22:20 UTC (permalink / raw)
To: alexei.starovoitov, bpf
Cc: daniel, andrii, eddyz87, memxor, ast, andrii, daniel, martin.lau,
eddyz87, yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 1728 bytes --]
> 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.
> diff --git a/include/linux/bpf.h b/include/linux/bpf.h
> --- a/include/linux/bpf.h
> +++ b/include/linux/bpf.h
[ ... ]
> @@ -1913,25 +1914,54 @@ struct bpf_prog_aux {
[ ... ]
> + 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 */
[ ... ]
> + /*
> + * 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
^ permalink raw reply [flat|nested] 13+ messages in thread
* Re: [PATCH v2 bpf-next 4/7] bpf: Take entries at BPF_PROG_LOAD
2026-12-02 21:27 ` [PATCH v2 bpf-next 4/7] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
@ 2026-12-02 22:20 ` bot+bpf-ci
0 siblings, 0 replies; 13+ messages in thread
From: bot+bpf-ci @ 2026-12-02 22:20 UTC (permalink / raw)
To: alexei.starovoitov, bpf
Cc: daniel, andrii, eddyz87, memxor, ast, andrii, daniel, martin.lau,
eddyz87, yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 1137 bytes --]
> 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?
> diff --git a/include/linux/bpf.h b/include/linux/bpf.h
> --- a/include/linux/bpf.h
> +++ b/include/linux/bpf.h
[ ... ]
> @@ -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
^ permalink raw reply [flat|nested] 13+ messages in thread
* Re: [PATCH v2 bpf-next 3/7] bpf: Generate landing pads for many main programs
2026-12-02 21:27 ` [PATCH v2 bpf-next 3/7] bpf: Generate landing pads for many main programs Alexei Starovoitov
@ 2026-12-02 22:21 ` bot+bpf-ci
0 siblings, 0 replies; 13+ messages in thread
From: bot+bpf-ci @ 2026-12-02 22:21 UTC (permalink / raw)
To: alexei.starovoitov, bpf
Cc: daniel, andrii, eddyz87, memxor, ast, andrii, daniel, martin.lau,
eddyz87, yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 2163 bytes --]
> 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.
> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c
[ ... ]
> @@ -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;
> }
[ ... ]
> @@ -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
^ permalink raw reply [flat|nested] 13+ messages in thread
* Re: [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns
2026-12-02 21:27 ` [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns Alexei Starovoitov
2026-12-02 22:15 ` sashiko-bot
@ 2026-12-02 22:35 ` bot+bpf-ci
1 sibling, 0 replies; 13+ messages in thread
From: bot+bpf-ci @ 2026-12-02 22:35 UTC (permalink / raw)
To: alexei.starovoitov, bpf
Cc: daniel, andrii, eddyz87, memxor, ast, andrii, daniel, martin.lau,
eddyz87, yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 2846 bytes --]
> 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.
> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c
[ ... ]
> @@ -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
^ permalink raw reply [flat|nested] 13+ messages in thread
end of thread, other threads:[~2026-12-02 22:35 UTC | newest]
Thread overview: 13+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-02 21:27 [PATCH v2 bpf-next 0/7] bpf: Share subprogs between programs Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 1/7] bpf: Prepare for many main programs in one load Alexei Starovoitov
2026-12-02 22:20 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 2/7] bpf: Check many main programs in one set of insns Alexei Starovoitov
2026-12-02 22:15 ` sashiko-bot
2026-12-02 22:35 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 3/7] bpf: Generate landing pads for many main programs Alexei Starovoitov
2026-12-02 22:21 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 4/7] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
2026-12-02 22:20 ` bot+bpf-ci
2026-12-02 21:27 ` [PATCH v2 bpf-next 5/7] libbpf, bpftool: Share subprogs between programs Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 6/7] libbpf: Share subprogs in light skeletons Alexei Starovoitov
2026-12-02 21:27 ` [PATCH v2 bpf-next 7/7] selftests/bpf: Test programs that share subprogs Alexei Starovoitov
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.