bpf: make the vmlinux BTF an on-demand loadable module (CONFIG_DEBUG_INFO_BTF=m) to save ~5.4 MB memory
Subsystems (14)
v3 cover bpf: make the vmlinux BTF an on-demand loadable module (CONFIG_DEBUG_INFO_BTF=m) to save ~5.4 MB memory
Based on and tested against bpf-next commit 6ac134ec9306 ("Merge branch 'file-descriptor-interface-for-bpf-streams'").
This series makes CONFIG_DEBUG_INFO_BTF a tristate, so that it can be set to =m. With =m the vmlinux BTF is carried by a module, btf_vmlinux, that the kernel loads the first time anything needs the BTF. On a system where nothing does, that saves ~5.4 MB of RAM with a distribution config; on a system that uses BTF, nothing differs from =y. =y itself is untouched.
Problem
-------
The vmlinux BTF that CONFIG_DEBUG_INFO_BTF=y builds into the kernel image takes ~5.4 MB of memory, resident from boot whether anything uses it or not. On small instances that is not negligible.
A distribution cannot simply turn it off for the users who do not need
it: it ships one kernel build for all its users, and BTF is not debug info anymore. CO-RE, fentry/fexit, kfuncs, struct_ops, sched_ext and bpf-lsm all depend on it, so =n takes those away from everyone who does use them.
Hence this series adds CONFIG_DEBUG_INFO_BTF=m: the BTF becomes an on-demand module.
Users who never use BTF get the memory back; for users who do, the first use loads it automatically and everything works as with =y.
Approach
--------
Do not remove anything, defer it. The BTF is generated exactly as before, but with =m it is not part of the kernel image: it is packed into a module, btf_vmlinux.ko, which the kernel loads itself the first time anything needs the BTF. Once loaded, the BTF stays, and nothing differs from =y.
Making that work ran into five problems. The first three are existing components that rely on the vmlinux BTF being present from boot, which a loadable module cannot provide; the last two follow from the BTF no longer being part of the image.
1. Verifier. Problem: bpf_check() fetched the vmlinux BTF for every program, so the first socket filter at boot would have loaded the module on every system. Solution: fetch the BTF only where kernel types enter a program (attach_btf, kfunc calls, ksyms, map pointer access, helpers that take or return kernel pointers). A program using none of these never touches it.
2. Initcall registrations. Problem: kfunc, dtor kfunc and struct_ops registrations run from initcalls and need the parsed BTF, which would again pull it in at boot. Solution: queue them and apply the queue when the BTF is parsed, before it is published, so no program can ever see a vmlinux BTF that lacks its kfuncs or struct_ops.
3. Module BTF. Problem: module BTF is split BTF against the vmlinux BTF and was parsed at module load. A module loaded before the vmlinux BTF cannot be parsed yet, and the module notifier cannot load btf_vmlinux (that would nest a module load inside a module load). Solution: keep the module's BTF aside (the same copy btf_parse_module() makes with =y, so module BTF costs the same in both; the saving is the vmlinux BTF only), expose it in /sys/kernel/btf right away, and parse and register it, together with the module's own kfuncs and struct_ops, once the vmlinux BTF arrives. Module BTF thus works regardless of load order, including out-of-tree modules with a .BTF.base, whose sysfs reader waits for the relocation.
4. Trust. Problem: the verifier treats the BTF as the description of the kernel's types, so a carrier from a different build must be refused even if vermagic lets it load. Solution: link the size and SHA-256 of the BTF into the image and check them when the module loads. The linked-in size also lets /sys/kernel/btf/vmlinux report its final size before the load, which tooling expects.
5. Tooling. Problem: pahole --btf_base for module BTF, bpftool and external module builds read .BTF from the vmlinux ELF. Solution:
keep .BTF in the ELF as a non-loadable section, so it is in the file but not in the image.
CONFIG_BPF_PRELOAD is made unavailable with =m: its preloaded programs attach through the vmlinux BTF, so every bpffs mount, which systemd does at boot, would load it and defeat the point.
Relation to the inline BTF series
---------------------------------
Alan's inline BTF series [2], now in bpf-next, adds inline function information to BTF, which is even larger than the BTF itself, and its cover letter leaves
delivering that information on demand, through a module and sysfs, to a follow-up. When Alexei suggested taking the same route for the vmlinux BTF, Alan pointed out where the difficulty would lie [3].
However, that approach cannot be used directly for the vmlinux BTF, because of what depends on the data:
1. Boot-time consumers. Nothing needs inline information at boot, so loading it late only concerns the sysfs file. The core vmlinux BTF is needed at boot by the verifier, by kfunc and struct_ops registrations, and by every module's BTF. Therefore we need to make each of those wait for the BTF instead of expecting it at boot: the verifier fetches it only when a program brings kernel types in, and the registrations are queued and replayed once it is parsed. That is most of this series.
2. Module BTF. Module BTF is split against the vmlinux BTF, so a module loaded before it has nothing to be parsed against, and the module notifier cannot load btf_vmlinux itself. Therefore we need to keep the module's BTF aside, create its sysfs file right away, and parse and register it once the vmlinux BTF arrives; the file of a module built against a distilled base (.BTF.base) serves it once relocated, the others serve the raw bytes as they are. Alan named this as the hard part; it works here regardless of whether the module loads before or after the vmlinux BTF.
The btf_vmlinux module added here could carry the inline information as well when that follow-up comes, so both would share one mechanism.
Patches Structure
-----------------
Patch 1 (refactor, no functional change): btf_parse_module() takes the vmlinux BTF as an argument and can adopt an existing copy of the module BTF data instead of duplicating it. Needed so that module BTF kept aside at load time can be parsed later without moving the buffer the sysfs file points at.
Patch 2 (refactor, no functional change): splits the kfunc, dtor kfunc and struct_ops registration functions into "find the BTF for the owner" and "add the registration to this BTF", so the second half can be replayed on a queued registration.
Patch 3 (verifier): stops fetching the vmlinux BTF up front in bpf_check() and fetches it where kernel types enter a program instead. Adds bpf_peek_btf_vmlinux() for the helpers that run in program context and cannot load anything. With =y the BTF is parsed at boot anyway, so this is invisible there.
Patch 4 (carrier): the runtime side of taking the vmlinux BTF from the btf_vmlinux module: request it on first use, copy it out of the module in the BTF module notifier after checking size and SHA-256 against .BTF.meta, and serve /sys/kernel/btf/vmlinux from the copy with its size known from boot. All under IS_MODULE(CONFIG_DEBUG_INFO_BTF), so unreachable until patch 9.
Patch 5 (vmlinux registrations): queues kfunc, dtor kfunc and struct_ops registrations for vmlinux made from initcalls and applies them when the BTF is parsed, before it is published.
Patch 6 (module BTF): keeps the BTF of modules loaded before the vmlinux BTF, with their own queued registrations, and parses, registers and publishes it when the vmlinux BTF arrives.
Patch 7 (.BTF.base sysfs): gives such a module with a .BTF.base its /sys/kernel/btf file from load, with a reader that waits for the relocation. Patches 5-7 are also unreachable until patch 9.
Patch 8 (preparation, no functional change): the #ifdef, Makefile and Kconfig checks of CONFIG_DEBUG_INFO_BTF that must hold for both =y and =m use IS_ENABLED(), $(subst m,y,...) and DEBUG_INFO_BTF=n, in bpf, tracing, netfilter, xfrm, Rust and modules.
Patch 9 (kbuild and Kconfig): makes CONFIG_DEBUG_INFO_BTF a tristate; with =m links .BTF into vmlinux as a non-loadable section, emits .BTF.meta, builds btf_vmlinux.ko with the vmlinux .BTF as its payload, strips .BTF from vmlinux (module BTF is generated against vmlinux.unstripped), excludes CONFIG_BPF_PRELOAD, and documents the option.
Patches 1-3 and 8 are independently useful or neutral; 4-7 are dead code until 9 flips the switch, which keeps each bisect step building and behaving as before.
Testing
-------
Tested with 1 GiB of memory, same tree, =y against =m, both with CONFIG_DEBUG_INFO_BTF_MODULES=y. The on-demand behaviour is easy to see by hand on an =m kernel:
# lsmod | grep btf_vmlinux
-> nothing: the BTF is not loaded at boot.
# ls -la /sys/kernel/btf/vmlinux
-> the file exists with its final size (from .BTF.meta), although
the BTF behind it is not loaded yet.
# modprobe ext4 nf_conntrack
# ls /sys/kernel/btf/
-> ext4, nf_conntrack, ... appear immediately, although their
BTF is only kept aside, not parsed: there is no vmlinux BTF to
parse it against yet.
# lsmod | grep btf_vmlinux
-> still nothing: loading modules does not load the vmlinux BTF.
# cat /sys/kernel/btf/ext4 > /dev/null
# lsmod | grep btf_vmlinux
-> still nothing: a module's BTF file is served from the raw copy,
reading it does not need the vmlinux BTF.
# grep VmallocUsed /proc/meminfo
-> baseline.
# cat /sys/kernel/btf/vmlinux > /dev/null
# lsmod | grep btf_vmlinux
-> btf_vmlinux ... [permanent]: the first use loaded it, and it
cannot be unloaded.
# grep VmallocUsed /proc/meminfo
-> up by ~5.5 MB: the BTF copy, allocated only now.
# bpftool btf list
-> vmlinux and every loaded module now have BTF ids; the modules
loaded before were parsed and registered on the way.The same with an out-of-tree module (built with M=, so its BTF is split against a distilled base, .BTF.base), on a fresh boot:
# insmod btf_extmod.ko
# ls -la /sys/kernel/btf/btf_extmod
-> the file exists with its final size, although the BTF behind
it is only valid once relocated against the vmlinux BTF.
# lsmod | grep btf_vmlinux
-> nothing: loading the module does not load the vmlinux BTF.
# cat /sys/kernel/btf/btf_extmod > /dev/null
# lsmod | grep btf_vmlinux
-> btf_vmlinux ... [permanent]: reading this file loaded the
vmlinux BTF, relocated the module's BTF and then returned it.
# bpftool btf dump file /sys/kernel/btf/btf_extmod
-> the module's own types, resolved against the vmlinux BTF.
# rmmod btf_extmod
-> unloads normally; its file goes away with it.Any BPF program that uses kernel types (kprobe with bpf_get_current_task_btf(), a kfunc call, fentry, a global subprogram taking the context, bpf_snprintf_btf(), CO-RE, ...) triggers the same load; a plain socket filter does not.
Results:
- MemTotal is ~5.4 MB higher with =m while the BTF is unused, which is the size of the .BTF section. Once the BTF is in use, MemFree is the same within run-to-run noise.
- Modules loaded before the trigger (ext4, nf_conntrack, which registers kfuncs from its init, xfrm_interface) get BTF ids once the BTF is loaded; a struct_ops map for tcp_congestion_ops and a syscall program calling bpf_task_from_pid() work; nf_nat loaded afterwards takes the usual path.
- stat() of /sys/kernel/btf/vmlinux reports the final size before the load; fstat/read/mmap agree afterwards.
- A carrier with one byte of .BTF changed is refused with -EINVAL.
- With the in-tree bpftool and clang-built programs as the first user on a fresh boot: bpftool btf dump file /sys/kernel/btf/vmlinux, bpftool btf list, a socket filter with a global subprogram taking struct __sk_buff *, a raw_tp program calling bpf_snprintf_btf(), a CO-RE field read, and a program calling a kfunc of an out-of-tree module (distilled .BTF.base, kfunc registered from init, loaded before the vmlinux BTF), and a read of that module's own sysfs file, each load the BTF and work; rmmod of that module afterwards is clean.
- lockdep and kmemleak kernels are clean in all of the above.
- =y and =n build and behave as before; =m without module BTF works; every patch builds on its own.
- The boot image on disk shrinks by the compressed BTF with =m (15.0 MB to 13.2 MB here).
Changes since v2 [5]:
- Rebased onto current bpf-next; v2 no longer applied there.
- Patch 8: the RUST and GENDWARFKSYMS pahole restrictions, written as "depends on !DEBUG_INFO_BTF", now say DEBUG_INFO_BTF=n, so they still hold with =m (found while checking the Sashiko question on bool options depending on DEBUG_INFO_BTF, which Kconfig handles:
a bool whose dependency is m can still be y).
Changes since v1 [4]:
- Split for review: v1 patch 5 is now patches 5-7 (vmlinux registrations, module BTF, .BTF.base sysfs), v1 patch 6 is now patches 8-9 (preparation of the existing checks, the switch).
- Fetch sites added for the program context type table (bpf_ctx_convert: global subprograms taking the context, ctx access of tracing/EXT programs), for bpf_snprintf_btf()/bpf_seq_printf_btf() and for CO-RE candidate lookup, which now fetches before taking cand_cache_mutex (Sashiko, bpf-ci, Jiri). Without CONFIG_DEBUG_INFO_BTF the new helper check is skipped, so nothing changes there.
- Module BTF is published only after its deferred registrations are applied; only modules past MODULE_STATE_LIVE are replayed, with the module pinned; a module still in init has its queue applied at LIVE. Fixes the concurrent registration and COMING-module lifetime issues (Sashiko, bpf-ci).
- The sysfs reader of a module with .BTF.base waits for the module's BTF to be relocated instead of serving the raw data (bpf-ci); sysfs files are no longer removed from the deferred parse path, and MODULE_STATE_GOING removes them outside btf_module_mutex.
- A module whose deferred BTF fails to parse or get an id keeps the buffer its sysfs file serves; nothing is freed under a reader (Sashiko).
- The vmlinux registration queue has its own mutex; no lock is taken under btf_vmlinux_lock that leads back to it (bpf-ci).
- A failed parse is not cached with =m (Sashiko).
- Only the carrier depends on vmlinux in Makefile.modfinal; POSIX dd instead of head -c (Sashiko).
- .BTF stripped from vmlinux with =m, so no boot image carries it, also where the image is an ELF copy of vmlinux; module BTF is generated against vmlinux.unstripped (Alan).
- Kconfig help: initramfs note, module BTF accounting (Alan).
- btf_struct_ops_add() renamed btf_struct_ops_register() (bpf-ci); its stub only defined where used.
- Tests with bpftool/libbpf userspace and an out-of-tree .BTF.base module added (Alan).
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/bpf/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/bpf/[email protected]/
[5] https://lore.kernel.org/bpf/[email protected]/
Jay Wang (9):
bpf: pass the vmlinux BTF to btf_parse_module() and let it adopt the
data
bpf: split the kfunc, dtor kfunc and struct_ops registration bodies
bpf: fetch the vmlinux BTF where kernel types enter a program
bpf: take the vmlinux BTF from the btf_vmlinux module
bpf: defer vmlinux kfunc and struct_ops registrations
bpf: keep module BTF until the vmlinux BTF is available
bpf: expose deferred .BTF.base module BTF in sysfs from module load bpf, trace, net: prepare CONFIG_DEBUG_INFO_BTF checks for a tristate kbuild, bpf: allow building the vmlinux BTF as a module
Documentation/bpf/btf.rst | 35 ++ Makefile | 8 +- include/asm-generic/vmlinux.lds.h | 31 +- include/linux/bpf.h | 1 + include/linux/btf.h | 6 + include/linux/btf_ids.h | 2 +- include/linux/compiler_types.h | 2 +- include/linux/module.h | 2 +- include/trace/trace_events.h | 2 +- init/Kconfig | 2 +- kernel/bpf/Makefile | 6 +- kernel/bpf/bpf_struct_ops.c | 3 +- kernel/bpf/btf.c | 922 ++++++++++++++++++++++++++---- kernel/bpf/btf_vmlinux.c | 23 + kernel/bpf/preload/Kconfig | 4 + kernel/bpf/syscall.c | 6 + kernel/bpf/sysfs_btf.c | 85 ++- kernel/bpf/verifier.c | 122 +++- kernel/module/Kconfig | 2 +- kernel/module/main.c | 4 +- kernel/trace/bpf_trace.c | 3 +- kernel/trace/trace_syscalls.c | 6 +- lib/Kconfig.debug | 22 +- net/netfilter/Makefile | 6 +- net/xfrm/Makefile | 4 +- scripts/Makefile.modfinal | 26 +- scripts/Makefile.vmlinux | 5 + scripts/gen-btf.sh | 95 ++- scripts/link-vmlinux.sh | 25 +- 29 files changed, 1302 insertions(+), 158 deletions(-) create mode 100644 kernel/bpf/btf_vmlinux.c
base-commit: 6ac134ec930642d5b574b63a72a0e999c2470c64
Signature · 1 line
2.47.3
PATCH v3 1/9 bpf: pass the vmlinux BTF to btf_parse_module() and let it adopt the data
Make btf_parse_module() take the vmlinux BTF as an argument instead of fetching it with bpf_get_btf_vmlinux(), and add a data_owned flag: when set, the passed .BTF data is an already kvmalloc()ed copy that the new btf takes ownership of on success (on failure the caller keeps it).
Factor the sysfs file creation out of the module notifier into btf_module_sysfs_add() and the teardown into btf_module_free(), and set btf_mod->module right after the allocation rather than under the mutex.
No functional change. This prepares for CONFIG_DEBUG_INFO_BTF=m, where a module can be loaded before the vmlinux BTF is available: its .BTF is then copied and exposed in sysfs first and parsed later, at which point the parser must take the copy as is so that the sysfs file keeps pointing at valid data.
--- kernel/bpf/btf.c | 105 +++++++++++++++++++++++++++++------------------ 1 file changed, 64 insertions(+), 41 deletions(-)
kernel/bpf/btf.c +64 -41
@@ -6868,16 +6868,20 @@ __u32 btf_relocate_id(const struct btf *btf, __u32 id)#ifdef CONFIG_DEBUG_INFO_BTF_MODULES -static struct btf *btf_parse_module (const char *module_name,const void *data, -unsigned int data_size,void *base_data, -unsigned int base_data_size) +/* +* Parse split module BTF against @vmlinux_btf. @data is the module's .BTF +* section; if @data_owned, it is an already kvmalloc()ed copy that the new +* btf takes ownership of on success (on failure the caller keeps it). +*/ +static struct btf *btf_parse_module (const char *module_name,struct btf *vmlinux_btf, +void *data,unsigned int data_size,bool data_owned, +void *base_data,unsigned int base_data_size) { -struct btf *btf =NULL , *vmlinux_btf, *base_btf =NULL ; +struct btf *btf =NULL , *base_btf =NULL ;struct btf_verifier_env *env =NULL ;struct bpf_verifier_log *log;int err =0 ; - vmlinux_btf =bpf_get_btf_vmlinux ();if (IS_ERR (vmlinux_btf))return vmlinux_btf;if (!vmlinux_btf)
@@ -6914,7 +6918,10 @@ static struct btf *btf_parse_module(const char *module_name, const void *data, btf->named_start_id =0 ;strscpy (btf->name, module_name); - btf->data =kvmemdup (data, data_size,GFP_KERNEL | __GFP_NOWARN); +if (data_owned) + btf->data = data; +else + btf->data =kvmemdup (data, data_size,GFP_KERNEL | __GFP_NOWARN);if (!btf->data) { err = -ENOMEM ; goto errout;
@@ -6957,7 +6964,8 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,if (!IS_ERR (base_btf) && base_btf != vmlinux_btf)btf_free (base_btf);if (btf) { -kvfree (btf->data); +if (!data_owned) +kvfree (btf->data);kvfree (btf->types);kfree (btf); }
@@ -8962,6 +8970,48 @@ static DEFINE_MUTEX(btf_module_mutex);static void purge_cand_cache (struct btf *btf); +static int btf_module_sysfs_add (struct btf_module *btf_mod,const char *name, +void *data,size_t data_size) +{ +struct bin_attribute *attr; +int err; + +if (!IS_ENABLED (CONFIG_SYSFS )) +return 0 ; + + attr =kzalloc_obj (*attr); +if (!attr) +return -ENOMEM ; + +sysfs_bin_attr_init (attr); + attr->attr.name = name; + attr->attr.mode =0444 ; + attr->size = data_size; + attr->private = data; + attr->read = sysfs_bin_attr_simple_read; + + err =sysfs_create_bin_file (btf_kobj, attr); +if (err) { +pr_warn ("failed to register module [%s] BTF in sysfs: %d\n" , + name, err); +kfree (attr); +return err; + } + + btf_mod->sysfs_attr = attr; +return 0 ; +} + +static void btf_module_free (struct btf_module *btf_mod) +{ +if (btf_mod->sysfs_attr) +sysfs_remove_bin_file (btf_kobj, btf_mod->sysfs_attr); +purge_cand_cache (btf_mod->btf); +btf_put (btf_mod->btf); +kfree (btf_mod->sysfs_attr); +kfree (btf_mod); +} +static int btf_module_notify (struct notifier_block *nb,unsigned long op,void *module) {
@@ -8982,7 +9032,10 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op, err = -ENOMEM ; goto out; } - btf =btf_parse_module (mod->name, mod->btf_data, mod->btf_data_size, + btf_mod->module = module; + + btf =btf_parse_module (mod->name,bpf_get_btf_vmlinux (), + mod->btf_data, mod->btf_data_size, false, mod->btf_base_data, mod->btf_base_data_size);if (IS_ERR (btf)) {kfree (btf_mod);
@@ -9004,37 +9057,12 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,purge_cand_cache (NULL );mutex_lock (&btf_module_mutex); - btf_mod->module = module; btf_mod->btf = btf;list_add (&btf_mod->list, &btf_modules);mutex_unlock (&btf_module_mutex); -if (IS_ENABLED (CONFIG_SYSFS )) { -struct bin_attribute *attr; - - attr =kzalloc_obj (*attr); -if (!attr) - goto out; - -sysfs_bin_attr_init (attr); - attr->attr.name = btf->name; - attr->attr.mode =0444 ; - attr->size = btf->data_size; - attr->private = btf->data; - attr->read = sysfs_bin_attr_simple_read; - - err =sysfs_create_bin_file (btf_kobj, attr); -if (err) { -pr_warn ("failed to register module [%s] BTF in sysfs: %d\n" , - mod->name, err); -kfree (attr); - err =0 ; - goto out; - } - - btf_mod->sysfs_attr = attr; - } - +/* not fatal, the module BTF is usable without the sysfs file */ +btf_module_sysfs_add (btf_mod, btf->name, btf->data, btf->data_size);break ;case MODULE_STATE_LIVE :mutex_lock (&btf_module_mutex);
@@ -9061,12 +9089,7 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,*/ btf_free_id (btf_mod->btf);list_del (&btf_mod->list); -if (btf_mod->sysfs_attr) -sysfs_remove_bin_file (btf_kobj, btf_mod->sysfs_attr); -purge_cand_cache (btf_mod->btf); -btf_put (btf_mod->btf); -kfree (btf_mod->sysfs_attr); -kfree (btf_mod); +btf_module_free (btf_mod);break ; }mutex_unlock (&btf_module_mutex);
Signature · 1 line
2.47.3
PATCH v3 2/9 bpf: split the kfunc, dtor kfunc and struct_ops registration bodies
In reply to Jay WangSplit __register_btf_kfunc_id_set(), register_btf_id_dtor_kfuncs() and __register_bpf_struct_ops() into the part that looks up the BTF for the owner and the part that adds the registration to a given BTF:btf_kfunc_id_set_add(), btf_dtor_kfuncs_add() and btf_struct_ops_register().
In is_valid_value_type(), look up bpf_struct_ops_common_value in the btf the function was given rather than in the btf_vmlinux global. The id is a vmlinux id and a module BTF resolves it through its base, so the result is the same; the function already uses the passed btf for every other lookup.
No functional change. With CONFIG_DEBUG_INFO_BTF=m, registrations made from initcalls before the vmlinux BTF is available are queued and applied later by the BTF parsing code, which needs the add-to-this-btf half on its own; the struct_ops ones are applied before the parsed vmlinux BTF is published, i.e. while btf_vmlinux is still NULL.
--- kernel/bpf/bpf_struct_ops.c | 3 +- kernel/bpf/btf.c | 91 ++++++++++++++++++++++--------------- 2 files changed, 57 insertions(+), 37 deletions(-)
kernel/bpf/bpf_struct_ops.c +2 -1
@@ -103,7 +103,8 @@ static bool is_valid_value_type(struct btf *btf, s32 value_id, } member =btf_type_member (vt); mt =btf_type_by_id (btf, member->type); - common_value_type =btf_type_by_id (btf_vmlinux, +/* a vmlinux id resolves through the base BTF of a module BTF too */ + common_value_type =btf_type_by_id (btf, st_ops_ids[IDX_ST_OPS_COMMON_VALUE_ID ]);if (mt != common_value_type) { pr_warn("The first member of %s should be bpf_struct_ops_common_value\n",
kernel/bpf/btf.c +55 -36
141 lines not on this page · raw message
Signature · 1 line
2.47.3
PATCH v3 3/9 bpf: fetch the vmlinux BTF where kernel types enter a program
In reply to Jay Wangbpf_check() fetches the vmlinux BTF up front for every program, whether the program uses kernel types or not. With the upcoming CONFIG_DEBUG_INFO_BTF=m that fetch loads a module and parses 5 MiB of BTF, and since systemd loads socket filters at boot, it would happen on every system, whether anything uses BTF or not.
Stop fetching up front and fetch at the points where kernel types enter the verifier state instead:
- bpf_add_kfunc_call(), for the first kfunc call of a program;
- check_pseudo_btf_id(), for ldimm64 of a kernel variable;
- check_ptr_to_map_access(), for accessing a map pointer's fields;
- check_helper_call(), when the helper's prototype takes or returns a PTR_TO_BTF_ID, or is bpf_snprintf_btf()/bpf_seq_printf_btf(), which take the kernel type id inside a struct btf_ptr instead (helper_uses_vmlinux_btf());
- the program context type table, bpf_ctx_convert, which btf_parse_vmlinux() fills in: global subprograms taking the context (btf_prepare_func_args()) and context access of tracing and EXT programs (btf_translate_to_vmlinux()) go through it, so its readers fetch the BTF (bpf_ctx_convert_type());
- CO-RE candidate lookup (bpf_core_apply(), btf_get_ptr_to_btf_id()), which fetches before taking cand_cache_mutex, so that loading the BTF never happens under that mutex; bpf_core_find_cands() itself only peeks.
Together with the existing fetch in bpf_prog_load() for attach_btf and the struct_ops map creation, every way kernel types enter a program goes through one of these sites. A program that uses none of them, such as a socket filter, no longer touches the vmlinux BTF.
The two callers that used the result of bpf_get_btf_vmlinux() without checking it, btf_prepare_func_args() and btf_check_kfunc_name(), now do.
bpf_snprintf_btf() and bpf_seq_printf_btf() run in program context and cannot afford a fetch that may sleep. Add bpf_peek_btf_vmlinux(), which returns the parsed vmlinux BTF or NULL without parsing anything, and use it there; the helpers fail with -EINVAL if the BTF is not parsed, as they do on a kernel without BTF.
With CONFIG_DEBUG_INFO_BTF=y the vmlinux BTF is parsed at boot by the first kfunc registration, and without BTF the new helper check is skipped, so nothing changes for either.
--- include/linux/bpf.h | 1 + kernel/bpf/btf.c | 56 ++++++++++++++++++++++++++++++----- kernel/bpf/verifier.c | 64 +++++++++++++++++++++++++++++++++++----- kernel/trace/bpf_trace.c | 3 +- 4 files changed, 108 insertions(+), 16 deletions(-)
include/linux/bpf.h +1 -0
@@ -3183,6 +3183,7 @@ static inline s32 bpf_call_args_imm(s16 idx)#endif struct btf *bpf_get_btf_vmlinux (void ); +struct btf *bpf_peek_btf_vmlinux (void );/* Map specifics */ struct xdp_frame ;
kernel/bpf/btf.c +49 -7
115 lines not on this page · raw message
kernel/bpf/verifier.c +56 -8
117 lines not on this page · raw message
kernel/trace/bpf_trace.c +2 -1
@@ -1015,7 +1015,8 @@ static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,if (btf_ptr_size !=sizeof (struct btf_ptr ))return -EINVAL ; - *btf =bpf_get_btf_vmlinux (); +/* Called from a running program: only use the BTF if it is parsed. */ + *btf =bpf_peek_btf_vmlinux ();if (IS_ERR_OR_NULL (*btf))return IS_ERR (*btf) ?PTR_ERR (*btf) : -EINVAL ;
Signature · 1 line
2.47.3
PATCH v3 4/9 bpf: take the vmlinux BTF from the btf_vmlinux module
In reply to Jay WangAdd the runtime side of delivering the vmlinux BTF as a module: with CONFIG_DEBUG_INFO_BTF=m the BTF is carried by a module named btf_vmlinux and installed by the BTF module notifier when it loads, and whoever needs the BTF first loads the module. Nothing in this patch is reachable yet:CONFIG_DEBUG_INFO_BTF is still a bool and every new path is under IS_MODULE(CONFIG_DEBUG_INFO_BTF); the kbuild side and the Kconfig change follow.
With CONFIG_DEBUG_INFO_BTF=y the vmlinux BTF, 5.4 MiB on x86-64 with a distribution config, is part of the kernel image and resident from boot whether anything uses it or not. Most systems never do. Carrying it in a module that is loaded on first use makes the memory a cost of using BTF rather than of having a kernel that supports it.
btf_vmlinux_data() hands out the raw vmlinux BTF: from __start_BTF with =y, or with =m from a vmalloc_user() copy that the notifier makes when the btf_vmlinux module loads. If the copy is not there and the caller asked to load, it calls request_module("btf_vmlinux"); the notifier installs the copy before init_module() returns, so the data is either present afterwards or the module is not available (yet). The result is not cached, a later call retries. btf_parse_vmlinux() and bpf_get_btf_vmlinux() use it; the latter loads outside btf_vmlinux_lock so that the notifier is never blocked by the caller, and returns NULL like a kernel without BTF when the module cannot be loaded. A failed parse is not remembered with =m: the payload was checked against the kernel when the module loaded, so a failure is a resource problem, and the next caller retries.
The verifier trusts the BTF as the description of this kernel's types, so the notifier only accepts a payload whose size and SHA-256 match the values linked into the kernel as .BTF.meta (struct btf_vmlinux_meta, filled in by scripts/gen-btf.sh in a later patch). A carrier from another build is refused with -EINVAL even if vermagic lets it load, and a second carrier is ignored. The copy is never freed: as with =y, the BTF stays for the lifetime of the kernel, and the carrier has no exit.
The module notifier, btf_parse_module() and the btf_data fields in struct module are compiled for CONFIG_DEBUG_INFO_BTF_MODULES or =m; with =m and no module BTF, the notifier only recognizes the carrier.
/sys/kernel/btf/vmlinux exists from boot with its final size, which is known from .BTF.meta before the BTF is loaded; the first read() or mmap() loads it. mmap() uses remap_vmalloc_range() on the copy. This keeps stat() working before the load, which is what the btf_sysfs selftest does.
BPF_BTF_GET_NEXT_ID loads the BTF too: kernel BTFs get their ids when the vmlinux BTF is parsed, and whoever enumerates BTF ids wants them.
--- include/linux/btf.h | 1 + include/linux/module.h | 2 +- kernel/bpf/btf.c | 156 ++++++++++++++++++++++++++++++++++++++--- kernel/bpf/syscall.c | 6 ++ kernel/bpf/sysfs_btf.c | 85 +++++++++++++++++++++- kernel/bpf/verifier.c | 51 ++++++++++---- kernel/module/main.c | 4 +- 7 files changed, 278 insertions(+), 27 deletions(-)
include/linux/btf.h +1 -0
@@ -602,6 +602,7 @@ __u32 *btf_field_iter_next(struct btf_field_iter *it);const char *btf_name_by_offset (const struct btf *btf,u32 offset);const char *btf_str_by_offset (const struct btf *btf,u32 offset);struct btf *btf_parse_vmlinux (void ); +void *btf_vmlinux_data (u32 *size,bool load);struct btf *bpf_prog_get_target_btf (const struct bpf_prog *prog);u32 *btf_kfunc_flags (const struct btf *btf,u32 kfunc_btf_id,const struct bpf_prog *prog);int btf_kfunc_check_flag (const struct btf *btf,u32 kfunc_btf_id,u32 flag);
include/linux/module.h +1 -1
@@ -497,7 +497,7 @@ struct module {unsigned int num_bpf_raw_events;struct bpf_raw_event_map *bpf_raw_events;#endif -#ifdef CONFIG_DEBUG_INFO_BTF_MODULES +#if IS_ENABLED (CONFIG_DEBUG_INFO_BTF_MODULES ) ||IS_MODULE (CONFIG_DEBUG_INFO_BTF )unsigned int btf_data_size;unsigned int btf_base_data_size;void *btf_data;
kernel/bpf/btf.c +148 -8
234 lines not on this page · raw message
kernel/bpf/syscall.c +6 -0
@@ -6435,6 +6435,12 @@ static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size, &map_idr, &map_idr_lock);break ;case BPF_BTF_GET_NEXT_ID : +/* +* With CONFIG_DEBUG_INFO_BTF=m the kernel BTFs get ids when the +* vmlinux BTF is loaded; whoever enumerates them wants them. +*/ +if (IS_MODULE (CONFIG_DEBUG_INFO_BTF )) +bpf_get_btf_vmlinux (); err =bpf_obj_get_next_id (&attr, uattr.user, &btf_idr, &btf_idr_lock);break ;
kernel/bpf/sysfs_btf.c +82 -3
102 lines not on this page · raw message
kernel/bpf/verifier.c +38 -13
64 lines not on this page · raw message
kernel/module/main.c +2 -2
@@ -2718,7 +2718,7 @@ static int find_module_sections(struct module *mod, struct load_info *info)sizeof (*mod->bpf_raw_events), &mod->num_bpf_raw_events);#endif -#ifdef CONFIG_DEBUG_INFO_BTF_MODULES +#if IS_ENABLED (CONFIG_DEBUG_INFO_BTF_MODULES ) ||IS_MODULE (CONFIG_DEBUG_INFO_BTF ) mod->btf_data =any_section_objs (info,".BTF" ,1 , &mod->btf_data_size); mod->btf_base_data =any_section_objs (info,".BTF.base" ,1 , &mod->btf_base_data_size);
@@ -3172,7 +3172,7 @@ static noinline int do_init_module(struct module *mod) mod->mem[type].size =0 ; } -#ifdef CONFIG_DEBUG_INFO_BTF_MODULES +#if IS_ENABLED (CONFIG_DEBUG_INFO_BTF_MODULES ) ||IS_MODULE (CONFIG_DEBUG_INFO_BTF )/* .BTF is not SHF_ALLOC and will get removed, so sanitize pointers */ mod->btf_data =NULL ; mod->btf_base_data =NULL ;
Signature · 1 line
2.47.3
PATCH v3 5/9 bpf: defer vmlinux kfunc and struct_ops registrations
In reply to Jay WangWith CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF is loaded on first use. For that to save anything, nothing may pull it in at boot. The verifier no longer does since the previous patches, but register_btf_kfunc_id_set(), register_btf_id_dtor_kfuncs() and register_bpf_struct_ops() for vmlinux run from initcalls and need the parsed BTF.
Queue them instead (btf_defer_reg()) and apply them in btf_parse_vmlinux(), before the BTF is published, so that no program can see a vmlinux BTF without its kfuncs and struct_ops. Applying a struct_ops runs its ->init(), which registers the kfunc sets of its hook; those land back on the queue, so it is drained in a loop until a pass adds nothing, and only then are new registrations applied directly. The dtor arrays are copied: every caller in the tree builds them on the stack of its initcall.
The queue has its own lock, btf_vmlinux_regs_mutex: it is drained under btf_vmlinux_lock, and btf_module_mutex must not nest inside that, since purge_cand_cache() takes cand_cache_mutex under btf_module_mutex and CO-RE takes btf_vmlinux_lock under cand_cache_mutex.
Module registrations are not queued yet; the next patch does that together with deferring the module BTF itself. With =y the BTF is present from boot and nothing is queued. Nothing here is reachable until the Kconfig symbol becomes a tristate.
--- kernel/bpf/btf.c | 207 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+)
kernel/bpf/btf.c +207 -0
@@ -6907,6 +6907,8 @@ static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *namereturn ERR_PTR (err); } +static void btf_apply_deferred_vmlinux_regs (struct btf *btf); +struct btf *btf_parse_vmlinux (void ) {struct btf_verifier_env *env =NULL ;
@@ -6938,7 +6940,15 @@ struct btf *btf_parse_vmlinux(void) bpf_ctx_convert.t =NULL ;btf_free (btf); btf =ERR_PTR (err); + goto err_out; } + +/* +* With CONFIG_DEBUG_INFO_BTF=m, kfunc, dtor kfunc and struct_ops +* registrations for vmlinux made before the BTF was available were +* queued; apply them now, before the BTF becomes visible to anyone. +*/ +btf_apply_deferred_vmlinux_regs (btf); err_out:btf_verifier_env_free (env);return btf;
@@ -9064,6 +9074,33 @@ enum {#define BTF_MODULE_NOTIFIER 1#endif +/* +* CONFIG_DEBUG_INFO_BTF=m: a kfunc, dtor kfunc or struct_ops registration +* made while the BTF it applies to is not available yet. Kept until the BTF +* arrives, see btf_defer_reg(). +*/ +enum btf_deferred_reg_kind { +BTF_DEFERRED_KFUNC_SET , +BTF_DEFERRED_DTOR_KFUNCS , +BTF_DEFERRED_STRUCT_OPS , +}; + +struct btf_deferred_reg { +struct list_head list; +enum btf_deferred_reg_kind kind; +union { +struct { +enum btf_kfunc_hook hook; +const struct btf_kfunc_id_set *kset; + } kfunc; +struct { +const struct btf_id_dtor_kfunc *dtors; +u32 cnt; + } dtor; +struct bpf_struct_ops *st_ops; + }; +}; + #ifdef BTF_MODULE_NOTIFIER struct btf_module { struct list_head list;
@@ -9848,12 +9885,22 @@ static int btf_kfunc_id_set_add(struct btf *btf, enum btf_kfunc_hook hook,return btf_populate_kfunc_set (btf, hook, kset); } +static int btf_defer_reg (struct module *owner,const struct btf_deferred_reg *tmpl); +static int __register_btf_kfunc_id_set (enum btf_kfunc_hook hook,const struct btf_kfunc_id_set *kset) { +struct btf_deferred_reg tmpl = { + .kind =BTF_DEFERRED_KFUNC_SET , + .kfunc = { .hook = hook, .kset = kset }, + };struct btf *btf;int ret; + ret =btf_defer_reg (kset->owner, &tmpl); +if (ret) +return ret >0 ?0 : ret; + btf =btf_get_module_btf (kset->owner);if (!btf)return check_btf_kconfigs (kset->owner,"kfunc" );
@@ -10022,9 +10069,17 @@ static int btf_dtor_kfuncs_add(struct btf *btf, const struct btf_id_dtor_kfunc *int register_btf_id_dtor_kfuncs (const struct btf_id_dtor_kfunc *dtors,u32 add_cnt,struct module *owner) { +struct btf_deferred_reg tmpl = { + .kind =BTF_DEFERRED_DTOR_KFUNCS , + .dtor = { .dtors = dtors, .cnt = add_cnt }, + };struct btf *btf;int ret; + ret =btf_defer_reg (owner, &tmpl); +if (ret) +return ret >0 ?0 : ret; + btf =btf_get_module_btf (owner);if (!btf)return check_btf_kconfigs (owner,"dtor kfuncs" );
@@ -10703,9 +10758,17 @@ static int btf_struct_ops_register(struct btf *btf, struct bpf_struct_ops *st_opint __register_bpf_struct_ops (struct bpf_struct_ops *st_ops) { +struct btf_deferred_reg tmpl = { + .kind =BTF_DEFERRED_STRUCT_OPS , + .st_ops = st_ops, + };struct btf *btf;int err; + err =btf_defer_reg (st_ops->owner, &tmpl); +if (err) +return err >0 ?0 : err; + btf =btf_get_module_btf (st_ops->owner);if (!btf)return check_btf_kconfigs (st_ops->owner,"struct_ops" );
@@ -10717,8 +10780,152 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)return err; }EXPORT_SYMBOL_GPL (__register_bpf_struct_ops); +#elif defined(BTF_MODULE_NOTIFIER ) +static int btf_struct_ops_register (struct btf *btf,struct bpf_struct_ops *st_ops) +{ +return -EOPNOTSUPP ; +}#endif +/* +* CONFIG_DEBUG_INFO_BTF=m: registrations for vmlinux made before its BTF is +* available wait in btf_vmlinux_deferred_regs until btf_parse_vmlinux() +* applies them. +*/ +#ifdef BTF_MODULE_NOTIFIER +/* +* The queue has its own lock: it is drained under btf_vmlinux_lock, and +* btf_module_mutex must not nest inside that (purge_cand_cache() takes +* cand_cache_mutex under btf_module_mutex, and CO-RE fetches the vmlinux +* BTF under cand_cache_mutex). +*/ +static DEFINE_MUTEX (btf_vmlinux_regs_mutex); +static LIST_HEAD (btf_vmlinux_deferred_regs); +/* Set when the vmlinux BTF is parsed; new registrations apply directly */ +static bool btf_vmlinux_regs_closed; + +/* +* Queue @tmpl if the BTF for @owner is not available yet. Returns 1 if the +* registration was queued and is to be considered done, 0 if the caller has +* to apply it, or -ENOMEM. Only vmlinux registrations are queued so far. +*/ +static int btf_defer_reg (struct module *owner,const struct btf_deferred_reg *tmpl) +{ +struct list_head *head =NULL ; +struct btf_deferred_reg *reg; + +if (!IS_MODULE (CONFIG_DEBUG_INFO_BTF ) || owner) +return 0 ; + +guard (mutex)(&btf_vmlinux_regs_mutex); +if (!btf_vmlinux_regs_closed) + head = &btf_vmlinux_deferred_regs; +if (!head) +return 0 ; + + reg =kmemdup (tmpl,sizeof (*reg),GFP_KERNEL ); +if (!reg) +return -ENOMEM ; +/* +* kfunc id sets and struct_ops are static data of their owner, but +* the dtor arrays are commonly built on the stack of the initcall. +*/ +if (reg->kind ==BTF_DEFERRED_DTOR_KFUNCS ) { + reg->dtor.dtors =kmemdup_array (tmpl->dtor.dtors, tmpl->dtor.cnt, +sizeof (*tmpl->dtor.dtors),GFP_KERNEL ); +if (!reg->dtor.dtors) { +kfree (reg); +return -ENOMEM ; + } + } +list_add_tail (®->list, head); +return 1 ; +} + +static void btf_free_deferred_reg (struct btf_deferred_reg *reg) +{ +if (reg->kind ==BTF_DEFERRED_DTOR_KFUNCS ) +kfree (reg->dtor.dtors); +kfree (reg); +} + +static const char *btf_deferred_reg_name (const struct btf_deferred_reg *reg) +{ +switch (reg->kind) { +case BTF_DEFERRED_KFUNC_SET :return "kfunc set" ; +case BTF_DEFERRED_DTOR_KFUNCS :return "dtor kfuncs" ; +case BTF_DEFERRED_STRUCT_OPS :return "struct_ops" ; + } +return "?" ; +} + +static int btf_apply_deferred_reg (struct btf *btf,const struct btf_deferred_reg *reg) +{ +switch (reg->kind) { +case BTF_DEFERRED_KFUNC_SET : +return btf_kfunc_id_set_add (btf, reg->kfunc.hook, reg->kfunc.kset); +case BTF_DEFERRED_DTOR_KFUNCS : +return btf_dtor_kfuncs_add (btf, reg->dtor.dtors, reg->dtor.cnt); +case BTF_DEFERRED_STRUCT_OPS : +return btf_struct_ops_register (btf, reg->st_ops); + } +return -EINVAL ; +} + +/* Apply and free the registrations in @regs to @btf. */ +static void btf_apply_deferred_regs (struct btf *btf,struct list_head *regs) +{ +struct btf_deferred_reg *reg, *tmp; +int err; + +list_for_each_entry_safe (reg, tmp, regs, list) { + err =btf_apply_deferred_reg (btf, reg); +if (err) +pr_warn ("failed to register deferred %s for [%s] BTF: %d\n" , +btf_deferred_reg_name (reg), btf->name, err); +list_del (®->list); +btf_free_deferred_reg (reg); + } +} + +/* +* The vmlinux BTF has just been parsed; apply the registrations that waited +* for it. Runs under btf_vmlinux_lock, before @btf is published, so nothing +* can observe a vmlinux BTF without its kfuncs and struct_ops. +* +* Applying a registration can queue further ones: a struct_ops ->init() +* registers the kfuncs of its hook. Those must not go through +* bpf_get_btf_vmlinux() (we hold its lock), so the queue stays open until +* a pass applies nothing new, and only then are registrations applied directly. +*/ +static void btf_apply_deferred_vmlinux_regs (struct btf *btf) +{ +LIST_HEAD (regs); + +if (!IS_MODULE (CONFIG_DEBUG_INFO_BTF )) +return ; + +mutex_lock (&btf_vmlinux_regs_mutex); +while (!list_empty (&btf_vmlinux_deferred_regs)) { +list_splice_init (&btf_vmlinux_deferred_regs, ®s); +mutex_unlock (&btf_vmlinux_regs_mutex); +btf_apply_deferred_regs (btf, ®s); +mutex_lock (&btf_vmlinux_regs_mutex); + } + btf_vmlinux_regs_closed = true; +mutex_unlock (&btf_vmlinux_regs_mutex); +} +#else +static int btf_defer_reg (struct module *owner,const struct btf_deferred_reg *tmpl) +{ +return 0 ; +} + +static void btf_apply_deferred_vmlinux_regs (struct btf *btf) +{ +} +#endif /* BTF_MODULE_NOTIFIER */ +bool btf_param_match_suffix (const struct btf *btf,const struct btf_param *arg,const char *suffix)
Signature · 1 line
2.47.3
PATCH v3 6/9 bpf: keep module BTF until the vmlinux BTF is available
In reply to Jay WangModule BTF is split BTF against the vmlinux BTF and is parsed in the module notifier. With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF may not be loaded yet when a module loads, and the notifier cannot load btf_vmlinux (that would nest a module load in a module load).
So a module loaded before the vmlinux BTF keeps a copy of its .BTF and .BTF.base and gets a list entry with btf == NULL; its kfunc, dtor kfunc and struct_ops registrations wait on that entry. Without a .BTF.base the data is final and is exposed in /sys/kernel/btf right away (the raw bytes need no parsing); with one, parsing relocates the data in place, so its file is created once parsed, as with =y. The next patch creates that file earlier.
When the vmlinux BTF arrives, btf_parse_deferred_modules() parses the kept copies (the copy is the one btf_parse_module() makes anyway, so an existing sysfs file keeps pointing at valid data), applies the waiting registrations and only then publishes the BTF with an id, so nobody sees a module BTF without its kfuncs. Applying walks the module list (btf_check_kfunc_name()) and so happens with btf_module_mutex dropped and the module pinned. A module that is still initializing when the vmlinux BTF arrives is only published; its init is still queueing registrations, and MODULE_STATE_LIVE applies them once init is done, which also keeps a module whose init fails from being touched after it is freed.
A module whose BTF turns out to mismatch at that point is already running and keeps running without BTF, with a warning; its entry stays, dead, until the module goes, and keeps the raw data a sysfs file may serve. With =y such a module would have been refused at load time unless CONFIG_MODULE_ALLOW_BTF_MISMATCH; that check only applies to modules loaded after the vmlinux BTF.
Walkers of the module BTF list skip entries whose BTF is not parsed yet. With =y the BTF is present from boot and the notifier takes the existing path. Still nothing is reachable until the Kconfig symbol becomes a tristate.
--- include/linux/btf.h | 5 + kernel/bpf/btf.c | 267 +++++++++++++++++++++++++++++++++++++++--- kernel/bpf/verifier.c | 9 +- 3 files changed, 262 insertions(+), 19 deletions(-)
include/linux/btf.h +5 -0
@@ -603,6 +603,11 @@ const char *btf_name_by_offset(const struct btf *btf, u32 offset);const char *btf_str_by_offset (const struct btf *btf,u32 offset);struct btf *btf_parse_vmlinux (void );void *btf_vmlinux_data (u32 *size,bool load); +#if IS_MODULE (CONFIG_DEBUG_INFO_BTF ) +void btf_parse_deferred_modules (void ); +#else +static inline void btf_parse_deferred_modules (void ) {} +#endif struct btf *bpf_prog_get_target_btf (const struct bpf_prog *prog);u32 *btf_kfunc_flags (const struct btf *btf,u32 kfunc_btf_id,const struct bpf_prog *prog);int btf_kfunc_check_flag (const struct btf *btf,u32 kfunc_btf_id,u32 flag);
kernel/bpf/btf.c +249 -18
373 lines not on this page · raw message
kernel/bpf/verifier.c +8 -1
@@ -21925,12 +21925,14 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt/* * Returns the parsed vmlinux BTF, NULL if the kernel has none, or an ERR_PTR * if it is malformed. With CONFIG_DEBUG_INFO_BTF=m the BTF lives in the -* btf_vmlinux module; the first caller loads it and parses it. May sleep. +* btf_vmlinux module; the first caller loads it, parses it and then registers +* the BTF of the modules that were loaded before it. May sleep. */ struct btf *bpf_get_btf_vmlinux (void ) {/* Pairs with the smp_store_release() on the parse path below. */ struct btf *btf =smp_load_acquire (&btf_vmlinux); +bool parsed = false;u32 size;if (btf || !IS_ENABLED (CONFIG_DEBUG_INFO_BTF ))
@@ -21965,8 +21967,13 @@ struct btf *bpf_get_btf_vmlinux(void)* on the lockless fast path above. */ smp_store_release (&btf_vmlinux, btf); + parsed = true; }mutex_unlock (&btf_vmlinux_lock); + +if (parsed &&IS_MODULE (CONFIG_DEBUG_INFO_BTF )) +btf_parse_deferred_modules (); +return btf; }
Signature · 1 line
2.47.3
PATCH v3 7/9 bpf: expose deferred .BTF.base module BTF in sysfs from module load
In reply to Jay WangA module with a .BTF.base section (built out of tree) that is loaded before the vmlinux BTF only gets its /sys/kernel/btf file once the vmlinux BTF has been loaded and its BTF relocated, because the raw .BTF is only valid against the distilled base and relocation rewrites it in place. Until then the module is missing from /sys/kernel/btf, unlike with =y, and reading its file cannot trigger the load.
Create the file at module load instead, with its final size: relocation only rewrites type ids and string offsets, never the length. Its reader, btf_module_sysfs_read_deferred(), loads the vmlinux BTF, which parses and relocates the kept modules, then waits until this module's BTF is published (btf_mod->ready) before serving it, so no unrelocated or half-relocated data is ever visible. If the module goes away or its BTF turns out unusable first (btf_mod->gone), the read fails with -ENODEV.
Because that reader may itself be the thread running btf_parse_deferred_modules(), and removing a sysfs file waits for its readers, nothing removes a sysfs file from that path (a failed entry stays dead until the module goes, which the previous patch already arranged), and MODULE_STATE_GOING removes the file after dropping btf_module_mutex, which the reader may need to get there.
Modules without .BTF.base are unchanged: their data is final and is served as is.
--- kernel/bpf/btf.c | 108 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 88 insertions(+), 20 deletions(-)
kernel/bpf/btf.c +88 -20
@@ -9124,17 +9124,27 @@ struct btf_module {u32 data_size;u32 base_data_size;struct list_head deferred_regs; -/* the kept BTF turned out unusable; the entry stays until the module goes */ +/* +* For the sysfs reader of a module whose data is only final once its +* BTF is relocated: @ready once @btf is published, @gone once the +* entry is dead (parse failed or module going). Both only ever go +* from false to true; waiters sleep on btf_module_wq. +*/ +bool ready;bool gone; };static LIST_HEAD (btf_modules);static DEFINE_MUTEX (btf_module_mutex); +static DECLARE_WAIT_QUEUE_HEAD (btf_module_wq);static void purge_cand_cache (struct btf *btf);static int btf_module_sysfs_add (struct btf_module *btf_mod,const char *name, -void *data,size_t data_size) +void *private,size_t size, +ssize_t (*read)(struct file *,struct kobject *, +const struct bin_attribute *, +char *,loff_t ,size_t )) {struct bin_attribute *attr;int err;
@@ -9149,9 +9159,9 @@ static int btf_module_sysfs_add(struct btf_module *btf_mod, const char *name,sysfs_bin_attr_init (attr); attr->attr.name = name; attr->attr.mode =0444 ; - attr->size = data_size; - attr->private = data; - attr->read = sysfs_bin_attr_simple_read; + attr->size = size; + attr->private = private; + attr->read = read; err =sysfs_create_bin_file (btf_kobj, attr);if (err) {
@@ -9165,8 +9175,14 @@ static int btf_module_sysfs_add(struct btf_module *btf_mod, const char *name,return 0 ; } +/* +* Called with btf_module_mutex NOT held: removing the sysfs file waits for +* readers to leave, and a deferred reader may need the mutex to get there. +*/ static void btf_module_free (struct btf_module *btf_mod) { +WRITE_ONCE (btf_mod->gone, true); +wake_up_all (&btf_module_wq);if (btf_mod->sysfs_attr)sysfs_remove_bin_file (btf_kobj, btf_mod->sysfs_attr);if (btf_mod->btf) {
@@ -9221,15 +9237,57 @@ static int btf_vmlinux_module_coming(struct module *mod)return 0 ; } +/* +* sysfs reader for a module kept aside with a .BTF.base section: its .BTF is +* split against the distilled base and only becomes valid split BTF against +* the vmlinux BTF once relocated, which rewrites the buffer in place. So +* first make sure the vmlinux BTF is loaded (which parses and relocates the +* kept modules), then wait until this module's BTF is published. The size +* does not change: relocation only rewrites ids and string offsets. +*/ +static bool btf_module_published (struct btf_module *btf_mod) +{ +/* Pairs with the smp_store_release() of @ready after btf_mod->btf is set */ +return smp_load_acquire (&btf_mod->ready); +} + +static ssize_t btf_module_sysfs_read_deferred (struct file *filp,struct kobject *kobj, +const struct bin_attribute *attr, +char *buf,loff_t off,size_t count) +{ +struct btf_module *btf_mod = attr->private; +int err; + +if (IS_ERR_OR_NULL (bpf_get_btf_vmlinux ())) +return -ENODEV ; + +/* +* Another thread may still be relocating and publishing it; if the +* module goes away or its BTF turns out unusable, btf_module_free() +* or btf_parse_deferred_modules() set @gone and wake us. +*/ + err =wait_event_interruptible (btf_module_wq, +btf_module_published (btf_mod) || +READ_ONCE (btf_mod->gone)); +if (err) +return err; +if (!btf_module_published (btf_mod)) +return -ENODEV ; + +/* sysfs clamps @off and @count to attr->size == btf->data_size */ +memcpy (buf, btf_mod->btf->data + off, count); +return count; +} +/* * The vmlinux BTF is not available yet and must not be loaded from the * module notifier (that would nest a module load into a module load). Keep * the module's BTF for btf_parse_deferred_modules(). * -* Without a .BTF.base section the .BTF data is final and can be exposed in -* sysfs right away, it needs no parsing. With one, parsing relocates the -* data in place against the vmlinux BTF, so the file is created afterwards, -* as with =y where it also only appears once the BTF is parsed. +* The sysfs file is created right away with its final size, as with =y. +* Without a .BTF.base section the .BTF data is final and is served as is; +* with one, it is only valid once relocated, so its reader waits for that +* (btf_module_sysfs_read_deferred()). */ static int btf_module_defer (struct btf_module *btf_mod,struct module *mod) {
@@ -9248,10 +9306,12 @@ static int btf_module_defer(struct btf_module *btf_mod, struct module *mod)return -ENOMEM ; } btf_mod->base_data_size = mod->btf_base_data_size; - }else {/* not fatal, the module BTF is usable without the sysfs file */ +btf_module_sysfs_add (btf_mod, mod->name, btf_mod, btf_mod->data_size, + btf_module_sysfs_read_deferred); + }else {btf_module_sysfs_add (btf_mod, mod->name, btf_mod->data, - btf_mod->data_size); + btf_mod->data_size, sysfs_bin_attr_simple_read); }list_add (&btf_mod->list, &btf_modules);
@@ -9345,7 +9405,8 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,mutex_unlock (&btf_module_mutex);/* not fatal, the module BTF is usable without the sysfs file */ -btf_module_sysfs_add (btf_mod, btf->name, btf->data, btf->data_size); +btf_module_sysfs_add (btf_mod, btf->name, btf->data, btf->data_size, + sysfs_bin_attr_simple_read);break ;case MODULE_STATE_LIVE :mutex_lock (&btf_module_mutex);
@@ -9393,8 +9454,10 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,if (btf_mod->btf)btf_free_id (btf_mod->btf);list_del (&btf_mod->list); +mutex_unlock (&btf_module_mutex); +/* off the list, nobody else can find it now */ btf_module_free (btf_mod); -break ; + goto out; }mutex_unlock (&btf_module_mutex);break ;
@@ -9419,8 +9482,10 @@ fs_initcall(btf_module_init);/* * A kept module whose BTF cannot be used after all. The module is loaded * and stays, so there is no way to reject it: the entry stays on the list, -* dead, until the module goes. A sysfs file it has keeps serving the raw -* data, which is kept for that. +* dead, until the module goes. Its sysfs file stays too, its reader, or +* the caller of this function, may be inside it right now: a .BTF.base +* reader wakes up and fails, a plain one keeps serving the raw data, which +* is kept for that. */ static void btf_module_dead (struct btf_module *btf_mod,const char *what,int err) {
@@ -9428,14 +9493,17 @@ static void btf_module_dead(struct btf_module *btf_mod, const char *what, int erkvfree (btf_mod->base_data); btf_mod->base_data =NULL ;btf_free_deferred_regs (&btf_mod->deferred_regs); - btf_mod->gone = true; +WRITE_ONCE (btf_mod->gone, true); +wake_up_all (&btf_module_wq); }/* * CONFIG_DEBUG_INFO_BTF=m: the vmlinux BTF has just become available. Parse * the BTF of the modules that were loaded before it, and apply the * registrations that waited for them. Called from bpf_get_btf_vmlinux() -* once btf_vmlinux is published, with no locks held. +* once btf_vmlinux is published, with no locks held -- possibly from the +* sysfs reader of one of these modules, which is why no sysfs file is +* removed here. * * A module's BTF is published (btf_mod->btf set, id allocated) only after * its queued registrations are applied, so nobody sees a module BTF without
@@ -9494,11 +9562,11 @@ void btf_parse_deferred_modules(void) goto restart; } -/* modules with .BTF.base get their sysfs file now, the data is relocated */ -if (!btf_mod->sysfs_attr) -btf_module_sysfs_add (btf_mod, btf->name, btf->data, btf->data_size); btf_mod->data =NULL ; btf_mod->btf = btf; +/* Pairs with the smp_load_acquire() in btf_module_sysfs_read_deferred() */ +smp_store_release (&btf_mod->ready, true); +wake_up_all (&btf_module_wq); parsed = true;/* the list may have changed while the mutex was dropped */ goto restart;
Signature · 1 line
2.47.3
PATCH v3 8/9 bpf, trace, net: prepare CONFIG_DEBUG_INFO_BTF checks for a tristate
In reply to Jay WangThe next patch makes CONFIG_DEBUG_INFO_BTF a tristate. With =m, Kconfig defines CONFIG_DEBUG_INFO_BTF_MODULE instead of CONFIG_DEBUG_INFO_BTF, so every check that must hold for both =y and =m has to be written for it:
- #ifdef CONFIG_DEBUG_INFO_BTF becomes #if IS_ENABLED(...) where the generated BTF and its id tables must be the same for =y and =m: the .BTF_ids tables (btf_ids.h), the BTF type tags (compiler_types.h), and the tracepoint and syscall BTF ids (trace_events.h, trace_syscalls.c). Leaving them would silently produce empty id sets with =m.
- obj-$(CONFIG_DEBUG_INFO_BTF) and include-$(CONFIG_DEBUG_INFO_BTF) become $(subst m,y,...) where the object is built into the kernel
regardless: sysfs_btf.o, the netfilter and xfrm kfunc objects, and scripts/Makefile.btf. Otherwise =m would try to build them as modules (xfrm_state_bpf.o fails modpost for lack of MODULE_LICENSE) or skip the BTF generation flags.
- "depends on !DEBUG_INFO_BTF" becomes "depends on DEBUG_INFO_BTF=n" for RUST and GENDWARFKSYMS: with =m the BTF is generated as with =y, so the pahole restrictions they express still apply, but !m is m, which a bool option takes as y.
No functional change: CONFIG_DEBUG_INFO_BTF is still a bool, for which IS_ENABLED() and #ifdef agree, $(subst m,y,y) is y and "=n" is "!".
--- Makefile | 3 ++- include/linux/btf_ids.h | 2 +- include/linux/compiler_types.h | 2 +- include/trace/trace_events.h | 2 +- init/Kconfig | 2 +- kernel/bpf/Makefile | 2 +- kernel/module/Kconfig | 2 +- kernel/trace/trace_syscalls.c | 6 +++--- net/netfilter/Makefile | 6 +++--- net/xfrm/Makefile | 4 ++-- 10 files changed, 16 insertions(+), 15 deletions(-)
Makefile +2 -1
@@ -1208,7 +1208,8 @@ endif # include additional Makefiles when needed include-y := scripts/Makefile.warn include-$(CONFIG_DEBUG_INFO) += scripts/Makefile.debug -include-$(CONFIG_DEBUG_INFO_BTF)+= scripts/Makefile.btf +# CONFIG_DEBUG_INFO_BTF is a tristate; BTF is generated for both y and m +include-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += scripts/Makefile.btf include-$(CONFIG_KASAN) += scripts/Makefile.kasan include-$(CONFIG_KCSAN) += scripts/Makefile.kcsan include-$(CONFIG_KMSAN) += scripts/Makefile.kmsan
include/linux/btf_ids.h +1 -1
@@ -22,7 +22,7 @@ struct btf_id_set8 { } pairs[]; }; -#ifdef CONFIG_DEBUG_INFO_BTF +#if IS_ENABLED (CONFIG_DEBUG_INFO_BTF )#include <linux/compiler.h> /* for __PASTE */ #include <linux/compiler_attributes.h> /* for __maybe_unused */
include/linux/compiler_types.h +1 -1
@@ -34,7 +34,7 @@* Skipped when running bindgen due to a libclang issue; * see https://github.com/rust-lang/rust-bindgen/issues/2244. */ -#if defined(CONFIG_DEBUG_INFO_BTF ) && defined(CONFIG_PAHOLE_HAS_BTF_TAG ) && \ +#if IS_ENABLED (CONFIG_DEBUG_INFO_BTF ) && defined(CONFIG_PAHOLE_HAS_BTF_TAG ) && \__has_attribute (btf_type_tag) && !defined(__BINDGEN__)# define BTF_TYPE_TAG (value) __attribute__((btf_type_tag(#value)))#else
include/trace/trace_events.h +1 -1
@@ -398,7 +398,7 @@ static inline notrace int trace_event_get_offsets_##call( \#define _TRACE_PERF_INIT (call)#endif /* CONFIG_PERF_EVENTS */ -#if defined(CONFIG_BPF_EVENTS ) && defined(CONFIG_DEBUG_INFO_BTF ) +#if defined(CONFIG_BPF_EVENTS ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF )/* * Per-template BTF id list, populated at link time by resolve_btfids: * [0] FUNC __bpf_trace_<call> (the BPF dispatcher)
init/Kconfig +1 -1
@@ -2257,7 +2257,7 @@ config RUST depends on !MODVERSIONS || GENDWARFKSYMS depends on !GCC_PLUGIN_RANDSTRUCT depends on !RANDSTRUCT - depends on !DEBUG_INFO_BTF || (PAHOLE_HAS_LANG_EXCLUDE && !LTO) + depends on DEBUG_INFO_BTF=n || (PAHOLE_HAS_LANG_EXCLUDE && !LTO) depends on !CFI || HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC select CFI_ICALL_NORMALIZE_INTEGERS if CFI depends on !KASAN || CC_IS_CLANG
kernel/bpf/Makefile +1 -1
@@ -41,7 +41,7 @@ ifeq ($(CONFIG_INET),y) obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o endif ifeq ($(CONFIG_SYSFS),y) -obj-$(CONFIG_DEBUG_INFO_BTF) += sysfs_btf.o +obj-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += sysfs_btf.o endif ifeq ($(CONFIG_BPF_JIT),y) obj-$(CONFIG_BPF_SYSCALL) += bpf_struct_ops.o
kernel/module/Kconfig +1 -1
@@ -197,7 +197,7 @@ config GENDWARFKSYMS # X86, requires pahole before commit 47dcb534e253 ("btf_encoder: Stop # indexing symbols for VARs") or after commit 9810758003ce ("btf_encoder: # Verify 0 address DWARF variables are in ELF section"). - depends on !X86 || !DEBUG_INFO_BTF || PAHOLE_VERSION < 128 || PAHOLE_VERSION > 129 + depends on !X86 || DEBUG_INFO_BTF=n || PAHOLE_VERSION < 128 || PAHOLE_VERSION > 129 help Calculate symbol versions from DWARF debugging information using gendwarfksyms. Requires DEBUG_INFO to be enabled.
kernel/trace/trace_syscalls.c +3 -3
@@ -1304,7 +1304,7 @@ struct trace_event_functions exit_syscall_print_funcs = { .trace = print_syscall_exit, }; -#if defined(CONFIG_BPF_EVENTS ) && defined(CONFIG_DEBUG_INFO_BTF ) +#if defined(CONFIG_BPF_EVENTS ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF )/* BTF id lists for the shared sys_enter/sys_exit dispatcher tracepoints. */ BTF_ID_LIST (syscall_enter_btf_ids)BTF_ID (func, __bpf_trace_sys_enter)
@@ -1321,7 +1321,7 @@ struct trace_event_class __refdata event_class_syscall_enter = { .fields_array = syscall_enter_fields_array, .get_fields = syscall_get_enter_fields, .raw_init = init_syscall_trace, -#if defined(CONFIG_BPF_EVENTS ) && defined(CONFIG_DEBUG_INFO_BTF ) +#if defined(CONFIG_BPF_EVENTS ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF ) .btf_ids = syscall_enter_btf_ids,#endif };
@@ -1336,7 +1336,7 @@ struct trace_event_class __refdata event_class_syscall_exit = { }, .fields = LIST_HEAD_INIT(event_class_syscall_exit.fields), .raw_init = init_syscall_trace, -#if defined(CONFIG_BPF_EVENTS ) && defined(CONFIG_DEBUG_INFO_BTF ) +#if defined(CONFIG_BPF_EVENTS ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF ) .btf_ids = syscall_exit_btf_ids,#endif };
net/netfilter/Makefile +3 -3
@@ -18,7 +18,7 @@ nf_conntrack-$(CONFIG_NF_CT_PROTO_GRE) += nf_conntrack_proto_gre.o ifeq ($(CONFIG_NF_CONNTRACK),m) nf_conntrack-$(CONFIG_DEBUG_INFO_BTF_MODULES) += nf_conntrack_bpf.o else ifeq ($(CONFIG_NF_CONNTRACK),y) -nf_conntrack-$(CONFIG_DEBUG_INFO_BTF) += nf_conntrack_bpf.o +nf_conntrack-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += nf_conntrack_bpf.o endif obj-$(CONFIG_NETFILTER) = netfilter.o
@@ -65,7 +65,7 @@ nf_nat-$(CONFIG_NF_NAT_OVS) += nf_nat_ovs.o ifeq ($(CONFIG_NF_NAT),m) nf_nat-$(CONFIG_DEBUG_INFO_BTF_MODULES) += nf_nat_bpf.o else ifeq ($(CONFIG_NF_NAT),y) -nf_nat-$(CONFIG_DEBUG_INFO_BTF) += nf_nat_bpf.o +nf_nat-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += nf_nat_bpf.o endif # NAT helpers
@@ -147,7 +147,7 @@ nf_flow_table-$(CONFIG_NF_FLOW_TABLE_PROCFS) += nf_flow_table_procfs.o ifeq ($(CONFIG_NF_FLOW_TABLE),m) nf_flow_table-$(CONFIG_DEBUG_INFO_BTF_MODULES) += nf_flow_table_bpf.o else ifeq ($(CONFIG_NF_FLOW_TABLE),y) -nf_flow_table-$(CONFIG_DEBUG_INFO_BTF) += nf_flow_table_bpf.o +nf_flow_table-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += nf_flow_table_bpf.o endif obj-$(CONFIG_NF_FLOW_TABLE_INET) += nf_flow_table_inet.o
net/xfrm/Makefile +2 -2
@@ -8,7 +8,7 @@ xfrm_interface-$(CONFIG_XFRM_INTERFACE) += xfrm_interface_core.o ifeq ($(CONFIG_XFRM_INTERFACE),m) xfrm_interface-$(CONFIG_DEBUG_INFO_BTF_MODULES) += xfrm_interface_bpf.o else ifeq ($(CONFIG_XFRM_INTERFACE),y) -xfrm_interface-$(CONFIG_DEBUG_INFO_BTF) += xfrm_interface_bpf.o +xfrm_interface-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += xfrm_interface_bpf.o endif obj-$(CONFIG_XFRM) := xfrm_policy.o xfrm_state.o xfrm_hash.o \
@@ -23,4 +23,4 @@ obj-$(CONFIG_XFRM_IPCOMP) += xfrm_ipcomp.o obj-$(CONFIG_XFRM_INTERFACE) += xfrm_interface.o obj-$(CONFIG_XFRM_IPTFS) += xfrm_iptfs.o obj-$(CONFIG_XFRM_ESPINTCP) += espintcp.o -obj-$(CONFIG_DEBUG_INFO_BTF) += xfrm_state_bpf.o +obj-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += xfrm_state_bpf.o
Signature · 1 line
2.47.3
PATCH v3 9/9 kbuild, bpf: allow building the vmlinux BTF as a module
In reply to Jay WangMake CONFIG_DEBUG_INFO_BTF a tristate. With =m the vmlinux BTF is not part of the kernel image: it is carried by a new module, btf_vmlinux, and loaded the first time something needs it. Nothing that works with =y stops working; the 5.4 MiB of read-only data (distribution config) is simply not there on systems where nothing uses it.
The only way to save that memory today is CONFIG_DEBUG_INFO_BTF=n, which a distribution cannot ship: one binary goes to every user, and off takes BTF away from the users of CO-RE, fentry/fexit, kfuncs, struct_ops, sched_ext or bpf-lsm. Whether BTF is used is a property of the workload, not of the build, so let the first user decide.
The BTF is generated as before, but with =m the .BTF section is linked as a non-loadable section (like .comment), so the kernel image does not load it, and the final step that makes vmlinux from vmlinux.unstripped strips it: every boot image made from vmlinux, whether a raw binary or an ELF copy, is without it. Module BTF is generated against vmlinux.unstripped, which keeps it. .BTF_ids stays loadable, the verifier needs it once the BTF is loaded. The object that carries .BTF also carries .BTF.meta, the size and SHA-256 of the BTF (struct btf_vmlinux_meta, checked by the module notifier); the first link, which the BTF is generated from, gets a zeroed .BTF.meta of the same size. kernel/bpf/btf_vmlinux.c is an empty carrier module; scripts/gen-btf.sh gives it the vmlinux .BTF as its own .BTF section instead of generating split BTF for it, so that one module depends on vmlinux with =m; with CONFIG_DEBUG_INFO_BTF_MODULES all of them do, as before.
CONFIG_BPF_PRELOAD is not selectable with =m: its iterator programs attach through the vmlinux BTF, so every bpffs mount (systemd does one at boot) would load it and defeat the point. Module BTF is still kept when a module loads, as with =y; the saving is the vmlinux BTF only. Programs that need kernel types before the root file system is mounted need btf_vmlinux.ko in the initramfs; the Kconfig help says so.
The module has no exit: once loaded the BTF stays, as with =y. The runtime side -- loading the module on first use, checking it against .BTF.meta, deferring kfunc and struct_ops registrations and module BTF until it arrives -- and the IS_ENABLED()/$(subst m,y,...) preparation of the existing checks are in the preceding patches; this one makes it selectable.
Tested with 1 GiB of memory, same tree, =y vs =m, both with CONFIG_DEBUG_INFO_BTF_MODULES=y:
- MemTotal is ~5.4 MB higher with =m while the BTF is unused: the size of the .BTF section.
- stat() of /sys/kernel/btf/vmlinux reports the BTF size before it is loaded, as the btf_sysfs selftest expects.
- With BTF in use, MemFree is the same within run-to-run noise.
- Modules loaded before the trigger (ext4, nf_conntrack and its kfuncs, xfrm_interface) appear in /sys/kernel/btf immediately and get BTF ids once the BTF is loaded; a socket filter loads without loading the module; a kprobe program calling bpf_get_current_task_btf(), opening /sys/kernel/btf/vmlinux or BPF_BTF_GET_NEXT_ID each load it.
- A carrier module with one byte of its .BTF changed is refused with "BTF does not match this kernel" and leaves no state behind.
- After the load: fstat/read/mmap of /sys/kernel/btf/vmlinux, a struct_ops map for tcp_congestion_ops, a syscall program calling the bpf_task_from_pid()/bpf_task_release() kfuncs, and modules loaded afterwards (nf_nat) all work as with =y.
- =m without DEBUG_INFO_BTF_MODULES, and =y, build and pass the same tests.
--- Documentation/bpf/btf.rst | 35 ++++++++++++ Makefile | 5 +- include/asm-generic/vmlinux.lds.h | 31 +++++++++- kernel/bpf/Makefile | 4 ++ kernel/bpf/btf_vmlinux.c | 23 ++++++++ kernel/bpf/preload/Kconfig | 4 ++ lib/Kconfig.debug | 22 ++++++- scripts/Makefile.modfinal | 26 +++++++-- scripts/Makefile.vmlinux | 5 ++ scripts/gen-btf.sh | 95 +++++++++++++++++++++++++++++-- scripts/link-vmlinux.sh | 25 ++++++-- 11 files changed, 257 insertions(+), 18 deletions(-) create mode 100644 kernel/bpf/btf_vmlinux.c
Documentation/bpf/btf.rst +35 -0
@@ -1276,6 +1276,41 @@ format.:: .long 58 .long 8206 # Line 8 Col 14 +6.1 Kernel BTF +-------------- + +With CONFIG_DEBUG_INFO_BTF=y the BTF of the kernel is generated at link time +from its DWARF and placed in the .BTF section of vmlinux, which is read-only +data of the kernel image. It is available as /sys/kernel/btf/vmlinux and, if +CONFIG_DEBUG_INFO_BTF_MODULES is set, module BTF is generated as split BTF +against it and available as /sys/kernel/btf/<module>. + +With CONFIG_DEBUG_INFO_BTF=m the same BTF is generated, but it is not part of +the kernel image or of the vmlinux ELF file (vmlinux.unstripped in the build +tree keeps it, for module BTF generation). It is delivered by the +btf_vmlinux module, which the kernel loads on demand the first time the BTF is +needed: when /sys/kernel/btf/vmlinux is read or mmap()ed, when kernel BTF +objects are enumerated (BPF_BTF_GET_NEXT_ID), or when a BPF program needs +kernel type information (an attach_btf_id, a kfunc call, a ksym, a map pointer +or a helper that takes or returns a kernel BTF pointer). Until then no memory +is used for it, and afterwards nothing differs from =y. In particular: + + * /sys/kernel/btf/vmlinux exists from boot with its final size. + * Modules loaded before the vmlinux BTF are exposed in /sys/kernel/btf right + away, their BTF is parsed and gets a BTF id once the vmlinux BTF is + loaded, together with their kfunc and struct_ops registrations. + * kfunc, dtor kfunc and struct_ops registrations of the kernel itself are + applied before the BTF becomes visible. + * The kernel only accepts the BTF it was built with: the size and SHA-256 of + the BTF are linked into the kernel and checked against the module. + * Once loaded the BTF stays; the module cannot be unloaded. + +If the module is not available (not installed, or the root file system is not +mounted yet), the kernel behaves as one built without BTF and retries next +time. CONFIG_BPF_PRELOAD is not available with =m: its iterators attach through +the vmlinux BTF, so mounting bpffs would load it. bpf_snprintf_btf() and bpf_seq_printf_btf() only use the BTF if it has +already been parsed, as they run in program context. + 7. Testing ==========
Makefile +3 -2
@@ -1745,8 +1745,9 @@ endif # # *.ko are usually independent of vmlinux, but CONFIG_DEBUG_INFO_BTF_MODULES -# is an exception. -ifdef CONFIG_DEBUG_INFO_BTF_MODULES +# is an exception, and so is the btf_vmlinux module with CONFIG_DEBUG_INFO_BTF=m, +# which carries the vmlinux BTF. +ifneq ($(CONFIG_DEBUG_INFO_BTF_MODULES)$(filter m,$(CONFIG_DEBUG_INFO_BTF)),) KBUILD_BUILTIN := y modules: vmlinux endif
include/asm-generic/vmlinux.lds.h +30 -1
@@ -674,8 +674,18 @@/* * .BTF +* +* With CONFIG_DEBUG_INFO_BTF=y the vmlinux BTF is loaded as read-only data and +* bounded by __start_BTF/__stop_BTF. With CONFIG_DEBUG_INFO_BTF=m it is +* linked as a non-loadable section (see BTF_NOLOAD in ELF_DETAILS), so that +* module BTF generation can read it from vmlinux.unstripped; it is stripped +* from vmlinux (scripts/Makefile.vmlinux), and the btf_vmlinux module carries +* a copy and provides it on demand at runtime. +* What is loaded instead is .BTF.meta, the size and hash of that BTF (see +* scripts/gen-btf.sh), empty in the first link that the BTF is generated +* from. .BTF_ids is needed by the kernel in both cases. */ -#ifdef CONFIG_DEBUG_INFO_BTF +#if IS_BUILTIN (CONFIG_DEBUG_INFO_BTF )#define BTF \ . = ALIGN(PAGE_SIZE); \ .BTF : AT(ADDR(.BTF) - LOAD_OFFSET) { \
@@ -685,10 +695,28 @@ .BTF_ids : AT(ADDR(.BTF_ids) - LOAD_OFFSET) { \ *(.BTF_ids) \ } +#elif IS_MODULE (CONFIG_DEBUG_INFO_BTF ) +#define BTF \ + . = ALIGN(8); \ + .BTF.meta : AT(ADDR(.BTF.meta) - LOAD_OFFSET) { \ + BOUNDED_SECTION_BY(.BTF.meta, _BTF_meta) \ + } \ + . = ALIGN(PAGE_SIZE); \ + .BTF_ids : AT(ADDR(.BTF_ids) - LOAD_OFFSET) { \ + *(.BTF_ids) \ + }#else #define BTF #endif +#if IS_MODULE (CONFIG_DEBUG_INFO_BTF ) +/* quoted: BTF is a macro, an unquoted .BTF here would expand it */ +#define BTF_NOLOAD \ + ".BTF" 0 : { *(".BTF") } +#else +#define BTF_NOLOAD +#endif +/* * Init task */
@@ -849,6 +877,7 @@/* Required sections not related to debugging. */ #define ELF_DETAILS \ .comment 0 : { *(.comment) } \ + BTF_NOLOAD \ .symtab 0 : { *(.symtab) } \ .strtab 0 : { *(.strtab) } \ .shstrtab 0 : { *(.shstrtab) } \
kernel/bpf/Makefile +4 -0
@@ -43,6 +43,10 @@ endif ifeq ($(CONFIG_SYSFS),y) obj-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += sysfs_btf.o endif +# With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF is carried by this module +ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +obj-m += btf_vmlinux.o +endif ifeq ($(CONFIG_BPF_JIT),y) obj-$(CONFIG_BPF_SYSCALL) += bpf_struct_ops.o obj-$(CONFIG_BPF_SYSCALL) += cpumask.o
kernel/bpf/btf_vmlinux.c new file +23 -0
@@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Carrier module for the vmlinux BTF when CONFIG_DEBUG_INFO_BTF=m. +* +* This module has no code of its own. Its .BTF section is a copy of the +* vmlinux BTF (see scripts/gen-btf.sh), which the BTF module notifier in +* kernel/bpf/btf.c recognizes by module name and installs as the vmlinux BTF. +* The kernel loads it on demand, the first time the vmlinux BTF is needed. +* +* There is deliberately no module_exit(): once the BTF is in use it cannot +* be taken away again, exactly as with CONFIG_DEBUG_INFO_BTF=y. +*/ +#include <linux/init.h> +#include <linux/module.h> + +static int __init btf_vmlinux_init (void ) +{ +return 0 ; +} +module_init (btf_vmlinux_init); + +MODULE_DESCRIPTION ("BTF type information for vmlinux" ); +MODULE_LICENSE ("GPL" );
kernel/bpf/preload/Kconfig +4 -0
@@ -6,6 +6,10 @@ menuconfig BPF_PRELOAD # The dependency on !COMPILE_TEST prevents it from being enabled # in allmodconfig or allyesconfig configurations depends on !COMPILE_TEST + # The preloaded iterators attach through the vmlinux BTF, so with + # CONFIG_DEBUG_INFO_BTF=m every bpffs mount would load the BTF, which + # defeats the point of =m on any system that mounts bpffs at boot. + depends on DEBUG_INFO_BTF!=m help This builds kernel module with several embedded BPF programs that are pinned into BPF FS mount point as human readable files that are
lib/Kconfig.debug +21 -1
@@ -396,7 +396,7 @@ config DEBUG_INFO_SPLIT Incompatible with older versions of ccache. config DEBUG_INFO_BTF - bool "Generate BTF type information" + tristate "Generate BTF type information" depends on !DEBUG_INFO_SPLIT && !DEBUG_INFO_REDUCED depends on !GCC_PLUGIN_RANDSTRUCT || COMPILE_TEST depends on BPF_SYSCALL
@@ -408,6 +408,26 @@ config DEBUG_INFO_BTF Turning this on requires pahole v1.22 or later, which will convert DWARF type info into equivalent deduplicated BTF type info. + If built as a module (=m), the vmlinux BTF is not part of the + kernel image. It is carried by the btf_vmlinux module, which is + loaded on demand the first time the BTF is needed: when a BPF + program requires kernel type information, or when + /sys/kernel/btf/vmlinux is opened. Until then, no memory is + spent on it. The vmlinux ELF file does not carry the BTF + either; module BTF is generated against vmlinux.unstripped, and + tools that read the BTF from a file can use that or + /sys/kernel/btf/vmlinux. + + Module BTF (DEBUG_INFO_BTF_MODULES) is kept when a module loads, + as with =y, and registered once the vmlinux BTF is available; the + saving is the vmlinux BTF only. + + If BPF programs that use kernel types run before the root file + system is mounted, put btf_vmlinux.ko into the initramfs: until + the module can be loaded, such programs fail as on a kernel + without BTF. Not compatible with BPF_PRELOAD, whose iterators + would load the BTF at every bpffs mount. + config PAHOLE_HAS_BTF_TAG def_bool PAHOLE_VERSION >= 123 depends on CC_IS_CLANG
scripts/Makefile.modfinal +20 -6
@@ -38,20 +38,34 @@ quiet_cmd_ld_ko_o = LD [M] $@ $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \ -T $(objtree)/scripts/module.lds -o $@ $(filter %.o, $^) +# The ELF file with the vmlinux BTF: with CONFIG_DEBUG_INFO_BTF=m the BTF is +# stripped from vmlinux (scripts/Makefile.vmlinux), vmlinux.unstripped keeps it. +btf-vmlinux := $(objtree)/vmlinux$(if $(filter m,$(CONFIG_DEBUG_INFO_BTF)),.unstripped) + quiet_cmd_btf_ko = BTF [M] $@ cmd_btf_ko = \ - if [ ! -f $(objtree)/vmlinux ]; then \ + if [ ! -f $(btf-vmlinux) ]; then \ printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \ else \ - $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \ + $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(btf-vmlinux) $@; \ fi; -# Re-generate module BTFs if either module's .ko or vmlinux changed -%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(objtree)/vmlinux) FORCE - +$(call if_changed,ld_ko_o) +# Modules that get a .BTF section: all of them with CONFIG_DEBUG_INFO_BTF_MODULES, +# otherwise only the vmlinux BTF carrier module with CONFIG_DEBUG_INFO_BTF=m. ifdef CONFIG_DEBUG_INFO_BTF_MODULES - +$(if $(newer-prereqs),$(call cmd,btf_ko)) +btf-modules := $(modules:%.o=%.ko) +else ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +btf-modules := $(filter %/btf_vmlinux.ko,$(modules:%.o=%.ko)) +# Only the carrier depends on vmlinux, not every module +ifdef KBUILD_BUILTIN +$(btf-modules): $(btf-vmlinux) +endif endif + +# Re-generate module BTFs if either module's .ko or vmlinux changed +%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(btf-vmlinux)) FORCE + +$(call if_changed,ld_ko_o) + +$(if $(and $(filter $@,$(btf-modules)),$(newer-prereqs)),$(call cmd,btf_ko)) +$(call cmd,check_tracepoint) targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
scripts/Makefile.vmlinux +5 -0
@@ -86,6 +86,11 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel*' '!.rel*.dyn' # for compatibility with binutils < 2.32 # https://sourceware.org/git/?p=binutils-gdb.git;a=commit;h=c12d9fa2afe7abcbe407a00e15719e1a1350c2a7 remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*' +# With CONFIG_DEBUG_INFO_BTF=m the btf_vmlinux module carries the vmlinux BTF; +# only vmlinux.unstripped keeps it, for module BTF generation. +ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +remove-section-y += .BTF +endif remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*'
scripts/gen-btf.sh +91 -4
146 lines not on this page · raw message
scripts/link-vmlinux.sh +21 -4
@@ -37,6 +37,15 @@ is_enabled() { grep -q "^$1=y" include/config/auto.conf } +is_module() { + grep -q "^$1=m" include/config/auto.conf +} + +# =y or =m +is_set() { + grep -q "^$1=[ym]" include/config/auto.conf +} + # Nice output in kbuild format # Will be suppressed by "make -s" info()
@@ -211,17 +220,25 @@ if is_enabled CONFIG_KALLSYMS; then kallsyms .tmp_vmlinux0.syms .tmp_vmlinux0.kallsyms fi -if is_enabled CONFIG_KALLSYMS || is_enabled CONFIG_DEBUG_INFO_BTF; then +if is_module CONFIG_DEBUG_INFO_BTF; then + # The kernel refers to the size and hash of its BTF, which only the + # BTF generated from the first link can provide; link a placeholder + # of the same layout until then. + ${CONFIG_SHELL} ${srctree}/scripts/gen-btf.sh --placeholder .tmp_vmlinux0 + btf_vmlinux_bin_o=.tmp_vmlinux0.btf.o +fi + +if is_enabled CONFIG_KALLSYMS || is_set CONFIG_DEBUG_INFO_BTF; then # The kallsyms linking does not need debug symbols, but the BTF does. - if ! is_enabled CONFIG_DEBUG_INFO_BTF; then + if ! is_set CONFIG_DEBUG_INFO_BTF; then strip_debug=1 fi vmlinux_link .tmp_vmlinux1 fi -if is_enabled CONFIG_DEBUG_INFO_BTF; then +if is_set CONFIG_DEBUG_INFO_BTF; then info BTF .tmp_vmlinux1 if ! ${CONFIG_SHELL} ${srctree}/scripts/gen-btf.sh .tmp_vmlinux1; then echo >&2 "Failed to generate BTF for vmlinux"
@@ -287,7 +304,7 @@ fi vmlinux_link "${VMLINUX}" -if is_enabled CONFIG_DEBUG_INFO_BTF; then +if is_set CONFIG_DEBUG_INFO_BTF; then info BTFIDS ${VMLINUX} ${RESOLVE_BTFIDS} --patch_btfids ${btfids_vmlinux} ${VMLINUX} fi
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH bpf-next v3 6/9] bpf: keep module BTF until the vmlinux BTF is available
In reply to Jay WangThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] bpf: memory leak of module BTF data on parse failure for .BTF.base modules --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] bpf: memory leak of module BTF data on parse failure for .BTF.base modules --
commit 10719f6f8154699a27d9151dc131b89e1ea34139
Author: Jay Wang <[email protected]>
bpf: keep module BTF until the vmlinux BTF is available
Module BTF is split BTF against the vmlinux BTF and is parsed in the module notifier. With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF may not be loaded yet when a module loads, and the notifier cannot load btf_vmlinux (that would nest a module load in a module load).
Quoted 4 lines
kernel/bpf/btf.c +0
-0
[ ... ]
Quoted 10 lines
kernel/bpf/btf.c +6
-0@@ -9309,6 +9414,101 @@ static int __init btf_module_init(void) }fs_initcall (btf_module_init); + +#if IS_MODULE (CONFIG_DEBUG_INFO_BTF ) +/* +* A kept module whose BTF cannot be used after all. The module is loaded +* and stays, so there is no way to reject it: the entry stays on the list, +* dead, until the module goes. A sysfs file it has keeps serving the raw
kernel/bpf/btf.c static int __init btf_module_init(void) · line 9432
Quoted 10 lines
kernel/bpf/btf.c +10
-0+* data, which is kept for that. +*/ +static void btf_module_dead (struct btf_module *btf_mod,const char *what,int err) +{ +pr_warn ("failed to %s module [%s] BTF: %d\n" , what, btf_mod->module->name, err); +kvfree (btf_mod->base_data); + btf_mod->base_data =NULL ; +btf_free_deferred_regs (&btf_mod->deferred_regs); + btf_mod->gone = true; +}
[Severity: Low]
Does this code leak btf_mod->data when parsing fails for modules with a .BTF.base section?
If a module with a .BTF.base section is loaded before the vmlinux BTF, and its deferred BTF parsing subsequently fails when the vmlinux BTF is loaded, the memory btf_mod->data is retained because btf_module_dead() assumes the sysfs file will continue to serve the raw data.
However, for .BTF.base modules, the sysfs file uses btf_module_sysfs_read_deferred(), which returns -ENODEV when the module is marked as gone. As a result, the memory is inaccessible and uselessly retained until the module is unloaded.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
[email protected]
AI reviewRe: [PATCH bpf-next v3 3/9] bpf: fetch the vmlinux BTF where kernel types enter a program
In reply to Jay WangThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf: state-dependent verification failure for BTF-independent programs --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: state-dependent verification failure for BTF-independent programs --
commit f6fc508c855b2ee6adf6ef6d3d2ccfe35410bcf1
Author: Jay Wang <[email protected]>
bpf: fetch the vmlinux BTF where kernel types enter a program
This commit delays fetching the vmlinux BTF until kernel types actually enter the verifier state. This prevents unnecessary loading and parsing of BTF for BTF-independent programs like socket filters, saving memory and parsing overhead.
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
kernel/bpf/verifier.c int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, · line 22583
Quoted 6 lines
kernel/bpf/verifier.c +1
-1@@ -22532,10 +22580,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,mark_verifier_state_clean (env); -if (IS_ERR (btf_vmlinux)) { +if (IS_ERR (bpf_peek_btf_vmlinux ())) {
[Severity: High]
Could this introduce a state-dependent verification failure for BTF-independent programs?
When a BTF-independent program (like a systemd socket filter) is loaded initially, the bpf_peek_btf_vmlinux() helper returns a null pointer and this check is bypassed.
If a BTF-dependent program is later loaded under memory pressure, the btf_parse_vmlinux() routine could fail with a memory allocation error. When the kernel is configured with BTF enabled, bpf_get_btf_vmlinux() permanently stores this error pointer in the global btf_vmlinux variable.
Subsequent loads of completely unrelated, BTF-independent programs will now see the error pointer returned by bpf_peek_btf_vmlinux() evaluate to true and fail with an in-kernel BTF is malformed error in bpf_check().
Will this unintentionally cause transient memory failures during BTF parsing to permanently break unrelated critical system services?
Quoted 7 lines
kernel/bpf/verifier.c +1
-1/* Either gcc or pahole or kernel are broken. */ verbose (env,"in-kernel BTF is malformed\n" ); - ret =PTR_ERR (btf_vmlinux); + ret =PTR_ERR (bpf_peek_btf_vmlinux ()); goto skip_full_check; }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
[email protected]
AI reviewRe: [PATCH bpf-next v3 8/9] bpf, trace, net: prepare CONFIG_DEBUG_INFO_BTF checks for a tristate
In reply to Jay WangCan this change introduce a deadlock when DEBUG_INFO_BTF=m and the btf_vmlinux module is not yet loaded?
Quoted 14 lines
Makefile +2
-1@@ -1208,7 +1208,8 @@ endif # include additional Makefiles when needed include-y := scripts/Makefile.warn include-$(CONFIG_DEBUG_INFO) += scripts/Makefile.debug -include-$(CONFIG_DEBUG_INFO_BTF)+= scripts/Makefile.btf +# CONFIG_DEBUG_INFO_BTF is a tristate; BTF is generated for both y and m +include-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += scripts/Makefile.btf include-$(CONFIG_KASAN) += scripts/Makefile.kasan include-$(CONFIG_KCSAN) += scripts/Makefile.kcsan include-$(CONFIG_KMSAN) += scripts/Makefile.kmsan
[ ... ]
include/trace/trace_events.h static inline notrace int trace_event_get_offsets_##call( \ · line 401
Quoted 10 lines
include/trace/trace_events.h +1
-1@@ -398,7 +398,7 @@ static inline notrace int trace_event_get_offsets_##call( \#define _TRACE_PERF_INIT (call)#endif /* CONFIG_PERF_EVENTS */ -#if defined(CONFIG_BPF_EVENTS ) && defined(CONFIG_DEBUG_INFO_BTF ) +#if defined(CONFIG_BPF_EVENTS ) &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF )
Can this change introduce a deadlock when DEBUG_INFO_BTF=m and the btf_vmlinux module is not yet loaded?
Before this change, with =m the preprocessor guard was false, so _TRACE_BTF_IDS_INIT() expanded to nothing and trace_event_class.btf_ids stayed NULL. With IS_ENABLED() the guard is now true for both =y and =m, so built-in tracepoint classes initialize .btf_ids and create events/<sys>/<event>/btf_ids tracefs files.
Reading that file for a built-in event goes through event_btf_ids_read() in kernel/trace/trace_events.c:
scoped_guard(mutex, &event_mutex) {
...
ids = call->class->btf_ids;
...
btf = btf_get_module_btf(mod); /* mod == NULL for built-in */btf_get_module_btf(NULL) calls bpf_get_btf_vmlinux(), which in the IS_MODULE(CONFIG_DEBUG_INFO_BTF) case calls request_module("btf_vmlinux") when the vmlinux BTF has not been loaded yet.
request_module() waits for modprobe to exit (UMH_WAIT_PROC) while event_mutex is still held. Meanwhile, modprobe does finit_module() -> load_module() -> prepare_coming_module(), which calls trace_module_notify():
mutex_lock(&event_mutex);
mutex_lock(&trace_types_lock);so the btf_vmlinux module load blocks on event_mutex held by the reader, and the reader blocks waiting for modprobe.
The reader hangs until SIGKILLed, and every other module load and event_mutex user (enabling/disabling events, kprobe/uprobe creation, etc.) is stuck. Trigger: with DEBUG_INFO_BTF=m and btf_vmlinux not yet loaded, cat /sys/kernel/tracing/events/sched/sched_switch/btf_ids (or any syscall event's btf_ids).
Should the BTF be resolved before taking event_mutex, or should this path return -ENOENT when the vmlinux BTF is not yet present?
[ ... ]
---
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/36198628965
[email protected]
AI reviewRe: [PATCH bpf-next v3 4/9] bpf: take the vmlinux BTF from the btf_vmlinux module
In reply to Jay WangDoes this error path account for deterministic parse failures?
Quoted 12 lines
include/linux/btf.h +1
-0@@ -602,6 +602,7 @@ __u32 *btf_field_iter_next(struct btf_field_iter *it);const char *btf_name_by_offset (const struct btf *btf,u32 offset);const char *btf_str_by_offset (const struct btf *btf,u32 offset);struct btf *btf_parse_vmlinux (void ); +void *btf_vmlinux_data (u32 *size,bool load); struct bpf_prog_get_target_btf(const struct bpf_prog *prog);u32 *btf_kfunc_flags (const struct btf *btf,u32 kfunc_btf_id,const struct bpf_prog *prog);int btf_kfunc_check_flag (const struct btf *btf,u32 kfunc_btf_id,u32 flag);
[ ... ]
Quoted 45 lines
kernel/bpf/verifier.c +20
-12@@ -21922,26 +21922,51 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btreturn 0 ; } +/* +* Returns the parsed vmlinux BTF, NULL if the kernel has none, or an ERR_PTR +* if it is malformed. With CONFIG_DEBUG_INFO_BTF=m the BTF lives in the +* btf_vmlinux module; the first caller loads it and parses it. May sleep. +*/ struct btf *bpf_get_btf_vmlinux (void ) {/* Pairs with the smp_store_release() on the parse path below. */ struct btf *btf =smp_load_acquire (&btf_vmlinux); +u32 size; -if (!btf &&IS_ENABLED (CONFIG_DEBUG_INFO_BTF )) { -mutex_lock (&btf_vmlinux_lock); - btf = btf_vmlinux; -if (!btf) { - btf =btf_parse_vmlinux (); -/* -* Order the parsed BTF contents and the globals the -* parse populated (e.g. bpf_ctx_convert.t) before -* the pointer publication. Pairs with the acquire -* on the lockless fast path above. -*/ -smp_store_release (&btf_vmlinux, btf); +if (btf || !IS_ENABLED (CONFIG_DEBUG_INFO_BTF )) +return btf; + +/* +* Loading the module may take a while and its notifier must not be +* blocked by us, so do it outside btf_vmlinux_lock. Not available: +* behave like a kernel without BTF, and retry next time. +*/ +if (!btf_vmlinux_data (&size, true)) +return NULL ; + +mutex_lock (&btf_vmlinux_lock); + btf = btf_vmlinux; +if (!btf) {
kernel/bpf/verifier.c int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt · line 21959
Quoted 10 lines
kernel/bpf/verifier.c +10
-0+ btf =btf_parse_vmlinux (); +/* +* With =m the BTF was checked against the kernel when the +* module loaded, so a failure here is a resource problem +* (-ENOMEM) rather than a broken BTF: do not remember it, +* the next caller retries. +*/ +if (IS_MODULE (CONFIG_DEBUG_INFO_BTF ) &&IS_ERR (btf)) { +mutex_unlock (&btf_vmlinux_lock); +return btf;
Does this error path account for deterministic parse failures?
The comment states that with CONFIG_DEBUG_INFO_BTF=m a parse failure here is a resource problem (-ENOMEM) because the payload was checked when the module loaded. btf_vmlinux_module_coming() does verify the size and SHA-256 match the .BTF.meta values this kernel was built with.
However, btf_parse_vmlinux() calls btf_parse_base(), which can still fail with errors that depend only on the content:
kernel/bpf/btf.c:btf_parse_base()
btf_parse_hdr() -> -E2BIG, -ENOENT, -EINVAL
btf_parse_str_sec() -> -EINVAL
btf_check_all_metas() -> -EINVAL for unknown kind or bad name
btf_check_modifier_chain_length() -> -ELOOPThese checks are deterministic. A broken BTF would fail on every attempt, yet the code never caches the error. With CONFIG_DEBUG_INFO_BTF=y the same condition gives 'in-kernel BTF is malformed' and the ERR_PTR is cached once. With =m, every later caller repeats the full parse of the ~5.4 MiB BTF while holding btf_vmlinux_lock: kvmalloc of the types array, a walk over all metas, then the free.
Callers include bpf_prog_load(), struct_ops map creation, BPF_BTF_GET_NEXT_ID (which runs before the CAP_SYS_ADMIN check in bpf_obj_get_next_id()), and read()/mmap() of the 0444 /sys/kernel/btf/vmlinux. An unprivileged user can therefore make the kernel re-parse repeatedly and serialize other BTF users behind the mutex.
Also, /sys/kernel/btf/vmlinux returns -ENODEV even though the raw bytes are present, because btf_sysfs_vmlinux_load() requires a successful parse.
Would it be better to cache only on content errors (e.g. all errors except -ENOMEM) and retry resource failures, or to skip caching only on specific errors?
kernel/bpf/verifier.c int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt · line 21971
Quoted 13 lines
kernel/bpf/verifier.c +8
-1} -mutex_unlock (&btf_vmlinux_lock); +/* +* Order the parsed BTF contents and the globals the +* parse populated (e.g. bpf_ctx_convert.t) before +* the pointer publication. Pairs with the acquire +* on the lockless fast path above. +*/ +smp_store_release (&btf_vmlinux, btf); } +mutex_unlock (&btf_vmlinux_lock);return btf; }
[ ... ]
---
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/36198628965
[email protected]
AI reviewRe: [PATCH bpf-next v3 7/9] bpf: expose deferred .BTF.base module BTF in sysfs from module load
In reply to Jay WangCan btf_module_notify() deadlock here during MODULE_STATE_GOING?
Quoted 4 lines
kernel/bpf/btf.c +0
-0
[ ... ]
Quoted 14 lines
kernel/bpf/btf.c +6
-0@@ -9165,8 +9175,14 @@ static int btf_module_sysfs_add(struct btf_module *btf_mod, const char *name,return 0 ; } +/* +* Called with btf_module_mutex NOT held: removing the sysfs file waits for +* readers to leave, and a deferred reader may need the mutex to get there. +*/ static void btf_module_free (struct btf_module *btf_mod) { +WRITE_ONCE (btf_mod->gone, true); +wake_up_all (&btf_module_wq);if (btf_mod->sysfs_attr)sysfs_remove_bin_file (btf_kobj, btf_mod->sysfs_attr);
[ ... ]
Quoted 27 lines
kernel/bpf/btf.c +23
-0@@ -9221,15 +9237,57 @@ static int btf_vmlinux_module_coming(struct module *mod)return 0 ; } +/* +* sysfs reader for a module kept aside with a .BTF.base section: its .BTF is +* split against the distilled base and only becomes valid split BTF against +* the vmlinux BTF once relocated, which rewrites the buffer in place. So +* first make sure the vmlinux BTF is loaded (which parses and relocates the +* kept modules), then wait until this module's BTF is published. The size +* does not change: relocation only rewrites ids and string offsets. +*/ +static bool btf_module_published (struct btf_module *btf_mod) +{ +/* Pairs with the smp_store_release() of @ready after btf_mod->btf is set */ +return smp_load_acquire (&btf_mod->ready); +} + +static ssize_t btf_module_sysfs_read_deferred (struct file *filp,struct kobject *kobj, +const struct bin_attribute *attr, +char *buf,loff_t off,size_t count) +{ +struct btf_module *btf_mod = attr->private; +int err; + +if (IS_ERR_OR_NULL (bpf_get_btf_vmlinux ())) +return -ENODEV ;
[ ... ]
kernel/bpf/btf.c static int btf_module_notify(struct notifier_block *nb, unsigned long op, · line 9463
Quoted 12 lines
kernel/bpf/btf.c +3
-1@@ -9393,8 +9454,10 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,if (btf_mod->btf)btf_free_id (btf_mod->btf);list_del (&btf_mod->list); +mutex_unlock (&btf_module_mutex); +/* off the list, nobody else can find it now */ btf_module_free (btf_mod); -break ; + goto out; }mutex_unlock (&btf_module_mutex);break ;
Can btf_module_notify() deadlock here during MODULE_STATE_GOING?
The MODULE_STATE_GOING notifier runs from blocking_notifier_call_chain(&module_notify_list, ...), which holds module_notify_list.rwsem for read. This patch moves btf_module_free() outside btf_module_mutex, and btf_module_free() calls sysfs_remove_bin_file(), which waits uninterruptibly in kernfs_drain() until every active reader has returned.
This patch made that reader btf_module_sysfs_read_deferred(), which starts with:
if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
return -ENODEV;If the vmlinux BTF has not been loaded yet, bpf_get_btf_vmlinux() calls btf_vmlinux_data(&size, true), which calls request_module("btf_vmlinux"). That waits (UMH_WAIT_PROC | UMH_KILLABLE) for modprobe.
modprobe's load_module() calls prepare_coming_module(), which calls blocking_notifier_call_chain_robust(&module_notify_list, MODULE_STATE_COMING, ...) and needs down_read() on the same rwsem.
If a writer is queued on that rwsem, new readers block once the handoff bit is set. Writers come from register_module_notifier() or unregister_module_notifier(), called for example from kunit_init() when kunit is modular, or from a module exit that unregisters its notifier.
The resulting cycle is:
rmmod X (GOING, holds rwsem for read)
-> kernfs_drain waits for the reader of /sys/kernel/btf/X
reader of X
-> request_module("btf_vmlinux") waits for modprobe modprobe btf_vmlinux
-> down_read(module_notify_list.rwsem) waits for the queued writer
writer
-> down_write waits for rmmod X to release its read side
Everything stays in D state until the reader gets SIGKILL. Meanwhile every other module load or unload also stalls on the notifier chain.
Before this patch, a deferred .BTF.base module had no sysfs file until btf_parse_deferred_modules() had relocated it. No reader could block, so the drain in GOING could not wait on a module load.
The new code conflicts with the rationale stated in btf_module_defer():
"The vmlinux BTF ... must not be loaded from the module notifier (that would nest a module load into a module load)". The GOING notifier now waits on exactly that nested load, through the reader.
Possible fixes: do not trigger the vmlinux BTF load from this reader (serve -ENODEV/-EAGAIN until the BTF is published, or only wait when btf_vmlinux is already set); or remove the sysfs file in a way that does not wait under the notifier chain (for example, kernfs_break_active_protection() in the reader around the request_module()/wait, with the btf_mod lifetime guarded separately).
Also, this patch changes the lock ordering that affects a comment elsewhere in the file. The comment for btf_vmlinux_regs_mutex justifies the separate mutex by saying that purge_cand_cache() takes cand_cache_mutex under btf_module_mutex. That was only true through btf_module_free() on the GOING path, which this patch moves outside btf_module_mutex (as shown above).
The remaining purge_cand_cache() callers, in btf_module_notify() COMING and at the end of btf_parse_deferred_modules(), already run without btf_module_mutex. No btf_module_mutex -> cand_cache_mutex chain is left, so the stated reason for the ordering rule is gone.
The ordering that matters now is kernfs active reference -> btf_vmlinux_lock/btf_module_mutex, which comes from the new deferred sysfs reader. Should that comment be updated to reflect the current lock ordering rationale?
---
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/36198628965
[email protected]
AI reviewRe: [PATCH bpf-next v3 5/9] bpf: defer vmlinux kfunc and struct_ops registrations
In reply to Jay WangDoes the lock ordering explanation match the actual code? Looking at the earlier patch 806240f10744 ("bpf: fetch the vmlinux BTF where kernel types enter a program"), both CO-RE callers now call…
Quoted 4 lines
kernel/bpf/btf.c +0
-0
[ ... ]
kernel/bpf/btf.c int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops) · line 10802
Quoted 8 lines
kernel/bpf/btf.c +8
-0+#ifdef BTF_MODULE_NOTIFIER +/* +* The queue has its own lock: it is drained under btf_vmlinux_lock, and +* btf_module_mutex must not nest inside that (purge_cand_cache() takes +* cand_cache_mutex under btf_module_mutex, and CO-RE fetches the vmlinux +* BTF under cand_cache_mutex). +*/ +static DEFINE_MUTEX (btf_vmlinux_regs_mutex);
Does the lock ordering explanation match the actual code? Looking at the earlier patch 806240f10744 ("bpf: fetch the vmlinux BTF where kernel types enter a program"), both CO-RE callers now call bpf_get_btf_vmlinux() before taking cand_cache_mutex:
kernel/bpf/btf.c:bpf_core_apply() {
/* candidates are kernel types: load the vmlinux BTF, outside the mutex */
if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
...
mutex_lock(&cand_cache_mutex);and bpf_core_find_cands() uses only bpf_peek_btf_vmlinux() under the mutex, which takes no lock. Its comment reads "Callers fetch the vmlinux BTF before taking cand_cache_mutex."
So the btf_vmlinux_lock -> btf_module_mutex -> cand_cache_mutex -> btf_vmlinux_lock cycle described here does not exist in this tree.
The separate lock is fine. Could the comment and commit message explain what actually prevents btf_module_mutex from nesting under btf_vmlinux_lock, or point to what the next patch adds that would create that constraint?
---
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/36198628965
[email protected]
AI reviewRe: [PATCH bpf-next v3 9/9] kbuild, bpf: allow building the vmlinux BTF as a module
In reply to Jay WangThe statement "Nothing that works with =y stops working" appears to have exceptions. The patch itself adds this to kernel/bpf/preload/Kconfig:
Quoted 5 lines
Make
CONFIG_DEBUG_INFO_BTFa tristate. With =m the vmlinux BTF is not part of the kernel image: it is carried by a new module,btf_vmlinux, and loaded the first time something needs it. Nothing that works with =y stops working; the 5.4 MiB of read-only data (distribution config) is simply not there on systems where nothing uses it.
The statement "Nothing that works with =y stops working" appears to have exceptions. The patch itself adds this to kernel/bpf/preload/Kconfig:
Quoted 1 line
depends on DEBUG_INFO_BTF!=m
This makes BPF_PRELOAD no longer selectable with =m, and a later paragraph acknowledges this ("CONFIG_BPF_PRELOAD is not selectable with =m").
Additionally, BPF programs that need kernel types before the root file system is mounted work with =y but fail with =m unless btf_vmlinux.ko is in the initramfs, which the changelog mentions later.
Could the opening sentence be reworded to acknowledge these exceptions, for example: "Apart from BPF_PRELOAD and early-boot users without btf_vmlinux.ko in the initramfs, nothing that works with =y stops working"?
Quoted 16 lines
Documentation/bpf/btf.rst +8
-0@@ -1276,6 +1276,41 @@ format.:: .long 58 .long 8206 # Line 8 Col 14 +6.1 Kernel BTF +-------------- + +With CONFIG_DEBUG_INFO_BTF=y the BTF of the kernel is generated at link time +from its DWARF and placed in the .BTF section of vmlinux, which is read-only +data of the kernel image. It is available as /sys/kernel/btf/vmlinux and, if +CONFIG_DEBUG_INFO_BTF_MODULES is set, module BTF is generated as split BTF +against it and available as /sys/kernel/btf/<module>.
Documentation/bpf/btf.rst format.:: · line 1296
Quoted 10 lines
Documentation/bpf/btf.rst +10
-0+ +With CONFIG_DEBUG_INFO_BTF=m the same BTF is generated, but it is not part of +the kernel image or of the vmlinux ELF file (vmlinux.unstripped in the build +tree keeps it, for module BTF generation). It is delivered by the +btf_vmlinux module, which the kernel loads on demand the first time the BTF is +needed: when /sys/kernel/btf/vmlinux is read or mmap()ed, when kernel BTF +objects are enumerated (BPF_BTF_GET_NEXT_ID), or when a BPF program needs +kernel type information (an attach_btf_id, a kfunc call, a ksym, a map pointer +or a helper that takes or returns a kernel BTF pointer). Until then no memory +is used for it, and afterwards nothing differs from =y. In particular:
The new section lists when the btf_vmlinux module is loaded, and mentions that bpf_snprintf_btf() and bpf_seq_printf_btf() handle the missing-BTF case because they run in program context. The ftrace argument printer is another caller that can reach the loader, and it can run with interrupts disabled.
With CONFIG_DEBUG_INFO_BTF=m, CONFIG_FUNCTION_TRACE_ARGS is still enabled because it depends on PROBE_EVENTS_BTF_ARGS, which is a bool that treats the m dependency as y. The func-args and funcgraph-args trace options print arguments through this call chain:
kernel/trace/trace_output.c:print_function_args():
t = btf_find_func_proto(name, &btf);
kernel/trace/trace_btf.c:btf_find_func_proto():
id = bpf_find_btf_id(func_name, BTF_KIND_FUNC, btf_p);
kernel/bpf/btf.c:bpf_find_btf_id():
btf = bpf_get_btf_vmlinux();
kernel/bpf/verifier.c:bpf_get_btf_vmlinux():
if (!btf_vmlinux_data(&size, true))
kernel/bpf/btf.c:btf_vmlinux_data():
request_module("btf_vmlinux");
This is also reached from ftrace_dump() in the oops/panic notifier and from sysrq-z:
kernel/trace/trace.c:ftrace_dump_one():
local_irq_save(flags);
...
ret = print_trace_line(&iter); -> ... -> print_function_args()
request_module() sleeps: it calls down_timeout() and call_modprobe(..., UMH_WAIT_PROC), which waits for a usermode helper. If the BTF has not been parsed yet, bpf_get_btf_vmlinux() takes mutex_lock(&btf_vmlinux_lock) with GFP_KERNEL allocations. Either way, this path sleeps with interrupts disabled. In panic, the other CPUs have been stopped, so the modprobe wait may hang and block the dump or any reboot after it.
With =y, late_initcall kfunc registrations parse the vmlinux BTF during boot, so this path only does the lockless acquire load. With =m, btf_defer_reg() queues those registrations and does not load the BTF, so it can stay NULL until the trace printer runs.
Can this be triggered with CONFIG_DEBUG_INFO_BTF=m, func-args or funcgraph-args set, ftrace_dump_on_oops (or sysrq-z), and no BPF user of the vmlinux BTF since boot?
One option is to make print_function_args() use bpf_peek_btf_vmlinux(), as bpf_btf_printf_prepare() already does. The doc trigger list also leaves out other non-program loaders: reading the trace file with func-args, kprobe/fprobe events with BTF arguments, struct_ops map creation, bpffs delegate_* options and netfilter ctx access.
Quoted 15 lines
Documentation/bpf/btf.rst +15
-0+ * /sys/kernel/btf/vmlinux exists from boot with its final size. + * Modules loaded before the vmlinux BTF are exposed in /sys/kernel/btf right + away, their BTF is parsed and gets a BTF id once the vmlinux BTF is + loaded, together with their kfunc and struct_ops registrations. + * kfunc, dtor kfunc and struct_ops registrations of the kernel itself are + applied before the BTF becomes visible. + * The kernel only accepts the BTF it was built with: the size and SHA-256 of + the BTF are linked into the kernel and checked against the module. + * Once loaded the BTF stays; the module cannot be unloaded. + +If the module is not available (not installed, or the root file system is not +mounted yet), the kernel behaves as one built without BTF and retries next +time. CONFIG_BPF_PRELOAD is not available with =m: its iterators attach through +the vmlinux BTF, so mounting bpffs would load it. bpf_snprintf_btf() and bpf_seq_printf_btf() only use the BTF if it has +already been parsed, as they run in program context.
[ ... ]
lib/Kconfig.debug config DEBUG_INFO_SPLIT · line 402
Quoted 13 lines
lib/Kconfig.debug +1
-1@@ -396,7 +396,7 @@ config DEBUG_INFO_SPLIT Incompatible with older versions of ccache. config DEBUG_INFO_BTF - bool "Generate BTF type information" + tristate "Generate BTF type information" depends on !DEBUG_INFO_SPLIT && !DEBUG_INFO_REDUCED depends on !GCC_PLUGIN_RANDSTRUCT || COMPILE_TEST depends on BPF_SYSCALL
Does making DEBUG_INFO_BTF selectable as =m keep PROBE_EVENTS_BTF_ARGS and FUNCTION_TRACE_ARGS enabled? Since bool dependents treat m as y, the tracing output path would call the vmlinux BTF lookup, and under =m that lookup can sleep.
The chain from the function_graph printers goes:print_fn_trace() -> print_function_args() -> btf_find_func_proto() -> bpf_find_btf_id() -> bpf_get_btf_vmlinux() -> btf_vmlinux_data(&size, true) -> request_module("btf_vmlinux").
request_module() calls down_timeout(), kmalloc(GFP_KERNEL) in call_modprobe(), and waits for modprobe with UMH_WAIT_PROC. These printers run from ftrace_dump_one(), which does local_irq_save(flags) before looping on print_trace_line(). ftrace_dump_one() is reached from ftrace_dump_on_oops/panic, sysrq-z, <func>:dump function probes, kdb ftdump and RCU stall dumps.
If the func-args or funcgraph-args option is on and nothing has loaded the BTF yet, the dump hits 'sleeping function called from invalid context' and schedules with IRQs disabled. In the panic/oops path the other CPUs are stopped and usermode helpers cannot run, so the dump can hang.
With =y the BTF is parsed at boot and bpf_get_btf_vmlinux() returns from its fast path, so this path could not sleep before this change. Earlier in the series, a commit added bpf_peek_btf_vmlinux() for bpf_snprintf_btf()/bpf_seq_printf_btf() because they 'cannot afford a fetch that may sleep', but the tracing output path was not converted.
Should btf_find_func_proto() use a non-loading lookup (bpf_peek_btf_vmlinux()) or skip the lookup when !preemptible(), or should PROBE_EVENTS_BTF_ARGS/FUNCTION_TRACE_ARGS depend on DEBUG_INFO_BTF=y?
lib/Kconfig.debug config DEBUG_INFO_BTF · line 419
Quoted 13 lines
lib/Kconfig.debug +9
-0@@ -408,6 +408,26 @@ config DEBUG_INFO_BTF Turning this on requires pahole v1.22 or later, which will convert DWARF type info into equivalent deduplicated BTF type info. + If built as a module (=m), the vmlinux BTF is not part of the + kernel image. It is carried by the btf_vmlinux module, which is + loaded on demand the first time the BTF is needed: when a BPF + program requires kernel type information, or when + /sys/kernel/btf/vmlinux is opened. Until then, no memory is + spent on it. The vmlinux ELF file does not carry the BTF + either; module BTF is generated against vmlinux.unstripped, and + tools that read the BTF from a file can use that or + /sys/kernel/btf/vmlinux.
The help text says the btf_vmlinux module is loaded when /sys/kernel/btf/vmlinux is opened. Does opening the file actually load the module?
Looking at kernel/bpf/sysfs_btf.c, the file is a bin_attribute, and struct bin_attribute has no open callback. The BTF is loaded only from btf_sysfs_vmlinux_read() and btf_sysfs_vmlinux_mmap(), and the comment there says 'the first read() or mmap() loads the BTF'. stat() and open() without a read leave the module unloaded, which the commit message's btf_sysfs selftest note about stat() relies on.
Should this say 'first read or mapped' instead of 'opened'? The commit message has the same wording ('opening /sys/kernel/btf/vmlinux ... each load it').
lib/Kconfig.debug config DEBUG_INFO_BTF · line 429
Quoted 9 lines
lib/Kconfig.debug +9
-0+ Module BTF (DEBUG_INFO_BTF_MODULES) is kept when a module loads, + as with =y, and registered once the vmlinux BTF is available; the + saving is the vmlinux BTF only. + + If BPF programs that use kernel types run before the root file + system is mounted, put btf_vmlinux.ko into the initramfs: until + the module can be loaded, such programs fail as on a kernel + without BTF. Not compatible with BPF_PRELOAD, whose iterators + would load the BTF at every bpffs mount.
Once DEBUG_INFO_BTF can be =m, does 'make localmodconfig' silently turn it off?
scripts/kconfig/streamline_config.pl maps loaded modules to configs only through obj-$(CONFIG_X) lines. Any =m config it cannot tie to a loaded module is written out as '# CONFIG_X is not set'. The only rule for the carrier module is kernel/bpf/Makefile 'ifeq ($(CONFIG_DEBUG_INFO_BTF),m)' / 'obj-m += btf_vmlinux.o', which the script cannot map, and btf_vmlinux is usually not loaded when lsmod is captured anyway.
So a distribution config with CONFIG_DEBUG_INFO_BTF=m loses DEBUG_INFO_BTF under localmodconfig. olddefconfig then also drops DEBUG_INFO_BTF_MODULES, SCHED_CLASS_EXT, NET_SCH_BPF, IO_URING_BPF_OPS, BINFMT_MISC_BPF and PROBE_EVENTS_BTF_ARGS. With =y these options were kept, because the script leaves built-in options alone. The only workaround is LMC_KEEP.
Could the Makefile use an obj-$(CONFIG_DEBUG_INFO_BTF)-style rule that streamline_config can map, or could streamline_config preserve this symbol?
[ ... ]
Quoted 11 lines
scripts/Makefile.modfinal +3
-0@@ -38,20 +38,34 @@ quiet_cmd_ld_ko_o = LD [M] $@ $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \ -T $(objtree)/scripts/module.lds -o $@ $(filter %.o, $^) +# The ELF file with the vmlinux BTF: with CONFIG_DEBUG_INFO_BTF=m the BTF is +# stripped from vmlinux (scripts/Makefile.vmlinux), vmlinux.unstripped keeps it. +btf-vmlinux := $(objtree)/vmlinux$(if $(filter m,$(CONFIG_DEBUG_INFO_BTF)),.unstripped)
scripts/Makefile.modfinal quiet_cmd_ld_ko_o = LD [M] $@ · line 51
Quoted 10 lines
scripts/Makefile.modfinal +3
-2+ quiet_cmd_btf_ko = BTF [M] $@ cmd_btf_ko = \ - if [ ! -f $(objtree)/vmlinux ]; then \ + if [ ! -f $(btf-vmlinux) ]; then \ printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \ else \ - $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \ + $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(btf-vmlinux) $@; \ fi;
With CONFIG_DEBUG_INFO_BTF=m, external modules (M=) now only get BTF if vmlinux.unstripped exists. The in-tree packaging still ships only vmlinux for this purpose.
scripts/package/PKGBUILD's _package-debug does 'install -Dt "${debugdir}" -m644 vmlinux' and 'ln -sr "${debugdir}/vmlinux" "${builddir}/vmlinux"' so that modules built against /usr/lib/modules/$KERNELRELEASE/build get split BTF. With =y that works. With =m, Makefile.vmlinux strips .BTF from that vmlinux, and cmd_btf_ko tests for build/vmlinux.unstripped, which nothing installs.
So every DKMS/out-of-tree module built against a pacman-pkg kernel with =m (and DEBUG_INFO_BTF_MODULES, which defaults to y) is built without .BTF, and the build still succeeds. The only sign is the stderr line "Skipping BTF generation for foo.ko due to unavailability of vmlinux", which is misleading because build/vmlinux is present; the missing file is vmlinux.unstripped.
At runtime those modules have no BTF: fentry/fexit and BTF-typed tracing of their functions are unavailable, and register_btf_kfunc_id_set() from such a module falls into check_btf_kconfigs() ("missing module BTF, cannot register kfunc"). This contradicts the changelog's "Nothing that works with =y stops working" for the external-module flow the tree itself packages.
Should scripts/package/PKGBUILD (and any other shipped build-tree layout) provide vmlinux.unstripped when CONFIG_DEBUG_INFO_BTF=m, or should cmd_btf_ko use another base source? At minimum, the error message should name $(btf-vmlinux) instead of saying "vmlinux".
Quoted 24 lines
scripts/Makefile.modfinal +14
-4-# Re-generate module BTFs if either module's .ko or vmlinux changed -%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(objtree)/vmlinux) FORCE - +$(call if_changed,ld_ko_o) +# Modules that get a .BTF section: all of them with CONFIG_DEBUG_INFO_BTF_MODULES, +# otherwise only the vmlinux BTF carrier module with CONFIG_DEBUG_INFO_BTF=m. ifdef CONFIG_DEBUG_INFO_BTF_MODULES - +$(if $(newer-prereqs),$(call cmd,btf_ko)) +btf-modules := $(modules:%.o=%.ko) +else ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +btf-modules := $(filter %/btf_vmlinux.ko,$(modules:%.o=%.ko)) +# Only the carrier depends on vmlinux, not every module +ifdef KBUILD_BUILTIN +$(btf-modules): $(btf-vmlinux) +endif endif + +# Re-generate module BTFs if either module's .ko or vmlinux changed +%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(btf-vmlinux)) FORCE + +$(call if_changed,ld_ko_o) + +$(if $(and $(filter $@,$(btf-modules)),$(newer-prereqs)),$(call cmd,btf_ko)) +$(call cmd,check_tracepoint) targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
[ ... ]
scripts/Makefile.vmlinux remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel*' '!.rel*.dyn' · line 93
Quoted 13 lines
scripts/Makefile.vmlinux +5
-0@@ -86,6 +86,11 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel*' '!.rel*.dyn' # for compatibility with binutils < 2.32 # https://sourceware.org/git/?p=binutils-gdb.git;a=commit;h=c12d9fa2afe7abcbe407a00e15719e1a1350c2a7 remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*' +# With CONFIG_DEBUG_INFO_BTF=m the btf_vmlinux module carries the vmlinux BTF; +# only vmlinux.unstripped keeps it, for module BTF generation. +ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +remove-section-y += .BTF +endif
With CONFIG_DEBUG_INFO_BTF=m this strips .BTF from the vmlinux ELF file, but the in-tree consumers that read the vmlinux BTF from that file were not updated. Only Makefile.modfinal was switched to vmlinux.unstripped.
The tools pick their BTF source like this (tools/bpf/bpftool/Makefile):
VMLINUX_BTF_PATHS ?= $(if $(O),$(O)/vmlinux) \
$(if $(KBUILD_OUTPUT),$(KBUILD_OUTPUT)/vmlinux) \
../../../vmlinux \
/sys/kernel/btf/vmlinux \
/boot/vmlinux-$(shell uname -r)
VMLINUX_BTF ?= $(abspath $(firstword $(wildcard $(VMLINUX_BTF_PATHS))))
...
$(OUTPUT)vmlinux.h: $(VMLINUX_BTF) $(BPFTOOL_BOOTSTRAP)
$(QUIET_GEN)$(BPFTOOL_BOOTSTRAP) btf dump file $< format c > $@$(wildcard) only checks that a file exists. In a tree where an =m kernel was built, it selects the build-tree vmlinux, which now has no .BTF section, and never reaches /sys/kernel/btf/vmlinux. btf_parse_elf() in tools/lib/bpf/btf.c then fails:
if (!secs.btf_data) {
pr_warn("failed to find '%s' ELF section in %s\n", BTF_ELF_SEC, path);
err = -ENODATA;do_dump() in bpftool reports "failed to load BTF from ...: No data available" and the vmlinux.h rule fails. The same VMLINUX_BTF_PATHS/firstword/wildcard logic followed by 'bpftool btf dump file $(VMLINUX_BTF) format c' appears in tools/testing/selftests/bpf/Makefile, tools/sched_ext/Makefile, tools/testing/selftests/sched_ext/Makefile, samples/bpf/Makefile, samples/hid/Makefile, drivers/hid/bpf/progs/Makefile and tools/testing/selftests/hid/Makefile.
So after an =m kernel build, the default builds of bpftool (with skeletons), the BPF selftests and the sched_ext tools fail unless VMLINUX_BTF is overridden. With =y all of these work. This contradicts the changelog's "Nothing that works with =y stops working". The Kconfig help says tools "can use that [vmlinux.unstripped] or /sys/kernel/btf/vmlinux", but none of the in-tree tools do so by default. No commit in the series touches tools/.
In-tree packaging has a related gap. scripts/package/PKGBUILD _package-debug installs vmlinux and links it as build/vmlinux. With =y, that is what Makefile.modfinal needs to generate BTF for external modules. With =m, Makefile.modfinal looks for vmlinux.unstripped, which is not packaged, and the packaged vmlinux no longer has .BTF. External module BTF generation against those packages is therefore skipped. The builddeb and kernel.spec debug vmlinux copies also no longer carry BTF.
Should VMLINUX_BTF_PATHS list vmlinux.unstripped before vmlinux, or should the vmlinux ELF file keep the non-loadable .BTF?
Quoted 12 lines
scripts/Makefile.vmlinux +1
-1remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*'@@ -93,7 +98,7 @@ quiet_cmd_strip_relocs = STRIPREL cmd_strip_relocs = $(OBJCOPY) $(foreach x,$(remove-section-y),--remove-section=$(x)) \ --set-section-flags .BTF=noload \ $(remove-symbols) \ - -o $@ $< + -o $@ $< $(if $(filter .BTF,$(remove-section-y))&& [ -n "$(remove-section-y)" ]) vmlinux: vmlinux.unstripped $(and $(CONFIG_DEBUG_INFO_BTF),$(RESOLVE_BTFIDS)) FORCE $(call if_changed,strip_relocs)
[ ... ]
Quoted 4 lines
scripts/gen-btf.sh +0
-0
[ ... ]
Quoted 22 lines
scripts/gen-btf.sh +18
-0@@ -191,6 +251,35 @@ if [ -n "${BTF_BASE}" ]; then BTFGEN_MODE="module" fi +if [ -n "${PLACEHOLDER}" ]; then + btf_data=${ELF_FILE}.btf.o + echo "" | ${CC} ${CLANG_FLAGS} ${KBUILD_CPPFLAGS} ${KBUILD_CFLAGS} -fno-lto -c -x c -o ${btf_data} - + dd if=/dev/zero of=${ELF_FILE}.BTF.meta bs=36 count=1 2>/dev/null + ${OBJCOPY} --add-section .BTF.meta=${ELF_FILE}.BTF.meta \ + --set-section-flags .BTF.meta=alloc,readonly ${btf_data} + ${OBJCOPY} --only-section=.BTF.meta --strip-all ${btf_data} + exit 0 +fi + +# CONFIG_DEBUG_INFO_BTF=m: the btf_vmlinux module carries the vmlinux BTF +# itself. Its own types are of no interest, so instead of generating split +# BTF for it, copy the (non-loadable) .BTF section of --btf_base +# (vmlinux.unstripped) into the module. +# The kernel recognizes the module by name and treats its .BTF as base BTF. +case "${BTFGEN_MODE}:${ELF_FILE}" in +module:*/btf_vmlinux.ko) + if is_module CONFIG_DEBUG_INFO_BTF; then
scripts/gen-btf.sh if [ -n "${BTF_BASE}" ]; then · line 281
Quoted 10 lines
scripts/gen-btf.sh +10
-0+ # -O binary only emits allocatable sections; make .BTF one for + # the extraction. ${BTF_BASE} itself is not modified. + ${OBJCOPY} -O binary --only-section=.BTF \ + --set-section-flags .BTF=alloc,load,readonly \ + "${BTF_BASE}" "${ELF_FILE}.BTF" + ${OBJCOPY} --add-section .BTF="${ELF_FILE}.BTF" "${ELF_FILE}" + exit 0 + fi + ;; +esac
The carrier module is recognized only when ELF_FILE contains a '/' before btf_vmlinux.ko. That holds for normal and O= builds (ELF_FILE is kernel/bpf/btf_vmlinux.ko). Does it hold for 'make M=kernel/bpf'?
Since the M= working-directory change, the top Makefile changes into the module directory. scripts/Makefile.build then skips the $(obj)/ prefix when obj is '.', so modules.order lists 'btf_vmlinux.o' and Makefile.modfinal passes $@ = 'btf_vmlinux.ko'. 'module:btf_vmlinux.ko' does not match 'module:*/btf_vmlinux.ko', so gen-btf.sh goes on to gen_btf_data/embed_btf_data.
With CONFIG_DEBUG_INFO_BTF_MODULES=y the carrier gets its own split BTF (plus a distilled .BTF.base, because KBUILD_EXTMOD adds --distill_base) instead of a copy of the vmlinux BTF. Without BTF_MODULES, Makefile.modfinal's matching '$(filter %/btf_vmlinux.ko,...)' also misses, so the carrier gets no .BTF at all.
In both cases btf_vmlinux_module_coming() fails its check 'if (mod->btf_data_size != btf_vmlinux_meta.size) { pr_err(...); return -EINVAL; }', btf_module_notify() returns notifier_from_errno(-EINVAL), and prepare_coming_module() makes the module load fail.
After 'make M=kernel/bpf modules_install' the broken carrier goes to $(MODLIB)/updates (Makefile.modinst: 'INSTALL_MOD_DIR ?= updates'), which depmod searches ahead of kernel/ by default. request_module("btf_vmlinux") from btf_vmlinux_data() then keeps loading the broken copy, and the vmlinux BTF stays unavailable until that file is removed.
Could the match here (and the same in the Makefile.modfinal filter) cover the bare name as well, e.g. 'module:btf_vmlinux.ko|module:*/btf_vmlinux.ko)'?
scripts/gen-btf.sh if [ -n "${BTF_BASE}" ]; then · line 225
Quoted 4 lines
scripts/gen-btf.sh +0
-0gen_btf_data case "${BTFGEN_MODE}" in
[ ... ]
---
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/36198628965
Re: [PATCH bpf-next v3 4/9] bpf: take the vmlinux BTF from the btf_vmlinux module
In reply to Jay Wangkernel/bpf/btf.c static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, · line 6503
Quoted 8 lines · Jay Wang
kernel/bpf/btf.c +8
-0+if (!data && load) { +/* +* The module notifier installs the BTF before init_module() +* returns, so it is either there after this or the module is +* not available (yet). Not cached: a later call retries, +* e.g. once the module becomes reachable on the root fs. +*/ +request_module ("btf_vmlinux" );
This will deadlock.event_btf_ids_read() calls btf_get_module_btf(NULL) with event_mutex held. With =m and BTF not loaded yet
cat /sys/kernel/tracing/events/sched/sched_switch/btf_ids
gets here and waits for modprobe. modprobe gets to trace_module_notify() which takes event_mutex.
lockdep doesn't see it.
print_function_args() gets here for every line of the trace, from ftrace_dump() with irqs off too. When the module is not installed that is one modprobe per line.
Every caller of bpf_get_btf_vmlinux() and bpf_find_btf_id() was written for a function that doesn't wait for user space.
pw-bot: cr
Re: [PATCH bpf-next v3 9/9] kbuild, bpf: allow building the vmlinux BTF as a module
In reply to Jay WangQuoted 35 lines · Jay Wang
Make
CONFIG_DEBUG_INFO_BTFa tristate. With =m the vmlinux BTF is not part of the kernel image: it is carried by a new module,btf_vmlinux, and loaded the first time something needs it. Nothing that works with =y stops working; the 5.4 MiB of read-only data (distribution config) is simply not there on systems where nothing uses it.The only way to save that memory today is
CONFIG_DEBUG_INFO_BTF=n, which a distribution cannot ship: one binary goes to every user, and off takes BTF away from the users of CO-RE, fentry/fexit, kfuncs,struct_ops,sched_extor bpf-lsm. Whether BTF is used is a property of the workload, not of the build, so let the first user decide.The BTF is generated as before, but with =m the .BTF section is linked as a non-loadable section (like .comment), so the kernel image does not load it, and the final step that makes vmlinux from vmlinux.unstripped strips it: every boot image made from vmlinux, whether a raw binary or an ELF copy, is without it. Module BTF is generated against vmlinux.unstripped, which keeps it. .BTF_ids stays loadable, the verifier needs it once the BTF is loaded. The object that carries .BTF also carries .BTF.meta, the size and SHA-256 of the BTF (struct
btf_vmlinux_meta, checked by the module notifier); the first link, which the BTF is generated from, gets a zeroed .BTF.meta of the same size.kernel/bpf/btf_vmlinux.cis an empty carrier module;scripts/gen-btf.shgives it the vmlinux .BTF as its own .BTF section instead of generating split BTF for it, so that one module depends on vmlinux with =m; withCONFIG_DEBUG_INFO_BTF_MODULESall of them do, as before.
CONFIG_BPF_PRELOADis not selectable with =m: its iterator programs attach through the vmlinux BTF, so every bpffs mount (systemd does one at boot) would load it and defeat the point. Module BTF is still kept when a module loads, as with =y; the saving is the vmlinux BTF only. Programs that need kernel types before the root file system is mounted need btf_vmlinux.ko in the initramfs; theKconfighelp says so.
Quoted 7 lines
The module has no exit: once loaded the BTF stays, as with =y. The runtime side -- loading the module on first use, checking it against .BTF.meta, deferring kfunc and
struct_opsregistrations and module BTF until it arrives -- and the IS_ENABLED()/$(subst m,y,...) preparation of the existing checks are in the preceding patches; this one makes it selectable.
A few thoughts here; .BTF.meta seems too vague as a name. This is very like .gnu_debuglink ; should we call it .BTF.link ? It also could be nicely extended to .BTF.inline (.BTF.inlink.link) where inline info is delivered as a module.
I also wonder if the right place to populate the section is in the script? We might run into endian issues etc; why not do it as part of resolve_btfids? Pass a --btf_link parameter or similar, and resolve_btfids (which has access to BTF size after carrying out various operations) can add it and the SHA. resolve_btfids is already updating other BTF-related sections so seems like a natural home for this.
Quoted 539 lines
Tested with 1 GiB of memory, same tree, =y vs =m, both with
CONFIG_DEBUG_INFO_BTF_MODULES=y:- MemTotal is ~5.4 MB higher with =m while the BTF is unused: the size of the .BTF section.
-stat()of/sys/kernel/btf/vmlinuxreports the BTF size before it is loaded, as thebtf_sysfsselftest expects.
- With BTF in use, MemFree is the same within run-to-run noise.
- Modules loaded before the trigger (ext4,nf_conntrackand its kfuncs,xfrm_interface) appear in/sys/kernel/btfimmediately and get BTF ids once the BTF is loaded; a socket filter loads without loading the module; a kprobe program callingbpf_get_current_task_btf(), opening/sys/kernel/btf/vmlinuxorBPF_BTF_GET_NEXT_IDeach load it.
- A carrier module with one byte of its .BTF changed is refused with "BTF does not match this kernel" and leaves no state behind.
- After the load: fstat/read/mmap of/sys/kernel/btf/vmlinux, astruct_opsmap fortcp_congestion_ops, a syscall program calling the bpf_task_from_pid()/bpf_task_release() kfuncs, and modules loaded afterwards (nf_nat) all work as with =y.
- =m withoutDEBUG_INFO_BTF_MODULES, and =y, build and pass the same tests.Signed-off-by Jay Wang <[email protected]>--- Documentation/bpf/btf.rst | 35 ++++++++++++ Makefile | 5 +- include/asm-generic/vmlinux.lds.h | 31 +++++++++- kernel/bpf/Makefile | 4 ++ kernel/bpf/btf_vmlinux.c | 23 ++++++++ kernel/bpf/preload/Kconfig | 4 ++ lib/Kconfig.debug | 22 ++++++- scripts/Makefile.modfinal | 26 +++++++-- scripts/Makefile.vmlinux | 5 ++ scripts/gen-btf.sh | 95 +++++++++++++++++++++++++++++-- scripts/link-vmlinux.sh | 25 ++++++-- 11 files changed, 257 insertions(+), 18 deletions(-) create mode 100644 kernel/bpf/btf_vmlinux.cDocumentation/bpf/btf.rst +35
-0@@ -1276,6 +1276,41 @@ format.:: .long 58 .long 8206 # Line 8 Col 14 +6.1 Kernel BTF +-------------- + +With CONFIG_DEBUG_INFO_BTF=y the BTF of the kernel is generated at link time +from its DWARF and placed in the .BTF section of vmlinux, which is read-only +data of the kernel image. It is available as /sys/kernel/btf/vmlinux and, if +CONFIG_DEBUG_INFO_BTF_MODULES is set, module BTF is generated as split BTF +against it and available as /sys/kernel/btf/<module>. + +With CONFIG_DEBUG_INFO_BTF=m the same BTF is generated, but it is not part of +the kernel image or of the vmlinux ELF file (vmlinux.unstripped in the build +tree keeps it, for module BTF generation). It is delivered by the +btf_vmlinux module, which the kernel loads on demand the first time the BTF is +needed: when /sys/kernel/btf/vmlinux is read or mmap()ed, when kernel BTF +objects are enumerated (BPF_BTF_GET_NEXT_ID), or when a BPF program needs +kernel type information (an attach_btf_id, a kfunc call, a ksym, a map pointer +or a helper that takes or returns a kernel BTF pointer). Until then no memory +is used for it, and afterwards nothing differs from =y. In particular: + + * /sys/kernel/btf/vmlinux exists from boot with its final size. + * Modules loaded before the vmlinux BTF are exposed in /sys/kernel/btf right + away, their BTF is parsed and gets a BTF id once the vmlinux BTF is + loaded, together with their kfunc and struct_ops registrations. + * kfunc, dtor kfunc and struct_ops registrations of the kernel itself are + applied before the BTF becomes visible. + * The kernel only accepts the BTF it was built with: the size and SHA-256 of + the BTF are linked into the kernel and checked against the module. + * Once loaded the BTF stays; the module cannot be unloaded. + +If the module is not available (not installed, or the root file system is not +mounted yet), the kernel behaves as one built without BTF and retries next +time. CONFIG_BPF_PRELOAD is not available with =m: its iterators attach through +the vmlinux BTF, so mounting bpffs would load it. bpf_snprintf_btf() and bpf_seq_printf_btf() only use the BTF if it has +already been parsed, as they run in program context. + 7. Testing ==========Makefile +3
-2@@ -1745,8 +1745,9 @@ endif # # *.ko are usually independent of vmlinux, but CONFIG_DEBUG_INFO_BTF_MODULES -# is an exception. -ifdef CONFIG_DEBUG_INFO_BTF_MODULES +# is an exception, and so is the btf_vmlinux module with CONFIG_DEBUG_INFO_BTF=m, +# which carries the vmlinux BTF. +ifneq ($(CONFIG_DEBUG_INFO_BTF_MODULES)$(filter m,$(CONFIG_DEBUG_INFO_BTF)),) KBUILD_BUILTIN := y modules: vmlinux endifinclude/asm-generic/vmlinux.lds.h +30
-1@@ -674,8 +674,18 @@/* * .BTF +* +* With CONFIG_DEBUG_INFO_BTF=y the vmlinux BTF is loaded as read-only data and +* bounded by __start_BTF/__stop_BTF. With CONFIG_DEBUG_INFO_BTF=m it is +* linked as a non-loadable section (see BTF_NOLOAD in ELF_DETAILS), so that +* module BTF generation can read it from vmlinux.unstripped; it is stripped +* from vmlinux (scripts/Makefile.vmlinux), and the btf_vmlinux module carries +* a copy and provides it on demand at runtime. +* What is loaded instead is .BTF.meta, the size and hash of that BTF (see +* scripts/gen-btf.sh), empty in the first link that the BTF is generated +* from. .BTF_ids is needed by the kernel in both cases. */ -#ifdef CONFIG_DEBUG_INFO_BTF +#if IS_BUILTIN (CONFIG_DEBUG_INFO_BTF )#define BTF \ . = ALIGN(PAGE_SIZE); \ .BTF : AT(ADDR(.BTF) - LOAD_OFFSET) { \@@ -685,10 +695,28 @@ .BTF_ids : AT(ADDR(.BTF_ids) - LOAD_OFFSET) { \ *(.BTF_ids) \ } +#elif IS_MODULE (CONFIG_DEBUG_INFO_BTF ) +#define BTF \ + . = ALIGN(8); \ + .BTF.meta : AT(ADDR(.BTF.meta) - LOAD_OFFSET) { \ + BOUNDED_SECTION_BY(.BTF.meta, _BTF_meta) \ + } \ + . = ALIGN(PAGE_SIZE); \ + .BTF_ids : AT(ADDR(.BTF_ids) - LOAD_OFFSET) { \ + *(.BTF_ids) \ + }#else #define BTF #endif +#if IS_MODULE (CONFIG_DEBUG_INFO_BTF ) +/* quoted: BTF is a macro, an unquoted .BTF here would expand it */ +#define BTF_NOLOAD \ + ".BTF" 0 : { *(".BTF") } +#else +#define BTF_NOLOAD +#endif +/* * Init task */ @@ -849,6 +877,7 @@/* Required sections not related to debugging. */ #define ELF_DETAILS \ .comment 0 : { *(.comment) } \ + BTF_NOLOAD \ .symtab 0 : { *(.symtab) } \ .strtab 0 : { *(.strtab) } \ .shstrtab 0 : { *(.shstrtab) } \kernel/bpf/Makefile +4
-0@@ -43,6 +43,10 @@ endif ifeq ($(CONFIG_SYSFS),y) obj-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += sysfs_btf.o endif +# With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF is carried by this module +ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +obj-m += btf_vmlinux.o +endif ifeq ($(CONFIG_BPF_JIT),y) obj-$(CONFIG_BPF_SYSCALL) += bpf_struct_ops.o obj-$(CONFIG_BPF_SYSCALL) += cpumask.okernel/bpf/btf_vmlinux.c new file +23
-0@@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Carrier module for the vmlinux BTF when CONFIG_DEBUG_INFO_BTF=m. +* +* This module has no code of its own. Its .BTF section is a copy of the +* vmlinux BTF (see scripts/gen-btf.sh), which the BTF module notifier in +* kernel/bpf/btf.c recognizes by module name and installs as the vmlinux BTF. +* The kernel loads it on demand, the first time the vmlinux BTF is needed. +* +* There is deliberately no module_exit(): once the BTF is in use it cannot +* be taken away again, exactly as with CONFIG_DEBUG_INFO_BTF=y. +*/ +#include <linux/init.h> +#include <linux/module.h> + +static int __init btf_vmlinux_init (void ) +{ +return 0 ; +} +module_init (btf_vmlinux_init); + +MODULE_DESCRIPTION ("BTF type information for vmlinux" ); +MODULE_LICENSE ("GPL" );kernel/bpf/preload/Kconfig +4
-0@@ -6,6 +6,10 @@ menuconfig BPF_PRELOAD # The dependency on !COMPILE_TEST prevents it from being enabled # in allmodconfig or allyesconfig configurations depends on !COMPILE_TEST + # The preloaded iterators attach through the vmlinux BTF, so with + # CONFIG_DEBUG_INFO_BTF=m every bpffs mount would load the BTF, which + # defeats the point of =m on any system that mounts bpffs at boot. + depends on DEBUG_INFO_BTF!=m help This builds kernel module with several embedded BPF programs that are pinned into BPF FS mount point as human readable files that arelib/Kconfig.debug +21
-1@@ -396,7 +396,7 @@ config DEBUG_INFO_SPLIT Incompatible with older versions of ccache. config DEBUG_INFO_BTF - bool "Generate BTF type information" + tristate "Generate BTF type information" depends on !DEBUG_INFO_SPLIT && !DEBUG_INFO_REDUCED depends on !GCC_PLUGIN_RANDSTRUCT || COMPILE_TEST depends on BPF_SYSCALL@@ -408,6 +408,26 @@ config DEBUG_INFO_BTF Turning this on requires pahole v1.22 or later, which will convert DWARF type info into equivalent deduplicated BTF type info. + If built as a module (=m), the vmlinux BTF is not part of the + kernel image. It is carried by the btf_vmlinux module, which is + loaded on demand the first time the BTF is needed: when a BPF + program requires kernel type information, or when + /sys/kernel/btf/vmlinux is opened. Until then, no memory is + spent on it. The vmlinux ELF file does not carry the BTF + either; module BTF is generated against vmlinux.unstripped, and + tools that read the BTF from a file can use that or + /sys/kernel/btf/vmlinux. + + Module BTF (DEBUG_INFO_BTF_MODULES) is kept when a module loads, + as with =y, and registered once the vmlinux BTF is available; the + saving is the vmlinux BTF only. + + If BPF programs that use kernel types run before the root file + system is mounted, put btf_vmlinux.ko into the initramfs: until + the module can be loaded, such programs fail as on a kernel + without BTF. Not compatible with BPF_PRELOAD, whose iterators + would load the BTF at every bpffs mount. + config PAHOLE_HAS_BTF_TAG def_bool PAHOLE_VERSION >= 123 depends on CC_IS_CLANGscripts/Makefile.modfinal +20
-6@@ -38,20 +38,34 @@ quiet_cmd_ld_ko_o = LD [M] $@ $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \ -T $(objtree)/scripts/module.lds -o $@ $(filter %.o, $^) +# The ELF file with the vmlinux BTF: with CONFIG_DEBUG_INFO_BTF=m the BTF is +# stripped from vmlinux (scripts/Makefile.vmlinux), vmlinux.unstripped keeps it. +btf-vmlinux := $(objtree)/vmlinux$(if $(filter m,$(CONFIG_DEBUG_INFO_BTF)),.unstripped) + quiet_cmd_btf_ko = BTF [M] $@ cmd_btf_ko = \ - if [ ! -f $(objtree)/vmlinux ]; then \ + if [ ! -f $(btf-vmlinux) ]; then \ printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \ else \ - $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \ + $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(btf-vmlinux) $@; \ fi; -# Re-generate module BTFs if either module's .ko or vmlinux changed -%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(objtree)/vmlinux) FORCE - +$(call if_changed,ld_ko_o) +# Modules that get a .BTF section: all of them with CONFIG_DEBUG_INFO_BTF_MODULES, +# otherwise only the vmlinux BTF carrier module with CONFIG_DEBUG_INFO_BTF=m. ifdef CONFIG_DEBUG_INFO_BTF_MODULES - +$(if $(newer-prereqs),$(call cmd,btf_ko)) +btf-modules := $(modules:%.o=%.ko) +else ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +btf-modules := $(filter %/btf_vmlinux.ko,$(modules:%.o=%.ko)) +# Only the carrier depends on vmlinux, not every module +ifdef KBUILD_BUILTIN +$(btf-modules): $(btf-vmlinux) +endif endif + +# Re-generate module BTFs if either module's .ko or vmlinux changed +%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(btf-vmlinux)) FORCE + +$(call if_changed,ld_ko_o) + +$(if $(and $(filter $@,$(btf-modules)),$(newer-prereqs)),$(call cmd,btf_ko)) +$(call cmd,check_tracepoint) targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.oscripts/Makefile.vmlinux +5
-0@@ -86,6 +86,11 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel*' '!.rel*.dyn' # for compatibility with binutils < 2.32 # https://sourceware.org/git/?p=binutils-gdb.git;a=commit;h=c12d9fa2afe7abcbe407a00e15719e1a1350c2a7 remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*' +# With CONFIG_DEBUG_INFO_BTF=m the btf_vmlinux module carries the vmlinux BTF; +# only vmlinux.unstripped keeps it, for module BTF generation. +ifeq ($(CONFIG_DEBUG_INFO_BTF),m) +remove-section-y += .BTF +endif remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*'scripts/gen-btf.sh +91
-4@@ -22,16 +22,27 @@ # - ${1}.btf.o ready for linking into vmlinux # - ${1}.BTF_ids with .BTF_ids data blob # This output is consumed by scripts/link-vmlinux.sh +# +# With CONFIG_DEBUG_INFO_BTF=m the .BTF section in ${1}.btf.o is not +# allocatable, so the kernel image does not carry the BTF; vmlinux.unstripped +# does, for module BTF generation, and scripts/Makefile.vmlinux strips it from +# vmlinux. ${1}.btf.o then also carries .BTF.meta, the size and SHA-256 of +# the BTF for the kernel (struct btf_vmlinux_meta); "--placeholder ${1}" +# produces a ${1}.btf.o with a zeroed .BTF.meta and no .BTF for the first +# vmlinux link, which the BTF is generated from. The btf_vmlinux module gets +# no BTF of its own; its .BTF section is a copy of the vmlinux BTF, extracted +# from --btf_base. set -e usage() { - echo "Usage: $0 [--btf_base <file>] <target ELF file>" + echo "Usage: $0 [--btf_base <file>] [--placeholder] <target ELF file>" exit 1 } BTF_BASE="" +PLACEHOLDER="" while [ $# -gt 0 ]; do case "$1" in@@ -39,6 +50,10 @@ while [ $# -gt 0 ]; do BTF_BASE="$2" shift 2 ;; + --placeholder) + PLACEHOLDER=1 + shift + ;; -*) echo "Unknown option: $1" >&2 usage@@ -60,6 +75,10 @@ is_enabled() { grep -q "^$1=y" ${objtree}/include/config/auto.conf } +is_module() { + grep -q "^$1=m" ${objtree}/include/config/auto.conf +} + case "${KBUILD_VERBOSE}" in *1*) set -x@@ -79,6 +98,30 @@ gen_btf_data() --btf ${btf1} "${ELF_FILE}" } +# Write one byte with value $1 (0..255) +put_byte() +{ + printf "\\$(printf '%03o' "$1")" +} + +# CONFIG_DEBUG_INFO_BTF=m: write struct btf_vmlinux_meta { u32 size; u8 +# sha256[32]; } for the BTF in $1 to $2, in the target's byte order. +gen_btf_meta() +{ + size=$(${CONFIG_SHELL} "${srctree}/scripts/file-size.sh" "$1") + sha256=$(sha256sum < "$1" | cut -d' ' -f1) + { + if is_enabled CONFIG_CPU_BIG_ENDIAN; then + for shift in 24 16 8 0; do put_byte $(( (size >> shift) & 255 )); done + else + for shift in 0 8 16 24; do put_byte $(( (size >> shift) & 255 )); done + fi + for byte in $(echo "${sha256}" | sed 's/../& /g'); do + put_byte $(( 0x${byte} )) + done + } > "$2" +} + gen_btf_o() { btf_data=${ELF_FILE}.btf.o@@ -88,9 +131,23 @@ gen_btf_o() # deletes all symbols including __start_BTF and __stop_BTF, which will # be redefined in the linker script. echo "" | ${CC} ${CLANG_FLAGS} ${KBUILD_CPPFLAGS} ${KBUILD_CFLAGS} -fno-lto -c -x c -o ${btf_data} - - ${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \ - --set-section-flags .BTF=alloc,readonly ${btf_data} - ${OBJCOPY} --only-section=.BTF --strip-all ${btf_data} + if is_module CONFIG_DEBUG_INFO_BTF; then + # CONFIG_DEBUG_INFO_BTF=m: .BTF stays non-allocatable, kept in + # vmlinux.unstripped for module BTF but not loaded; the btf_vmlinux + # module provides it at runtime. What is loaded is .BTF.meta, + # its size and hash, so that /sys/kernel/btf/vmlinux has the right + # size from boot and only the matching BTF is accepted. + gen_btf_meta ${ELF_FILE}.BTF ${ELF_FILE}.BTF.meta + ${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \ + --set-section-flags .BTF=readonly \ + --add-section .BTF.meta=${ELF_FILE}.BTF.meta \ + --set-section-flags .BTF.meta=alloc,readonly ${btf_data} + ${OBJCOPY} --only-section=.BTF --only-section=.BTF.meta --strip-all ${btf_data} + else + ${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \ + --set-section-flags .BTF=alloc,readonly ${btf_data} + ${OBJCOPY} --only-section=.BTF --strip-all ${btf_data} + fi # Change e_type to ET_REL so that it can be used to link final vmlinux. # GNU ld 2.35+ and lld do not allow an ET_EXEC input.@@ -121,6 +178,7 @@ cleanup() { rm -f "${ELF_FILE}.BTF.1" rm -f "${ELF_FILE}.BTF" + rm -f "${ELF_FILE}.BTF.meta" if [ "${BTFGEN_MODE}" = "module" ]; then rm -f "${ELF_FILE}.BTF.base" rm -f "${ELF_FILE}.BTF_ids"@@ -133,6 +191,35 @@ if [ -n "${BTF_BASE}" ]; then BTFGEN_MODE="module" fi +if [ -n "${PLACEHOLDER}" ]; then + btf_data=${ELF_FILE}.btf.o + echo "" | ${CC} ${CLANG_FLAGS} ${KBUILD_CPPFLAGS} ${KBUILD_CFLAGS} -fno-lto -c -x c -o ${btf_data} - + dd if=/dev/zero of=${ELF_FILE}.BTF.meta bs=36 count=1 2>/dev/null + ${OBJCOPY} --add-section .BTF.meta=${ELF_FILE}.BTF.meta \ + --set-section-flags .BTF.meta=alloc,readonly ${btf_data} + ${OBJCOPY} --only-section=.BTF.meta --strip-all ${btf_data} + exit 0 +fi + +# CONFIG_DEBUG_INFO_BTF=m: the btf_vmlinux module carries the vmlinux BTF +# itself. Its own types are of no interest, so instead of generating split +# BTF for it, copy the (non-loadable) .BTF section of --btf_base +# (vmlinux.unstripped) into the module. +# The kernel recognizes the module by name and treats its .BTF as base BTF. +case "${BTFGEN_MODE}:${ELF_FILE}" in +module:*/btf_vmlinux.ko) + if is_module CONFIG_DEBUG_INFO_BTF; then + # -O binary only emits allocatable sections; make .BTF one for + # the extraction. ${BTF_BASE} itself is not modified. + ${OBJCOPY} -O binary --only-section=.BTF \ + --set-section-flags .BTF=alloc,load,readonly \ + "${BTF_BASE}" "${ELF_FILE}.BTF" + ${OBJCOPY} --add-section .BTF="${ELF_FILE}.BTF" "${ELF_FILE}" + exit 0 + fi + ;; +esac + gen_btf_data case "${BTFGEN_MODE}" inscripts/link-vmlinux.sh +21
-4@@ -37,6 +37,15 @@ is_enabled() { grep -q "^$1=y" include/config/auto.conf } +is_module() { + grep -q "^$1=m" include/config/auto.conf +} + +# =y or =m +is_set() { + grep -q "^$1=[ym]" include/config/auto.conf +} + # Nice output in kbuild format # Will be suppressed by "make -s" info()@@ -211,17 +220,25 @@ if is_enabled CONFIG_KALLSYMS; then kallsyms .tmp_vmlinux0.syms .tmp_vmlinux0.kallsyms fi -if is_enabled CONFIG_KALLSYMS || is_enabled CONFIG_DEBUG_INFO_BTF; then +if is_module CONFIG_DEBUG_INFO_BTF; then + # The kernel refers to the size and hash of its BTF, which only the + # BTF generated from the first link can provide; link a placeholder + # of the same layout until then. + ${CONFIG_SHELL} ${srctree}/scripts/gen-btf.sh --placeholder .tmp_vmlinux0 + btf_vmlinux_bin_o=.tmp_vmlinux0.btf.o +fi + +if is_enabled CONFIG_KALLSYMS || is_set CONFIG_DEBUG_INFO_BTF; then # The kallsyms linking does not need debug symbols, but the BTF does. - if ! is_enabled CONFIG_DEBUG_INFO_BTF; then + if ! is_set CONFIG_DEBUG_INFO_BTF; then strip_debug=1 fi vmlinux_link .tmp_vmlinux1 fi -if is_enabled CONFIG_DEBUG_INFO_BTF; then +if is_set CONFIG_DEBUG_INFO_BTF; then info BTF .tmp_vmlinux1 if ! ${CONFIG_SHELL} ${srctree}/scripts/gen-btf.sh .tmp_vmlinux1; then echo >&2 "Failed to generate BTF for vmlinux"@@ -287,7 +304,7 @@ fi vmlinux_link "${VMLINUX}" -if is_enabled CONFIG_DEBUG_INFO_BTF; then +if is_set CONFIG_DEBUG_INFO_BTF; then info BTFIDS ${VMLINUX} ${RESOLVE_BTFIDS} --patch_btfids ${btfids_vmlinux} ${VMLINUX} fiSignature · 1 line
2.47.3
Re: [PATCH bpf-next v3 9/9] kbuild, bpf: allow building the vmlinux BTF as a module
In reply to a message not in the archiveQuoted 1 line · Jay
Alan and Alexei, I’ll address both of your comments in V4 and provide more detailed responses later as well.
Sounds good. To expand on what I had in mind, as I've tried putting together a generic approach that will work both for your use case - BTF vmlinux delivered as a module - and mine - inline vmlinux BTF delivered as a module. They'd need to be separate modules as some folks might want vmlinux BTF as a module but not want inline BTF.
The idea is close to what you had; we have a .BTF.link / .BTF.inline.link ELF section which consists of:
#define BTF_LINK_SHA256_LEN 32
/*
* A .BTF.link or .BTF.inline.link section identifies the module which
* carries a vmlinux BTF section. The module name is NUL terminated and the
* field is padded to __MODULE_NAME_LEN.
*/
struct btf_link {
char module_name[__MODULE_NAME_LEN];
u8 sha256[BTF_LINK_SHA256_LEN];
u32 btf_size;
} __packed;These sections .BTF.link / .BTF.inline.link live in vmlinux and tell it
- the module that delivers the payload
- the SHA; and
- the size
again similar to what you had.
The link section is populated at the same time resolve_btfids populates the .BTF_ids section; we add support to resolve_btfids for a --btf_link option of the form
--btf_link <section>:<module>:<raw-btf-file>
So in your case it will be
--btf_link .BTF:btf_vmlinux:vmlinux.BTF
and in mine
--btf_link .BTF.inline:btf_vmlinux_inline:vmlinux.BTF.inline
The attached patch adds resolve_btfids support for this to give an idea of the approach, and at the final vmlinux linking where we patch BTF ids, we would add the above options. resolve_btfids is written to support multiple --btf_link options, so whichever work lands first could add the support that the other series uses. Hope this helps,
Alan
From 9cb9d0e0bd348a03960e0d7f7fb6ef1a76166d56 Mon Sep 17 00:00:00 2001
From: Alan Maguire <[email protected]>
Date: Tue, 29 Sep 2026 18:50:14 +0100
Subject: [PATCH v3 bpf-next 2/4] resolve_btfids: Populate BTF link section
Allow the final BTF patch pass to populate one or more BTF link records. A link identifies the BTF section to be delivered, its carrier module, and the raw finalized BTF payload:
--btf_link <section>:<module>:<raw-btf-file>
Use the raw file size and SHA-256 digest to populate the corresponding <section>.link record. This avoids reparsing BTF during final ELF patching and supports both inline BTF and a future module-delivered vmlinux BTF.
--- tools/bpf/resolve_btfids/main.c | 187 +++++++++++++++++++++++++++++++- 1 file changed, 183 insertions(+), 4 deletions(-)
tools/bpf/resolve_btfids/main.c +183 -4
@@ -93,8 +93,13 @@#include <subcmd/parse-options.h> #define BTF_IDS_SECTION ".BTF_ids" +#define BTF_LINK_MODULE_NAME_MAX 64 +#define LIBBPF_SHA256_DIGEST_LENGTH 32#define BTF_ID_PREFIX "__BTF_ID__" +void libbpf_sha256 (const void *data,size_t len, +__u8 out[LIBBPF_SHA256_DIGEST_LENGTH ]); +#define BTF_STRUCT "struct"#define BTF_UNION "union"#define BTF_TYPEDEF "typedef"
@@ -157,6 +162,7 @@ struct object {size_t strtabidx;unsigned long idlist_addr;int encoding; +int elf_class;const char **func_symbols;u32 func_symbols_cnt;u32 func_symbols_cap;
@@ -179,6 +185,19 @@ struct object {u32 addr_syms_cap; }; +struct btf_link { +char *value; +char *section; +char *module; +char *btf_path; +}; + +struct btf_links { +struct btf_link *links; +u32 cnt; +u32 cap; +}; +#define DECL_TAG_FASTCALL "bpf_fastcall"#define DECL_TAG_KFUNC "bpf_kfunc"
@@ -266,6 +285,49 @@ static int __ensure_mem(void **data, u32 *cap, u32 cnt, size_t elem_sz)#define ensure_mem (arr_ptr, cap_ptr, cnt) \ __ensure_mem((void **)(arr_ptr), (cap_ptr), (cnt), sizeof(**(arr_ptr))) +static int parse_btf_link (const struct option *opt,const char *arg,int unset) +{ +struct btf_links *links = opt->value; +struct btf_link *link; +char *separator; + +if (unset) +return -EINVAL ; +if (__ensure_mem ((void **)&links->links, &links->cap, links->cnt +1 , +sizeof (*links->links))) +return -ENOMEM ; + link = &links->links[links->cnt]; +memset (link,0 ,sizeof (*link)); + link->value =strdup (arg); +if (!link->value) +return -ENOMEM ; + link->section = link->value; + separator =strchr (link->section,':' ); +if (!separator || separator == link->section) + goto err_value; + *separator++ ='\0' ; + link->module = separator; + separator =strchr (link->module,':' ); +if (!separator || separator == link->module || !separator[1 ]) + goto err_value; + *separator++ ='\0' ; + link->btf_path = separator; + links->cnt++; +return 0 ; +err_value: +free (link->value); +return -EINVAL ; +} + +static void free_btf_links (struct btf_links *links) +{ +u32 i; + +for (i =0 ; i < links->cnt; i++) +free (links->links[i].value); +free (links->links); +} +static bool is_btf_id (const char *name) {return name && !strncmp (name,BTF_ID_PREFIX ,sizeof (BTF_ID_PREFIX ) -1 );
@@ -487,6 +549,7 @@ static int elf_collect(struct object *obj)return -1 ; } obj->efile.encoding = ehdr.e_ident[EI_DATA ]; + obj->efile.elf_class = ehdr.e_ident[EI_CLASS ];/* * Scan all the elf sections and look for save data
@@ -1036,6 +1099,106 @@ static int dump_raw_btf(struct btf *btf, const char *out_path)return 0 ; } +static int patch_btf_link (struct object *obj,const struct btf_link *link) +{ +void *raw_btf_data; +Elf_Scn *scn =NULL ; +Elf_Data *data; +GElf_Shdr sh; +char section[128 ]; +char *name; +size_t shdrstrndx, module_name_len; +int fd, err =-1 ; +struct stat st; +FILE *btf_file; +u32 raw_btf_size; +Elf *elf; +u8 *size; + +if (stat (link->btf_path, &st) || st.st_size >UINT_MAX ) +return -EINVAL ; + raw_btf_size = st.st_size; + raw_btf_data =malloc (raw_btf_size); +if (!raw_btf_data) +return -ENOMEM ; + btf_file =fopen (link->btf_path,"rb" ); +if (!btf_file) + goto out_data; +if (fread (raw_btf_data, raw_btf_size,1 , btf_file) !=1 ) + goto out_file; +fclose (btf_file); +if (obj->efile.elf_class ==ELFCLASS32 ) + module_name_len =BTF_LINK_MODULE_NAME_MAX -4 ; +else if (obj->efile.elf_class ==ELFCLASS64 ) + module_name_len =BTF_LINK_MODULE_NAME_MAX -8 ; +else + goto out_data; +if (strlen (link->module) >= module_name_len) + goto out_data; + +snprintf (section,sizeof (section),"%s.link" , link->section); + fd =open (obj->path,O_RDWR ); +if (fd <0 ) + goto out_data; + elf =elf_begin (fd,ELF_C_RDWR_MMAP ,NULL ); +if (!elf) { + err = -EINVAL ; + goto out_close; + } +elf_flagelf (elf,ELF_C_SET ,ELF_F_LAYOUT ); +if (elf_getshdrstrndx (elf, &shdrstrndx)) + goto out_elf; +while ((scn =elf_nextscn (elf, scn))) { +if (gelf_getshdr (scn, &sh) != &sh) + goto out_elf; + name =elf_strptr (elf, shdrstrndx, sh.sh_name); +if (name && !strcmp (name, section)) +break ; + } +if (!scn) { +pr_err ("FAILED: section %s not found in %s\n" , section, obj->path); + goto out_elf; + } + data =elf_getdata (scn,NULL ); +if (!data || data->d_size != module_name_len + +LIBBPF_SHA256_DIGEST_LENGTH +sizeof (u32)) { +pr_err ("FAILED: section %s has unexpected size\n" , section); + goto out_elf; + } +memset (data->d_buf,0 , data->d_size); +memcpy (data->d_buf, link->module,strlen (link->module) +1 ); +libbpf_sha256 (raw_btf_data, raw_btf_size, + (u8 *)data->d_buf + module_name_len); + size = (u8 *)data->d_buf + module_name_len +LIBBPF_SHA256_DIGEST_LENGTH ; +if (obj->efile.encoding ==ELFDATA2LSB ) { + size[0 ] = raw_btf_size; + size[1 ] = raw_btf_size >>8 ; + size[2 ] = raw_btf_size >>16 ; + size[3 ] = raw_btf_size >>24 ; + }else if (obj->efile.encoding ==ELFDATA2MSB ) { + size[0 ] = raw_btf_size >>24 ; + size[1 ] = raw_btf_size >>16 ; + size[2 ] = raw_btf_size >>8 ; + size[3 ] = raw_btf_size; + }else { + goto out_elf; + } +elf_flagdata (data,ELF_C_SET ,ELF_F_DIRTY ); +if (elf_update (elf,ELF_C_WRITE ) >=0 ) + err =0 ; +out_elf: +elf_end (elf); +out_close: +close (fd); +free (raw_btf_data); +return err; +out_file: +fclose (btf_file); +out_data: +free (raw_btf_data); +return err; +} +static const struct btf_type *btf_type_skip_qualifiers (const struct btf *btf,s32 type_id) {const struct btf_type *t =btf__type_by_id (btf, type_id);
@@ -1908,6 +2071,7 @@ int main(int argc, const char **argv) .sets = RB_ROOT, };const char *btfids_path =NULL ; +struct btf_links btf_links = {};bool fatal_warnings = false;bool resolve_btfids = true;char out_path[PATH_MAX ];
@@ -1925,6 +2089,8 @@ int main(int argc, const char **argv) "distill --btf_base and emit .BTF.base section data"),OPT_BOOLEAN (0 ,"inline" , &obj.extract_inline,"extract location BTF into a .BTF.inline file" ), +OPT_CALLBACK (0 ,"btf_link" , &btf_links,"section:module:btf-file" , +"patch a BTF link" , parse_btf_link),OPT_STRING (0 ,"patch_btfids" , &btfids_path,"file" ,"path to .BTF_ids section data blob to patch into ELF file" ),OPT_END ()
@@ -1938,9 +2104,22 @@ int main(int argc, const char **argv) obj.path = argv[0 ]; -if (btfids_path) -return patch_btfids (btfids_path, obj.path); - +if (btfids_path) { + err =patch_btfids (btfids_path, obj.path); +if (err || !btf_links.cnt) + goto out; +if (elf_collect (&obj)) { + err = -EINVAL ; + goto out; + } +for (u32 i =0 ; i < btf_links.cnt; i++) { +struct btf_link *link = &btf_links.links[i]; + err =patch_btf_link (&obj, link); +if (err) +break ; + } + goto out; + }if (elf_collect (&obj)) goto out;if (obj.extract_inline &&collect_func_symbols (&obj))
@@ -2001,10 +2180,10 @@ int main(int argc, const char **argv)if (err) goto out; } -if (!(fatal_warnings && warnings)) err =0 ; out: +free_btf_links (&btf_links);btf__free (obj.inline_btf);btf__free (obj.btf);btf__free (obj.base_btf);
Signature · 1 line
2.43.5
Re: [PATCH bpf-next v3 3/9] bpf: fetch the vmlinux BTF where kernel types enter a program
In reply to [email protected]The scenario does not happen; v4 keeps this behaviour:
https://lore.kernel.org/bpf/[email protected]/
With CONFIG_DEBUG_INFO_BTF=m an allocation failure of the parse is not
stored: bpf_load_btf_vmlinux(), which parses the BTF in v4, returns the error without publishing it, btf_vmlinux stays NULL, the next request retries, and this check does not fire for anyone. What v4 does store with =m, as a later bpf-ci review asked, is a parse failure for any other reason. The payload was checked against the kernel's size and SHA-256 when btf_vmlinux.ko loaded, so that means the build produced a broken BTF. The same happens with =y, where upstream already fails every later bpf_check() with this message.
With =y the parse happens at boot, through the first vmlinux kfunc registration, as it does today.
Jay
Re: [PATCH bpf-next v3 4/9] bpf: take the vmlinux BTF from the btf_vmlinux module
In reply to Alexei StarovoitovQuoted 18 lines · Alexei Starovoitov
kernel/bpf/btf.c static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, · line 6503
Quoted 8 lines · Jay Wang
kernel/bpf/btf.c +8
-0+if (!data && load) { +/* +* The module notifier installs the BTF before init_module() +* returns, so it is either there after this or the module is +* not available (yet). Not cached: a later call retries, +* e.g. once the module becomes reachable on the root fs. +*/ +request_module ("btf_vmlinux" );This will deadlock.
event_btf_ids_read()callsbtf_get_module_btf(NULL)withevent_mutexheld. With =m and BTF not loaded yet
cat/sys/kernel/tracing/events/sched/sched_switch/btf_ids
gets here and waits for modprobe. modprobe gets totrace_module_notify()which takesevent_mutex.
lockdep doesn't see it.
Quoted 6 lines
print_function_args()gets here for every line of the trace, fromftrace_dump()with irqs off too. When the module is not installed that is one modprobe per line.Every caller of
bpf_get_btf_vmlinux()andbpf_find_btf_id()was written for a function that doesn't wait for user space.
Right. Given that fixing those callers one by one does not work, as there are too many and every new one would have to know, I went with a different mechanism in v4:
https://lore.kernel.org/bpf/[email protected]/
In short, the lookups no longer load the BTF; only requests from user space do, at their start.
The lookups cannot wait for the module, because they run in places that must not sleep, or that hold locks the module load needs too: under event_mutex in your btf_ids case, with interrupts off in ftrace_dump(), inside a running BPF program. Loading the module means waiting for modprobe, so waiting in any of them can deadlock or sleep where it must not.
Loading at the start of a request from user space is enough, because that is where every need for the BTF begins: a program or map that uses kernel types, a read of the BTF file, a probe event with BTF arguments. At that point the request holds nothing yet, so it can safely wait for modprobe. And once it has loaded the BTF, the lookups it makes later find it there, so they have no reason to wait. Only the kernel's own early users, the kfunc and struct_ops registrations at boot and the BTF of modules loaded before it, come before any such request, and they are queued until the BTF arrives.
With =m, bpf_get_btf_vmlinux() and bpf_find_btf_id() never load the module and never sleep. Until the BTF is loaded they fail as on a kernel without BTF (NULL, -EINVAL), so every existing caller keeps the assumptions it was written with. The only function that loads the BTF is a new bpf_load_btf_vmlinux(), called at the start of such a request, with nothing held that loading a module needs:
- on entry to the bpf() syscall: a BPF_PROG_LOAD, BPF_MAP_CREATE or BPF_BTF_LOAD that failed while the BTF was missing is run once more after loading it, the way tc and nf_tables retry after loading a module. The verifier itself never waits, and bpf_sys_bpf() does not go through that entry;
- BPF_BTF_GET_NEXT_ID with CAP_SYS_ADMIN, and loading a syscall program, since a light skeleton loader loads its programs while it runs;
- read() of /sys/kernel/btf/vmlinux. Not mmap(): it runs with the caller's mmap_lock held, and a uprobe registration holds event_mutex while it takes the mmap_lock of every mm mapping the probed file, which would close a loop through the module load. mmap() fails until the BTF is loaded, and libbpf then falls back to read();
- read() of the sysfs file of a module built against a distilled base (.BTF.base), through a work item: the reader holds the file's kernfs active reference, which MODULE_STATE_GOING drains with the module notifier chain held;
- reading btf_ids (before event_mutex), creating probe events with BTF arguments (the parser holds only dyn_event_ops_mutex, which no module load takes), and mounting bpffs with delegate options that name commands or types.
print_function_args() only uses the BTF if it is already loaded and never waits for it, so no modprobe per line. Both of your cases now work as the first BTF user after boot: the cat of btf_ids loads the BTF before taking event_mutex and prints the ids, and func-args with sysrq-z prints the functions without arguments, as on a kernel without BTF; the arguments show up once a request from user space has loaded the BTF.
Jay
Re: [PATCH bpf-next v3 4/9] bpf: take the vmlinux BTF from the btf_vmlinux module
In reply to [email protected]Agreed on both, changed in v4 (patch 4/12):
https://lore.kernel.org/bpf/[email protected]/
Only -ENOMEM from btf_parse_vmlinux() is left uncached with =m; any other failure is a broken BTF and is remembered as with =y, so it is parsed once, not again by every later request. And /sys/kernel/btf/vmlinux now serves the raw bytes whenever btf_vmlinux.ko supplied them, whether they parse or not, as with =y.
Jay
Re: [PATCH bpf-next v3 5/9] bpf: defer vmlinux kfunc and struct_ops registrations
In reply to [email protected]Right, the comment and changelog were stale. v4 (patches 6 and 7/12) states what the separate lock does keep:
https://lore.kernel.org/bpf/[email protected]/
With its own lock, btf_module_mutex, which the module notifier takes, is never taken under btf_vmlinux_lock, so the two stay unordered. The code is unchanged. In v4 fetching the BTF no longer takes btf_vmlinux_lock with =m at all (it never loads or parses, see the reply to Alexei on 4/9), so CO-RE fetches it under cand_cache_mutex again, as upstream does; with =y nothing is queued.
Jay
Re: [PATCH bpf-next v3 6/9] bpf: keep module BTF until the vmlinux BTF is available
In reply to [email protected]Right, fixed in v4 (patch 8/12, where the deferred reader is added):
https://lore.kernel.org/bpf/[email protected]/
A dead entry now keeps its raw data only if its sysfs file serves it as is (sysfs_bin_attr_simple_read); for a .BTF.base module, whose reader fails with -ENODEV once the entry is gone and never touches the data, or without a sysfs file, the data is freed with the rest. Tested with a .BTF.base module whose .BTF is corrupted, loaded before the vmlinux BTF:
its file fails with -ENODEV after the parse failure, rmmod is clean, and kmemleak reports nothing; the same module without .BTF.base keeps serving its raw bytes.
Jay
Re: [PATCH bpf-next v3 7/9] bpf: expose deferred .BTF.base module BTF in sysfs from module load
In reply to [email protected]Right, fixed in v4 (patch 8/12):
https://lore.kernel.org/bpf/[email protected]/
The reader no longer loads the vmlinux BTF itself. If it is not there yet, the reader queues a work item that calls bpf_load_btf_vmlinux(), and waits for the module's BTF to be published, for @gone, or for the load attempt to end without the BTF. MODULE_STATE_GOING sets @gone and wakes before it removes the file, so the drain no longer waits on a module load: in your cycle the reader returns -ENODEV, the drain completes, GOING returns, and the kworker's modprobe gets the rwsem once the writer is done.
On the lock comment, you are right that the btf_module_mutex -> cand_cache_mutex edge is gone. v4 states what the separate lock does
keep: btf_module_mutex, which the module notifier takes, is never taken under btf_vmlinux_lock.
Jay
Re: [PATCH bpf-next v3 8/9] bpf, trace, net: prepare CONFIG_DEBUG_INFO_BTF checks for a tristate
In reply to [email protected]Right, fixed in v4 (patch 5/12, with the other tracefs and bpffs requests that load the BTF):
https://lore.kernel.org/bpf/[email protected]/
event_btf_ids_read() now calls bpf_load_btf_vmlinux() before it takes event_mutex, so the btf_vmlinux module load and its trace notifier run without it; btf_get_module_btf(NULL) under the mutex then finds the BTF already parsed. More generally, in v4 the lookups themselves never load the BTF any more (see the reply to Alexei on 4/9): the probe argument parser (PROBE_EVENTS_BTF_ARGS) loads it explicitly, holding only dyn_event_ops_mutex, which loading a module never takes. Tested by reading events/sched/sched_switch/btf_ids, and by creating kprobe events with BTF arguments, each as the first BTF user after boot.
Jay
Re: [PATCH bpf-next v3 9/9] kbuild, bpf: allow building the vmlinux BTF as a module
In reply to Alan MaguireQuoted 9 lines · Alan Maguire
The idea is close to what you had; we have a .BTF.link / .BTF.inline.link ELF section which consists of:
#define
BTF_LINK_SHA256_LEN32/*
* A .BTF.link or .BTF.inline.link section identifies the module which
* carries a vmlinux BTF section. The module name is NUL terminated and the
* field is padded to__MODULE_NAME_LEN.
*/
Quoted 5 lines
struct btf_link {
char module_name[__MODULE_NAME_LEN];
u8 sha256[BTF_LINK_SHA256_LEN];
u32 btf_size;
} __packed;Thanks, this works well for this series too, and it also covers both points of your first mail. v4 has it:
https://lore.kernel.org/bpf/[email protected]/
struct btf_link has this layout, and the kernel now takes the name of the module to load from it: request_module() and the module notifier use module_name instead of a hard-coded "btf_vmlinux" (patch 4/12).
Quoted 8 lines
The link section is populated at the same time
resolve_btfidspopulates the .BTF_ids section; we add support toresolve_btfidsfor a --btf_link option of the form--btf_link <section>:<module>:<raw-btf-file>So in your case it will be
--btf_link .BTF:btf_vmlinux:vmlinux.BTF
That is what link-vmlinux.sh passes to the final --patch_btfids now, with .tmp_vmlinux1.BTF as the file, which gen-btf.sh keeps for it with =m (patch 12/12). The printf code in gen-btf.sh is gone.
Filling the record in at the end also removed v3's placeholder object for the first link: the zeroed record is now defined in C next to struct btf_link, so it has its final size in every link, and the size check in resolve_btfids also catches the kernel and the tool disagreeing on the layout.
Quoted 2 lines
resolve_btfidsis written to support multiple --btf_link options, so whichever work lands first could add the support that the other series uses. Hope this helps,
Your patch is 10/12, without the inline BTF context, which I will leave to a separate patch series later. I reworded its subject and changelog and made a few small changes, all listed in the bracketed note above my Signed-off-by. Please check that you are fine with it in that form.
Tested with 32- and 64-bit, little- and big-endian objects, also with two --btf_link options in one run, and on x86-64 and i386 =m kernels, where .BTF.link matches the BTF in btf_vmlinux.ko.
Jay
Re: [PATCH bpf-next v3 9/9] kbuild, bpf: allow building the vmlinux BTF as a module
In reply to [email protected]All three are addressed in v4:
https://lore.kernel.org/bpf/[email protected]/
- The ftrace argument printer is a real problem: it can run from ftrace_dump() with interrupts disabled. print_function_args() now only prints the arguments if the vmlinux BTF is already loaded (bpf_peek_btf_vmlinux(), patch 5/12), like bpf_snprintf_btf(); in v4 the lookup it uses would not load the BTF anyway. Tested with func-args on and sysrq-z as the first thing touching BTF after boot, on a kernel with CONFIG_DEBUG_ATOMIC_SLEEP.
- The opening of the changelog now names the exceptions: BPF_PRELOAD, users of kernel types that run before btf_vmlinux.ko can be loaded, and code that assumes the vmlinux BTF has id 1.
- btf.rst now lists the requests that load the BTF, including struct_ops maps, kprobe events with BTF arguments, tracepoint btf_ids files and bpffs delegate_* options.
PROBE_EVENTS_BTF_ARGS and FUNCTION_TRACE_ARGS do stay enabled with =m, which is intended: creating a probe with BTF arguments loads the BTF, in process context, and the argument printer uses it once it is there.
Jay