bpf: make the vmlinux BTF an on-demand loadable module (CONFIG_DEBUG_INFO_BTF=m) to save ~5.4 MB memory
Subsystems (13)
v2 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 b4d936547f5a ("Merge branch 'bpf-arena-fix-range_tree-consistency-on-allocation-failure'").
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] 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 and Makefile checks of CONFIG_DEBUG_INFO_BTF that must hold for both =y and =m use IS_ENABLED() and $(subst m,y,...), in bpf, tracing, netfilter and xfrm.
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 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]/
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 +- 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/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 +- 27 files changed, 1300 insertions(+), 156 deletions(-) create mode 100644 kernel/bpf/btf_vmlinux.c
base-commit: b4d936547f5a3ca5563f48ee81f153c928336027
Signature · 1 line
2.47.3
PATCH v2 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
@@ -6516,16 +6516,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)
@@ -6562,7 +6566,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;
@@ -6605,7 +6612,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); }
@@ -8610,6 +8618,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) {
@@ -8630,7 +8680,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);
@@ -8652,37 +8705,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);
@@ -8709,12 +8737,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 v2 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 v2 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
@@ -3165,6 +3165,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 v2 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
@@ -581,6 +581,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
@@ -6406,6 +6406,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 v2 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
@@ -6555,6 +6555,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 ;
@@ -6586,7 +6588,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;
@@ -8712,6 +8722,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;
@@ -9496,12 +9533,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" );
@@ -9670,9 +9717,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" );
@@ -10351,9 +10406,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" );
@@ -10365,8 +10428,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 v2 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
@@ -582,6 +582,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
@@ -21166,12 +21166,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 ))
@@ -21206,8 +21208,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 v2 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
@@ -8772,17 +8772,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;
@@ -8797,9 +8807,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) {
@@ -8813,8 +8823,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) {
@@ -8869,15 +8885,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) {
@@ -8896,10 +8954,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);
@@ -8993,7 +9053,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);
@@ -9041,8 +9102,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 ;
@@ -9067,8 +9130,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) {
@@ -9076,14 +9141,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
@@ -9142,11 +9210,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 v2 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.
No functional change: CONFIG_DEBUG_INFO_BTF is still a bool, for which IS_ENABLED() and #ifdef agree and $(subst m,y,y) is y.
--- Makefile | 3 ++- include/linux/btf_ids.h | 2 +- include/linux/compiler_types.h | 2 +- include/trace/trace_events.h | 2 +- kernel/bpf/Makefile | 2 +- kernel/trace/trace_syscalls.c | 6 +++--- net/netfilter/Makefile | 6 +++--- net/xfrm/Makefile | 4 ++-- 8 files changed, 14 insertions(+), 13 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)
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/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 v2 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
@@ -1197,6 +1197,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 v2 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: - [High] bpf: Use-After-Free in MODULE_STATE_LIVE notifier due to lockless module memory access --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: Use-After-Free in MODULE_STATE_LIVE notifier due to lockless module memory access --
commit 93f5bd60bb80b8878d6319aa725f17dde3127d2c
Author: Jay Wang <[email protected]>
bpf: keep module BTF until the vmlinux BTF is available
This commit delays the parsing and registration of module BTF until the vmlinux BTF is available when the kernel is built with CONFIG_DEBUG_INFO_BTF=m. It keeps a copy of the module's BTF data and processes deferred kfunc, dtor, and struct_ops registrations once the vmlinux BTF arrives.
Quoted 4 lines
kernel/bpf/btf.c +0
-0
[ ... ]
Quoted 13 lines
kernel/bpf/btf.c +9
-0@@ -8918,6 +9002,26 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,continue ; btf_mod->flags |=BTF_MODULE_F_LIVE ; +if (IS_MODULE (CONFIG_DEBUG_INFO_BTF ) && btf_mod->btf && + !list_empty (&btf_mod->deferred_regs)) { +/* +* The vmlinux BTF arrived while this module was +* initializing: btf_parse_deferred_modules() +* parsed its BTF but left the registrations its +* init queued to us, now that init is done and +* the module is not going anywhere. Applying +* them walks btf_modules, so drop the mutex.
kernel/bpf/btf.c static int btf_module_notify(struct notifier_block *nb, unsigned long op, · line 9023
Quoted 10 lines
kernel/bpf/btf.c +10
-0+*/ +LIST_HEAD (regs); + + btf = btf_mod->btf; +btf_get (btf); +list_splice_init (&btf_mod->deferred_regs, ®s); +mutex_unlock (&btf_module_mutex); +btf_apply_deferred_regs (btf, ®s); +btf_put (btf); + goto out;
[Severity: High]
Is it possible for a concurrent module unload to free the module memory while btf_apply_deferred_regs() is still running here?
The MODULE_STATE_LIVE notifier drops btf_module_mutex to call btf_apply_deferred_regs(), which processes deferred_regs that point to the module's memory (such as reg->kfunc.kset). However, it doesn't appear to acquire a module reference via try_module_get() before dropping the lock.
Because the initial module reference count is dropped to 0 by do_init_module() before calling the MODULE_STATE_LIVE notifiers, could a concurrent sys_delete_module() successfully unmap the module memory, leading to a use-after-free when btf_apply_deferred_regs() dereferences those pointers?
Quoted 4 lines
kernel/bpf/btf.c +1
-0+ }break ; }mutex_unlock (&btf_module_mutex);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
[email protected]
AI reviewRe: [PATCH bpf-next v2 9/9] kbuild, bpf: allow building the vmlinux BTF as a module
In reply to Jay WangThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] kconfig: turning DEBUG_INFO_BTF into tristate silently disables dependent bool features --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] kconfig: turning DEBUG_INFO_BTF into tristate silently disables dependent bool features --
commit f23aaa487601db0500af9e21873fa5fc4f1af7b5
Author: Jay Wang <[email protected]>
kbuild, bpf: allow building the vmlinux BTF as a module
This commit makes CONFIG_DEBUG_INFO_BTF a tristate. It allows the vmlinux BTF to be built as a module (btf_vmlinux) that is loaded on demand, saving memory when it is not needed.
lib/Kconfig.debug config DEBUG_INFO_SPLIT · line 399
Quoted 10 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"
[Severity: High]
Does this change cause a regression where dependent boolean features are disabled when CONFIG_DEBUG_INFO_BTF is configured as a module?
In Kconfig, when a bool option depends on an expression that evaluates to m, its upper bound is restricted. Since a bool cannot hold an m value, Kconfig evaluates the option to disabled.
Several major kernel features are boolean options that depend directly on CONFIG_DEBUG_INFO_BTF, including CONFIG_SCHED_CLASS_EXT, CONFIG_NET_SCH_BPF, CONFIG_DEBUG_INFO_BTF_MODULES, and CONFIG_PROBE_EVENTS_BTF_ARGS.
Setting CONFIG_DEBUG_INFO_BTF to m evaluates these dependencies to m, which causes these features to be omitted from the build.
Could the dependencies be updated to evaluate to y when BTF is built as a module, such as using depends on DEBUG_INFO_BTF != n?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
[email protected]
AI reviewRe: [PATCH bpf-next v2 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: NULL pointer dereference in process_arg_ptr_to_btf_id due to missing…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: NULL pointer dereference in process_arg_ptr_to_btf_id due to missing ARG_PTR_TO_BTF_ID_SOCK_COMMON --
commit 84d2361be82e8cb989ae15ca8d3347130aa3ce1b
Author: Jay Wang <[email protected]>
bpf: fetch the vmlinux BTF where kernel types enter a program
This commit defers fetching the vmlinux BTF in the BPF verifier until kernel types are actually needed by a program. This optimization avoids loading and parsing BTF data for programs that do not use kernel types, such as simple socket filters.
Quoted 4 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 8 lines
kernel/bpf/verifier.c +4
-0@@ -11568,6 +11570,24 @@ static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,return err; } +/* Does calling helper @func_id bring kernel BTF types into the program? */ +static bool helper_uses_vmlinux_btf (enum bpf_func_id func_id, +const struct bpf_func_proto *fn) +{
kernel/bpf/verifier.c static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, · line 11586
Quoted 10 lines
kernel/bpf/verifier.c +10
-0+int i; + +/* these take the kernel type id in a struct btf_ptr, not in a register */ +if (func_id == BPF_FUNC_snprintf_btf || func_id == BPF_FUNC_seq_printf_btf) +return true; +if (base_type (fn->ret_type) ==RET_PTR_TO_BTF_ID ) +return true; +for (i =0 ; i <MAX_BPF_FUNC_ARGS ; i++) { +if (base_type (fn->arg_type[i]) ==ARG_PTR_TO_BTF_ID ) +return true;
[Severity: High]
Does this logic also need to check for ARG_PTR_TO_BTF_ID_SOCK_COMMON?
If ARG_PTR_TO_BTF_ID_SOCK_COMMON is omitted here, helpers like bpf_sk_release() that accept this argument type will skip loading btf_vmlinux.
If a program synthesizes a PTR_TO_BTF_ID pointing to a module's BTF using ldimm64, btf_vmlinux could remain NULL. Later, in check_func_args(), arg_btf is assigned from btf_vmlinux:
check_func_args() {
...
case ARG_PTR_TO_BTF_ID:
case ARG_PTR_TO_BTF_ID_SOCK_COMMON:
{
const u32 *arg_btf_id = fn->arg_btf_id[arg];
const struct btf *arg_btf = meta->btf ?: btf_vmlinux;
...
}Because btf_vmlinux is NULL, arg_btf becomes NULL. Could this lead to a NULL pointer dereference when process_arg_ptr_to_btf_id() unconditionally dereferences it?
process_arg_ptr_to_btf_id() {
...
arg_t = btf_type_skip_modifiers(arg_btf, arg_btf_id, &arg_btf_id);
...
}Quoted 4 lines
kernel/bpf/verifier.c +4
-0+ } +return false; +} +
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH bpf-next v2 3/9] bpf: fetch the vmlinux BTF where kernel types enter a program
No change for this in v3:
https://lore.kernel.org/bpf/[email protected]/
This cannot be reached with btf_vmlinux NULL. In check_reg_type(), for ARG_PTR_TO_BTF_ID and ARG_PTR_TO_BTF_ID_SOCK_COMMON without meta->btf, arg_btf is only used when the register is PTR_TO_BTF_ID; a PTR_TO_SOCKET, PTR_TO_SOCK_COMMON or PTR_TO_TCP_SOCK argument breaks out before it. A PTR_TO_BTF_ID register only comes from a place that has loaded the vmlinux BTF: attach_btf, kfunc returns, BTF-typed helper returns, map pointer access, the program context types, kptrs (bpf_find_btf_id() fetches it), or a ksym.
The ldimm64 case in the report needs a module BTF fd, and with =m a module BTF only gets an id once the vmlinux BTF is published:bpf_get_btf_vmlinux() does smp_store_release(&btf_vmlinux) before btf_parse_deferred_modules() parses and registers the modules kept until then, and a module loaded afterwards is parsed against the published vmlinux BTF. So a program holding a module BTF implies a non-NULL btf_vmlinux.
Matching ARG_PTR_TO_BTF_ID_SOCK_COMMON in helper_uses_vmlinux_btf() would load the vmlinux BTF for every tc, XDP and sk_lookup program that calls bpf_sk_release() on a socket from bpf_sk_lookup_*(), which never touches kernel BTF, so the series leaves it out.
Jay
Re: [PATCH bpf-next v2 6/9] bpf: keep module BTF until the vmlinux BTF is available
In reply to [email protected]No change for this in v3:
https://lore.kernel.org/bpf/[email protected]/
I don't think this can happen. do_init_module() runs the MODULE_STATE_LIVE notifier chain before it drops the reference it holds during initialization: the "Drop initial reference." module_put() comes after the notifiers, under module_mutex. While the LIVE notifier runs, the refcount is therefore above MODULE_REF_BASE, and a concurrent delete_module() fails in try_stop_module() with -EWOULDBLOCK (short of a forced unload, which is unsafe for any user of the module). So the module and its kfunc sets and struct_ops stay valid for the whole of btf_apply_deferred_regs() here, without a try_module_get().
Jay
Re: [PATCH bpf-next v2 9/9] kbuild, bpf: allow building the vmlinux BTF as a module
In reply to [email protected]For "depends on DEBUG_INFO_BTF" this does not happen: Kconfig turns an m upper bound into y for a bool symbol (scripts/kconfig/symbol.c, sym_calc_visibility()). I checked it with olddefconfig: with SCHED_CLASS_EXT, NET_SCH_BPF, PROBE_EVENTS_BTF_ARGS, BINFMT_MISC_BPF, IO_URING_BPF_OPS and DEBUG_INFO_BTF_MODULES enabled, switching DEBUG_INFO_BTF from y to m changes nothing but BPF_PRELOAD, which the series excludes on purpose.
Looking at the other uses turned up the reverse case, though: RUST and GENDWARFKSYMS say "depends on !DEBUG_INFO_BTF", and !m is m, which a bool again takes as y, so with =m those pahole restrictions no longer applied. v3 writes them as DEBUG_INFO_BTF=n (patch 8/9):
https://lore.kernel.org/bpf/[email protected]/
Jay