* [PATCH bpf-next 0/6] bpf: Share subprogs between programs
@ 2026-12-02 0:16 Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 1/6] bpf: Prepare for many main programs in one load Alexei Starovoitov
` (5 more replies)
0 siblings, 6 replies; 11+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 0:16 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 JITs that support bpf_throw(). 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.15 s
one copy 33118 31070 143034 bytes 0.08 s
sched_ext schedulers:
x86-64 code, bytes verified insns
progs copies shared copies shared
scx_qmap 26 106139 48249 36855 36855
scx_lavd 36 115018 66090 51788 54599
scx_rusty 14 40451 24870 12707 12707
scx_chaos 24 74870 55777 16325 16368
scx_p2dq 23 55318 47068 12543 12543
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 %
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Alexei Starovoitov (6):
bpf: Prepare for many main programs in one load
bpf: Check many main programs in one set of insns
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 | 91 +++-
include/linux/bpf.h | 87 ++--
include/linux/bpf_verifier.h | 40 +-
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 | 113 +++--
kernel/bpf/flow.c | 54 ++-
kernel/bpf/precision.c | 2 +
kernel/bpf/stream.c | 33 +-
kernel/bpf/syscall.c | 302 ++++++++++--
kernel/bpf/verifier.c | 435 ++++++++++++++++--
kernel/events/core.c | 4 +
kernel/sched/ext/ext.c | 2 +-
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 | 341 ++++++++++++--
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 | 134 ++++++
.../selftests/bpf/prog_tests/unwind_attach.c | 4 +-
.../selftests/bpf/progs/pro_epilogue.c | 4 +-
.../selftests/bpf/progs/share_subprogs.c | 143 ++++++
.../bpf/progs/share_subprogs_signed.c | 87 ++++
36 files changed, 2023 insertions(+), 268 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_signed.c
base-commit: ac69c149f965b55e85798e516cb66e2bceb63f00
--
2.55.0
^ permalink raw reply [flat|nested] 11+ messages in thread
* [PATCH bpf-next 1/6] bpf: Prepare for many main programs in one load
2026-12-02 0:16 [PATCH bpf-next 0/6] bpf: Share subprogs between programs Alexei Starovoitov
@ 2026-12-02 0:16 ` Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns Alexei Starovoitov
` (4 subsequent siblings)
5 siblings, 0 replies; 11+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 0:16 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 | 65 ++++++++++++----------
include/linux/bpf_verifier.h | 22 +++++++-
kernel/bpf/btf.c | 10 ++--
kernel/bpf/failing_path.c | 2 +-
kernel/bpf/fixups.c | 104 ++++++++++++++++++++++-------------
kernel/bpf/syscall.c | 42 +++++++++-----
kernel/bpf/verifier.c | 52 +++++++++++-------
7 files changed, 192 insertions(+), 105 deletions(-)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 0fef8e2f43cc..a4e3ba8bf582 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -1908,25 +1908,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 real_func_cnt; /* includes hidden progs, only used for JIT and freeing progs */
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;
@@ -1937,25 +1966,17 @@ 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 exception_cb;
bool exception_boundary;
- bool jits_use_priv_stack;
- bool priv_stack_requested;
- bool changes_pkt_data;
bool has_prologue;
- bool might_sleep;
bool might_throw;
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 {
@@ -1966,18 +1987,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 */
@@ -1992,7 +2003,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;
@@ -2001,7 +2011,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];
u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64);
u16 stack_arg_sp_adjust;
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 50b3f8ab9720..c0a5cf642caf 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -1169,6 +1169,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 */
@@ -1206,7 +1209,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;
@@ -1234,6 +1237,11 @@ struct bpf_subprog_info {
u16 max_out_stack_arg_cnt;
};
+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)
@@ -1378,6 +1386,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 */
@@ -2206,6 +2216,16 @@ static inline int bpf_head_guard_target(const struct bpf_verifier_env *env, int
}
bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
+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 0e70ae5282ad..b7b1cf948c5f 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 677ec4236226..e3b809aba27b 100644
--- a/kernel/bpf/failing_path.c
+++ b/kernel/bpf/failing_path.c
@@ -187,7 +187,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 a7116e2cb7d6..68425dc04848 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -980,16 +980,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);
@@ -998,18 +1000,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);
@@ -1067,7 +1069,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 */
*patch++ = BPF_JMP32_IMM(BPF_JSET, BPF_REG_ARENA_SP,
BPF_ARENA_STACK_SLOW, 5);
@@ -1091,7 +1093,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;
@@ -1257,35 +1259,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)
@@ -1298,28 +1296,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
@@ -1332,11 +1351,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 */
@@ -1397,8 +1426,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 */
@@ -1660,6 +1688,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)
@@ -1686,6 +1715,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++) {
@@ -1785,7 +1815,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
func[i]->aux->can_unwind = env->subprog_info[i].can_unwind;
func[i]->aux->in_recursion = env->subprog_info[i].in_recursion;
func[i]->aux->token = prog->aux->token;
- if (!i)
+ if (main)
func[i]->aux->exception_boundary = env->seen_exception;
func[i] = bpf_int_jit_compile(env, func[i]);
if (!func[i]->jited) {
@@ -3117,7 +3147,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/syscall.c b/kernel/bpf/syscall.c
index 801175b809e7..1d8783622a94 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -2953,7 +2953,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;
@@ -2964,9 +2964,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 |
@@ -2976,14 +2973,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
@@ -3176,6 +3173,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)
@@ -3221,15 +3242,6 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
*/
__bpf_prog_put_noref(prog, prog->aux->real_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 2e3be7c11221..15a73e3991f9 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -453,7 +453,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))
@@ -3202,6 +3202,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);
bpf_mark_subprog_exc_cb(env, env->exception_callback_subprog);
@@ -5533,7 +5538,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)
@@ -5720,6 +5725,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 */
@@ -6007,7 +6016,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;
@@ -6048,7 +6057,8 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
if (plain_callx && si[s].addr_taken)
si[s].plain_call = true;
si[s].bail_unwinds = si[s].can_unwind ||
- (s && !si[s].plain_call && !bpf_subprog_is_global(env, s) &&
+ (!si[s].main && !si[s].plain_call &&
+ !bpf_subprog_is_global(env, s) &&
bpf_jit_supports_unwind() &&
!bpf_prog_is_offloaded(env->prog->aux));
}
@@ -6059,7 +6069,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;
}
@@ -11960,7 +11970,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;
/*
@@ -15591,6 +15602,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;
@@ -19629,7 +19642,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;
}
@@ -20573,7 +20586,7 @@ static int process_bpf_exit_full(struct bpf_verifier_env *env,
* 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);
@@ -21414,8 +21427,8 @@ static bool state_can_unwind(struct bpf_verifier_env *env, const struct bpf_veri
return false;
/* the kernel called it: either exit ends it */
top = !st->curframe && !st->callers_unknown &&
- (!frame->subprogno || frame->in_async_callback_fn);
- if (top && !frame->subprogno && !zero_is_valid_retval(env))
+ (sub->main || frame->in_async_callback_fn);
+ if (top && sub->main && !zero_is_valid_retval(env))
return false;
return top || sub->bail_unwinds || or_exit;
}
@@ -23214,7 +23227,7 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
state->speculative = false;
state->in_sleepable = context == BPF_FUNC_CTX_SLEEPABLE;
/* nobody knows what the callers of a global function or of an extension hold */
- state->callers_unknown = subprog || env->prog->type == BPF_PROG_TYPE_EXT;
+ state->callers_unknown = !sub->main || env->prog->type == BPF_PROG_TYPE_EXT;
env->no_rcu_read_lock = context == BPF_FUNC_CTX_NO_RCU_LOCK;
state->frame[0] = kzalloc_obj(struct bpf_func_state, BPF_VERIFIER_GFP);
if (!state->frame[0]) {
@@ -23229,7 +23242,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 (state->callers_unknown) {
const char *sub_name = bpf_subprog_name(env, subprog);
struct bpf_subprog_arg_info *arg;
struct bpf_reg_state *reg;
@@ -23321,11 +23334,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;
}
}
@@ -23336,7 +23349,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)
@@ -23571,7 +23584,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;
@@ -23913,7 +23926,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]))
@@ -23943,7 +23956,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,
@@ -26145,6 +26158,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] 11+ messages in thread
* [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns
2026-12-02 0:16 [PATCH bpf-next 0/6] bpf: Share subprogs between programs Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 1/6] bpf: Prepare for many main programs in one load Alexei Starovoitov
@ 2026-12-02 0:16 ` Alexei Starovoitov
2026-12-02 1:13 ` bot+bpf-ci
2026-12-02 1:18 ` sashiko-bot
2026-12-02 0:16 ` [PATCH bpf-next 3/6] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
` (3 subsequent siblings)
5 siblings, 2 replies; 11+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 0:16 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.15 s
one copy 33118 31070 143034 bytes 0.08 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 %
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.
An insn has one rewrite and the limits are for the whole load, 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 patch adds the UAPI.
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
include/linux/bpf.h | 11 +-
include/linux/bpf_verifier.h | 20 +-
kernel/bpf/cfg.c | 8 +-
kernel/bpf/failing_path.c | 4 +-
kernel/bpf/fixups.c | 8 +-
kernel/bpf/flow.c | 54 ++++-
kernel/bpf/precision.c | 2 +
kernel/bpf/verifier.c | 380 ++++++++++++++++++++++++++++++++---
kernel/sched/ext/ext.c | 2 +-
net/ipv4/bpf_tcp_ops.c | 3 +-
10 files changed, 443 insertions(+), 49 deletions(-)
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index a4e3ba8bf582..98dc2ef373f2 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -1805,8 +1805,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];
@@ -1913,6 +1914,8 @@ struct bpf_prog_aux {
u32 real_func_cnt; /* includes hidden progs, only used for JIT and freeing progs */
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().
@@ -1979,6 +1982,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;
@@ -4531,7 +4536,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 c0a5cf642caf..e0a2a4d52913 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -880,7 +880,7 @@ struct bpf_loop {
/* not rt_bounded: there are places for may_goto, see guard_to in bpf_insn_aux_data */
bool has_guards;
- /* 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: */
@@ -981,6 +981,8 @@ struct bpf_insn_aux_data {
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 guard_unwinds:1; /* it leaves the subprog */
+ 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() */
@@ -1172,6 +1174,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 */
@@ -1237,6 +1242,7 @@ struct bpf_subprog_info {
u16 max_out_stack_arg_cnt;
};
+/* 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 */
@@ -1387,7 +1393,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 */
@@ -1400,6 +1406,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;
@@ -1422,6 +1429,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;
@@ -1485,7 +1493,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;
@@ -1872,7 +1881,9 @@ 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_drop_guards(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);
+int bpf_flow_drop_guards(struct bpf_verifier_env *env);
int bpf_flow_place_guards(struct bpf_verifier_env *env);
/* verifier.c, for flow.c */
int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
@@ -2221,6 +2232,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 e3b809aba27b..b86d43350b5b 100644
--- a/kernel/bpf/failing_path.c
+++ b/kernel/bpf/failing_path.c
@@ -112,11 +112,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 68425dc04848..7227032e1347 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -1744,12 +1744,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;
@@ -1875,6 +1878,9 @@ static int jit_subprogs(struct bpf_verifier_env *env)
for (i = 0; i < env->subprog_cnt; i++) {
func[i]->aux->used_maps = NULL;
func[i]->aux->used_map_cnt = 0;
+ /* bpf_throw() finds the func of an entry */
+ func[i]->aux->bpf_exception_cb =
+ (void *)func[env->exception_callback_subprog]->bpf_func;
}
/* finally lock prog and jit images for all functions and
diff --git a/kernel/bpf/flow.c b/kernel/bpf/flow.c
index 33e50e1ad8cb..0987cbaba5f6 100644
--- a/kernel/bpf/flow.c
+++ b/kernel/bpf/flow.c
@@ -448,11 +448,24 @@ 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. A loop needs may_goto only if a state had no trip count. */
-void bpf_flow_drop_guards(struct bpf_verifier_env *env)
+/* 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;
+ }
+}
+
+/* A loop needs may_goto only if a state had no trip count */
+int bpf_flow_drop_guards(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux = env->insn_aux_data;
int i, h;
@@ -460,8 +473,13 @@ 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;
+ 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;
}
/*
@@ -491,8 +509,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 = loop->has_guards && !bpf_prog_is_offloaded(env->prog->aux);
if (aux[h].guard_at_header)
ret = 1;
}
@@ -528,6 +544,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 = loop->has_guards && !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 33b180b35c88..ef8e7aee7180 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -1780,6 +1780,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 15a73e3991f9..58b30c1c2b0b 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -402,6 +402,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;
@@ -3202,7 +3237,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;
@@ -3219,6 +3254,64 @@ 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_exceptions())
+ 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;
@@ -3348,7 +3441,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)
@@ -3356,7 +3449,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;
}
@@ -6017,7 +6110,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;
}
@@ -6135,6 +6229,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);
@@ -10610,6 +10707,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
@@ -11892,6 +11994,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)
{
@@ -11951,11 +12062,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);
@@ -12968,7 +13079,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;
}
@@ -13047,6 +13160,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);
@@ -15345,7 +15460,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;
@@ -15881,6 +15998,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);
@@ -21488,9 +21607,7 @@ 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)
- return 0;
- if (!(env->path_sensitive ? loop->infinite : loop->guarded)) {
+ if (loop->rt_bounded || !(env->path_sensitive ? loop->infinite : loop->guarded)) {
loop->this_pass.no_guard_edges = true;
return 0;
}
@@ -21540,6 +21657,9 @@ static int check_loop_guard(struct bpf_verifier_env *env)
env->run_has_guess |= aux->guard_no_unwind &&
state_can_unwind(env, env->cur_state, aux->guard_unset_reg);
out:
+ /* the states so far took the other way */
+ loop->this_pass.no_guard_edges |= aux->loop_guard &&
+ aux->guard_unwinds == aux->guard_no_unwind;
aux->loop_guard = true;
aux->guard_unwinds = !aux->guard_no_unwind;
if (aux->guard_no_unwind)
@@ -22360,7 +22480,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;
@@ -22438,6 +22559,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");
@@ -23072,6 +23198,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)
{
@@ -23081,7 +23209,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 */
@@ -23334,6 +23462,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 ||
@@ -23433,7 +23563,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;
@@ -23446,7 +23576,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++;
}
}
@@ -23463,12 +23593,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;
}
@@ -23479,6 +23619,7 @@ struct bpf_snapshot {
struct bpf_insn_fixups *insns;
struct bpf_subprog_info *subprogs;
struct bpf_func_info_aux *funcs;
+ size_t bytes;
struct bpf_prog prog;
};
@@ -23533,7 +23674,7 @@ static struct bpf_snapshot *save_snapshot(struct bpf_verifier_env *env,
BPF_VERIFIER_GFP);
if (!snapshot)
return NULL;
- env->mem += insns + subprogs;
+ env->mem += snapshot->bytes = insns + subprogs;
snapshot->insns = (void *)(snapshot + 1);
snapshot->subprogs = (void *)snapshot->insns + insns;
snapshot->funcs = (void *)snapshot->subprogs + subprogs;
@@ -23542,6 +23683,12 @@ static struct bpf_snapshot *save_snapshot(struct bpf_verifier_env *env,
return snapshot;
}
+static void free_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *snapshot)
+{
+ env->mem -= snapshot ? snapshot->bytes : 0;
+ kvfree(snapshot);
+}
+
static void restore_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *snapshot)
{
copy_snapshot(env, snapshot, false);
@@ -23579,6 +23726,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;
@@ -23607,12 +23759,10 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
int ret;
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);
- ret = do_check_main(env) ?: do_check_subprogs(env) ?: bpf_check_limits(env);
+ ret = do_check_main(env) ?: bpf_check_limits(env);
env->log.level = level;
env->pass_max_cost = U64_MAX;
return ret == -EINTR ? ret : env->err ?: ret;
@@ -23626,7 +23776,7 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
verbose(env, "pass %u\n", env->pass);
bpf_precision_new_pass(env);
ret = check_funcs(env, initial);
- if (ret || pass_needs_restart(env))
+ if (ret || pass_needs_restart(env) || env->pass_main + 1 < env->main_cnt)
return ret;
ret = check_after_pass(env);
if (ret)
@@ -23796,7 +23946,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);
@@ -23822,7 +23972,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))
continue;
if (env->for_log && (!offload || replay))
@@ -23902,11 +24052,27 @@ 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);
+ bpf_precision_free(env);
+ free_snapshot(env, initial);
+ free_snapshot(env, good_pass);
+ return err;
+}
+
+/* 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 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->max_cost = max_cost;
+ env->max_mem = max_mem;
+ bpf_flow_new_main(env);
+ err = do_check_all(env);
+ }
+ err = err ?: bpf_flow_drop_guards(env);
if (!err && env->sleepable_async_cb)
mark_sleepable_async_cb(env);
- bpf_precision_free(env);
- kvfree(initial);
- kvfree(good_pass);
return err;
}
@@ -24503,6 +24669,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 (aux->func && aux->func[subprog]->aux->exception_cb) {
bpf_log(log,
"%s programs cannot attach to exception callback\n",
@@ -25057,6 +25232,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)
@@ -25905,6 +26212,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)
@@ -25940,7 +26251,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;
@@ -26007,7 +26318,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)
@@ -26021,6 +26332,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
ret = bpf_insert_loop_guards(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);
@@ -26097,6 +26411,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/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
index efa1d01d03af..cb0240e848f2 100644
--- a/kernel/sched/ext/ext.c
+++ b/kernel/sched/ext/ext.c
@@ -12370,7 +12370,7 @@ int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id)
* add_subprog_and_kfunc() collects all kfunc calls, including dead code
* guarded by bpf_ksym_exists(), before check_attach_btf_id() sets
* prog->aux->st_ops. Allow all kfuncs when st_ops is not yet set;
- * do_check_main() re-runs the filter with st_ops set and enforces the
+ * do_check_mains() re-runs the filter with st_ops set and enforces the
* actual restrictions.
*/
if (!prog->aux->st_ops)
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] 11+ messages in thread
* [PATCH bpf-next 3/6] bpf: Take entries at BPF_PROG_LOAD
2026-12-02 0:16 [PATCH bpf-next 0/6] bpf: Share subprogs between programs Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 1/6] bpf: Prepare for many main programs in one load Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns Alexei Starovoitov
@ 2026-12-02 0:16 ` Alexei Starovoitov
2026-12-02 1:13 ` bot+bpf-ci
2026-12-02 0:16 ` [PATCH bpf-next 4/6] libbpf, bpftool: Share subprogs between programs Alexei Starovoitov
` (2 subsequent siblings)
5 siblings, 1 reply; 11+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 0:16 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.
The walk of the stack works where bpf_throw() does. Other JITs get
-EOPNOTSUPP, see bpf_jit_supports_exceptions().
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
---
Documentation/bpf/verifier.rst | 91 +++++-
include/linux/bpf.h | 11 +-
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 +
kernel/events/core.c | 4 +
tools/include/uapi/linux/bpf.h | 32 ++-
.../selftests/bpf/prog_tests/bpf_attr_size.c | 2 +-
13 files changed, 519 insertions(+), 68 deletions(-)
diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index 0bffb2b1476a..491fe3276945 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 +-------------------+
@@ -919,6 +920,91 @@ with an empty stack. ``callx`` is checked as a call of each function that the
register can hold. ``bpf_throw()`` ends the program from any frame, so nothing
can be held there.
+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. The owner has an id, but it 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. The limits of a load are for all of them.
+
+Each main program has passes of its own, see ``do_check_mains()``. They start
+with no precision, and with the fixups of the programs before it. These are not
+checked again. So the load is rejected when a loop gets ``may_goto`` and one of
+them did not take its edges. The call graph is checked after the last one.
+
+``enter_main()`` makes ``env->prog`` answer for the attach point of the main
+program. It swaps the attach type, ``sleepable`` and a range
+of fields of ``struct bpf_prog_aux``. An entry gets what the verifier has found
+from the owner, but for the part of the ctx that it reads. What a main program
+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, have one
+attach type, so they 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. A helper has to have the prototype that the first main program
+gets.
+
+An insn still has one fixup, so a static function can be rejected where two
+copies of it are valid. A kfunc that has a form that does not sleep gets it for
+all main programs, when one that is not sleepable calls it. The associated
+struct_ops map, cgroup storage and the count of ``may_goto`` are those of the
+owner. Each main program resets the count when it starts. There is no private
+stack: it has one frame of a function, and main programs run on top of each
+other.
+
+What is printed or reported goes to the streams of the main program that runs,
+``bpf_prog_find_main()`` finds it in the stack. An async callback has none below
+it, it uses the streams of the owner. So does a function that is an async
+callback when a helper like ``bpf_loop()`` calls it. The first entry has the
+streams of the owner, and none of its own. So the loader can read them without
+the fd of the owner, which takes ``CAP_SYS_ADMIN``.
+
+These cannot have entries: tracing, LSM, extension and device bound programs,
+a load that has a signature (a signed loader can load programs with entries),
+programs with tail calls, an exception callback or exclusive maps,
+programs that read ``tstamp_type`` or change ``pt_regs``, and programs for JITs
+that do not support ``bpf_throw()``. No value in a map is taken
+for a pointer to a function, so ``callx`` has no tables of functions. None can
+call ``bpf_tcp_ops_set_rcvlowat()``, which reads the member from ``aux``. None
+can have a ``__ref`` argument when one has a stack in arena. An extension can
+replace a main program, not a function that it calls. A tracing program names
+such a function through any entry, and sees the calls from all of them.
+
+An entry holds the maps of all main programs. When one of them holds the entry
+until it is freed, neither goes. The kernel does not refuse that, as it does not
+refuse a program that uses the map which holds it. libbpf makes copies for
+cpumap and devmap programs, and for objects with a ``BPF_F_PRESERVE_ELEMS`` map.
+There are longer cycles. A ``struct bpf_ksock`` in a map holds its netns and its
+cgroup, and so what is attached there without a link. An associated struct_ops
+map holds its programs and their maps.
+
+Kfuncs get the struct_ops map that has the entries. They get none, for good,
+once two maps had entries at the same time. The symbol of an entry goes with it,
+its code with the owner. All entries have the tag of the owner.
+
+The LSM hook ``bpf_prog_load`` sees the owner first, with all insns. Then it sees
+each entry with its type, attach point and name in ``prog`` and ``attr``. An
+entry has ``aux->is_entry`` set and no code yet. Audit and
+``PERF_RECORD_BPF_EVENT`` tell of the owner and of each entry.
+``PERF_RECORD_KSYMBOL`` comes and goes with the code, so with the owner.
+
After an error
==============
@@ -1477,7 +1563,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
@@ -1506,6 +1592,7 @@ leftover all trips that are not peeled
live read later, before it is written
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 98dc2ef373f2..d2bb0565ad22 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -1916,6 +1916,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().
@@ -1975,6 +1976,7 @@ struct bpf_prog_aux {
bool xdp_has_frags;
bool exception_cb;
bool exception_boundary;
+ bool async_cb;
bool has_prologue;
bool might_throw;
bool can_unwind;
@@ -2067,6 +2069,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 {
@@ -2423,7 +2426,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,
@@ -2508,8 +2511,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;
}
@@ -3414,6 +3416,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);
@@ -4490,6 +4493,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);
@@ -4553,6 +4557,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 5d44bce55d5e..d961b15da233 100644
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -288,6 +288,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).
@@ -1567,6 +1571,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,
@@ -1737,6 +1760,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 */
@@ -5456,6 +5483,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.
*
@@ -6886,7 +6916,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 1c118f3da5a4..a0052c2bfd3e 100644
--- a/kernel/bpf/arena.c
+++ b/kernel/bpf/arena.c
@@ -1405,7 +1405,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 32a267656c0e..958c68198a96 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -924,7 +924,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);
@@ -3541,11 +3541,29 @@ static void bpf_prog_free_images(struct work_struct *work)
if (aux->real_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;
@@ -3558,6 +3576,8 @@ static void bpf_prog_free_deferred(struct work_struct *work)
*/
ksyms = aux->real_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
@@ -4265,6 +4285,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)
@@ -4280,19 +4301,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 7227032e1347..061195b92b47 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -1753,6 +1753,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 1d8783622a94..8ed6620f143a 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -2689,6 +2689,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;
@@ -2701,18 +2705,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);
@@ -2951,11 +2960,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;
@@ -2976,6 +2986,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);
@@ -3045,12 +3056,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 */
@@ -3066,8 +3086,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);
@@ -3088,10 +3107,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);
@@ -3185,6 +3204,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;
@@ -3206,6 +3371,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);
@@ -3227,8 +3396,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)
@@ -3236,6 +3411,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.
@@ -5127,7 +5303,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)
@@ -5253,7 +5430,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;
@@ -5269,6 +5446,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));
@@ -6422,20 +6600,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
@@ -6485,22 +6661,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,
@@ -6710,18 +6884,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 58b30c1c2b0b..b2d20e07e686 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -25297,6 +25297,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;
@@ -26144,6 +26145,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/kernel/events/core.c b/kernel/events/core.c
index 614f9f0e6500..4af192089d6b 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -10478,6 +10478,10 @@ static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
int i;
+ /* its owner has the code */
+ if (prog->aux->is_entry)
+ return;
+
perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
(u64)(unsigned long)prog->bpf_func,
prog->jited_len, unregister,
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index 5d44bce55d5e..d961b15da233 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -288,6 +288,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).
@@ -1567,6 +1571,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,
@@ -1737,6 +1760,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 */
@@ -5456,6 +5483,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.
*
@@ -6886,7 +6916,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] 11+ messages in thread
* [PATCH bpf-next 4/6] libbpf, bpftool: Share subprogs between programs
2026-12-02 0:16 [PATCH bpf-next 0/6] bpf: Share subprogs between programs Alexei Starovoitov
` (2 preceding siblings ...)
2026-12-02 0:16 ` [PATCH bpf-next 3/6] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
@ 2026-12-02 0:16 ` Alexei Starovoitov
2026-12-02 1:13 ` bot+bpf-ci
2026-12-02 0:16 ` [PATCH bpf-next 5/6] libbpf: Share subprogs in light skeletons Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 6/6] selftests/bpf: Test programs that share subprogs Alexei Starovoitov
5 siblings, 1 reply; 11+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 0:16 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. The same when a log level is set.
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 106139 48249 36855 36855
scx_lavd 36 115018 66090 51788 54599
scx_rusty 14 40451 24870 12707 12707
scx_chaos 24 74870 55777 16325 16368
scx_p2dq 23 55318 47068 12543 12543
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 | 297 +++++++++++++++++-
.../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, 398 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..8369ecb96839 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)
+ goto out;
+
if (log_level == 0) {
log_level = 1;
goto retry_load;
@@ -9119,6 +9134,247 @@ 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->log_level || 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)
+ 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 +9382,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 +9395,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 +11030,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 37e03b3e0ee8..9bfd9c2df38c 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] 11+ messages in thread
* [PATCH bpf-next 5/6] libbpf: Share subprogs in light skeletons
2026-12-02 0:16 [PATCH bpf-next 0/6] bpf: Share subprogs between programs Alexei Starovoitov
` (3 preceding siblings ...)
2026-12-02 0:16 ` [PATCH bpf-next 4/6] libbpf, bpftool: Share subprogs between programs Alexei Starovoitov
@ 2026-12-02 0:16 ` Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 6/6] selftests/bpf: Test programs that share subprogs Alexei Starovoitov
5 siblings, 0 replies; 11+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 0:16 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 9131135 48438960
shared 5916765 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 8369ecb96839..e76492b988a6 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;
}
@@ -9134,6 +9133,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)
{
@@ -9267,9 +9279,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);
@@ -9287,6 +9302,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;
@@ -9303,6 +9319,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++) {
@@ -9331,6 +9352,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;
@@ -9352,16 +9375,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);
}
@@ -9373,6 +9399,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
@@ -9383,7 +9410,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];
@@ -10091,19 +10118,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] 11+ messages in thread
* [PATCH bpf-next 6/6] selftests/bpf: Test programs that share subprogs
2026-12-02 0:16 [PATCH bpf-next 0/6] bpf: Share subprogs between programs Alexei Starovoitov
` (4 preceding siblings ...)
2026-12-02 0:16 ` [PATCH bpf-next 5/6] libbpf: Share subprogs in light skeletons Alexei Starovoitov
@ 2026-12-02 0:16 ` Alexei Starovoitov
5 siblings, 0 replies; 11+ messages in thread
From: Alexei Starovoitov @ 2026-12-02 0:16 UTC (permalink / raw)
To: bpf; +Cc: daniel, andrii, eddyz87, memxor
From: Alexei Starovoitov <ast@kernel.org>
Run entries that call, print and throw. 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 | 134 ++++++++++++++++
.../selftests/bpf/progs/share_subprogs.c | 143 ++++++++++++++++++
.../bpf/progs/share_subprogs_signed.c | 87 +++++++++++
4 files changed, 365 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_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..808b8c8fe09c
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/share_subprogs.c
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <network_helpers.h>
+#include "share_subprogs.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");
+ 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 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 && errno == ENOTSUPP) {
+ test__skip();
+ return;
+ }
+ if (!ASSERT_OK_PTR(skel, "load"))
+ return;
+ if (test__start_subtest("calls"))
+ test_calls(skel);
+ if (test__start_subtest("may_goto"))
+ ASSERT_EQ(owner_of(bpf_program__fd(skel->progs.bounded)), 0, "copies");
+
+ 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..ea5198f9dd2b
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/share_subprogs.c
@@ -0,0 +1,143 @@
+// 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";
+
+int zero, traced;
+
+static __noinline int inc(int x)
+{
+ return x + 1;
+}
+
+__noinline int add(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(1, 2);
+}
+
+SEC("tc")
+int second(struct __sk_buff *skb)
+{
+ return inc(zero) + add(10, 20);
+}
+
+SEC("tc")
+int third(struct __sk_buff *skb)
+{
+ return throws(inc(zero));
+}
+
+static __noinline __u64 down(__u64 n)
+{
+ while (n > 7) {
+ n--;
+ barrier_var(n);
+ }
+ return n;
+}
+
+__u64 buf[8];
+
+/* It is out of bounds when may_goto ends the loop */
+SEC("tc")
+int bounded(struct __sk_buff *skb)
+{
+ return buf[down(skb->len & 0xffff)];
+}
+
+SEC("tc")
+int unbounded(struct __sk_buff *skb)
+{
+ return down(buf[0]);
+}
+
+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);
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..76a2bc9c21d9
--- /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(int x)
+{
+ bpf_rcu_read_lock();
+ sum += x;
+ bpf_rcu_read_unlock();
+ return 0;
+}
+
+SEC("struct_ops")
+int BPF_PROG(test_1)
+{
+ return add(1);
+}
+
+SEC("struct_ops")
+void BPF_PROG(test_2, int a, int b)
+{
+ add(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] 11+ messages in thread
* Re: [PATCH bpf-next 3/6] bpf: Take entries at BPF_PROG_LOAD
2026-12-02 0:16 ` [PATCH bpf-next 3/6] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
@ 2026-12-02 1:13 ` bot+bpf-ci
0 siblings, 0 replies; 11+ messages in thread
From: bot+bpf-ci @ 2026-12-02 1:13 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: 2271 bytes --]
> bpf: Take entries at BPF_PROG_LOAD
TL;DR: Documentation nit in verifier.rst: the sentence on what an entry gets
from the owner is incomplete. It may mislead readers into thinking entries
inherit the owner's changes_pkt_data and might_sleep, which are per main
program.
> diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
> --- a/Documentation/bpf/verifier.rst
> +++ b/Documentation/bpf/verifier.rst
[ ... ]
> +``enter_main()`` makes ``env->prog`` answer for the attach point of the main
> +program. It swaps the attach type, ``sleepable`` and a range
> +of fields of ``struct bpf_prog_aux``. An entry gets what the verifier has found
> +from the owner, but for the part of the ctx that it reads. What a main program
> +calls is checked like this:
This isn't a bug, but is this sentence complete enough about what an entry
gets from the owner?
finish_entry() copies the max_ctx_offset..cgroup_storage group from the
owner, and then sets more than the ctx fields from the main program's own
values:
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;
changes_pkt_data and might_sleep are also per main program, and the attach
checks read them. For example, check_attach_btf_id() takes
tgt_changes_pkt_data and tgt_might_sleep from aux->changes_pkt_data and
aux->might_sleep when the target is an entry (aux->func is NULL).
stack_depth is per entry too.
A reader who trusts the sentence could conclude that an entry carries the
owner's changes_pkt_data and might_sleep, i.e. the values for the whole
load.
Could the sentence list those fields, or say that what depends on the main
program (ctx reads, packet writes, sleeping, stack depth) belongs to the
entry?
---
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/46780056583
^ permalink raw reply [flat|nested] 11+ messages in thread
* Re: [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns
2026-12-02 0:16 ` [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns Alexei Starovoitov
@ 2026-12-02 1:13 ` bot+bpf-ci
2026-12-02 1:18 ` sashiko-bot
1 sibling, 0 replies; 11+ messages in thread
From: bot+bpf-ci @ 2026-12-02 1:13 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: 2944 bytes --]
> bpf: Check many main programs in one set of insns
TL;DR: bpf_precision_free() may not return all env->mem charges (the seen hash
set, the hops_to_err part), so later main programs could spuriously fail with
"too complex: memory".
> diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
> --- a/kernel/bpf/precision.c
> +++ b/kernel/bpf/precision.c
[ ... ]
> @@ -1780,6 +1780,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);
Does this return all of the memory charged against env->mem for the
precision data? With do_check_mains() now running do_check_all() once per
main program, any charge left behind stays in env->mem for every later main.
Two charges look like they are not returned. First, the failing-path hash
set is charged each time it grows in bpf_failing_path_was_here():
set = kvcalloc(2 * size, sizeof(*set), BPF_VERIFIER_GFP);
...
env->mem += size * sizeof(*set);
kvfree(prec->seen);
prec->seen = set;
bpf_precision_free() does kvfree(prec->seen) but does not subtract that
charge. The next main starts with seen == NULL and seen_bits == 0, so the
table is reallocated and charged again. This is reachable when a pass
fails, find_failing_path() -> run_path_sensitive() -> do_check() ->
flow_add() -> bpf_failing_path_was_here() runs at join points, and a later
pass then succeeds.
Second, when alloc_masks() fails after its charge:
env->mem += 18 * prec->words * sizeof(long) + 5 * env->prog->len * sizeof(u16);
err = bpf_check_limits(env);
masks = err ? NULL : kvcalloc(...);
if (!masks) {
env->mem -= 18 * prec->words * sizeof(long);
return err ?: -ENOMEM;
}
the 5 * env->prog->len * sizeof(u16) part stays charged while
prec->data_deps is NULL. A main can still be accepted in that case, since
bpf_partition_for_pessimized() returns the error and do_check_all() takes
the !offload accept path. The "if (prec->data_deps)" test above then skips
the subtraction even though hops_to_err is freed.
do_check_mains() resets env->max_mem to the load-wide limit before each
main, so the stale bytes count against it. Could a later entry then fail
in bpf_check_limits() with "BPF program is too complex: ... memory" for
memory that was already freed? The stale amount grows with the number of
entries, and the commit message targets loads with 32 or more.
Should bpf_precision_free() also subtract the size charged for prec->seen,
and should the hops_to_err part be keyed on prec->hops_to_err rather than
prec->data_deps?
---
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/46780056583
^ permalink raw reply [flat|nested] 11+ messages in thread
* Re: [PATCH bpf-next 4/6] libbpf, bpftool: Share subprogs between programs
2026-12-02 0:16 ` [PATCH bpf-next 4/6] libbpf, bpftool: Share subprogs between programs Alexei Starovoitov
@ 2026-12-02 1:13 ` bot+bpf-ci
0 siblings, 0 replies; 11+ messages in thread
From: bot+bpf-ci @ 2026-12-02 1:13 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: 4383 bytes --]
> libbpf, bpftool: Share subprogs between programs
TL;DR:
- prog_can_share() may miss BPF_F_PRESERVE_ELEMS on map-in-map inner
templates, possibly leaking programs via a reference cycle
- Sharing is on by default with no opt-out, so existing freplace users get
-EOPNOTSUPP and fentry on subprogs fires for siblings
> diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
> --- a/tools/lib/bpf/libbpf.c
> +++ b/tools/lib/bpf/libbpf.c
[ ... ]
> +static bool prog_can_share(struct bpf_object *obj, struct bpf_program *prog)
> +{
[ ... ]
> + bpf_object__for_each_map(map, obj)
> + if (map->excl_prog == prog || (map->def.map_flags & BPF_F_PRESERVE_ELEMS))
> + return false;
The commit message says copies are kept "for objects with a
BPF_F_PRESERVE_ELEMS map" because "a map that holds a program and is used by
its sibling would never be freed".
This loop only looks at obj->maps. The inner map template of a map-in-map
(map->inner_map) is allocated separately in bpf_object__init_user_btf_map()
and is not in obj->maps. For example:
struct inner { __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
__uint(map_flags, BPF_F_PRESERVE_ELEMS); ... };
struct { __uint(type, BPF_MAP_TYPE_ARRAY_OF_MAPS);
__array(values, struct inner); } outer SEC(".maps");
Here prog_can_share() never sees the flag and still lets the programs share.
The kernel allows this layout, since bpf_map_meta_equal() requires the inner
maps to have the template's map_flags, and array_of_maps_map_ops has no
map_release_uref.
Can this form the cycle the check is meant to prevent? Program Q references
outer and shares a subprog with P (two kprobes, for instance). P is attached
to a perf event E with PERF_EVENT_IOC_SET_BPF, and E sits in an inner map I:
P -> owner -> outer -> I -> E -> P
With sharing, each entry holds the owner through bpf_prog_entries_new_fds()
-> bpf_prog_add(), and the owner's used_maps include outer, so the chain
stays after all user fds are closed. Without sharing, freeing Q frees outer,
then I, then E, then P.
The same gap seems to apply to an inner template given with
bpf_map__set_inner_map_fd().
[ ... ]
> static int
> bpf_object__load_progs(struct bpf_object *obj, int log_level)
> {
[ ... ]
> + 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))
[ ... ]
> + bpf_object_load_shared(obj, prog);
> + if (prog->fd >= 0)
> + continue;
Sharing is now on for every bpf_object__load() caller and cannot be turned
off for the whole object. A program avoids it only when it has a log level,
when the object is a light skeleton, or when it is switched to
BPF_PROG_LOAD_STRATEGY_MANUAL and loaded by hand with bpf_program__load().
No bpf_object_open_opts field turns it off.
For a program that becomes an entry, the kernel then behaves differently for
existing users. An attach_prog_fd naming a subprog of an entry is sent to
the owner, and bpf_check_attach_target() rejects it:
if (aux->entry_cnt && prog_extension) {
bpf_log(log, "Cannot replace a function of a program with entries\n");
return -EOPNOTSUPP;
}
An fentry/fexit on such a subprog is also sent to the owner, so it fires for
calls from every sibling program.
For example, an application loads an object with two programs of one type
that call the same global function, and then loads a BPF_PROG_TYPE_EXT
program with bpf_program__set_attach_target(ext, bpf_program__fd(main),
"func"). That worked before this change. After a libbpf upgrade with no
change to the application, the extension load fails with -EOPNOTSUPP.
The patch itself has to change selftests/bpf/prog_tests/unwind_attach.c to
keep the old behaviour:
bpf_program__set_load_strategy(tgt->progs.shared_pad,
BPF_PROG_LOAD_STRATEGY_MANUAL);
Should sharing be opt-in, or at least have an object-level open option to
disable it, so existing freplace/fentry-on-subprog users keep working?
---
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/46780056583
^ permalink raw reply [flat|nested] 11+ messages in thread
* Re: [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns
2026-12-02 0:16 ` [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns Alexei Starovoitov
2026-12-02 1:13 ` bot+bpf-ci
@ 2026-12-02 1:18 ` sashiko-bot
1 sibling, 0 replies; 11+ messages in thread
From: sashiko-bot @ 2026-12-02 1:18 UTC (permalink / raw)
To: Alexei Starovoitov, bpf
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] bpf: missing sleepable_async_cb propagation in
mark_sleepable_async_cb()
--
commit e81391289aecdf18a4497171d32e314bcc48b1a9
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 instruction buffer so that they can share common
subprograms.
> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> index 15a73e3991f9f..58b30c1c2b0b1 100644
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c
[ ... ]
> @@ -23902,11 +24052,27 @@ static int do_check_all(struct bpf_verifier_env *env)
[ ... ]
> +/* 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 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->max_cost = max_cost;
> + env->max_mem = max_mem;
> + bpf_flow_new_main(env);
> + err = do_check_all(env);
> + }
> + err = err ?: bpf_flow_drop_guards(env);
> if (!err && env->sleepable_async_cb)
> mark_sleepable_async_cb(env);
> - bpf_precision_free(env);
> - kvfree(initial);
> - kvfree(good_pass);
> return err;
> }
[ ... ]
> @@ -25057,6 +25232,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;
> +}
[ ... ]
> +/* 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;
[ ... ]
> + memcpy(aux_fields(aux, max_ctx_offset), aux_fields(from, max_ctx_offset),
> + aux_fields_size(max_ctx_offset, cgroup_storage));
[ ... ]
> + 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);
> +}
[Severity: Medium]
Can a non-sleepable struct_ops entry miss sleepable_async_cb and map
sleepable_refcnt accounting when the first entry in the load is sleepable?
can_share_subprogs() allows struct_ops entries in the same load to mix
sleepable and non-sleepable programs. When any entry registers a sleepable
async callback, do_check_mains() calls mark_sleepable_async_cb(env) with
env->prog->sleepable restored to the first entry's value:
kernel/bpf/verifier.c:mark_sleepable_async_cb() {
int i;
if (bpf_prog_runs_sleepable(env->prog))
return;
env->prog->aux->sleepable_async_cb = true;
for (i = 0; i < env->used_map_cnt; i++)
atomic64_inc(&env->used_maps[i]->sleepable_refcnt);
}
If the first entry is sleepable, mark_sleepable_async_cb() returns early
without setting env->prog->aux->sleepable_async_cb = true. finish_entry()
then copies sleepable_async_cb == false into every entry, so for a
non-sleepable entry in the same load bpf_prog_runs_sleepable(entry) is
false: finish_entry() skips incrementing sleepable_refcnt on its used_maps,
and freeing that entry uses call_rcu() instead of call_rcu_tasks_trace().
Setting env->prog->aux->sleepable_async_cb = true before the early return in
mark_sleepable_async_cb() would allow finish_entry() to propagate it to all
entries without double-incrementing sleepable_refcnt on env->prog's maps.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261202001639.2301557-1-alexei.starovoitov@gmail.com?part=2
^ permalink raw reply [flat|nested] 11+ messages in thread
end of thread, other threads:[~2026-12-02 1:18 UTC | newest]
Thread overview: 11+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-02 0:16 [PATCH bpf-next 0/6] bpf: Share subprogs between programs Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 1/6] bpf: Prepare for many main programs in one load Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 2/6] bpf: Check many main programs in one set of insns Alexei Starovoitov
2026-12-02 1:13 ` bot+bpf-ci
2026-12-02 1:18 ` sashiko-bot
2026-12-02 0:16 ` [PATCH bpf-next 3/6] bpf: Take entries at BPF_PROG_LOAD Alexei Starovoitov
2026-12-02 1:13 ` bot+bpf-ci
2026-12-02 0:16 ` [PATCH bpf-next 4/6] libbpf, bpftool: Share subprogs between programs Alexei Starovoitov
2026-12-02 1:13 ` bot+bpf-ci
2026-12-02 0:16 ` [PATCH bpf-next 5/6] libbpf: Share subprogs in light skeletons Alexei Starovoitov
2026-12-02 0:16 ` [PATCH bpf-next 6/6] selftests/bpf: Test programs that share subprogs Alexei Starovoitov
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox