libbpf: Support kernel-side kfunc variants
Subsystems (8)
Ihor Solodrai
reviewerv3 cover libbpf: Support kernel-side kfunc variants
A kfunc prototype change breaks BPF programs built against the old prototype. For example, 8fe4dc4f6456 ("bpf: change prototype of bpf_session_{cookie,is_return}") made this change in v7.0:
before: bool bpf_session_is_return(void); v7.0: bool bpf_session_is_return(void *ctx);
A program built before v7.0 declares bpf_session_is_return(void), and libbpf can't resolve it on v7.0. The kernel has no way to keep the old prototype available to such programs. sched_ext works around the same problem with ___v2___compat names in compat.bpf.h.
With this series, the kernel can keep the old prototype as a variant:
bool bpf_session_is_return(void *ctx); bool bpf_session_is_return___v1(void);
and libbpf binds each declaration to the function with a matching BTF prototype.
The new lookup changes what some existing declarations resolve to.
A replay of kfunc resolution against v6.18, v7.2 and bpf-next BTF covered 1302 BPF objects: 1174 sched_ext schedulers from Meta's internal builds, and 128 public objects from the scx repo, tools/sched_ext, the selftests and bpftrace. It also covered 16 objects declaring every kfunc from each x86 vmlinux.h in the scx repo's history, counted here as public. No strong declaration changes. These __weak declarations change, counted in objects per kernel:
public Meta
lost on v7.2 and bpf-next, no candidate:
scx_bpf_dsq_insert___v2___compat 36 136
scx_bpf_dsq_move_to_local___v2___compat 33 27
scx_bpf_reenqueue_local___v2___compat 9 44
lost on v7.2 and bpf-next, struct names differ:
bpf_io_uring_get_region(struct io_ring_ctx *) 1 0
bpf_io_uring_submit_sqes(struct io_ring_ctx *) 1 0 lost on bpf-next, struct names differ:
bpf_cpumask_populate(struct cpumask *) 8 88
lost on v6.18 and v7.2, struct names differ:
bpf_cpumask_populate(struct bpf_cpumask *) 4 0
gained on v7.2 and bpf-next:
scx_bpf_dsq_move_to_local___v2(u64, u64) 7 120
scx_bpf_dsq_insert___v2(...) 8 0
scx_bpf_reenqueue_local___v2(void) 8 0In-tree compat.bpf.h now tries the plain ___v2 names first. Objects that gain a ___v2 kfunc now call it instead of their fallback path.
---
v2->v3:
* Move relevant bpftool dependencies from libbpf_internal.h to libbpf_tools.h, so that bpftool only includes the new header (Quentin).
* sched_ext patch: check scx_bpf_reenqueue_local___v2 too in __COMPAT_scx_bpf_reenqueue_local_from_anywhere() (bpf-ci bot).
* libbpf: load module BTFs before the lookup, so that the load errors aren't reported as "no compatible prototype" (bpf-ci bot).
* docs: explain how older libbpf and light skeletons resolve a ___vN kfunc (bpf-ci bot).
v2: https://lore.kernel.org/bpf/[email protected]/
v1->v2:
* Pick a kfunc by prototype among all funcs with the same essential name, without preferring the exact name (Andrii, Eduard).
* Compare struct and union names, ignoring ___ suffixes, instead of using bpf_core_types_are_compat(), so that variants can differ only in a pointee type (Eduard, Andrii).
* Drop the alias exception that kept ___v2___compat names working (Eduard). New patch 2 updates compat.bpf.h instead.
* resolve_btfids: check registered kfuncs within vmlinux or a module with libbpf's new matcher and report every matching pair. New patch #1 shares libbpf internals with it instead of wrapping them (Eduard).
* Call kernel-side ___ functions "variants". "Flavor" stays CO-RE's term for local suffixes.
* Rewrite the docs for the new rules.
v1: https://lore.kernel.org/bpf/[email protected]/
---
Ihor Solodrai (6):
libbpf: Separate interfaces shared with in-tree tools
sched_ext: Prefer ___v2 kfunc names in compat.bpf.h
libbpf: Resolve kfunc variants by prototype selftests/bpf: Test kfunc variant selection by prototype
resolve_btfids: Reject ambiguous kfunc variants docs/bpf: Describe how to change a kfunc's prototype
Documentation/bpf/kfuncs.rst | 99 ++++++++++ tools/bpf/bpftool/Makefile | 6 +- tools/bpf/bpftool/common.c | 2 +- tools/bpf/bpftool/gen.c | 3 +- tools/bpf/bpftool/prog.c | 2 +- tools/bpf/bpftool/xlated_dumper.c | 2 +- tools/bpf/resolve_btfids/btf_colors.c | 15 +- tools/bpf/resolve_btfids/btf_colors.h | 4 - tools/bpf/resolve_btfids/main.c | 74 ++++++- tools/lib/bpf/btf.c | 99 +++++++++- tools/lib/bpf/libbpf.c | 112 +++++++---- tools/lib/bpf/libbpf_internal.h | 164 +-------------- tools/lib/bpf/libbpf_tools.h | 186 ++++++++++++++++++ tools/sched_ext/include/scx/compat.bpf.h | 48 +++-- .../selftests/bpf/prog_tests/verifier.c | 3 + .../selftests/bpf/progs/kfunc_variants.c | 32 +++ .../selftests/bpf/test_kmods/bpf_testmod.c | 12 ++ .../bpf/test_kmods/bpf_testmod_kfunc.h | 3 + 18 files changed, 629 insertions(+), 237 deletions(-) create mode 100644 tools/lib/bpf/libbpf_tools.h create mode 100644 tools/testing/selftests/bpf/progs/kfunc_variants.c
base-commit: a58375b858fac35afb78a3dd68ad6a19c01799eb
Signature · 1 line
2.56.0
Ihor Solodrai
reviewerPATCH v3 1/6 libbpf: Separate interfaces shared with in-tree tools
resolve_btfids and bpftool link libbpf statically and use some of its internal helpers from libbpf_internal.h. That header also defines logging macros and poisons kernel integer typedefs, so resolve_btfids wraps the SHA-256 helper in a separate source file.
Move the declarations these tools use to libbpf_tools.h and include it instead of libbpf_internal.h. The header is for in-tree tools and stays uninstalled. No shared-library symbols change.
No functional change.
--- tools/bpf/bpftool/Makefile | 6 +- tools/bpf/bpftool/common.c | 2 +- tools/bpf/bpftool/gen.c | 3 +- tools/bpf/bpftool/prog.c | 2 +- tools/bpf/bpftool/xlated_dumper.c | 2 +- tools/bpf/resolve_btfids/btf_colors.c | 15 +-- tools/bpf/resolve_btfids/btf_colors.h | 4 - tools/bpf/resolve_btfids/main.c | 5 +- tools/lib/bpf/libbpf_internal.h | 162 +---------------------- tools/lib/bpf/libbpf_tools.h | 184 ++++++++++++++++++++++++++ 10 files changed, 199 insertions(+), 186 deletions(-) create mode 100644 tools/lib/bpf/libbpf_tools.h
tools/bpf/bpftool/Makefile +3 -3
@@ -28,10 +28,10 @@ LIBBPF_BOOTSTRAP_INCLUDE := $(LIBBPF_BOOTSTRAP_DESTDIR)include LIBBPF_BOOTSTRAP_HDRS_DIR := $(LIBBPF_BOOTSTRAP_INCLUDE)/bpf LIBBPF_BOOTSTRAP := $(LIBBPF_BOOTSTRAP_OUTPUT)libbpf.a -# We need to copy hashmap.h, nlattr.h, relo_core.h and libbpf_internal.h +# We need to copy hashmap.h, nlattr.h, relo_core.h and libbpf_tools.h # which are not otherwise exported by libbpf, but still required by bpftool. -LIBBPF_INTERNAL_HDRS := $(addprefix $(LIBBPF_HDRS_DIR)/,hashmap.h nlattr.h relo_core.h libbpf_internal.h) -LIBBPF_BOOTSTRAP_INTERNAL_HDRS := $(addprefix $(LIBBPF_BOOTSTRAP_HDRS_DIR)/,hashmap.h relo_core.h libbpf_internal.h) +LIBBPF_INTERNAL_HDRS := $(addprefix $(LIBBPF_HDRS_DIR)/,hashmap.h nlattr.h relo_core.h libbpf_tools.h) +LIBBPF_BOOTSTRAP_INTERNAL_HDRS := $(addprefix $(LIBBPF_BOOTSTRAP_HDRS_DIR)/,hashmap.h relo_core.h libbpf_tools.h) $(LIBBPF_OUTPUT) $(BOOTSTRAP_OUTPUT) $(LIBBPF_BOOTSTRAP_OUTPUT) $(LIBBPF_HDRS_DIR) $(LIBBPF_BOOTSTRAP_HDRS_DIR): $(QUIET_MKDIR)mkdir -p $@
tools/bpf/bpftool/common.c +1 -1
@@ -31,7 +31,7 @@#include <bpf/bpf.h> #include <bpf/hashmap.h> #include <bpf/libbpf.h> /* libbpf_num_possible_cpus */ -#include <bpf/libbpf_internal.h> +#include <bpf/libbpf_tools.h> #include <bpf/btf.h> #include <zlib.h>
tools/bpf/bpftool/gen.c +2 -1
@@ -15,7 +15,8 @@#include <unistd.h> #include <bpf/bpf.h> #include <bpf/libbpf.h> -#include <bpf/libbpf_internal.h> +#include <bpf/libbpf_tools.h> +#include <bpf/relo_core.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h>
tools/bpf/bpftool/prog.c +1 -1
@@ -29,7 +29,7 @@#include <bpf/btf.h> #include <bpf/hashmap.h> #include <bpf/libbpf.h> -#include <bpf/libbpf_internal.h> +#include <bpf/libbpf_tools.h> #include <bpf/skel_internal.h> #include "cfg.h"
tools/bpf/bpftool/xlated_dumper.c +1 -1
@@ -10,7 +10,7 @@#include <string.h> #include <sys/types.h> #include <bpf/libbpf.h> -#include <bpf/libbpf_internal.h> +#include <bpf/libbpf_tools.h> #include "disasm.h" #include "json_writer.h"
tools/bpf/resolve_btfids/btf_colors.c +3 -12
@@ -1,18 +1,9 @@// SPDX-License-Identifier: GPL-2.0-only -#include <bpf/libbpf_internal.h> +#include <errno.h> +#include <stdlib.h> +#include <bpf/libbpf_tools.h> #include "btf_colors.h" -/* -* Functions in this file mainly exist to refer to functions from libbpf_internal.h, -* which can't be included in main.c because of the u32 poison and pr_warn macro conflicts. -*/ - -void btf_sha256 (const void *data,size_t len, -__u8 out[BTF_SHA256_DIGEST_LENGTH ]) -{ -libbpf_sha256 (data, len, out); -} -/* * Marks `root_id` and local types reachable from it with `color`. * `colors` is indexed by source ID; worklist has room for every local type.
tools/bpf/resolve_btfids/btf_colors.h +0 -4
@@ -11,10 +11,6 @@ enum btf_color { BTF_COLOR_SHARED = BTF_COLOR_MAIN | BTF_COLOR_LOC, }; -#define BTF_SHA256_DIGEST_LENGTH 32 - -void btf_sha256 (const void *data,size_t len, -__u8 out[BTF_SHA256_DIGEST_LENGTH ]);void btf_mark_reachable (struct btf *btf,__u32 root,enum btf_color color,__u8 *colors,__u32 *worklist);
tools/bpf/resolve_btfids/main.c +3 -2
@@ -93,12 +93,14 @@#include <linux/limits.h> #include <bpf/btf.h> #include <bpf/libbpf.h> +#include <bpf/libbpf_tools.h> #include "btf_colors.h" #include "fmodret.h" #include <subcmd/parse-options.h> #define BTF_IDS_SECTION ".BTF_ids"#define BTF_LINK_MODULE_NAME_MAX 64 +#define BTF_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH#define BTF_ID_PREFIX "__BTF_ID__"#define BTF_STRUCT "struct"
@@ -1205,8 +1207,7 @@ static int patch_btf_link(struct object *obj, const struct btf_link *link) }memset (data->d_buf,0 , data->d_size);memcpy (data->d_buf, link->module,strlen (link->module) +1 ); -btf_sha256 (raw_btf_data, raw_btf_size, - (u8 *)data->d_buf + module_name_len); +libbpf_sha256 (raw_btf_data, raw_btf_size, (u8 *)data->d_buf + module_name_len); size = (u8 *)data->d_buf + module_name_len +BTF_SHA256_DIGEST_LENGTH ;if (obj->efile.encoding ==ELFDATA2LSB ) { size[0 ] = raw_btf_size;
tools/lib/bpf/libbpf_internal.h +1 -161
221 lines not on this page · raw message
tools/lib/bpf/libbpf_tools.h new file +184 -0
184 lines not on this page · raw message
Signature · 1 line
2.56.0
Ihor Solodrai
reviewerRe: [PATCH bpf-next v3 1/6] libbpf: Separate interfaces shared with in-tree tools
Quoted 10 lines · Ihor Solodrai
resolve_btfidsand bpftool link libbpf statically and use some of its internal helpers fromlibbpf_internal.h. That header also defines logging macros and poisons kernel integer typedefs, soresolve_btfidswraps the SHA-256 helper in a separate source file.Move the declarations these tools use to
libbpf_tools.hand include it instead oflibbpf_internal.h. The header is for in-tree tools and stays uninstalled. No shared-library symbols change.No functional change.
I posted v3 with the refactoring as described in my comment [1].
However now I'm thinking it might be an overkill. With the re-design vs v1, resolve_btfids now only needs btf_kfunc_proto_match(), if it includes relo_core.h, so the new libbpf_tools.h is not as appealing.
Speaking of "API levels", libbpf_internal.h has already been functioning as the "in-tree users only", and there is another special user among those: the selftests (see paste below). So if v3 is landed as posted, we now have two "levels" of in-tree users.
It's... fine, but not exciting. Adding libbpf_tools.h doesn't help that much, and dropping it doesn't hurt. It's all bikeshedding, not directly relevant to the series, ultimately caused by name collisions between resolve_btfids and libbpf (u32 poisoning and pr_* macros).
Quentin, Andrii, Eduard, please let me know if anyone has a strong preference here, I'm happy to respin. Thanks!
[1] https://lore.kernel.org/bpf/[email protected]/
$ grep -rl --include="*.[ch]" 'include.*libbpf_internal.h' tools/testing/selftests/bpf tools/testing/selftests/bpf/prog_tests/bpf_obj_pinning.c tools/testing/selftests/bpf/prog_tests/btf_field_iter.c tools/testing/selftests/bpf/prog_tests/btf_sanitize.c tools/testing/selftests/bpf/prog_tests/core_reloc_raw.c tools/testing/selftests/bpf/prog_tests/cpu_mask.c tools/testing/selftests/bpf/prog_tests/fill_link_info.c tools/testing/selftests/bpf/prog_tests/get_smp_processor_id.c tools/testing/selftests/bpf/prog_tests/global_data_init.c tools/testing/selftests/bpf/prog_tests/kprobe_multi_test.c tools/testing/selftests/bpf/prog_tests/kprobe_multi_testmod_test.c tools/testing/selftests/bpf/prog_tests/module_fentry_shadow.c tools/testing/selftests/bpf/prog_tests/perf_branches.c tools/testing/selftests/bpf/prog_tests/perf_buffer.c tools/testing/selftests/bpf/prog_tests/raw_tp_test_run.c tools/testing/selftests/bpf/prog_tests/recursive_attach.c tools/testing/selftests/bpf/prog_tests/sha256.c tools/testing/selftests/bpf/prog_tests/test_global_funcs.c tools/testing/selftests/bpf/prog_tests/uprobe_multi_test.c tools/testing/selftests/bpf/prog_tests/uprobe_syscall.c tools/testing/selftests/bpf/prog_tests/signed_loader.c tools/testing/selftests/bpf/prog_tests/tracing_multi.c tools/testing/selftests/bpf/urandom_read.c tools/testing/selftests/bpf/urandom_read_lib1.c tools/testing/selftests/bpf/trace_helpers.c
Quoted 17 lines
Signed-off-by Ihor Solodrai <[email protected]>--- tools/bpf/bpftool/Makefile | 6 +- tools/bpf/bpftool/common.c | 2 +- tools/bpf/bpftool/gen.c | 3 +- tools/bpf/bpftool/prog.c | 2 +- tools/bpf/bpftool/xlated_dumper.c | 2 +- tools/bpf/resolve_btfids/btf_colors.c | 15 +-- tools/bpf/resolve_btfids/btf_colors.h | 4 - tools/bpf/resolve_btfids/main.c | 5 +- tools/lib/bpf/libbpf_internal.h | 162 +---------------------- tools/lib/bpf/libbpf_tools.h | 184 ++++++++++++++++++++++++++ 10 files changed, 199 insertions(+), 186 deletions(-)create mode 100644
tools/lib/bpf/libbpf_tools.h[...]
Re: [PATCH bpf-next v3 1/6] libbpf: Separate interfaces shared with in-tree tools
Quoted 24 lines · Ihor Solodrai
Quoted 10 lines · Ihor Solodrai
resolve_btfidsand bpftool link libbpf statically and use some of its internal helpers fromlibbpf_internal.h. That header also defines logging macros and poisons kernel integer typedefs, soresolve_btfidswraps the SHA-256 helper in a separate source file.Move the declarations these tools use to
libbpf_tools.hand include it instead oflibbpf_internal.h. The header is for in-tree tools and stays uninstalled. No shared-library symbols change.No functional change.
I posted v3 with the refactoring as described in my comment [1].
However now I'm thinking it might be an overkill. With the re-design vs v1,
resolve_btfidsnow only needsbtf_kfunc_proto_match(), if it includesrelo_core.h, so the newlibbpf_tools.his not as appealing.Speaking of "API levels",
libbpf_internal.hhas already been functioning as the "in-tree users only", and there is another special user among those: the selftests (see paste below). So if v3 is landed as posted, we now have two "levels" of in-tree users.
Quoted 8 lines
It's... fine, but not exciting. Adding
libbpf_tools.hdoesn't help that much, and dropping it doesn't hurt. It's all bikeshedding, not directly relevant to the series, ultimately caused by name collisions betweenresolve_btfidsand libbpf (u32 poisoning and pr_* macros).Quentin, Andrii, Eduard, please let me know if anyone has a strong preference here, I'm happy to respin. Thanks!
heh, we raced to the minute. I don't like libbpf_tools.h approach, if GCC poison is a problem I'd rather guard that.
don't respin just yet, let Eduard do a pass at least
Quoted 48 lines
[1]
https://lore.kernel.org/bpf/[email protected]/$ grep -rl --include="*.[ch]" 'include.*libbpf_internal.h' tools/testing/selftests/bpf tools/testing/selftests/bpf/prog_tests/bpf_obj_pinning.c tools/testing/selftests/bpf/prog_tests/btf_field_iter.c tools/testing/selftests/bpf/prog_tests/btf_sanitize.c tools/testing/selftests/bpf/prog_tests/core_reloc_raw.c tools/testing/selftests/bpf/prog_tests/cpu_mask.c tools/testing/selftests/bpf/prog_tests/fill_link_info.c tools/testing/selftests/bpf/prog_tests/get_smp_processor_id.c tools/testing/selftests/bpf/prog_tests/global_data_init.c tools/testing/selftests/bpf/prog_tests/kprobe_multi_test.c tools/testing/selftests/bpf/prog_tests/kprobe_multi_testmod_test.c tools/testing/selftests/bpf/prog_tests/module_fentry_shadow.c tools/testing/selftests/bpf/prog_tests/perf_branches.c tools/testing/selftests/bpf/prog_tests/perf_buffer.c tools/testing/selftests/bpf/prog_tests/raw_tp_test_run.c tools/testing/selftests/bpf/prog_tests/recursive_attach.c tools/testing/selftests/bpf/prog_tests/sha256.c tools/testing/selftests/bpf/prog_tests/test_global_funcs.c tools/testing/selftests/bpf/prog_tests/uprobe_multi_test.c tools/testing/selftests/bpf/prog_tests/uprobe_syscall.c tools/testing/selftests/bpf/prog_tests/signed_loader.c tools/testing/selftests/bpf/prog_tests/tracing_multi.c tools/testing/selftests/bpf/urandom_read.c tools/testing/selftests/bpf/urandom_read_lib1.c tools/testing/selftests/bpf/trace_helpers.cQuoted 17 lines
Signed-off-by Ihor Solodrai <[email protected]>--- tools/bpf/bpftool/Makefile | 6 +- tools/bpf/bpftool/common.c | 2 +- tools/bpf/bpftool/gen.c | 3 +- tools/bpf/bpftool/prog.c | 2 +- tools/bpf/bpftool/xlated_dumper.c | 2 +- tools/bpf/resolve_btfids/btf_colors.c | 15 +-- tools/bpf/resolve_btfids/btf_colors.h | 4 - tools/bpf/resolve_btfids/main.c | 5 +- tools/lib/bpf/libbpf_internal.h | 162 +---------------------- tools/lib/bpf/libbpf_tools.h | 184 ++++++++++++++++++++++++++ 10 files changed, 199 insertions(+), 186 deletions(-)create mode 100644
tools/lib/bpf/libbpf_tools.h[...]
[email protected]
AI reviewRe: [PATCH bpf-next v3 1/6] libbpf: Separate interfaces shared with in-tree tools
In reply to Ihor SolodraiTL;DR: Design question: Andrii Nakryiko objected earlier to the new libbpf_tools.h header and preferred guarding the u32 poison pragmas in libbpf_internal.h; this version doesn't address that.
Quoted 1 line
libbpf: Separate interfaces shared with in-tree tools
TL;DR: Design question: Andrii Nakryiko objected earlier to the new libbpf_tools.h header and preferred guarding the u32 poison pragmas in libbpf_internal.h; this version doesn't address that.
tools/lib/bpf/libbpf_tools.h line 3
Quoted 9 lines
tools/lib/bpf/libbpf_tools.h new file +3
-0@@ -0,0 +1,184 @@ +/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ +#ifndef __LIBBPF_TOOLS_H +#define __LIBBPF_TOOLS_H
Andrii Nakryiko objected to introducing libbpf_tools.h in the v2 and v3 discussions. He prefers keeping these declarations in libbpf_internal.h and guarding the u32 poison pragmas with an #ifdef that resolve_btfids can disable:
I don't like libbpf_tools.h approach, if GCC poison is a problem I'd rather guard that.
The poisoning is the root cause in the commit message, and this version still adds the new header without a respin addressing that.
Should the poison pragmas in libbpf_internal.h be guarded instead of splitting out libbpf_tools.h?
---
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/45506767613
Ihor Solodrai
reviewerPATCH v3 2/6 sched_ext: Prefer ___v2 kfunc names in compat.bpf.h
In reply to Ihor Solodraicompat.bpf.h declares scx_bpf_dsq_insert___v2___compat and similar names. libbpf drops the last ___ suffix of a declaration and looks up the rest exactly, so these resolve the kernel's ___v2 kfuncs.
The next patch makes libbpf drop the last suffix of kernel function names too and select a variant by prototype. The ___v2___compat names then resolve nothing, and the wrappers silently fall back to the ___v1 kfuncs. For example, scx_bpf_dsq_move_to_local() drops enq_flags.
Try the ___v2 names first. libbpf with that patch resolves them by prototype. Older libbpf leaves them unresolved, because the unsuffixed kfunc has a different prototype, and still resolves the ___v2___compat names that follow.
__COMPAT_scx_bpf_reenqueue_local_from_anywhere() checks both names for the same reason.
--- tools/sched_ext/include/scx/compat.bpf.h | 48 +++++++++++++++++------- 1 file changed, 34 insertions(+), 14 deletions(-)
tools/sched_ext/include/scx/compat.bpf.h +34 -14
@@ -29,8 +29,10 @@ struct cgroup *scx_bpf_task_cgroup___new(struct task_struct *p) __ksym __weak;* scx_bpf_dispatch_from_dsq() and friends were added during v6.12 by * 4c30f5ce4f7a ("sched_ext: Implement scx_bpf_dispatch[_vtime]_from_dsq()"). * -* v7.1: scx_bpf_dsq_move_to_local___v2() to add @enq_flags. +* v7.1: scx_bpf_dsq_move_to_local___v2() to add @enq_flags. Older libbpf can +* resolve it only through the extra ___compat suffix. */ +bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags) __ksym __weak; bool scx_bpf_dsq_move_to_local___v2___compat(u64 dsq_id, u64 enq_flags) __ksym __weak; bool scx_bpf_dsq_move_to_local___v1(u64 dsq_id) __ksym __weak; void scx_bpf_dsq_move_set_slice___new(struct bpf_iter_scx_dsq *it__iter, u64 slice) __ksym __weak;
@@ -45,11 +47,13 @@ bool scx_bpf_dispatch_from_dsq___old(struct bpf_iter_scx_dsq *it__iter, struct t bool scx_bpf_dispatch_vtime_from_dsq___old(struct bpf_iter_scx_dsq *it__iter, struct task_struct *p, u64 dsq_id, u64 enq_flags) __ksym __weak;#define scx_bpf_dsq_move_to_local (dsq_id, enq_flags) \ - (bpf_ksym_exists(scx_bpf_dsq_move_to_local___v2___compat) ? \ - scx_bpf_dsq_move_to_local___v2___compat((dsq_id), (enq_flags)) : \ - (bpf_ksym_exists(scx_bpf_dsq_move_to_local___v1) ? \ - scx_bpf_dsq_move_to_local___v1((dsq_id)) : \ - scx_bpf_consume___old((dsq_id)))) + (bpf_ksym_exists(scx_bpf_dsq_move_to_local___v2) ? \ + scx_bpf_dsq_move_to_local___v2((dsq_id), (enq_flags)) : \ + (bpf_ksym_exists(scx_bpf_dsq_move_to_local___v2___compat) ? \ + scx_bpf_dsq_move_to_local___v2___compat((dsq_id), (enq_flags)) : \ + (bpf_ksym_exists(scx_bpf_dsq_move_to_local___v1) ? \ + scx_bpf_dsq_move_to_local___v1((dsq_id)) : \ + scx_bpf_consume___old((dsq_id)))))#define scx_bpf_dsq_move_set_slice (it__iter, slice) \ (bpf_ksym_exists(scx_bpf_dsq_move_set_slice___new) ? \
@@ -430,12 +434,13 @@ scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id, u64 slice, u64 vtime/* * v6.19: scx_bpf_dsq_insert() now returns bool instead of void. Move * scx_bpf_dsq_insert() decl to common.bpf.h and drop compat helper after v6.22. -* The extra ___compat suffix is to work around libbpf not ignoring __SUFFIX on -* kernel side. The entire suffix can be dropped later. +* Older libbpf can resolve scx_bpf_dsq_insert___v2() only through the extra +* ___compat suffix. * * v6.13: scx_bpf_dsq_insert() renaming is also handled here. See the block on * dispatch renaming above for more details. */ +bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id, u64 slice, u64 enq_flags) __ksym __weak; bool scx_bpf_dsq_insert___v2___compat(struct task_struct *p, u64 dsq_id, u64 slice, u64 enq_flags) __ksym __weak; void scx_bpf_dsq_insert___v1(struct task_struct *p, u64 dsq_id, u64 slice, u64 enq_flags) __ksym __weak; void scx_bpf_dispatch___compat(struct task_struct *p, u64 dsq_id, u64 slice, u64 enq_flags) __ksym __weak;
@@ -443,7 +448,9 @@ void scx_bpf_dispatch___compat(struct task_struct *p, u64 dsq_id, u64 slice, u64static inline bool scx_bpf_dsq_insert (struct task_struct *p,u64 dsq_id,u64 slice,u64 enq_flags) { -if (bpf_ksym_exists (scx_bpf_dsq_insert___v2___compat)) { +if (bpf_ksym_exists (scx_bpf_dsq_insert___v2)) { +return scx_bpf_dsq_insert___v2 (p, dsq_id, slice, enq_flags); + }else if (bpf_ksym_exists (scx_bpf_dsq_insert___v2___compat)) {return scx_bpf_dsq_insert___v2___compat (p, dsq_id, slice, enq_flags); }else if (bpf_ksym_exists (scx_bpf_dsq_insert___v1)) {scx_bpf_dsq_insert___v1 (p, dsq_id, slice, enq_flags);
@@ -506,23 +513,32 @@ static inline bool __COMPAT_has_dsq_reenq_task(void)/* * v6.19: The new void variant can be called from anywhere while the older v1 -* variant can only be called from ops.cpu_release(). The double ___ prefixes on -* the v2 variant need to be removed once libbpf is updated to ignore ___ prefix -* on kernel side. Drop the wrapper and move the decl to common.bpf.h after -* v6.22. +* variant can only be called from ops.cpu_release(). Older libbpf can resolve +* the v2 variant only through the extra ___compat suffix. Drop the wrapper and +* move the decl to common.bpf.h after v6.22. */ u32 scx_bpf_reenqueue_local___v1(void) __ksym __weak; +void scx_bpf_reenqueue_local___v2(void) __ksym __weak; void scx_bpf_reenqueue_local___v2___compat(void) __ksym __weak;static inline bool __COMPAT_scx_bpf_reenqueue_local_from_anywhere (void ) { -return bpf_ksym_exists (scx_bpf_reenqueue_local___v2___compat); +bool v2 =bpf_ksym_exists (scx_bpf_reenqueue_local___v2); + +/* +* Without the barrier, clang folds || into a bitwise OR of the two ksym +* addresses, which the verifier rejects. +*/ +barrier_var (v2); +return v2 ||bpf_ksym_exists (scx_bpf_reenqueue_local___v2___compat); }static inline void scx_bpf_reenqueue_local (void ) {if (__COMPAT_has_generic_reenq ())scx_bpf_dsq_reenq___compat (SCX_DSQ_LOCAL ,0 ); +else if (bpf_ksym_exists (scx_bpf_reenqueue_local___v2)) +scx_bpf_reenqueue_local___v2 ();else if (__COMPAT_scx_bpf_reenqueue_local_from_anywhere ())scx_bpf_reenqueue_local___v2___compat ();else
@@ -541,6 +557,10 @@ static inline int scx_bpf_reenqueue_local_from_anywhere(void)scx_bpf_dsq_reenq___compat (SCX_DSQ_LOCAL ,0 );return 0 ; } +if (bpf_ksym_exists (scx_bpf_reenqueue_local___v2)) { +scx_bpf_reenqueue_local___v2 (); +return 0 ; + }if (__COMPAT_scx_bpf_reenqueue_local_from_anywhere ()) {scx_bpf_reenqueue_local___v2___compat ();return 0 ;
Signature · 1 line
2.56.0
Ihor Solodrai
reviewerPATCH v3 3/6 libbpf: Resolve kfunc variants by prototype
In reply to Ihor Solodrailibbpf resolves a kfunc declaration by exact name, after dropping its last ___ suffix, and only then checks the prototype. The name alone picks the kernel function, so the kernel can't serve both prototypes of a changed kfunc. For example, vmlinux.h declares:
bool scx_bpf_dsq_move_to_local(u64 dsq_id); bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags);
libbpf resolves the second to scx_bpf_dsq_move_to_local() and rejects its prototype. Keeping the old prototype as ___v1 and giving the new one the unsuffixed name would break old declarations the same way.
Select a kfunc in two steps instead:
1. Collect the functions in vmlinux and module BTFs with the same essential name as the declaration, as CO-RE does for types. The "bpf_kfunc" decl tag is ignored.
2. Resolve the candidate with a compatible prototype. If there is none, a __weak kfunc stays unresolved. More than one is an error, even for a __weak kfunc.
The prototype check is stricter than bpf_core_types_are_compat(). It also compares the names of structs, unions and forward declarations, ignoring ___ suffixes. Members aren't compared. Typedefs and qualifiers are skipped. For example:
typedef struct foo foo_t;
void kfunc(struct foo *arg); void kfunc(struct foo___local *arg); void kfunc(foo_t *arg);
are compatible, but not with:
void kfunc(struct bar *arg);
So a declaration with an outdated struct name no longer resolves. For example, commit 8740156ad33b ("bpf: Require a BPF cpumask for bpf_cpumask_populate()") changed:
before: int bpf_cpumask_populate(struct cpumask *, void *, size_t); after: int bpf_cpumask_populate(struct bpf_cpumask *, void *, size_t);
Each declaration now resolves only on a kernel with the same prototype. A stacked suffix, as in foo___v2___compat, no longer resolves foo___v2, because its essential name is foo___v2. compat.bpf.h now tries foo___v2 first.
Module BTFs are now loaded for every object with kfuncs: 0.5 and 1.4 ms for 8 and 32 small modules in a VM. Lookup cost per kfunc:
before (hit / miss) after sorted, 23 modules 0.14 / 0.65 us 0.8 us unsorted (v6.18) 0.1 / 0.5 ms 0.7 ms
--- tools/lib/bpf/btf.c | 99 +++++++++++++++++++++++++++- tools/lib/bpf/libbpf.c | 112 ++++++++++++++++++++++---------- tools/lib/bpf/libbpf_internal.h | 2 + tools/lib/bpf/libbpf_tools.h | 2 + 4 files changed, 178 insertions(+), 37 deletions(-)
tools/lib/bpf/btf.c +96 -3
@@ -1140,7 +1140,7 @@ static void btf_check_sorted(struct btf *btf) }static __s32 btf_find_type_by_name_bsearch (const struct btf *btf,const char *name, -__s32 start_id) +size_t name_len,__s32 start_id) {const struct btf_type *t;const char *tname;
@@ -1152,7 +1152,7 @@ static __s32 btf_find_type_by_name_bsearch(const struct btf *btf, const char *na m = l + (r - l) /2 ; t =btf_type_by_id (btf, m); tname =btf__str_by_offset (btf, t->name_off); -if (strcmp (tname, name) >=0 ) { +if (strncmp (tname, name, name_len) >=0 ) {if (l == r)return r; r = m;
@@ -1164,6 +1164,99 @@ static __s32 btf_find_type_by_name_bsearch(const struct btf *btf, const char *nareturn btf__type_cnt (btf); } +/* +* Set [*start, *end) to the range of own type IDs that may match the +* first name_len bytes of name. For unsorted BTF, include all own type IDs. +*/ +void btf_name_prefix_range (const struct btf *btf,const char *name,size_t name_len, +__u32 *start,__u32 *end) +{ +__u32 i, n =btf__type_cnt (btf); + +if (btf->named_start_id <=0 ) { + *start = btf->start_id; + *end = n; +return ; + } + *start =btf_find_type_by_name_bsearch (btf, name, name_len, btf->named_start_id); +for (i = *start; i < n; i++) { +const struct btf_type *t =btf_type_by_id (btf, i); +const char *tname =btf__str_by_offset (btf, t->name_off); + +if (strncmp (tname, name, name_len) !=0 ) +break ; + } + *end = i; +} + +static __u16 kfunc_type_kind (const struct btf_type *t) +{ +if (btf_is_fwd (t)) +return btf_kflag (t) ?BTF_KIND_UNION :BTF_KIND_STRUCT ; +if (btf_is_enum64 (t)) +return BTF_KIND_ENUM ; +return btf_kind (t); +} + +/* +* Return 1 if the types match, 0 if they don't, or -EINVAL if a type +* can't be looked up or the types nest deeper than depth. +*/ +static int kfunc_type_match (const struct btf *a,__u32 a_id, +const struct btf *b,__u32 b_id,int depth) +{ +const struct btf_type *at =skip_mods_and_typedefs (a, a_id,NULL ); +const struct btf_type *bt =skip_mods_and_typedefs (b, b_id,NULL ); +__u16 kind; +int i, ret; + +if (!at || !bt || !depth) +return -EINVAL ; + + kind =kfunc_type_kind (at); +if (kind !=kfunc_type_kind (bt)) +return 0 ; + +switch (kind) { +case BTF_KIND_STRUCT : +case BTF_KIND_UNION : { +const char *an =btf__name_by_offset (a, at->name_off); +const char *bn =btf__name_by_offset (b, bt->name_off); +size_t name_len =bpf_core_essential_name_len (an); + +return name_len ==bpf_core_essential_name_len (bn) && +strncmp (an, bn, name_len) ==0 ; + } +case BTF_KIND_UNKN : +case BTF_KIND_ENUM : +return 1 ; +case BTF_KIND_INT : +return btf_int_offset (at) ==0 &&btf_int_offset (bt) ==0 ; +case BTF_KIND_PTR : +return kfunc_type_match (a, at->type, b, bt->type, depth -1 ); +case BTF_KIND_ARRAY : +return kfunc_type_match (a,btf_array (at)->type, b,btf_array (bt)->type, depth -1 ); +case BTF_KIND_FUNC_PROTO : +if (btf_vlen (at) !=btf_vlen (bt)) +return 0 ; +for (i =0 ; i <btf_vlen (at); i++) { + ret =kfunc_type_match (a,btf_params (at)[i].type, + b,btf_params (bt)[i].type, depth -1 ); +if (ret <=0 ) +return ret; + } +return kfunc_type_match (a, at->type, b, bt->type, depth -1 ); +default : +return 0 ; + } +} + +int btf_kfunc_proto_match (const struct btf *a,__u32 a_id, +const struct btf *b,__u32 b_id) +{ +return kfunc_type_match (a, a_id, b, b_id,32 ); +} +static __s32 btf_find_by_name_kind (const struct btf *btf,int start_id,const char *type_name,__s32 kind) {
@@ -1185,7 +1278,7 @@ static __s32 btf_find_by_name_kind(const struct btf *btf, int start_id,if (btf->named_start_id >0 && type_name[0 ]) { start_id =max (start_id, btf->named_start_id); - id =btf_find_type_by_name_bsearch (btf, type_name, start_id); + id =btf_find_type_by_name_bsearch (btf, type_name,strlen (type_name), start_id);for (; id < nr_types; id++) { t =btf__type_by_id (btf, id); tname =btf__str_by_offset (btf, t->name_off);
tools/lib/bpf/libbpf.c +78 -34
165 lines not on this page · raw message
tools/lib/bpf/libbpf_internal.h +2 -0
@@ -215,6 +215,8 @@ struct btf_type *btf_type_by_id(const struct btf *btf, __u32 type_id);void btf_set_base_btf (struct btf *btf,const struct btf *base_btf);int btf_relocate (struct btf *btf,const struct btf *base_btf,__u32 **id_map,__u32 **str_map); +void btf_name_prefix_range (const struct btf *btf,const char *name,size_t name_len, +__u32 *start,__u32 *end);bool btf_type_is_traceable_func (const struct btf *btf,const struct btf_type *t);static inline enum btf_func_linkage btf_func_linkage (const struct btf_type *t)
tools/lib/bpf/libbpf_tools.h +2 -0
@@ -52,6 +52,8 @@ struct bpf_core_cand;struct bpf_core_cand_list ;const struct btf_header *btf_header (const struct btf *btf); +int btf_kfunc_proto_match (const struct btf *a,__u32 a_id, +const struct btf *b,__u32 b_id);const char *btf_kind_str (const struct btf_type *t);const struct btf_type *skip_mods_and_typedefs (const struct btf *btf,__u32 id,__u32 *res_id);
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH bpf-next v3 3/6] libbpf: Resolve kfunc variants by prototype
TL;DR: The stricter struct-name check in libbpf kfunc resolution may make programs using UAPI aliases (e.g. struct __sk_buff in bpf_dynptr_from_skb) fail to load with -EINVAL on v6.3-v6.10 kernels.
Quoted 1 line
libbpf: Resolve kfunc variants by prototype
TL;DR: The stricter struct-name check in libbpf kfunc resolution may make programs using UAPI aliases (e.g. struct __sk_buff in bpf_dynptr_from_skb) fail to load with -EINVAL on v6.3-v6.10 kernels.
Quoted 3 lines
tools/lib/bpf/btf.c +0
-0
[ ... ]
Quoted 3 lines
tools/lib/bpf/btf.c +3
-0+static int kfunc_type_match (const struct btf *a,__u32 a_id, +const struct btf *b,__u32 b_id,int depth) +{
[ ... ]
tools/lib/bpf/btf.c static __s32 btf_find_type_by_name_bsearch(const struct btf *btf, const char *na · line 1229
Quoted 10 lines
tools/lib/bpf/btf.c +10
-0+switch (kind) { +case BTF_KIND_STRUCT : +case BTF_KIND_UNION : { +const char *an =btf__name_by_offset (a, at->name_off); +const char *bn =btf__name_by_offset (b, bt->name_off); +size_t name_len =bpf_core_essential_name_len (an); + +return name_len ==bpf_core_essential_name_len (bn) && +strncmp (an, bn, name_len) ==0 ; + }
Can this break loading of existing programs on older kernels? Before this patch, bpf_object__resolve_ksym_func_btf_id() used bpf_core_types_are_compat(), which treats any two structs as compatible without comparing names.
Until commit cce4c40b9606 ("bpf: treewide: Align kfunc signatures to prog point-of-view"), several kfuncs were defined with kernel-facing types, while BPF programs declared them with UAPI types:
-__bpf_kfunc int bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags, -__bpf_kfunc int bpf_dynptr_from_xdp(struct xdp_buff *xdp, u64 flags, -__bpf_kfunc int bpf_dynptr_adjust(struct bpf_dynptr_kern *ptr, u32 start, u32 end) -__bpf_kfunc int bpf_verify_pkcs7_signature(struct bpf_dynptr_kern *data_ptr,
and tools/testing/selftests/bpf/bpf_kfuncs.h still has:
extern int bpf_dynptr_from_skb(struct __sk_buff *skb, __u64 flags,
struct bpf_dynptr *ptr__uninit) __ksym;
The commit message of cce4c40b9606 says "It wasn't an issue before, as the verifier allows aliased types." A vmlinux.h generated on v6.11 or later declares them the same way.
On a v6.3 to v6.10 kernel, this now goes:
bpf_object__resolve_ksym_func_btf_id()
-> find_kfunc_btf_id(): one candidate, bpf_dynptr_from_skb
-> btf_kfunc_proto_match() -> kfunc_type_match(FUNC_PROTO)
-> param 0: PTR -> STRUCT "__sk_buff" vs STRUCT "sk_buff"
essential name lengths 9 != 7 -> return 0
-> nr_cands == 1, kfunc_id == 0 -> return -EINVALso bpf_object__load() fails with -EINVAL, where the old code resolved the same declaration on the same kernel. For a __weak declaration the kfunc now stays unresolved silently, so bpf_ksym_exists() is false on kernels that do provide the kfunc.
The commit message says "a declaration with an outdated struct name no longer resolves" and uses bpf_cpumask_populate() as the example. There the kernel changed which type it accepts. Here the declaration is not
outdated: it uses the UAPI alias that the verifier accepts on those kernels.
Nothing later in the series (ea0b8db17e5e, 7848a838c614, 88fb7cd2ca9c) seems to handle these aliases. Will existing binaries that load today on still-supported LTS kernels start failing after a libbpf upgrade?
---
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/45506767613
Re: [PATCH bpf-next v3 3/6] libbpf: Resolve kfunc variants by prototype
In reply to Ihor SolodraiQuoted 50 lines · Ihor Solodrai
libbpf resolves a kfunc declaration by exact name, after dropping its last ___ suffix, and only then checks the prototype. The name alone picks the kernel function, so the kernel can't serve both prototypes of a changed kfunc. For example,
vmlinux.hdeclares:bool scx_bpf_dsq_move_to_local(u64 dsq_id); bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags);libbpf resolves the second to
scx_bpf_dsq_move_to_local()and rejects its prototype. Keeping the old prototype as___v1and giving the new one the unsuffixed name would break old declarations the same way.Select a kfunc in two steps instead:
1. Collect the functions in vmlinux and module BTFs with the same essential name as the declaration, as CO-RE does for types. The "
bpf_kfunc" decl tag is ignored.2. Resolve the candidate with a compatible prototype. If there is none, a
__weakkfunc stays unresolved. More than one is an error, even for a__weakkfunc.The prototype check is stricter than
bpf_core_types_are_compat(). It also compares the names of structs, unions and forward declarations, ignoring ___ suffixes. Members aren't compared. Typedefs and qualifiers are skipped. For example:typedef struct foo
foo_t;void kfunc(struct foo *arg); void kfunc(struct foo___local *arg); void kfunc(foo_t *arg);are compatible, but not with:
void kfunc(struct bar *arg);So a declaration with an outdated struct name no longer resolves. For example, commit
8740156ad33b("bpf: Require a BPF cpumask forbpf_cpumask_populate()") changed:before: int bpf_cpumask_populate(struct cpumask *, void *, size_t); after: int bpf_cpumask_populate(struct bpf_cpumask *, void *, size_t);Each declaration now resolves only on a kernel with the same prototype. A stacked suffix, as in
foo___v2___compat, no longer resolvesfoo___v2, because its essential name isfoo___v2.compat.bpf.hnow triesfoo___v2first.
Quoted 6 lines
Module BTFs are now loaded for every object with kfuncs: 0.5 and 1.4 ms for 8 and 32 small modules in a VM. Lookup cost per kfunc:
before (hit / miss) after sorted, 23 modules 0.14 / 0.65 us 0.8 us unsorted (v6.18) 0.1 / 0.5 ms 0.7 ms
for CO-RE relocations, when we search for candidate types, I think we follow a different logic: if we find at least one candidate in vmlinux BTF, we don't go searching for module BTF. See bpf_core_find_cands(). I think we should try doing the same here, instead of potentially opening tons of irrelevant BTFs.
So far this logic worked adequately, I think for kfuncs it will be good enough as well. We can still support case where module provides a newer kfunc version, in this case we won't find any matching candidate in vmlinux, then will continue looking for candidates across modules, right?
pw-bot: cr
Quoted 345 lines
Signed-off-by Ihor Solodrai <[email protected]>--- tools/lib/bpf/btf.c | 99 +++++++++++++++++++++++++++- tools/lib/bpf/libbpf.c | 112 ++++++++++++++++++++++---------- tools/lib/bpf/libbpf_internal.h | 2 + tools/lib/bpf/libbpf_tools.h | 2 + 4 files changed, 178 insertions(+), 37 deletions(-)tools/lib/bpf/btf.c +96
-3@@ -1140,7 +1140,7 @@ static void btf_check_sorted(struct btf *btf) }static __s32 btf_find_type_by_name_bsearch (const struct btf *btf,const char *name, -__s32 start_id) +size_t name_len,__s32 start_id) {const struct btf_type *t;const char *tname;@@ -1152,7 +1152,7 @@ static __s32 btf_find_type_by_name_bsearch(const struct btf *btf, const char *na m = l + (r - l) /2 ; t =btf_type_by_id (btf, m); tname =btf__str_by_offset (btf, t->name_off); -if (strcmp (tname, name) >=0 ) { +if (strncmp (tname, name, name_len) >=0 ) {if (l == r)return r; r = m;@@ -1164,6 +1164,99 @@ static __s32 btf_find_type_by_name_bsearch(const struct btf *btf, const char *nareturn btf__type_cnt (btf); } +/* +* Set [*start, *end) to the range of own type IDs that may match the +* first name_len bytes of name. For unsorted BTF, include all own type IDs. +*/ +void btf_name_prefix_range (const struct btf *btf,const char *name,size_t name_len, +__u32 *start,__u32 *end) +{ +__u32 i, n =btf__type_cnt (btf); + +if (btf->named_start_id <=0 ) { + *start = btf->start_id; + *end = n; +return ; + } + *start =btf_find_type_by_name_bsearch (btf, name, name_len, btf->named_start_id); +for (i = *start; i < n; i++) { +const struct btf_type *t =btf_type_by_id (btf, i); +const char *tname =btf__str_by_offset (btf, t->name_off); + +if (strncmp (tname, name, name_len) !=0 ) +break ; + } + *end = i; +} + +static __u16 kfunc_type_kind (const struct btf_type *t) +{ +if (btf_is_fwd (t)) +return btf_kflag (t) ?BTF_KIND_UNION :BTF_KIND_STRUCT ; +if (btf_is_enum64 (t)) +return BTF_KIND_ENUM ; +return btf_kind (t); +} + +/* +* Return 1 if the types match, 0 if they don't, or -EINVAL if a type +* can't be looked up or the types nest deeper than depth. +*/ +static int kfunc_type_match (const struct btf *a,__u32 a_id, +const struct btf *b,__u32 b_id,int depth) +{ +const struct btf_type *at =skip_mods_and_typedefs (a, a_id,NULL ); +const struct btf_type *bt =skip_mods_and_typedefs (b, b_id,NULL ); +__u16 kind; +int i, ret; + +if (!at || !bt || !depth) +return -EINVAL ; + + kind =kfunc_type_kind (at); +if (kind !=kfunc_type_kind (bt)) +return 0 ; + +switch (kind) { +case BTF_KIND_STRUCT : +case BTF_KIND_UNION : { +const char *an =btf__name_by_offset (a, at->name_off); +const char *bn =btf__name_by_offset (b, bt->name_off); +size_t name_len =bpf_core_essential_name_len (an); + +return name_len ==bpf_core_essential_name_len (bn) && +strncmp (an, bn, name_len) ==0 ; + } +case BTF_KIND_UNKN : +case BTF_KIND_ENUM : +return 1 ; +case BTF_KIND_INT : +return btf_int_offset (at) ==0 &&btf_int_offset (bt) ==0 ; +case BTF_KIND_PTR : +return kfunc_type_match (a, at->type, b, bt->type, depth -1 ); +case BTF_KIND_ARRAY : +return kfunc_type_match (a,btf_array (at)->type, b,btf_array (bt)->type, depth -1 ); +case BTF_KIND_FUNC_PROTO : +if (btf_vlen (at) !=btf_vlen (bt)) +return 0 ; +for (i =0 ; i <btf_vlen (at); i++) { + ret =kfunc_type_match (a,btf_params (at)[i].type, + b,btf_params (bt)[i].type, depth -1 ); +if (ret <=0 ) +return ret; + } +return kfunc_type_match (a, at->type, b, bt->type, depth -1 ); +default : +return 0 ; + } +} + +int btf_kfunc_proto_match (const struct btf *a,__u32 a_id, +const struct btf *b,__u32 b_id) +{ +return kfunc_type_match (a, a_id, b, b_id,32 ); +} +static __s32 btf_find_by_name_kind (const struct btf *btf,int start_id,const char *type_name,__s32 kind) {@@ -1185,7 +1278,7 @@ static __s32 btf_find_by_name_kind(const struct btf *btf, int start_id,if (btf->named_start_id >0 && type_name[0 ]) { start_id =max (start_id, btf->named_start_id); - id =btf_find_type_by_name_bsearch (btf, type_name, start_id); + id =btf_find_type_by_name_bsearch (btf, type_name,strlen (type_name), start_id);for (; id < nr_types; id++) { t =btf__type_by_id (btf, id); tname =btf__str_by_offset (btf, t->name_off);tools/lib/bpf/libbpf.c +78
-34@@ -641,7 +641,6 @@ struct extern_desc {int btf_id;int sec_btf_id;char *name; -char *essent_name;bool is_set;bool is_weak;union {@@ -4446,7 +4445,6 @@ static int bpf_object__collect_externs(struct bpf_object *obj)struct extern_desc *ext;int i, n, off, dummy_var_btf_id;const char *ext_name, *sec_name; -size_t ext_essent_len;Elf_Scn *scn;Elf64_Shdr *sh;@@ -4498,14 +4496,6 @@ static int bpf_object__collect_externs(struct bpf_object *obj) ext->sym_idx = i; ext->is_weak =ELF64_ST_BIND (sym->st_info) ==STB_WEAK ; - ext_essent_len =bpf_core_essential_name_len (ext->name); - ext->essent_name =NULL ; -if (ext_essent_len !=strlen (ext->name)) { - ext->essent_name =strndup (ext->name, ext_essent_len); -if (!ext->essent_name) -return -ENOMEM ; - } - ext->sec_btf_id =find_extern_sec_btf_id (obj->btf, ext->btf_id);if (ext->sec_btf_id <=0 ) { pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",@@ -9513,41 +9503,96 @@ static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,return 0 ; } +/* t is a FUNC whose essential name is the first name_len bytes of name */ +static bool btf_is_kfunc_candidate (const struct btf *btf,const struct btf_type *t, +const char *name,size_t name_len) +{ +const char *tname; + +if (!btf_is_func (t)) +return false; + tname =btf__name_by_offset (btf, t->name_off); +if (strncmp (tname, name, name_len) !=0 ) +return false; +return bpf_core_essential_name_len (tname) == name_len; +} + +/* +* Search vmlinux and module BTFs. Return: +* - a BTF ID for a unique match; +* - -ESRCH if the family is absent; +* - -EINVAL if no candidate has a compatible prototype; +* - -ENOTUNIQ if more than one candidate has a compatible prototype. +*/ +static int find_kfunc_btf_id (struct bpf_object *obj,const struct extern_desc *ext, +struct btf **res_btf,struct module_btf **res_mod_btf) +{ +size_t name_len =bpf_core_essential_name_len (ext->name); +int kfunc_id =0 , nr_cands =0 ; +size_t i; + +for (i =0 ; i <= obj->btf_module_cnt; i++) { +struct module_btf *mod = i ? &obj->btf_modules[i -1 ] :NULL ; +struct btf *btf = mod ? mod->btf : obj->btf_vmlinux; +__u32 id, end; + +btf_name_prefix_range (btf, ext->name, name_len, &id, &end); +for (; id < end; id++) { +const struct btf_type *t =btf__type_by_id (btf, id); + +if (!btf_is_kfunc_candidate (btf, t, ext->name, name_len)) +continue ; + nr_cands++; +if (btf_kfunc_proto_match (obj->btf, ext->ksym.type_id, btf, t->type) <=0 ) +continue ; +if (kfunc_id) +return -ENOTUNIQ ; + kfunc_id = id; + *res_btf = btf; + *res_mod_btf = mod; + } + } +if (!nr_cands) +return -ESRCH ; +if (!kfunc_id) +return -EINVAL ; +return kfunc_id; +} +static int bpf_object__resolve_ksym_func_btf_id (struct bpf_object *obj,struct extern_desc *ext) { -int local_func_proto_id, kfunc_proto_id, kfunc_id;struct module_btf *mod_btf =NULL ;const struct btf_type *kern_func;struct btf *kern_btf =NULL ; -int ret; +int kfunc_id, ret; - local_func_proto_id = ext->ksym.type_id; + ret =load_module_btfs (obj); +if (ret) +return ret; - kfunc_id =find_ksym_btf_id (obj, ext->essent_name ?: ext->name,BTF_KIND_FUNC , &kern_btf, - &mod_btf); -if (kfunc_id <0 ) { -if (kfunc_id == -ESRCH && ext->is_weak) + kfunc_id =find_kfunc_btf_id (obj, ext, &kern_btf, &mod_btf); +if (kfunc_id == -ESRCH ) { +if (ext->is_weak)return 0 ;pr_warn ("extern (func ksym) '%s': not found in kernel or module BTFs\n" , ext->name);return kfunc_id; } - - kern_func =btf__type_by_id (kern_btf, kfunc_id); - kfunc_proto_id = kern_func->type; - - ret =bpf_core_types_are_compat (obj->btf, local_func_proto_id, - kern_btf, kfunc_proto_id); -if (ret <=0 ) { +if (kfunc_id == -EINVAL ) {if (ext->is_weak)return 0 ; - -pr_warn ("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n" , - ext->name, local_func_proto_id, - mod_btf ? mod_btf->name :"vmlinux" , kfunc_proto_id); -return -EINVAL ; +pr_warn ("extern (func ksym) '%s': no compatible prototype in kernel or module BTFs\n" , + ext->name); +return kfunc_id; } +/* an error even for a weak kfunc: ambiguity isn't absence */ +if (kfunc_id == -ENOTUNIQ ) { +pr_warn ("extern (func ksym) '%s': more than one compatible prototype in kernel or module BTFs\n" , + ext->name); +return kfunc_id; + } + kern_func =btf__type_by_id (kern_btf, kfunc_id);/* set index for module BTF fd in fd_array, if unset */ if (mod_btf && !mod_btf->fd_array_idx) {@@ -9579,8 +9624,9 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,* {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64. */ ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd :0 ; -pr_debug ("extern (func ksym) '%s': resolved to %s [%d]\n" , - ext->name, mod_btf ? mod_btf->name :"vmlinux" , kfunc_id); +pr_debug ("extern (func ksym) '%s': resolved to %s '%s' [%d]\n" , + ext->name, mod_btf ? mod_btf->name :"vmlinux" , +btf__name_by_offset (kern_btf, kern_func->name_off), kfunc_id);return 0 ; }@@ -10441,10 +10487,8 @@ void bpf_object__close(struct bpf_object *obj)zfree (&obj->btf_custom_path);zfree (&obj->kconfig); -for (i =0 ; i < obj->nr_extern; i++) { +for (i =0 ; i < obj->nr_extern; i++)zfree (&obj->externs[i].name); -zfree (&obj->externs[i].essent_name); - }zfree (&obj->externs); obj->nr_extern =0 ;tools/lib/bpf/libbpf_internal.h +2
-0@@ -215,6 +215,8 @@ struct btf_type *btf_type_by_id(const struct btf *btf, __u32 type_id);void btf_set_base_btf (struct btf *btf,const struct btf *base_btf);int btf_relocate (struct btf *btf,const struct btf *base_btf,__u32 **id_map,__u32 **str_map); +void btf_name_prefix_range (const struct btf *btf,const char *name,size_t name_len, +__u32 *start,__u32 *end);bool btf_type_is_traceable_func (const struct btf *btf,const struct btf_type *t);static inline enum btf_func_linkage btf_func_linkage (const struct btf_type *t)tools/lib/bpf/libbpf_tools.h +2
-1@@ -52,6 +52,8 @@ struct bpf_core_cand;struct bpf_core_cand_list ;const struct btf_header *btf_header (const struct btf *btf); +int btf_kfunc_proto_match (const struct btf *a,__u32 a_id, +const struct btf *b,__u32 b_id);const char *btf_kind_str (const struct btf_type *t);const struct btf_type *skip_mods_and_typedefs (const struct btf *btf,__u32 id,__u32 *res_id); --2.56.0
Ihor Solodrai
reviewerPATCH v3 4/6 selftests/bpf: Test kfunc variant selection by prototype
In reply to Ihor SolodraiRegister two kfunc variants in bpf_testmod that differ only in a struct pointee:
int bpf_kfunc_variant(struct task_struct *p); int bpf_kfunc_variant___v2(struct file *p);
Check that a declaration of each resolves to it, and that a __weak declaration with struct inode * stays unresolved.
--- .../selftests/bpf/prog_tests/verifier.c | 3 ++ .../selftests/bpf/progs/kfunc_variants.c | 32 +++++++++++++++++++ .../selftests/bpf/test_kmods/bpf_testmod.c | 12 +++++++ .../bpf/test_kmods/bpf_testmod_kfunc.h | 3 ++ 4 files changed, 50 insertions(+) create mode 100644 tools/testing/selftests/bpf/progs/kfunc_variants.c
tools/testing/selftests/bpf/prog_tests/verifier.c +3 -0
@@ -8,6 +8,7 @@#include "cap_helpers.h" #include "sysctl_helpers.h" #include "cb_refs.skel.h" +#include "kfunc_variants.skel.h" #include "verifier_aggregate_arg.skel.h" #include "verifier_aggregate_ret.skel.h" #include "verifier_alu_range.skel.h"
@@ -225,6 +226,8 @@ void test_arena_kfunc_jit(void) { RUN_TESTS(arena_kfunc_jit); }void test_cb_refs (void ) {RUN_TESTS (cb_refs); } +void test_kfunc_variants (void ) {RUN_TESTS (kfunc_variants); } +void test_verifier_aggregate_arg (void ) {RUN_TESTS (verifier_aggregate_arg); }void test_verifier_aggregate_ret (void ) {RUN_TESTS (verifier_aggregate_ret); }void test_verifier_alu_range (void ) {RUN (verifier_alu_range); }
tools/testing/selftests/bpf/progs/kfunc_variants.c new file +32 -0
@@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */ + +#include <vmlinux.h> +#include <bpf/bpf_helpers.h> +#include "bpf_misc.h" +#include "../test_kmods/bpf_testmod_kfunc.h" + +extern int bpf_kfunc_variant___none(struct inode *p) __weak __ksym; + +char _license[] SEC("license") = "GPL"; + +SEC("syscall") +__retval(1) +int unsuffixed_name (void *ctx) +{ +return bpf_kfunc_variant (NULL ); +} + +SEC("syscall") +__retval(2) +int kernel_variant (void *ctx) +{ +return bpf_kfunc_variant___v2 (NULL ); +} + +SEC("syscall") +__retval(0) +int no_match (void *ctx) +{ +return bpf_ksym_exists (bpf_kfunc_variant___none); +}
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +12 -0
@@ -1928,6 +1928,16 @@ __bpf_kfunc void bpf_kfunc_trigger_ctx_check(void)irq_work_queue (&ctx_check_irq); } +__bpf_kfunc int bpf_kfunc_variant(struct task_struct *p__nullable) +{ +return 1 ; +} + +__bpf_kfunc int bpf_kfunc_variant___v2(struct file *p__nullable) +{ +return 2 ; +} + BTF_KFUNCS_START(bpf_testmod_check_kfunc_ids) BTF_ID_FLAGS(func, bpf_testmod_test_mod_kfunc, KF_SPINLOCK_SAFE) BTF_ID_FLAGS(func, bpf_kfunc_call_test1)
@@ -2019,6 +2029,8 @@ BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy_impl) BTF_ID_FLAGS(func, bpf_kfunc_trigger_ctx_check) +BTF_ID_FLAGS(func, bpf_kfunc_variant) +BTF_ID_FLAGS(func, bpf_kfunc_variant___v2)BTF_KFUNCS_END (bpf_testmod_check_kfunc_ids) static int bpf_testmod_ops_init(struct btf *btf)
tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h +3 -0
@@ -381,4 +381,7 @@ void bpf_testmod_test_hardirq_fn(void);void bpf_testmod_test_softirq_fn (void ); void bpf_kfunc_trigger_ctx_check(void) __ksym; +int bpf_kfunc_variant(struct task_struct *p__nullable) __ksym; +int bpf_kfunc_variant___v2(struct file *p__nullable) __ksym; +#endif /* _BPF_TESTMOD_KFUNC_H */
Signature · 1 line
2.56.0
Ihor Solodrai
reviewerPATCH v3 5/6 resolve_btfids: Reject ambiguous kfunc variants
In reply to Ihor Solodrailibbpf fails to load a program if a kfunc declaration matches more than one kfunc variant. For example, libbpf doesn't distinguish integer widths, so a declaration of either of these matches both:
int bpf_foo(u32 flags); int bpf_foo___v1(u64 flags);
Check the kfuncs registered in vmlinux or a module at build time, so that such a pair fails the build instead. Group them by essential name and compare prototypes with libbpf's matcher. Skip unregistered functions, which libbpf also considers, so that code unrelated to kfuncs can't fail the build. Variants split across modules or vmlinux are also caught only by libbpf.
--- tools/bpf/resolve_btfids/main.c | 69 +++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)
tools/bpf/resolve_btfids/main.c +69 -0
@@ -94,6 +94,7 @@#include <bpf/btf.h> #include <bpf/libbpf.h> #include <bpf/libbpf_tools.h> +#include <bpf/relo_core.h> #include "btf_colors.h" #include "fmodret.h" #include <subcmd/parse-options.h>
@@ -1918,6 +1919,70 @@ static int sort_btf_by_name(struct btf *btf)return err; } +struct kfunc_variant { +const char *name; +size_t essent_len; +u32 id; +}; + +static int cmp_kfunc_variants (const void *lhs,const void *rhs) +{ +const struct kfunc_variant *a = lhs, *b = rhs; +int ret =strncmp (a->name, b->name,min (a->essent_len, b->essent_len)); + +return ret ?: (a->essent_len > b->essent_len) - (a->essent_len < b->essent_len); +} + +/* libbpf rejects a declaration that matches more than one kfunc variant */ +static int check_kfunc_variants (const struct btf *btf) +{ +const struct btf *base =btf__base_btf (btf); +struct kfunc_variant *kfuncs =NULL ; +u32 cnt =0 , cap =0 ; +int err =0 ; + +for (u32 id = base ?btf__type_cnt (base) :1 ; id <btf__type_cnt (btf); id++) { +const struct btf_type *t =btf__type_by_id (btf, id); +const char *name; + +if (!btf_is_decl_tag (t) ||btf_decl_tag (t)->component_idx !=-1 ) +continue ; +if (strcmp (btf__name_by_offset (btf, t->name_off),DECL_TAG_KFUNC ) !=0 ) +continue ; + + err =ensure_mem (&kfuncs, &cap, cnt +1 ); +if (err) + goto out; + name =btf__name_by_offset (btf,btf__type_by_id (btf, t->type)->name_off); + kfuncs[cnt++] = (struct kfunc_variant ){ + .name = name, + .essent_len =bpf_core_essential_name_len (name), + .id = t->type, + }; + } +qsort (kfuncs, cnt,sizeof (*kfuncs), cmp_kfunc_variants); + +for (u32 i =0 ; i < cnt; i++) { +const struct btf_type *a =btf__type_by_id (btf, kfuncs[i].id); + +for (u32 j = i +1 ; j < cnt; j++) { +const struct btf_type *b; + +if (cmp_kfunc_variants (&kfuncs[i], &kfuncs[j]) !=0 ) +break ; + b =btf__type_by_id (btf, kfuncs[j].id); +if (btf_kfunc_proto_match (btf, a->type, btf, b->type) <=0 ) +continue ; +pr_err ("ERROR: resolve_btfids: kfuncs %s and %s have matching prototypes\n" , + kfuncs[i].name, kfuncs[j].name); + err = -EINVAL ; + } + } +out: +free (kfuncs); +return err; +} +static int finalize_btf (struct object *obj) {struct btf *base_btf = obj->base_btf, *btf = obj->btf;
@@ -1929,6 +1994,10 @@ static int finalize_btf(struct object *obj)return err; } + err =check_kfunc_variants (obj->btf); +if (err) +return err; +if (obj->base_btf && obj->distill_base) { err =btf__distill_base (obj->btf, &base_btf, &btf);if (err) {
Signature · 1 line
2.56.0
Ihor Solodrai
reviewerPATCH v3 6/6 docs/bpf: Describe how to change a kfunc's prototype
In reply to Ihor SolodraiAdd a section on changing a kfunc's prototype to the kfunc lifecycle expectations. libbpf now binds a ___-suffixed kfunc by prototype and resolve_btfids rejects kfuncs that libbpf can't tell apart, so kernel developers can keep BPF programs built against an old prototype loading, provided they follow the rules this section describes.
--- Documentation/bpf/kfuncs.rst | 99 ++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+)
Documentation/bpf/kfuncs.rst +99 -0
@@ -800,6 +800,105 @@ procedure is followed for removal: 3. After the deprecation period the kfunc will be removed. At this point, BPF programs calling the kfunc will be rejected by the verifier. +3.2 Changing a kfunc's prototype +-------------------------------- + +libbpf drops the last ``___suffix`` from the name of a kfunc declared in a BPF +program and from the names of functions in kernel and module BTF, as it does +for CO-RE type names. Among the functions with the same remaining name, it +binds the one with a prototype that matches the declaration. Types are +compared kind by kind, and structs and unions by name only: + +.. code-block:: c + + typedef struct task_struct task_t; + + /* these match */ + int bpf_foo(struct task_struct *p, u32 flags); + int bpf_foo(const task_t *p, u64 flags); + int bpf_foo(struct task_struct___local *p, int flags); + + /* none of these match the ones above */ + int bpf_foo(struct file *p, u32 flags); + int bpf_foo(struct task_struct *p); + void bpf_foo(struct task_struct *p, u32 flags); + +If the old and new prototypes match, change the kfunc in place. Otherwise the +new prototype keeps the name, and the old one stays available as +``<name>___v1`` (``___v2`` for the next change, and so on) for a deprecation +period, usually as a thin wrapper registered with the same flags: + +.. code-block:: c + + __bpf_kfunc int bpf_foo(struct task_struct *p, u64 flags) + { + ... + } + + /* bpf_foo() before flags was added */ + __bpf_kfunc int bpf_foo___v1(struct task_struct *p) + { + return bpf_foo(p, 0); + } + + BTF_ID_FLAGS(func, bpf_foo, KF_RCU) + BTF_ID_FLAGS(func, bpf_foo___v1, KF_RCU) + +BPF programs built against either prototype then load: + +.. code-block:: c + + /* built against the old prototype: binds bpf_foo___v1 */ + extern int bpf_foo(struct task_struct *p) __ksym; + + /* built against the new prototype: binds bpf_foo */ + extern int bpf_foo(struct task_struct *p, u64 flags) __ksym; + + /* the suffix doesn't select a kfunc: both bind bpf_foo___v1 */ + extern int bpf_foo___v1(struct task_struct *p) __ksym; + extern int bpf_foo___local(struct task_struct *p) __ksym; + + /* a stacked suffix binds nothing */ + extern int bpf_foo___v1___local(struct task_struct *p) __ksym; + +Only libbpf 1.9 and later look for ``bpf_foo___v1`` when resolving ``bpf_foo``. +Older libbpf and light skeletons see only ``bpf_foo``, as after an in-place +change. + +If two kfunc names differ only in the ``___`` suffix, their prototypes must not +match, not even for aliases: libbpf can't tell them apart and fails to load a +program that declares either one, even as ``__weak``. For example, this widens +an offset to 64 bits and keeps the old prototype as ``bpf_bar___v1``: + +.. code-block:: c + + __bpf_kfunc int bpf_bar(const struct bpf_dynptr *p, u64 offset); + + /* bpf_bar() before offset was widened */ + __bpf_kfunc int bpf_bar___v1(const struct bpf_dynptr *p, u32 offset); + +``resolve_btfids`` rejects it:: + + ERROR: resolve_btfids: kfuncs bpf_bar and bpf_bar___v1 have matching prototypes + +Widening keeps the prototype matching, so it is done in place instead: drop +``bpf_bar___v1``, and programs built against the old prototype bind +``bpf_bar``. ``resolve_btfids`` checks registered kfuncs within vmlinux or one +module. libbpf catches other matches, such as between two modules, when loading +the program. + +Give the new prototype a name outside the family, not ``<name>___*``, if: + +- programs loaded by older libbpf or light skeletons must keep working, or +- the prototypes match but the change breaks callers, e.g. two integer + parameters swap places. + +Older libbpf resolves ``bpf_foo___v1`` only from a declaration with a stacked +suffix, such as ``bpf_foo___v1___compat``, and light skeletons only from +``bpf_foo___v1`` itself. Don't rename a ``<name>___vN`` kfunc while programs +declaring it that way are in use. libbpf 1.9 and later bind by prototype, so a +rename doesn't affect them. + 4. Core kfuncs ==============
Signature · 1 line
2.56.0