| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/09/27 16:07 | flow | patch-triage |
1mArgs:null Results: {
"EnableConfigs": [
"DEBUG_INFO_BTF",
"DEBUG_INFO_BTF_MODULES",
"BPF_SYSCALL",
"SYSFS",
"MODULES"
],
"FocusSymbols": [
"bpf_get_btf_vmlinux",
"btf_vmlinux_data",
"btf_parse_deferred_modules",
"btf_parse_vmlinux",
"btf_module_notify",
"btf_sysfs_vmlinux_read",
"btf_sysfs_vmlinux_mmap",
"btf_defer_reg"
],
"KMSANReasoning": "The patch series introduces support for building kernel BTF as an on-demand module (CONFIG_DEBUG_INFO_BTF=m). It adds on-demand module loading, deferred registration queues for kfuncs and struct_ops, and sysfs handling for unparsed/deferred BTF data.\n\nKMSAN vs KASAN applicability analysis:\n1. Heap and stack structures: All new data structures (such as struct btf_module, struct bin_attribute, and verifier logs) are allocated using kzalloc_obj() or vmalloc_user(), ensuring zero-initialization. Deferred registration entries and BTF data buffers are cloned via kmemdup()/kvmemdup() with explicit sizes.\n2. User space memory transfers: Sysfs binary file read() and mmap() handlers (/sys/kernel/btf/*) operate on buffers fully populated from the module ELF sections with bounds clamped to the validated section size, posing no risk of uninitialized memory info-leaks.\n3. No branching or logic depends on uninitialized memory.\n4. The risks introduced by this change center around module lifecycle, concurrency (lock ordering, waitqueue synchronization), and resource management (use-after-free, memory leaks), which are detectable by KASAN, LOCKDEP, and KMEMLEAK.\n\nTherefore, dedicated KMSAN fuzzing is not justified for these changes.",
"NeedsKMSAN": false,
"Reasoning": "The patch series adds support for building kernel BTF type information as a loadable module (CONFIG_DEBUG_INFO_BTF=m). It introduces significant logic and state handling across core BPF, BTF parsing, sysfs, verifier, and module notifier code paths, including on-demand loading of BTF, deferred module BTF parsing, queuing and draining of kfunc/struct_ops registrations, wait queue synchronization, SHA-256 integrity verification, and custom sysfs mmap/read handlers. These paths are directly exposed to userspace through sysfs and the BPF syscall.",
"WorthFuzzing": true
} |
| 1/1 | 2026/09/27 16:07 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit d1f4e4b40f45a48572f7ab842ce9ed972bf1576d\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Sun Sep 27 16:07:09 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/Documentation/bpf/btf.rst b/Documentation/bpf/btf.rst\nindex 004aa1058d857..b637f83c85c4c 100644\n--- a/Documentation/bpf/btf.rst\n+++ b/Documentation/bpf/btf.rst\n@@ -1197,6 +1197,41 @@ format.::\n .long 58\n .long 8206 # Line 8 Col 14\n \n+6.1 Kernel BTF\n+--------------\n+\n+With CONFIG_DEBUG_INFO_BTF=y the BTF of the kernel is generated at link time\n+from its DWARF and placed in the .BTF section of vmlinux, which is read-only\n+data of the kernel image. It is available as /sys/kernel/btf/vmlinux and, if\n+CONFIG_DEBUG_INFO_BTF_MODULES is set, module BTF is generated as split BTF\n+against it and available as /sys/kernel/btf/\u003cmodule\u003e.\n+\n+With CONFIG_DEBUG_INFO_BTF=m the same BTF is generated, but it is not part of\n+the kernel image or of the vmlinux ELF file (vmlinux.unstripped in the build\n+tree keeps it, for module BTF generation). It is delivered by the\n+btf_vmlinux module, which the kernel loads on demand the first time the BTF is\n+needed: when /sys/kernel/btf/vmlinux is read or mmap()ed, when kernel BTF\n+objects are enumerated (BPF_BTF_GET_NEXT_ID), or when a BPF program needs\n+kernel type information (an attach_btf_id, a kfunc call, a ksym, a map pointer\n+or a helper that takes or returns a kernel BTF pointer). Until then no memory\n+is used for it, and afterwards nothing differs from =y. In particular:\n+\n+ * /sys/kernel/btf/vmlinux exists from boot with its final size.\n+ * Modules loaded before the vmlinux BTF are exposed in /sys/kernel/btf right\n+ away, their BTF is parsed and gets a BTF id once the vmlinux BTF is\n+ loaded, together with their kfunc and struct_ops registrations.\n+ * kfunc, dtor kfunc and struct_ops registrations of the kernel itself are\n+ applied before the BTF becomes visible.\n+ * The kernel only accepts the BTF it was built with: the size and SHA-256 of\n+ the BTF are linked into the kernel and checked against the module.\n+ * Once loaded the BTF stays; the module cannot be unloaded.\n+\n+If the module is not available (not installed, or the root file system is not\n+mounted yet), the kernel behaves as one built without BTF and retries next\n+time. CONFIG_BPF_PRELOAD is not available with =m: its iterators attach through\n+the vmlinux BTF, so mounting bpffs would load it. bpf_snprintf_btf() and bpf_seq_printf_btf() only use the BTF if it has\n+already been parsed, as they run in program context.\n+\n 7. Testing\n ==========\n \ndiff --git a/Makefile b/Makefile\nindex 66654fa71655b..0a37decd9d013 100644\n--- a/Makefile\n+++ b/Makefile\n@@ -1208,7 +1208,8 @@ endif\n # include additional Makefiles when needed\n include-y\t\t\t:= scripts/Makefile.warn\n include-$(CONFIG_DEBUG_INFO)\t+= scripts/Makefile.debug\n-include-$(CONFIG_DEBUG_INFO_BTF)+= scripts/Makefile.btf\n+# CONFIG_DEBUG_INFO_BTF is a tristate; BTF is generated for both y and m\n+include-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += scripts/Makefile.btf\n include-$(CONFIG_KASAN)\t\t+= scripts/Makefile.kasan\n include-$(CONFIG_KCSAN)\t\t+= scripts/Makefile.kcsan\n include-$(CONFIG_KMSAN)\t\t+= scripts/Makefile.kmsan\n@@ -1744,8 +1745,9 @@ endif\n #\n \n # *.ko are usually independent of vmlinux, but CONFIG_DEBUG_INFO_BTF_MODULES\n-# is an exception.\n-ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+# is an exception, and so is the btf_vmlinux module with CONFIG_DEBUG_INFO_BTF=m,\n+# which carries the vmlinux BTF.\n+ifneq ($(CONFIG_DEBUG_INFO_BTF_MODULES)$(filter m,$(CONFIG_DEBUG_INFO_BTF)),)\n KBUILD_BUILTIN := y\n modules: vmlinux\n endif\ndiff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h\nindex b2988aa12f664..204a9ee171c6d 100644\n--- a/include/asm-generic/vmlinux.lds.h\n+++ b/include/asm-generic/vmlinux.lds.h\n@@ -674,8 +674,18 @@\n \n /*\n * .BTF\n+ *\n+ * With CONFIG_DEBUG_INFO_BTF=y the vmlinux BTF is loaded as read-only data and\n+ * bounded by __start_BTF/__stop_BTF. With CONFIG_DEBUG_INFO_BTF=m it is\n+ * linked as a non-loadable section (see BTF_NOLOAD in ELF_DETAILS), so that\n+ * module BTF generation can read it from vmlinux.unstripped; it is stripped\n+ * from vmlinux (scripts/Makefile.vmlinux), and the btf_vmlinux module carries\n+ * a copy and provides it on demand at runtime.\n+ * What is loaded instead is .BTF.meta, the size and hash of that BTF (see\n+ * scripts/gen-btf.sh), empty in the first link that the BTF is generated\n+ * from. .BTF_ids is needed by the kernel in both cases.\n */\n-#ifdef CONFIG_DEBUG_INFO_BTF\n+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)\n #define BTF\t\t\t\t\t\t\t\t\\\n \t. = ALIGN(PAGE_SIZE);\t\t\t\t\t\t\\\n \t.BTF : AT(ADDR(.BTF) - LOAD_OFFSET) {\t\t\t\t\\\n@@ -685,10 +695,28 @@\n \t.BTF_ids : AT(ADDR(.BTF_ids) - LOAD_OFFSET) {\t\t\t\\\n \t\t*(.BTF_ids)\t\t\t\t\t\t\\\n \t}\n+#elif IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+#define BTF\t\t\t\t\t\t\t\t\\\n+\t. = ALIGN(8);\t\t\t\t\t\t\t\\\n+\t.BTF.meta : AT(ADDR(.BTF.meta) - LOAD_OFFSET) {\t\t\t\\\n+\t\tBOUNDED_SECTION_BY(.BTF.meta, _BTF_meta)\t\t\\\n+\t}\t\t\t\t\t\t\t\t\\\n+\t. = ALIGN(PAGE_SIZE);\t\t\t\t\t\t\\\n+\t.BTF_ids : AT(ADDR(.BTF_ids) - LOAD_OFFSET) {\t\t\t\\\n+\t\t*(.BTF_ids)\t\t\t\t\t\t\\\n+\t}\n #else\n #define BTF\n #endif\n \n+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+/* quoted: BTF is a macro, an unquoted .BTF here would expand it */\n+#define BTF_NOLOAD\t\t\t\t\t\t\t\\\n+\t\t\".BTF\" 0 : { *(\".BTF\") }\n+#else\n+#define BTF_NOLOAD\n+#endif\n+\n /*\n * Init task\n */\n@@ -849,6 +877,7 @@\n /* Required sections not related to debugging. */\n #define ELF_DETAILS\t\t\t\t\t\t\t\\\n \t\t.comment 0 : { *(.comment) }\t\t\t\t\\\n+\t\tBTF_NOLOAD\t\t\t\t\t\t\\\n \t\t.symtab 0 : { *(.symtab) }\t\t\t\t\\\n \t\t.strtab 0 : { *(.strtab) }\t\t\t\t\\\n \t\t.shstrtab 0 : { *(.shstrtab) }\t\t\t\t\\\ndiff --git a/include/linux/bpf.h b/include/linux/bpf.h\nindex e7c5e203edddb..a3c4caad5dfc6 100644\n--- a/include/linux/bpf.h\n+++ b/include/linux/bpf.h\n@@ -3165,6 +3165,7 @@ static inline s32 bpf_call_args_imm(s16 idx)\n #endif\n \n struct btf *bpf_get_btf_vmlinux(void);\n+struct btf *bpf_peek_btf_vmlinux(void);\n \n /* Map specifics */\n struct xdp_frame;\ndiff --git a/include/linux/btf.h b/include/linux/btf.h\nindex ddd0f4f32d24b..586361fa03a0a 100644\n--- a/include/linux/btf.h\n+++ b/include/linux/btf.h\n@@ -581,6 +581,12 @@ __u32 *btf_field_iter_next(struct btf_field_iter *it);\n const char *btf_name_by_offset(const struct btf *btf, u32 offset);\n const char *btf_str_by_offset(const struct btf *btf, u32 offset);\n struct btf *btf_parse_vmlinux(void);\n+void *btf_vmlinux_data(u32 *size, bool load);\n+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+void btf_parse_deferred_modules(void);\n+#else\n+static inline void btf_parse_deferred_modules(void) {}\n+#endif\n struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog);\n u32 *btf_kfunc_flags(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog);\n int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag);\ndiff --git a/include/linux/btf_ids.h b/include/linux/btf_ids.h\nindex 8b5a9ee92513d..c665afff100e7 100644\n--- a/include/linux/btf_ids.h\n+++ b/include/linux/btf_ids.h\n@@ -22,7 +22,7 @@ struct btf_id_set8 {\n \t} pairs[];\n };\n \n-#ifdef CONFIG_DEBUG_INFO_BTF\n+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF)\n \n #include \u003clinux/compiler.h\u003e /* for __PASTE */\n #include \u003clinux/compiler_attributes.h\u003e /* for __maybe_unused */\ndiff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h\nindex c5921f1390079..a90a99849ceed 100644\n--- a/include/linux/compiler_types.h\n+++ b/include/linux/compiler_types.h\n@@ -34,7 +34,7 @@\n * Skipped when running bindgen due to a libclang issue;\n * see https://github.com/rust-lang/rust-bindgen/issues/2244.\n */\n-#if defined(CONFIG_DEBUG_INFO_BTF) \u0026\u0026 defined(CONFIG_PAHOLE_HAS_BTF_TAG) \u0026\u0026 \\\n+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF) \u0026\u0026 defined(CONFIG_PAHOLE_HAS_BTF_TAG) \u0026\u0026 \\\n \t__has_attribute(btf_type_tag) \u0026\u0026 !defined(__BINDGEN__)\n # define BTF_TYPE_TAG(value) __attribute__((btf_type_tag(#value)))\n #else\ndiff --git a/include/linux/module.h b/include/linux/module.h\nindex 96cc98568eea5..82734996a862b 100644\n--- a/include/linux/module.h\n+++ b/include/linux/module.h\n@@ -497,7 +497,7 @@ struct module {\n \tunsigned int num_bpf_raw_events;\n \tstruct bpf_raw_event_map *bpf_raw_events;\n #endif\n-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n \tunsigned int btf_data_size;\n \tunsigned int btf_base_data_size;\n \tvoid *btf_data;\ndiff --git a/include/trace/trace_events.h b/include/trace/trace_events.h\nindex 93011f800d0f7..2a0098929771b 100644\n--- a/include/trace/trace_events.h\n+++ b/include/trace/trace_events.h\n@@ -398,7 +398,7 @@ static inline notrace int trace_event_get_offsets_##call(\t\t\\\n #define _TRACE_PERF_INIT(call)\n #endif /* CONFIG_PERF_EVENTS */\n \n-#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 defined(CONFIG_DEBUG_INFO_BTF)\n+#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF)\n /*\n * Per-template BTF id list, populated at link time by resolve_btfids:\n * [0] FUNC __bpf_trace_\u003ccall\u003e (the BPF dispatcher)\ndiff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile\nindex 9a92c348bbda6..8ab46f496fa48 100644\n--- a/kernel/bpf/Makefile\n+++ b/kernel/bpf/Makefile\n@@ -41,7 +41,11 @@ ifeq ($(CONFIG_INET),y)\n obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o\n endif\n ifeq ($(CONFIG_SYSFS),y)\n-obj-$(CONFIG_DEBUG_INFO_BTF) += sysfs_btf.o\n+obj-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += sysfs_btf.o\n+endif\n+# With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF is carried by this module\n+ifeq ($(CONFIG_DEBUG_INFO_BTF),m)\n+obj-m += btf_vmlinux.o\n endif\n ifeq ($(CONFIG_BPF_JIT),y)\n obj-$(CONFIG_BPF_SYSCALL) += bpf_struct_ops.o\ndiff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c\nindex 1178acd72296e..bf3004908d15a 100644\n--- a/kernel/bpf/bpf_struct_ops.c\n+++ b/kernel/bpf/bpf_struct_ops.c\n@@ -103,7 +103,8 @@ static bool is_valid_value_type(struct btf *btf, s32 value_id,\n \t}\n \tmember = btf_type_member(vt);\n \tmt = btf_type_by_id(btf, member-\u003etype);\n-\tcommon_value_type = btf_type_by_id(btf_vmlinux,\n+\t/* a vmlinux id resolves through the base BTF of a module BTF too */\n+\tcommon_value_type = btf_type_by_id(btf,\n \t\t\t\t\t st_ops_ids[IDX_ST_OPS_COMMON_VALUE_ID]);\n \tif (mt != common_value_type) {\n \t\tpr_warn(\"The first member of %s should be bpf_struct_ops_common_value\\n\",\ndiff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c\nindex 4a1fa4fbdf4e8..00d65199b45e4 100644\n--- a/kernel/bpf/btf.c\n+++ b/kernel/bpf/btf.c\n@@ -29,6 +29,7 @@\n #include \u003clinux/string.h\u003e\n #include \u003clinux/sysfs.h\u003e\n #include \u003clinux/overflow.h\u003e\n+#include \u003ccrypto/sha2.h\u003e\n #include \u003clinux/bitops.h\u003e\n \n #include \u003cnet/netfilter/nf_bpf_link.h\u003e\n@@ -6092,10 +6093,73 @@ static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,\n \treturn ERR_PTR(err);\n }\n \n+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)\n extern char __start_BTF[];\n extern char __stop_BTF[];\n+#endif\n extern struct btf *btf_vmlinux;\n \n+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+/*\n+ * With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF is not part of the kernel\n+ * image. The btf_vmlinux module carries it in its .BTF section; when the\n+ * module loads, btf_module_notify() copies the section here. The copy is\n+ * made with vmalloc_user() so that /sys/kernel/btf/vmlinux can be mmap()ed\n+ * as with the built-in BTF. Set once, never cleared: like the built-in\n+ * BTF, once present it stays for the lifetime of the kernel.\n+ *\n+ * The size and SHA-256 of the BTF are linked into the kernel as .BTF.meta\n+ * by scripts/gen-btf.sh: the size makes /sys/kernel/btf/vmlinux report its\n+ * size before the BTF is loaded, the hash makes sure only the BTF this\n+ * kernel was built with is accepted.\n+ */\n+struct btf_vmlinux_meta {\n+\tu32 size;\n+\tu8 sha256[SHA256_DIGEST_SIZE];\n+} __packed;\n+\n+extern const struct btf_vmlinux_meta __start_BTF_meta[];\n+#define btf_vmlinux_meta (__start_BTF_meta[0])\n+\n+static void *btf_vmlinux_raw;\n+#endif\n+\n+/**\n+ * btf_vmlinux_data - get the raw vmlinux BTF\n+ * @size: where to store the size of the BTF, also when it is not loaded yet\n+ * @load: with CONFIG_DEBUG_INFO_BTF=m, load the btf_vmlinux module if the\n+ *\t BTF is not present yet; may sleep\n+ *\n+ * Return: the raw BTF, or NULL if it is not available.\n+ */\n+void *btf_vmlinux_data(u32 *size, bool load)\n+{\n+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)\n+\t*size = __stop_BTF - __start_BTF;\n+\treturn __start_BTF;\n+#elif IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+\t/* Pairs with the smp_store_release() in btf_vmlinux_module_coming() */\n+\tvoid *data = smp_load_acquire(\u0026btf_vmlinux_raw);\n+\n+\tif (!data \u0026\u0026 load) {\n+\t\t/*\n+\t\t * The module notifier installs the BTF before init_module()\n+\t\t * returns, so it is either there after this or the module is\n+\t\t * not available (yet). Not cached: a later call retries,\n+\t\t * e.g. once the module becomes reachable on the root fs.\n+\t\t */\n+\t\trequest_module(\"btf_vmlinux\");\n+\t\t/* Same pairing as above */\n+\t\tdata = smp_load_acquire(\u0026btf_vmlinux_raw);\n+\t}\n+\t*size = btf_vmlinux_meta.size;\n+\treturn data;\n+#else\n+\t*size = 0;\n+\treturn NULL;\n+#endif\n+}\n+\n #define BPF_MAP_TYPE(_id, _ops)\n #define BPF_LINK_TYPE(_id, _name)\n static union {\n@@ -6126,12 +6190,25 @@ static u8 bpf_ctx_convert_map[] = {\n #undef BPF_MAP_TYPE\n #undef BPF_LINK_TYPE\n \n+/*\n+ * bpf_ctx_convert.t is filled in by btf_parse_vmlinux(). With\n+ * CONFIG_DEBUG_INFO_BTF=m that may not have run yet: the program context\n+ * types are kernel types too, so this is one of the places that loads the\n+ * vmlinux BTF. Only called from the verifier, which may sleep.\n+ */\n+static const struct btf_type *bpf_ctx_convert_type(void)\n+{\n+\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))\n+\t\treturn NULL;\n+\treturn bpf_ctx_convert.t;\n+}\n+\n static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)\n {\n \tconst struct btf_type *conv_struct;\n \tconst struct btf_member *ctx_type;\n \n-\tconv_struct = bpf_ctx_convert.t;\n+\tconv_struct = bpf_ctx_convert_type();\n \tif (!conv_struct)\n \t\treturn NULL;\n \t/* prog_type is valid bpf program type. No need for bounds check. */\n@@ -6147,7 +6224,7 @@ static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)\n \tconst struct btf_type *conv_struct;\n \tconst struct btf_member *ctx_type;\n \n-\tconv_struct = bpf_ctx_convert.t;\n+\tconv_struct = bpf_ctx_convert_type();\n \tif (!conv_struct)\n \t\treturn -EFAULT;\n \t/* prog_type is valid bpf program type. No need for bounds check. */\n@@ -6406,7 +6483,11 @@ int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_ty\n \tconst struct btf_type *kctx_type;\n \tu32 kctx_type_id;\n \n-\tconv_struct = bpf_ctx_convert.t;\n+\tconv_struct = bpf_ctx_convert_type();\n+\tif (!conv_struct) {\n+\t\tbpf_log(log, \"btf_vmlinux is malformed\\n\");\n+\t\treturn -EINVAL;\n+\t}\n \t/* get member for kernel ctx type */\n \tkctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;\n \tkctx_type_id = kctx_member-\u003etype;\n@@ -6474,20 +6555,29 @@ static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name\n \treturn ERR_PTR(err);\n }\n \n+static void btf_apply_deferred_vmlinux_regs(struct btf *btf);\n+\n struct btf *btf_parse_vmlinux(void)\n {\n \tstruct btf_verifier_env *env = NULL;\n \tstruct bpf_verifier_log *log;\n \tstruct btf *btf;\n+\tvoid *data;\n+\tu32 size;\n \tint err;\n \n+\t/* The caller made sure the BTF is present, see bpf_get_btf_vmlinux() */\n+\tdata = btf_vmlinux_data(\u0026size, false);\n+\tif (!data)\n+\t\treturn ERR_PTR(-ENOENT);\n+\n \tenv = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);\n \tif (!env)\n \t\treturn ERR_PTR(-ENOMEM);\n \n \tlog = \u0026env-\u003elog;\n \tlog-\u003elevel = BPF_LOG_KERNEL;\n-\tbtf = btf_parse_base(env, \"vmlinux\", __start_BTF, __stop_BTF - __start_BTF);\n+\tbtf = btf_parse_base(env, \"vmlinux\", data, size);\n \tif (IS_ERR(btf))\n \t\tgoto err_out;\n \n@@ -6495,9 +6585,18 @@ struct btf *btf_parse_vmlinux(void)\n \tbpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);\n \terr = btf_alloc_id(btf);\n \tif (err) {\n+\t\tbpf_ctx_convert.t = NULL;\n \t\tbtf_free(btf);\n \t\tbtf = ERR_PTR(err);\n+\t\tgoto err_out;\n \t}\n+\n+\t/*\n+\t * With CONFIG_DEBUG_INFO_BTF=m, kfunc, dtor kfunc and struct_ops\n+\t * registrations for vmlinux made before the BTF was available were\n+\t * queued; apply them now, before the BTF becomes visible to anyone.\n+\t */\n+\tbtf_apply_deferred_vmlinux_regs(btf);\n err_out:\n \tbtf_verifier_env_free(env);\n \treturn btf;\n@@ -6514,18 +6613,22 @@ __u32 btf_relocate_id(const struct btf *btf, __u32 id)\n \treturn btf-\u003ebase_id_map[id];\n }\n \n-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n \n-static struct btf *btf_parse_module(const char *module_name, const void *data,\n-\t\t\t\t unsigned int data_size, void *base_data,\n-\t\t\t\t unsigned int base_data_size)\n+/*\n+ * Parse split module BTF against @vmlinux_btf. @data is the module's .BTF\n+ * section; if @data_owned, it is an already kvmalloc()ed copy that the new\n+ * btf takes ownership of on success (on failure the caller keeps it).\n+ */\n+static struct btf *btf_parse_module(const char *module_name, struct btf *vmlinux_btf,\n+\t\t\t\t void *data, unsigned int data_size, bool data_owned,\n+\t\t\t\t void *base_data, unsigned int base_data_size)\n {\n-\tstruct btf *btf = NULL, *vmlinux_btf, *base_btf = NULL;\n+\tstruct btf *btf = NULL, *base_btf = NULL;\n \tstruct btf_verifier_env *env = NULL;\n \tstruct bpf_verifier_log *log;\n \tint err = 0;\n \n-\tvmlinux_btf = bpf_get_btf_vmlinux();\n \tif (IS_ERR(vmlinux_btf))\n \t\treturn vmlinux_btf;\n \tif (!vmlinux_btf)\n@@ -6562,7 +6665,10 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,\n \tbtf-\u003enamed_start_id = 0;\n \tstrscpy(btf-\u003ename, module_name);\n \n-\tbtf-\u003edata = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);\n+\tif (data_owned)\n+\t\tbtf-\u003edata = data;\n+\telse\n+\t\tbtf-\u003edata = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);\n \tif (!btf-\u003edata) {\n \t\terr = -ENOMEM;\n \t\tgoto errout;\n@@ -6605,14 +6711,15 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,\n \tif (!IS_ERR(base_btf) \u0026\u0026 base_btf != vmlinux_btf)\n \t\tbtf_free(base_btf);\n \tif (btf) {\n-\t\tkvfree(btf-\u003edata);\n+\t\tif (!data_owned)\n+\t\t\tkvfree(btf-\u003edata);\n \t\tkvfree(btf-\u003etypes);\n \t\tkfree(btf);\n \t}\n \treturn ERR_PTR(err);\n }\n \n-#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */\n+#endif /* CONFIG_DEBUG_INFO_BTF_MODULES || CONFIG_DEBUG_INFO_BTF=m */\n \n struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)\n {\n@@ -7876,6 +7983,13 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,\n \t\tt = btf_type_by_id(btf, t-\u003etype);\n \t}\n \n+\t/* candidates are kernel types: load the vmlinux BTF, outside the mutex */\n+\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {\n+\t\tbpf_log(log, \"arg#%d reference type('%s %s') needs the vmlinux BTF\\n\",\n+\t\t\targ_idx, btf_type_str(t), __btf_name_by_offset(btf, t-\u003ename_off));\n+\t\treturn -EINVAL;\n+\t}\n+\n \tmutex_lock(\u0026cand_cache_mutex);\n \tcc = bpf_core_find_cands(\u0026ctx, type_id);\n \tif (IS_ERR(cc)) {\n@@ -8227,7 +8341,10 @@ int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)\n \t\t\tif (kern_type_id \u003c 0)\n \t\t\t\treturn kern_type_id;\n \n+\t\t\t/* present: btf_get_ptr_to_btf_id() found the candidate in it */\n \t\t\tvmlinux_btf = bpf_get_btf_vmlinux();\n+\t\t\tif (IS_ERR_OR_NULL(vmlinux_btf))\n+\t\t\t\treturn -EINVAL;\n \t\t\tref_t = btf_type_by_id(vmlinux_btf, kern_type_id);\n \t\t\tif (!btf_type_is_struct(ref_t)) {\n \t\t\t\ttname = __btf_name_by_offset(vmlinux_btf, t-\u003ename_off);\n@@ -8596,20 +8713,270 @@ enum {\n \tBTF_MODULE_F_LIVE = (1 \u003c\u003c 0),\n };\n \n-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+/*\n+ * The module notifier registers module BTF (CONFIG_DEBUG_INFO_BTF_MODULES)\n+ * and picks up the vmlinux BTF from the btf_vmlinux module\n+ * (CONFIG_DEBUG_INFO_BTF=m).\n+ */\n+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+#define BTF_MODULE_NOTIFIER 1\n+#endif\n+\n+/*\n+ * CONFIG_DEBUG_INFO_BTF=m: a kfunc, dtor kfunc or struct_ops registration\n+ * made while the BTF it applies to is not available yet. Kept until the BTF\n+ * arrives, see btf_defer_reg() and btf_apply_deferred_regs().\n+ */\n+enum btf_deferred_reg_kind {\n+\tBTF_DEFERRED_KFUNC_SET,\n+\tBTF_DEFERRED_DTOR_KFUNCS,\n+\tBTF_DEFERRED_STRUCT_OPS,\n+};\n+\n+struct btf_deferred_reg {\n+\tstruct list_head list;\n+\tenum btf_deferred_reg_kind kind;\n+\tunion {\n+\t\tstruct {\n+\t\t\tenum btf_kfunc_hook hook;\n+\t\t\tconst struct btf_kfunc_id_set *kset;\n+\t\t} kfunc;\n+\t\tstruct {\n+\t\t\tconst struct btf_id_dtor_kfunc *dtors;\n+\t\t\tu32 cnt;\n+\t\t} dtor;\n+\t\tstruct bpf_struct_ops *st_ops;\n+\t};\n+};\n+\n+#ifdef BTF_MODULE_NOTIFIER\n+static void btf_free_deferred_regs(struct list_head *regs);\n+static void btf_apply_deferred_regs(struct btf *btf, struct list_head *regs);\n+\n struct btf_module {\n \tstruct list_head list;\n \tstruct module *module;\n \tstruct btf *btf;\n \tstruct bin_attribute *sysfs_attr;\n \tint flags;\n+\t/*\n+\t * CONFIG_DEBUG_INFO_BTF=m: a module loaded before the vmlinux BTF is\n+\t * available cannot have its BTF parsed yet. Its .BTF and .BTF.base\n+\t * sections are copied here and parsed once the vmlinux BTF arrives\n+\t * (btf_parse_deferred_modules()); @btf is NULL until then.\n+\t * Registrations of the module's kfuncs, dtor kfuncs and struct_ops\n+\t * wait in @deferred_regs.\n+\t */\n+\tvoid *data;\n+\tvoid *base_data;\n+\tu32 data_size;\n+\tu32 base_data_size;\n+\tstruct list_head deferred_regs;\n+\t/*\n+\t * For the sysfs reader of a module whose data is only final once its\n+\t * BTF is relocated: @ready once @btf is published, @gone once the\n+\t * entry is dead (parse failed or module going). Both only ever go\n+\t * from false to true; waiters sleep on btf_module_wq.\n+\t */\n+\tbool ready;\n+\tbool gone;\n };\n \n static LIST_HEAD(btf_modules);\n static DEFINE_MUTEX(btf_module_mutex);\n+static DECLARE_WAIT_QUEUE_HEAD(btf_module_wq);\n \n static void purge_cand_cache(struct btf *btf);\n \n+static int btf_module_sysfs_add(struct btf_module *btf_mod, const char *name,\n+\t\t\t\tvoid *private, size_t size,\n+\t\t\t\tssize_t (*read)(struct file *, struct kobject *,\n+\t\t\t\t\t\tconst struct bin_attribute *,\n+\t\t\t\t\t\tchar *, loff_t, size_t))\n+{\n+\tstruct bin_attribute *attr;\n+\tint err;\n+\n+\tif (!IS_ENABLED(CONFIG_SYSFS))\n+\t\treturn 0;\n+\n+\tattr = kzalloc_obj(*attr);\n+\tif (!attr)\n+\t\treturn -ENOMEM;\n+\n+\tsysfs_bin_attr_init(attr);\n+\tattr-\u003eattr.name = name;\n+\tattr-\u003eattr.mode = 0444;\n+\tattr-\u003esize = size;\n+\tattr-\u003eprivate = private;\n+\tattr-\u003eread = read;\n+\n+\terr = sysfs_create_bin_file(btf_kobj, attr);\n+\tif (err) {\n+\t\tpr_warn(\"failed to register module [%s] BTF in sysfs: %d\\n\",\n+\t\t\tname, err);\n+\t\tkfree(attr);\n+\t\treturn err;\n+\t}\n+\n+\tbtf_mod-\u003esysfs_attr = attr;\n+\treturn 0;\n+}\n+\n+/*\n+ * Called with btf_module_mutex NOT held: removing the sysfs file waits for\n+ * readers to leave, and a deferred reader may need the mutex to get there.\n+ */\n+static void btf_module_free(struct btf_module *btf_mod)\n+{\n+\tWRITE_ONCE(btf_mod-\u003egone, true);\n+\twake_up_all(\u0026btf_module_wq);\n+\tif (btf_mod-\u003esysfs_attr)\n+\t\tsysfs_remove_bin_file(btf_kobj, btf_mod-\u003esysfs_attr);\n+\tif (btf_mod-\u003ebtf) {\n+\t\tpurge_cand_cache(btf_mod-\u003ebtf);\n+\t\tbtf_put(btf_mod-\u003ebtf);\n+\t} else {\n+\t\tkvfree(btf_mod-\u003edata);\n+\t\tkvfree(btf_mod-\u003ebase_data);\n+\t}\n+\tbtf_free_deferred_regs(\u0026btf_mod-\u003edeferred_regs);\n+\tkfree(btf_mod-\u003esysfs_attr);\n+\tkfree(btf_mod);\n+}\n+\n+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+/*\n+ * The btf_vmlinux module carries the vmlinux BTF in its .BTF section\n+ * (scripts/gen-btf.sh). Keep a copy; the module is only the carrier and\n+ * has no BTF of its own.\n+ */\n+static int btf_vmlinux_module_coming(struct module *mod)\n+{\n+\tu8 sha256sum[SHA256_DIGEST_SIZE];\n+\tvoid *data;\n+\n+\tif (btf_vmlinux_raw)\n+\t\treturn 0;\n+\n+\t/*\n+\t * The verifier trusts the BTF as the description of this kernel's\n+\t * types, so a BTF from a different build must not get in even if\n+\t * the module otherwise loads (same release string, same vermagic).\n+\t */\n+\tif (mod-\u003ebtf_data_size != btf_vmlinux_meta.size) {\n+\t\tpr_err(\"module [%s]: BTF size %u does not match this kernel (%u)\\n\",\n+\t\t mod-\u003ename, mod-\u003ebtf_data_size, btf_vmlinux_meta.size);\n+\t\treturn -EINVAL;\n+\t}\n+\tsha256(mod-\u003ebtf_data, mod-\u003ebtf_data_size, sha256sum);\n+\tif (memcmp(sha256sum, btf_vmlinux_meta.sha256, sizeof(sha256sum))) {\n+\t\tpr_err(\"module [%s]: BTF does not match this kernel\\n\", mod-\u003ename);\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tdata = vmalloc_user(mod-\u003ebtf_data_size);\n+\tif (!data)\n+\t\treturn -ENOMEM;\n+\tmemcpy(data, mod-\u003ebtf_data, mod-\u003ebtf_data_size);\n+\n+\t/* Pairs with the smp_load_acquire() in btf_vmlinux_data() */\n+\tsmp_store_release(\u0026btf_vmlinux_raw, data);\n+\treturn 0;\n+}\n+\n+/*\n+ * sysfs reader for a module kept aside with a .BTF.base section: its .BTF is\n+ * split against the distilled base and only becomes valid split BTF against\n+ * the vmlinux BTF once relocated, which rewrites the buffer in place. So\n+ * first make sure the vmlinux BTF is loaded (which parses and relocates the\n+ * kept modules), then wait until this module's BTF is published. The size\n+ * does not change: relocation only rewrites ids and string offsets.\n+ */\n+static bool btf_module_published(struct btf_module *btf_mod)\n+{\n+\t/* Pairs with the smp_store_release() of @ready after btf_mod-\u003ebtf is set */\n+\treturn smp_load_acquire(\u0026btf_mod-\u003eready);\n+}\n+\n+static ssize_t btf_module_sysfs_read_deferred(struct file *filp, struct kobject *kobj,\n+\t\t\t\t\t const struct bin_attribute *attr,\n+\t\t\t\t\t char *buf, loff_t off, size_t count)\n+{\n+\tstruct btf_module *btf_mod = attr-\u003eprivate;\n+\tint err;\n+\n+\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))\n+\t\treturn -ENODEV;\n+\n+\t/*\n+\t * Another thread may still be relocating and publishing it; if the\n+\t * module goes away or its BTF turns out unusable, btf_module_free()\n+\t * or btf_parse_deferred_modules() set @gone and wake us.\n+\t */\n+\terr = wait_event_interruptible(btf_module_wq,\n+\t\t\t\t btf_module_published(btf_mod) ||\n+\t\t\t\t READ_ONCE(btf_mod-\u003egone));\n+\tif (err)\n+\t\treturn err;\n+\tif (!btf_module_published(btf_mod))\n+\t\treturn -ENODEV;\n+\n+\t/* sysfs clamps @off and @count to attr-\u003esize == btf-\u003edata_size */\n+\tmemcpy(buf, btf_mod-\u003ebtf-\u003edata + off, count);\n+\treturn count;\n+}\n+\n+/*\n+ * The vmlinux BTF is not available yet and must not be loaded from the\n+ * module notifier (that would nest a module load into a module load). Keep\n+ * the module's BTF for btf_parse_deferred_modules().\n+ *\n+ * The sysfs file is created right away with its final size, as with =y.\n+ * Without a .BTF.base section the .BTF data is final and is served as is;\n+ * with one, it is only valid once relocated, so its reader waits for that\n+ * (btf_module_sysfs_read_deferred()).\n+ */\n+static int btf_module_defer(struct btf_module *btf_mod, struct module *mod)\n+{\n+\tbtf_mod-\u003edata = kvmemdup(mod-\u003ebtf_data, mod-\u003ebtf_data_size,\n+\t\t\t\t GFP_KERNEL | __GFP_NOWARN);\n+\tif (!btf_mod-\u003edata)\n+\t\treturn -ENOMEM;\n+\tbtf_mod-\u003edata_size = mod-\u003ebtf_data_size;\n+\n+\tif (mod-\u003ebtf_base_data) {\n+\t\tbtf_mod-\u003ebase_data = kvmemdup(mod-\u003ebtf_base_data,\n+\t\t\t\t\t mod-\u003ebtf_base_data_size,\n+\t\t\t\t\t GFP_KERNEL | __GFP_NOWARN);\n+\t\tif (!btf_mod-\u003ebase_data) {\n+\t\t\tkvfree(btf_mod-\u003edata);\n+\t\t\treturn -ENOMEM;\n+\t\t}\n+\t\tbtf_mod-\u003ebase_data_size = mod-\u003ebtf_base_data_size;\n+\t\t/* not fatal, the module BTF is usable without the sysfs file */\n+\t\tbtf_module_sysfs_add(btf_mod, mod-\u003ename, btf_mod, btf_mod-\u003edata_size,\n+\t\t\t\t btf_module_sysfs_read_deferred);\n+\t} else {\n+\t\tbtf_module_sysfs_add(btf_mod, mod-\u003ename, btf_mod-\u003edata,\n+\t\t\t\t btf_mod-\u003edata_size, sysfs_bin_attr_simple_read);\n+\t}\n+\n+\tlist_add(\u0026btf_mod-\u003elist, \u0026btf_modules);\n+\treturn 0;\n+}\n+#else\n+static int btf_vmlinux_module_coming(struct module *mod)\n+{\n+\treturn 0;\n+}\n+\n+static int btf_module_defer(struct btf_module *btf_mod, struct module *mod)\n+{\n+\treturn 0;\n+}\n+#endif\n+\n static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \t\t\t void *module)\n {\n@@ -8618,9 +8985,17 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \tstruct btf *btf;\n \tint err = 0;\n \n-\tif (mod-\u003ebtf_data_size == 0 ||\n-\t (op != MODULE_STATE_COMING \u0026\u0026 op != MODULE_STATE_LIVE \u0026\u0026\n-\t op != MODULE_STATE_GOING))\n+\tif (op != MODULE_STATE_COMING \u0026\u0026 op != MODULE_STATE_LIVE \u0026\u0026\n+\t op != MODULE_STATE_GOING)\n+\t\tgoto out;\n+\n+\tif (IS_MODULE(CONFIG_DEBUG_INFO_BTF) \u0026\u0026 !strcmp(mod-\u003ename, \"btf_vmlinux\")) {\n+\t\tif (op == MODULE_STATE_COMING)\n+\t\t\terr = btf_vmlinux_module_coming(mod);\n+\t\tgoto out;\n+\t}\n+\n+\tif (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || mod-\u003ebtf_data_size == 0)\n \t\tgoto out;\n \n \tswitch (op) {\n@@ -8630,7 +9005,28 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \t\t\terr = -ENOMEM;\n \t\t\tgoto out;\n \t\t}\n-\t\tbtf = btf_parse_module(mod-\u003ename, mod-\u003ebtf_data, mod-\u003ebtf_data_size,\n+\t\tbtf_mod-\u003emodule = module;\n+\t\tINIT_LIST_HEAD(\u0026btf_mod-\u003edeferred_regs);\n+\n+\t\tif (IS_MODULE(CONFIG_DEBUG_INFO_BTF)) {\n+\t\t\tmutex_lock(\u0026btf_module_mutex);\n+\t\t\t/* Pairs with the publication in bpf_get_btf_vmlinux() */\n+\t\t\tif (!smp_load_acquire(\u0026btf_vmlinux)) {\n+\t\t\t\terr = btf_module_defer(btf_mod, mod);\n+\t\t\t\tmutex_unlock(\u0026btf_module_mutex);\n+\t\t\t\tif (err) {\n+\t\t\t\t\tpr_warn(\"failed to keep module [%s] BTF: %d\\n\",\n+\t\t\t\t\t\tmod-\u003ename, err);\n+\t\t\t\t\tkfree(btf_mod);\n+\t\t\t\t\terr = 0;\n+\t\t\t\t}\n+\t\t\t\tgoto out;\n+\t\t\t}\n+\t\t\tmutex_unlock(\u0026btf_module_mutex);\n+\t\t}\n+\n+\t\tbtf = btf_parse_module(mod-\u003ename, bpf_get_btf_vmlinux(),\n+\t\t\t\t mod-\u003ebtf_data, mod-\u003ebtf_data_size, false,\n \t\t\t\t mod-\u003ebtf_base_data, mod-\u003ebtf_base_data_size);\n \t\tif (IS_ERR(btf)) {\n \t\t\tkfree(btf_mod);\n@@ -8652,37 +9048,13 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \n \t\tpurge_cand_cache(NULL);\n \t\tmutex_lock(\u0026btf_module_mutex);\n-\t\tbtf_mod-\u003emodule = module;\n \t\tbtf_mod-\u003ebtf = btf;\n \t\tlist_add(\u0026btf_mod-\u003elist, \u0026btf_modules);\n \t\tmutex_unlock(\u0026btf_module_mutex);\n \n-\t\tif (IS_ENABLED(CONFIG_SYSFS)) {\n-\t\t\tstruct bin_attribute *attr;\n-\n-\t\t\tattr = kzalloc_obj(*attr);\n-\t\t\tif (!attr)\n-\t\t\t\tgoto out;\n-\n-\t\t\tsysfs_bin_attr_init(attr);\n-\t\t\tattr-\u003eattr.name = btf-\u003ename;\n-\t\t\tattr-\u003eattr.mode = 0444;\n-\t\t\tattr-\u003esize = btf-\u003edata_size;\n-\t\t\tattr-\u003eprivate = btf-\u003edata;\n-\t\t\tattr-\u003eread = sysfs_bin_attr_simple_read;\n-\n-\t\t\terr = sysfs_create_bin_file(btf_kobj, attr);\n-\t\t\tif (err) {\n-\t\t\t\tpr_warn(\"failed to register module [%s] BTF in sysfs: %d\\n\",\n-\t\t\t\t\tmod-\u003ename, err);\n-\t\t\t\tkfree(attr);\n-\t\t\t\terr = 0;\n-\t\t\t\tgoto out;\n-\t\t\t}\n-\n-\t\t\tbtf_mod-\u003esysfs_attr = attr;\n-\t\t}\n-\n+\t\t/* not fatal, the module BTF is usable without the sysfs file */\n+\t\tbtf_module_sysfs_add(btf_mod, btf-\u003ename, btf-\u003edata, btf-\u003edata_size,\n+\t\t\t\t sysfs_bin_attr_simple_read);\n \t\tbreak;\n \tcase MODULE_STATE_LIVE:\n \t\tmutex_lock(\u0026btf_module_mutex);\n@@ -8691,6 +9063,26 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \t\t\t\tcontinue;\n \n \t\t\tbtf_mod-\u003eflags |= BTF_MODULE_F_LIVE;\n+\t\t\tif (IS_MODULE(CONFIG_DEBUG_INFO_BTF) \u0026\u0026 btf_mod-\u003ebtf \u0026\u0026\n+\t\t\t !list_empty(\u0026btf_mod-\u003edeferred_regs)) {\n+\t\t\t\t/*\n+\t\t\t\t * The vmlinux BTF arrived while this module was\n+\t\t\t\t * initializing: btf_parse_deferred_modules()\n+\t\t\t\t * parsed its BTF but left the registrations its\n+\t\t\t\t * init queued to us, now that init is done and\n+\t\t\t\t * the module is not going anywhere. Applying\n+\t\t\t\t * them walks btf_modules, so drop the mutex.\n+\t\t\t\t */\n+\t\t\t\tLIST_HEAD(regs);\n+\n+\t\t\t\tbtf = btf_mod-\u003ebtf;\n+\t\t\t\tbtf_get(btf);\n+\t\t\t\tlist_splice_init(\u0026btf_mod-\u003edeferred_regs, \u0026regs);\n+\t\t\t\tmutex_unlock(\u0026btf_module_mutex);\n+\t\t\t\tbtf_apply_deferred_regs(btf, \u0026regs);\n+\t\t\t\tbtf_put(btf);\n+\t\t\t\tgoto out;\n+\t\t\t}\n \t\t\tbreak;\n \t\t}\n \t\tmutex_unlock(\u0026btf_module_mutex);\n@@ -8707,15 +9099,13 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \t\t\t * btf_try_get_module() on such BTFs will fail. This may\n \t\t\t * be called again on btf_put(), but it's ok to do so.\n \t\t\t */\n-\t\t\tbtf_free_id(btf_mod-\u003ebtf);\n+\t\t\tif (btf_mod-\u003ebtf)\n+\t\t\t\tbtf_free_id(btf_mod-\u003ebtf);\n \t\t\tlist_del(\u0026btf_mod-\u003elist);\n-\t\t\tif (btf_mod-\u003esysfs_attr)\n-\t\t\t\tsysfs_remove_bin_file(btf_kobj, btf_mod-\u003esysfs_attr);\n-\t\t\tpurge_cand_cache(btf_mod-\u003ebtf);\n-\t\t\tbtf_put(btf_mod-\u003ebtf);\n-\t\t\tkfree(btf_mod-\u003esysfs_attr);\n-\t\t\tkfree(btf_mod);\n-\t\t\tbreak;\n+\t\t\tmutex_unlock(\u0026btf_module_mutex);\n+\t\t\t/* off the list, nobody else can find it now */\n+\t\t\tbtf_module_free(btf_mod);\n+\t\t\tgoto out;\n \t\t}\n \t\tmutex_unlock(\u0026btf_module_mutex);\n \t\tbreak;\n@@ -8735,7 +9125,107 @@ static int __init btf_module_init(void)\n }\n \n fs_initcall(btf_module_init);\n-#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */\n+\n+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n+/*\n+ * A kept module whose BTF cannot be used after all. The module is loaded\n+ * and stays, so there is no way to reject it: the entry stays on the list,\n+ * dead, until the module goes. Its sysfs file stays too, its reader, or\n+ * the caller of this function, may be inside it right now: a .BTF.base\n+ * reader wakes up and fails, a plain one keeps serving the raw data, which\n+ * is kept for that.\n+ */\n+static void btf_module_dead(struct btf_module *btf_mod, const char *what, int err)\n+{\n+\tpr_warn(\"failed to %s module [%s] BTF: %d\\n\", what, btf_mod-\u003emodule-\u003ename, err);\n+\tkvfree(btf_mod-\u003ebase_data);\n+\tbtf_mod-\u003ebase_data = NULL;\n+\tbtf_free_deferred_regs(\u0026btf_mod-\u003edeferred_regs);\n+\tWRITE_ONCE(btf_mod-\u003egone, true);\n+\twake_up_all(\u0026btf_module_wq);\n+}\n+\n+/*\n+ * CONFIG_DEBUG_INFO_BTF=m: the vmlinux BTF has just become available. Parse\n+ * the BTF of the modules that were loaded before it, and apply the\n+ * registrations that waited for them. Called from bpf_get_btf_vmlinux()\n+ * once btf_vmlinux is published, with no locks held -- possibly from the\n+ * sysfs reader of one of these modules, which is why no sysfs file is\n+ * removed here.\n+ *\n+ * A module's BTF is published (btf_mod-\u003ebtf set, id allocated) only after\n+ * its queued registrations are applied, so nobody sees a module BTF without\n+ * its kfuncs and struct_ops, as with the vmlinux BTF. Applying walks\n+ * btf_modules (btf_check_kfunc_name()) and so needs the mutex dropped; the\n+ * module is pinned for that, and the scan restarts afterwards. A module\n+ * that is still initializing is only published: its init is still queueing\n+ * registrations, and MODULE_STATE_LIVE applies them once it is done.\n+ */\n+void btf_parse_deferred_modules(void)\n+{\n+\t/* Pairs with the publication in bpf_get_btf_vmlinux() */\n+\tstruct btf *vmlinux_btf = smp_load_acquire(\u0026btf_vmlinux);\n+\tstruct btf_module *btf_mod;\n+\tbool parsed = false;\n+\tLIST_HEAD(regs);\n+\tstruct btf *btf;\n+\tint err;\n+\n+\tif (IS_ERR_OR_NULL(vmlinux_btf))\n+\t\treturn;\n+\n+\tmutex_lock(\u0026btf_module_mutex);\n+restart:\n+\tlist_for_each_entry(btf_mod, \u0026btf_modules, list) {\n+\t\tif (btf_mod-\u003ebtf || btf_mod-\u003egone)\n+\t\t\tcontinue;\n+\n+\t\tbtf = btf_parse_module(btf_mod-\u003emodule-\u003ename, vmlinux_btf,\n+\t\t\t\t btf_mod-\u003edata, btf_mod-\u003edata_size, true,\n+\t\t\t\t btf_mod-\u003ebase_data, btf_mod-\u003ebase_data_size);\n+\t\tif (IS_ERR(btf)) {\n+\t\t\t/* on failure the caller keeps the data */\n+\t\t\tbtf_module_dead(btf_mod, \"validate\", PTR_ERR(btf));\n+\t\t\tcontinue;\n+\t\t}\n+\t\t/* btf-\u003edata is btf_mod-\u003edata now, the sysfs file keeps pointing at valid data */\n+\t\tkvfree(btf_mod-\u003ebase_data);\n+\t\tbtf_mod-\u003ebase_data = NULL;\n+\n+\t\tif ((btf_mod-\u003eflags \u0026 BTF_MODULE_F_LIVE) \u0026\u0026\n+\t\t try_module_get(btf_mod-\u003emodule)) {\n+\t\t\tlist_splice_init(\u0026btf_mod-\u003edeferred_regs, \u0026regs);\n+\t\t\tmutex_unlock(\u0026btf_module_mutex);\n+\t\t\tbtf_apply_deferred_regs(btf, \u0026regs);\n+\t\t\tmutex_lock(\u0026btf_module_mutex);\n+\t\t\tmodule_put(btf_mod-\u003emodule);\n+\t\t}\n+\n+\t\terr = btf_alloc_id(btf);\n+\t\tif (err) {\n+\t\t\t/* give the data back to the entry, the sysfs file may serve it */\n+\t\t\tbtf-\u003edata = NULL;\n+\t\t\tbtf_free(btf);\n+\t\t\tbtf_module_dead(btf_mod, \"register\", err);\n+\t\t\tgoto restart;\n+\t\t}\n+\n+\t\tbtf_mod-\u003edata = NULL;\n+\t\tbtf_mod-\u003ebtf = btf;\n+\t\t/* Pairs with the smp_load_acquire() in btf_module_sysfs_read_deferred() */\n+\t\tsmp_store_release(\u0026btf_mod-\u003eready, true);\n+\t\twake_up_all(\u0026btf_module_wq);\n+\t\tparsed = true;\n+\t\t/* the list may have changed while the mutex was dropped */\n+\t\tgoto restart;\n+\t}\n+\tmutex_unlock(\u0026btf_module_mutex);\n+\n+\tif (parsed)\n+\t\tpurge_cand_cache(NULL);\n+}\n+#endif /* IS_MODULE(CONFIG_DEBUG_INFO_BTF) */\n+#endif /* BTF_MODULE_NOTIFIER */\n \n struct module *btf_try_get_module(const struct btf *btf)\n {\n@@ -8787,8 +9277,11 @@ struct btf *btf_get_module_btf(const struct module *module)\n \t\tif (btf_mod-\u003emodule != module)\n \t\t\tcontinue;\n \n-\t\tbtf_get(btf_mod-\u003ebtf);\n-\t\tbtf = btf_mod-\u003ebtf;\n+\t\t/* NULL while waiting for the vmlinux BTF (CONFIG_DEBUG_INFO_BTF=m) */\n+\t\tif (btf_mod-\u003ebtf) {\n+\t\t\tbtf_get(btf_mod-\u003ebtf);\n+\t\t\tbtf = btf_mod-\u003ebtf;\n+\t\t}\n \t\tbreak;\n \t}\n \tmutex_unlock(\u0026btf_module_mutex);\n@@ -8950,12 +9443,18 @@ static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind\n #ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n \tstruct btf_module *btf_mod, *tmp;\n #endif\n+\tstruct btf *vmlinux_btf;\n \ts32 id;\n \n \tif (!btf_is_module(btf))\n \t\treturn 0;\n \n-\tid = btf_find_by_name_kind(bpf_get_btf_vmlinux(), func_name, kind);\n+\t/* a module BTF only exists once the vmlinux BTF is parsed */\n+\tvmlinux_btf = bpf_get_btf_vmlinux();\n+\tif (IS_ERR_OR_NULL(vmlinux_btf))\n+\t\treturn -EINVAL;\n+\n+\tid = btf_find_by_name_kind(vmlinux_btf, func_name, kind);\n \tif (id \u003e= 0) {\n \t\tpr_err(\"kfunc %s (id: %d) is already present in vmlinux.\\n\",\n \t\t func_name, id);\n@@ -8965,7 +9464,8 @@ static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind\n #ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n \tguard(mutex)(\u0026btf_module_mutex);\n \tlist_for_each_entry_safe(btf_mod, tmp, \u0026btf_modules, list) {\n-\t\tif (btf_mod-\u003ebtf == btf)\n+\t\t/* skip ourselves and, with CONFIG_DEBUG_INFO_BTF=m, unparsed BTF */\n+\t\tif (btf_mod-\u003ebtf == btf || !btf_mod-\u003ebtf)\n \t\t\tcontinue;\n \t\tid = btf_find_by_name_kind(btf_mod-\u003ebtf, func_name, kind);\n \t\tif (id \u003e= 0) {\n@@ -9290,11 +9790,36 @@ u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,\n \treturn btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);\n }\n \n+static int btf_kfunc_id_set_add(struct btf *btf, enum btf_kfunc_hook hook,\n+\t\t\t\tconst struct btf_kfunc_id_set *kset)\n+{\n+\tint ret, i;\n+\n+\tfor (i = 0; i \u003c kset-\u003eset-\u003ecnt; i++) {\n+\t\tret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset-\u003eset-\u003epairs[i].id),\n+\t\t\t\t\t kset-\u003eset-\u003epairs[i].flags);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\n+\treturn btf_populate_kfunc_set(btf, hook, kset);\n+}\n+\n+static int btf_defer_reg(struct module *owner, const struct btf_deferred_reg *tmpl);\n+\n static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,\n \t\t\t\t const struct btf_kfunc_id_set *kset)\n {\n+\tstruct btf_deferred_reg tmpl = {\n+\t\t.kind = BTF_DEFERRED_KFUNC_SET,\n+\t\t.kfunc = { .hook = hook, .kset = kset },\n+\t};\n \tstruct btf *btf;\n-\tint ret, i;\n+\tint ret;\n+\n+\tret = btf_defer_reg(kset-\u003eowner, \u0026tmpl);\n+\tif (ret)\n+\t\treturn ret \u003e 0 ? 0 : ret;\n \n \tbtf = btf_get_module_btf(kset-\u003eowner);\n \tif (!btf)\n@@ -9302,16 +9827,7 @@ static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,\n \tif (IS_ERR(btf))\n \t\treturn PTR_ERR(btf);\n \n-\tfor (i = 0; i \u003c kset-\u003eset-\u003ecnt; i++) {\n-\t\tret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset-\u003eset-\u003epairs[i].id),\n-\t\t\t\t\t kset-\u003eset-\u003epairs[i].flags);\n-\t\tif (ret)\n-\t\t\tgoto err_out;\n-\t}\n-\n-\tret = btf_populate_kfunc_set(btf, hook, kset);\n-\n-err_out:\n+\tret = btf_kfunc_id_set_add(btf, hook, kset);\n \tbtf_put(btf);\n \treturn ret;\n }\n@@ -9403,21 +9919,13 @@ static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc\n \treturn 0;\n }\n \n-/* This function must be invoked only from initcalls/module init functions */\n-int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,\n-\t\t\t\tstruct module *owner)\n+static int btf_dtor_kfuncs_add(struct btf *btf, const struct btf_id_dtor_kfunc *dtors,\n+\t\t\t u32 add_cnt)\n {\n \tstruct btf_id_dtor_kfunc_tab *tab;\n-\tstruct btf *btf;\n \tu32 tab_cnt, i;\n \tint ret;\n \n-\tbtf = btf_get_module_btf(owner);\n-\tif (!btf)\n-\t\treturn check_btf_kconfigs(owner, \"dtor kfuncs\");\n-\tif (IS_ERR(btf))\n-\t\treturn PTR_ERR(btf);\n-\n \tif (add_cnt \u003e= BTF_DTOR_KFUNC_MAX_CNT) {\n \t\tpr_err(\"cannot register more than %d kfunc destructors\\n\", BTF_DTOR_KFUNC_MAX_CNT);\n \t\tret = -E2BIG;\n@@ -9474,6 +9982,31 @@ int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_c\n end:\n \tif (ret)\n \t\tbtf_free_dtor_kfunc_tab(btf);\n+\treturn ret;\n+}\n+\n+/* This function must be invoked only from initcalls/module init functions */\n+int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,\n+\t\t\t\tstruct module *owner)\n+{\n+\tstruct btf_deferred_reg tmpl = {\n+\t\t.kind = BTF_DEFERRED_DTOR_KFUNCS,\n+\t\t.dtor = { .dtors = dtors, .cnt = add_cnt },\n+\t};\n+\tstruct btf *btf;\n+\tint ret;\n+\n+\tret = btf_defer_reg(owner, \u0026tmpl);\n+\tif (ret)\n+\t\treturn ret \u003e 0 ? 0 : ret;\n+\n+\tbtf = btf_get_module_btf(owner);\n+\tif (!btf)\n+\t\treturn check_btf_kconfigs(owner, \"dtor kfuncs\");\n+\tif (IS_ERR(btf))\n+\t\treturn PTR_ERR(btf);\n+\n+\tret = btf_dtor_kfuncs_add(btf, dtors, add_cnt);\n \tbtf_put(btf);\n \treturn ret;\n }\n@@ -9677,6 +10210,11 @@ static void purge_cand_cache(struct btf *btf)\n \t__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);\n \tmutex_unlock(\u0026cand_cache_mutex);\n }\n+#elif defined(BTF_MODULE_NOTIFIER)\n+/* CONFIG_DEBUG_INFO_BTF=m without module BTF: nothing is ever cached */\n+static void purge_cand_cache(struct btf *btf)\n+{\n+}\n #endif\n \n static struct bpf_cand_cache *\n@@ -9740,9 +10278,11 @@ bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)\n \tconst char *name;\n \tint id;\n \n-\tmain_btf = bpf_get_btf_vmlinux();\n-\tif (IS_ERR(main_btf))\n-\t\treturn ERR_CAST(main_btf);\n+\t/*\n+\t * Callers fetch the vmlinux BTF before taking cand_cache_mutex, so\n+\t * that loading it (CONFIG_DEBUG_INFO_BTF=m) happens outside the lock.\n+\t */\n+\tmain_btf = bpf_peek_btf_vmlinux();\n \tif (!main_btf)\n \t\treturn ERR_PTR(-EINVAL);\n \n@@ -9845,6 +10385,13 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,\n \t\tstruct bpf_cand_cache *cc;\n \t\tint i;\n \n+\t\t/* candidates are kernel types: load the vmlinux BTF, outside the mutex */\n+\t\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {\n+\t\t\tbpf_log(ctx-\u003elog, \"relo #%u: needs the vmlinux BTF\\n\", relo_idx);\n+\t\t\tkfree(specs);\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\n \t\tmutex_lock(\u0026cand_cache_mutex);\n \t\tcc = bpf_core_find_cands(ctx, relo-\u003etype_id);\n \t\tif (IS_ERR(cc)) {\n@@ -10112,11 +10659,35 @@ bpf_struct_ops_find(struct btf *btf, u32 type_id)\n \treturn NULL;\n }\n \n-int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n+static int btf_struct_ops_register(struct btf *btf, struct bpf_struct_ops *st_ops)\n {\n \tstruct bpf_verifier_log *log;\n+\tint err;\n+\n+\tlog = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);\n+\tif (!log)\n+\t\treturn -ENOMEM;\n+\n+\tlog-\u003elevel = BPF_LOG_KERNEL;\n+\n+\terr = btf_add_struct_ops(btf, st_ops, log);\n+\n+\tkfree(log);\n+\treturn err;\n+}\n+\n+int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n+{\n+\tstruct btf_deferred_reg tmpl = {\n+\t\t.kind = BTF_DEFERRED_STRUCT_OPS,\n+\t\t.st_ops = st_ops,\n+\t};\n \tstruct btf *btf;\n-\tint err = 0;\n+\tint err;\n+\n+\terr = btf_defer_reg(st_ops-\u003eowner, \u0026tmpl);\n+\tif (err)\n+\t\treturn err \u003e 0 ? 0 : err;\n \n \tbtf = btf_get_module_btf(st_ops-\u003eowner);\n \tif (!btf)\n@@ -10124,24 +10695,183 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n \tif (IS_ERR(btf))\n \t\treturn PTR_ERR(btf);\n \n-\tlog = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);\n-\tif (!log) {\n-\t\terr = -ENOMEM;\n-\t\tgoto errout;\n+\terr = btf_struct_ops_register(btf, st_ops);\n+\tbtf_put(btf);\n+\treturn err;\n+}\n+EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);\n+#elif defined(BTF_MODULE_NOTIFIER)\n+static int btf_struct_ops_register(struct btf *btf, struct bpf_struct_ops *st_ops)\n+{\n+\treturn -EOPNOTSUPP;\n+}\n+#endif\n+\n+/*\n+ * CONFIG_DEBUG_INFO_BTF=m: registrations made before the BTF they apply to\n+ * is available. Registrations for vmlinux wait in btf_vmlinux_deferred_regs\n+ * until btf_parse_vmlinux() applies them; registrations for a module wait in\n+ * its struct btf_module, under btf_module_mutex, until\n+ * btf_parse_deferred_modules() does.\n+ */\n+#ifdef BTF_MODULE_NOTIFIER\n+/*\n+ * The vmlinux queue has its own lock: it is drained under btf_vmlinux_lock,\n+ * and btf_module_mutex must not nest inside that (purge_cand_cache() takes\n+ * cand_cache_mutex under btf_module_mutex, and CO-RE fetches the vmlinux\n+ * BTF under cand_cache_mutex).\n+ */\n+static DEFINE_MUTEX(btf_vmlinux_regs_mutex);\n+static LIST_HEAD(btf_vmlinux_deferred_regs);\n+/* Set when the vmlinux BTF is parsed; new registrations apply directly */\n+static bool btf_vmlinux_regs_closed;\n+\n+/*\n+ * Queue @tmpl if the BTF for @owner is not available yet. Returns 1 if the\n+ * registration was queued and is to be considered done, 0 if the caller has\n+ * to apply it, or -ENOMEM.\n+ */\n+static int btf_defer_reg(struct module *owner, const struct btf_deferred_reg *tmpl)\n+{\n+\tstruct list_head *head = NULL;\n+\tstruct btf_deferred_reg *reg;\n+\tstruct btf_module *btf_mod;\n+\n+\tif (!IS_MODULE(CONFIG_DEBUG_INFO_BTF))\n+\t\treturn 0;\n+\n+\tguard(mutex)(owner ? \u0026btf_module_mutex : \u0026btf_vmlinux_regs_mutex);\n+\tif (!owner) {\n+\t\tif (!btf_vmlinux_regs_closed)\n+\t\t\thead = \u0026btf_vmlinux_deferred_regs;\n+\t} else {\n+\t\tlist_for_each_entry(btf_mod, \u0026btf_modules, list) {\n+\t\t\tif (btf_mod-\u003emodule != owner)\n+\t\t\t\tcontinue;\n+\t\t\t/* a dead entry has no BTF to register with, as with =y */\n+\t\t\tif (!btf_mod-\u003ebtf \u0026\u0026 !btf_mod-\u003egone)\n+\t\t\t\thead = \u0026btf_mod-\u003edeferred_regs;\n+\t\t\tbreak;\n+\t\t}\n \t}\n+\tif (!head)\n+\t\treturn 0;\n \n-\tlog-\u003elevel = BPF_LOG_KERNEL;\n+\treg = kmemdup(tmpl, sizeof(*reg), GFP_KERNEL);\n+\tif (!reg)\n+\t\treturn -ENOMEM;\n+\t/*\n+\t * kfunc id sets and struct_ops are static data of their owner, but\n+\t * the dtor arrays are commonly built on the stack of the initcall.\n+\t */\n+\tif (reg-\u003ekind == BTF_DEFERRED_DTOR_KFUNCS) {\n+\t\treg-\u003edtor.dtors = kmemdup_array(tmpl-\u003edtor.dtors, tmpl-\u003edtor.cnt,\n+\t\t\t\t\t\tsizeof(*tmpl-\u003edtor.dtors), GFP_KERNEL);\n+\t\tif (!reg-\u003edtor.dtors) {\n+\t\t\tkfree(reg);\n+\t\t\treturn -ENOMEM;\n+\t\t}\n+\t}\n+\tlist_add_tail(\u0026reg-\u003elist, head);\n+\treturn 1;\n+}\n \n-\terr = btf_add_struct_ops(btf, st_ops, log);\n+static void btf_free_deferred_reg(struct btf_deferred_reg *reg)\n+{\n+\tif (reg-\u003ekind == BTF_DEFERRED_DTOR_KFUNCS)\n+\t\tkfree(reg-\u003edtor.dtors);\n+\tkfree(reg);\n+}\n \n-errout:\n-\tkfree(log);\n-\tbtf_put(btf);\n+static const char *btf_deferred_reg_name(const struct btf_deferred_reg *reg)\n+{\n+\tswitch (reg-\u003ekind) {\n+\tcase BTF_DEFERRED_KFUNC_SET:\treturn \"kfunc set\";\n+\tcase BTF_DEFERRED_DTOR_KFUNCS:\treturn \"dtor kfuncs\";\n+\tcase BTF_DEFERRED_STRUCT_OPS:\treturn \"struct_ops\";\n+\t}\n+\treturn \"?\";\n+}\n \n-\treturn err;\n+static int btf_apply_deferred_reg(struct btf *btf, const struct btf_deferred_reg *reg)\n+{\n+\tswitch (reg-\u003ekind) {\n+\tcase BTF_DEFERRED_KFUNC_SET:\n+\t\treturn btf_kfunc_id_set_add(btf, reg-\u003ekfunc.hook, reg-\u003ekfunc.kset);\n+\tcase BTF_DEFERRED_DTOR_KFUNCS:\n+\t\treturn btf_dtor_kfuncs_add(btf, reg-\u003edtor.dtors, reg-\u003edtor.cnt);\n+\tcase BTF_DEFERRED_STRUCT_OPS:\n+\t\treturn btf_struct_ops_register(btf, reg-\u003est_ops);\n+\t}\n+\treturn -EINVAL;\n }\n-EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);\n-#endif\n+\n+/*\n+ * Apply and free the registrations in @regs to @btf. For a module BTF the\n+ * caller holds a reference on @btf and makes sure the owning module stays.\n+ */\n+static void btf_apply_deferred_regs(struct btf *btf, struct list_head *regs)\n+{\n+\tstruct btf_deferred_reg *reg, *tmp;\n+\tint err;\n+\n+\tlist_for_each_entry_safe(reg, tmp, regs, list) {\n+\t\terr = btf_apply_deferred_reg(btf, reg);\n+\t\tif (err)\n+\t\t\tpr_warn(\"failed to register deferred %s for [%s] BTF: %d\\n\",\n+\t\t\t\tbtf_deferred_reg_name(reg), btf-\u003ename, err);\n+\t\tlist_del(\u0026reg-\u003elist);\n+\t\tbtf_free_deferred_reg(reg);\n+\t}\n+}\n+\n+static void btf_free_deferred_regs(struct list_head *regs)\n+{\n+\tstruct btf_deferred_reg *reg, *tmp;\n+\n+\tlist_for_each_entry_safe(reg, tmp, regs, list) {\n+\t\tlist_del(\u0026reg-\u003elist);\n+\t\tbtf_free_deferred_reg(reg);\n+\t}\n+}\n+\n+/*\n+ * The vmlinux BTF has just been parsed; apply the registrations that waited\n+ * for it. Runs under btf_vmlinux_lock, before @btf is published, so nothing\n+ * can observe a vmlinux BTF without its kfuncs and struct_ops.\n+ *\n+ * Applying a registration can queue further ones: a struct_ops -\u003einit()\n+ * registers the kfuncs of its hook. Those must not go through\n+ * bpf_get_btf_vmlinux() (we hold its lock), so the queue stays open until\n+ * a pass applies nothing new, and only then are registrations applied directly.\n+ */\n+static void btf_apply_deferred_vmlinux_regs(struct btf *btf)\n+{\n+\tLIST_HEAD(regs);\n+\n+\tif (!IS_MODULE(CONFIG_DEBUG_INFO_BTF))\n+\t\treturn;\n+\n+\tmutex_lock(\u0026btf_vmlinux_regs_mutex);\n+\twhile (!list_empty(\u0026btf_vmlinux_deferred_regs)) {\n+\t\tlist_splice_init(\u0026btf_vmlinux_deferred_regs, \u0026regs);\n+\t\tmutex_unlock(\u0026btf_vmlinux_regs_mutex);\n+\t\tbtf_apply_deferred_regs(btf, \u0026regs);\n+\t\tmutex_lock(\u0026btf_vmlinux_regs_mutex);\n+\t}\n+\tbtf_vmlinux_regs_closed = true;\n+\tmutex_unlock(\u0026btf_vmlinux_regs_mutex);\n+}\n+#else\n+static int btf_defer_reg(struct module *owner, const struct btf_deferred_reg *tmpl)\n+{\n+\treturn 0;\n+}\n+\n+static void btf_apply_deferred_vmlinux_regs(struct btf *btf)\n+{\n+}\n+#endif /* BTF_MODULE_NOTIFIER */\n \n bool btf_param_match_suffix(const struct btf *btf,\n \t\t\t const struct btf_param *arg,\ndiff --git a/kernel/bpf/btf_vmlinux.c b/kernel/bpf/btf_vmlinux.c\nnew file mode 100644\nindex 0000000000000..8d89b4bb3c432\n--- /dev/null\n+++ b/kernel/bpf/btf_vmlinux.c\n@@ -0,0 +1,23 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Carrier module for the vmlinux BTF when CONFIG_DEBUG_INFO_BTF=m.\n+ *\n+ * This module has no code of its own. Its .BTF section is a copy of the\n+ * vmlinux BTF (see scripts/gen-btf.sh), which the BTF module notifier in\n+ * kernel/bpf/btf.c recognizes by module name and installs as the vmlinux BTF.\n+ * The kernel loads it on demand, the first time the vmlinux BTF is needed.\n+ *\n+ * There is deliberately no module_exit(): once the BTF is in use it cannot\n+ * be taken away again, exactly as with CONFIG_DEBUG_INFO_BTF=y.\n+ */\n+#include \u003clinux/init.h\u003e\n+#include \u003clinux/module.h\u003e\n+\n+static int __init btf_vmlinux_init(void)\n+{\n+\treturn 0;\n+}\n+module_init(btf_vmlinux_init);\n+\n+MODULE_DESCRIPTION(\"BTF type information for vmlinux\");\n+MODULE_LICENSE(\"GPL\");\ndiff --git a/kernel/bpf/preload/Kconfig b/kernel/bpf/preload/Kconfig\nindex aef7b0bc96d61..b1600bdce7a06 100644\n--- a/kernel/bpf/preload/Kconfig\n+++ b/kernel/bpf/preload/Kconfig\n@@ -6,6 +6,10 @@ menuconfig BPF_PRELOAD\n \t# The dependency on !COMPILE_TEST prevents it from being enabled\n \t# in allmodconfig or allyesconfig configurations\n \tdepends on !COMPILE_TEST\n+\t# The preloaded iterators attach through the vmlinux BTF, so with\n+\t# CONFIG_DEBUG_INFO_BTF=m every bpffs mount would load the BTF, which\n+\t# defeats the point of =m on any system that mounts bpffs at boot.\n+\tdepends on DEBUG_INFO_BTF!=m\n \thelp\n \t This builds kernel module with several embedded BPF programs that are\n \t pinned into BPF FS mount point as human readable files that are\ndiff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c\nindex 74496fd716d3b..9e9eaa7988138 100644\n--- a/kernel/bpf/syscall.c\n+++ b/kernel/bpf/syscall.c\n@@ -6406,6 +6406,12 @@ static int __sys_bpf(enum bpf_cmd cmd, bpfptr_t uattr, unsigned int size,\n \t\t\t\t\t \u0026map_idr, \u0026map_idr_lock);\n \t\tbreak;\n \tcase BPF_BTF_GET_NEXT_ID:\n+\t\t/*\n+\t\t * With CONFIG_DEBUG_INFO_BTF=m the kernel BTFs get ids when the\n+\t\t * vmlinux BTF is loaded; whoever enumerates them wants them.\n+\t\t */\n+\t\tif (IS_MODULE(CONFIG_DEBUG_INFO_BTF))\n+\t\t\tbpf_get_btf_vmlinux();\n \t\terr = bpf_obj_get_next_id(\u0026attr, uattr.user,\n \t\t\t\t\t \u0026btf_idr, \u0026btf_idr_lock);\n \t\tbreak;\ndiff --git a/kernel/bpf/sysfs_btf.c b/kernel/bpf/sysfs_btf.c\nindex 9cbe15ce3540c..b2408878412a8 100644\n--- a/kernel/bpf/sysfs_btf.c\n+++ b/kernel/bpf/sysfs_btf.c\n@@ -9,8 +9,13 @@\n #include \u003clinux/sysfs.h\u003e\n #include \u003clinux/mm.h\u003e\n #include \u003clinux/io.h\u003e\n+#include \u003clinux/bpf.h\u003e\n #include \u003clinux/btf.h\u003e\n+#include \u003clinux/vmalloc.h\u003e\n \n+struct kobject *btf_kobj;\n+\n+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)\n /* See scripts/link-vmlinux.sh, gen_btf() func for details */\n extern char __start_BTF[];\n extern char __stop_BTF[];\n@@ -49,12 +54,86 @@ static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {\n \t.mmap = btf_sysfs_vmlinux_mmap,\n };\n \n-struct kobject *btf_kobj;\n-\n-static int __init btf_vmlinux_init(void)\n+static void __init btf_sysfs_vmlinux_init(void)\n {\n \tbin_attr_btf_vmlinux.private = __start_BTF;\n \tbin_attr_btf_vmlinux.size = __stop_BTF - __start_BTF;\n+}\n+\n+#else /* CONFIG_DEBUG_INFO_BTF=m */\n+\n+/*\n+ * The BTF is carried by the btf_vmlinux module and only loaded when\n+ * something needs it. Its size is known from the start, so the file has\n+ * its final size from boot; the first read() or mmap() loads the BTF.\n+ */\n+static void *btf_sysfs_vmlinux_load(u32 *size)\n+{\n+\t/* Loads the module, parses the BTF and registers module BTFs. */\n+\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))\n+\t\treturn NULL;\n+\treturn btf_vmlinux_data(size, false);\n+}\n+\n+static ssize_t btf_sysfs_vmlinux_read(struct file *filp, struct kobject *kobj,\n+\t\t\t\t const struct bin_attribute *attr,\n+\t\t\t\t char *buf, loff_t off, size_t count)\n+{\n+\tu32 size;\n+\tvoid *data = btf_sysfs_vmlinux_load(\u0026size);\n+\n+\tif (!data)\n+\t\treturn -ENODEV;\n+\n+\t/* sysfs clamps @off and @count to attr-\u003esize, which is @size */\n+\tmemcpy(buf, data + off, count);\n+\treturn count;\n+}\n+\n+static int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,\n+\t\t\t\t const struct bin_attribute *attr,\n+\t\t\t\t struct vm_area_struct *vma)\n+{\n+\tsize_t vm_size = vma-\u003evm_end - vma-\u003evm_start;\n+\tu32 size;\n+\tvoid *data = btf_sysfs_vmlinux_load(\u0026size);\n+\n+\tif (!data)\n+\t\treturn -ENODEV;\n+\n+\tif (vma-\u003evm_pgoff)\n+\t\treturn -EINVAL;\n+\n+\tif (vma-\u003evm_flags \u0026 (VM_WRITE | VM_EXEC | VM_MAYSHARE))\n+\t\treturn -EACCES;\n+\n+\tif (vm_size \u003e PAGE_ALIGN(size))\n+\t\treturn -EINVAL;\n+\n+\tvm_flags_mod(vma, VM_DONTDUMP, VM_MAYEXEC | VM_MAYWRITE);\n+\t/* the copy was made with vmalloc_user() for this purpose */\n+\treturn remap_vmalloc_range(vma, data, 0);\n+}\n+\n+static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {\n+\t.attr = { .name = \"vmlinux\", .mode = 0444, },\n+\t.read = btf_sysfs_vmlinux_read,\n+\t.mmap = btf_sysfs_vmlinux_mmap,\n+};\n+\n+static void __init btf_sysfs_vmlinux_init(void)\n+{\n+\tu32 size;\n+\n+\t/* known before the BTF is loaded, see .BTF.meta */\n+\tbtf_vmlinux_data(\u0026size, false);\n+\tbin_attr_btf_vmlinux.size = size;\n+}\n+#endif\n+\n+static int __init btf_vmlinux_init(void)\n+{\n+\tbtf_sysfs_vmlinux_init();\n \n \tif (bin_attr_btf_vmlinux.size == 0)\n \t\treturn 0;\ndiff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c\nindex a7c9e2d8965d5..72edabbc2db51 100644\n--- a/kernel/bpf/verifier.c\n+++ b/kernel/bpf/verifier.c\n@@ -2873,7 +2873,8 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n \ttab = prog_aux-\u003ekfunc_tab;\n \tbtf_tab = prog_aux-\u003ekfunc_btf_tab;\n \tif (!tab) {\n-\t\tif (!btf_vmlinux) {\n+\t\t/* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */\n+\t\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {\n \t\t\tverbose(env, \"calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\\n\");\n \t\t\treturn -ENOTSUPP;\n \t\t}\n@@ -6257,7 +6258,8 @@ static int check_ptr_to_map_access(struct bpf_verifier_env *env,\n \tu32 btf_id;\n \tint ret;\n \n-\tif (!btf_vmlinux) {\n+\t/* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */\n+\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {\n \t\tverbose(env, \"map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\\n\");\n \t\treturn -ENOTSUPP;\n \t}\n@@ -11568,6 +11570,24 @@ static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n \treturn err;\n }\n \n+/* Does calling helper @func_id bring kernel BTF types into the program? */\n+static bool helper_uses_vmlinux_btf(enum bpf_func_id func_id,\n+\t\t\t\t const struct bpf_func_proto *fn)\n+{\n+\tint i;\n+\n+\t/* these take the kernel type id in a struct btf_ptr, not in a register */\n+\tif (func_id == BPF_FUNC_snprintf_btf || func_id == BPF_FUNC_seq_printf_btf)\n+\t\treturn true;\n+\tif (base_type(fn-\u003eret_type) == RET_PTR_TO_BTF_ID)\n+\t\treturn true;\n+\tfor (i = 0; i \u003c MAX_BPF_FUNC_ARGS; i++) {\n+\t\tif (base_type(fn-\u003earg_type[i]) == ARG_PTR_TO_BTF_ID)\n+\t\t\treturn true;\n+\t}\n+\treturn false;\n+}\n+\n static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n \t\t\t int *insn_idx_p)\n {\n@@ -11637,6 +11657,18 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn\n \t\treturn err;\n \t}\n \n+\t/*\n+\t * Helpers that take or return kernel BTF pointers need the vmlinux\n+\t * BTF; with CONFIG_DEBUG_INFO_BTF=m this is where it gets loaded.\n+\t * Without CONFIG_DEBUG_INFO_BTF they keep failing as they always did.\n+\t */\n+\tif (IS_ENABLED(CONFIG_DEBUG_INFO_BTF) \u0026\u0026 helper_uses_vmlinux_btf(func_id, fn) \u0026\u0026\n+\t IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {\n+\t\tverbose(env, \"helper %s#%d is not supported without vmlinux BTF\\n\",\n+\t\t\tfunc_id_name(func_id), func_id);\n+\t\treturn -ENOTSUPP;\n+\t}\n+\n \tif (fn-\u003emight_sleep \u0026\u0026 !in_sleepable_context(env)) {\n \t\tverbose(env, \"sleepable helper %s#%d in %s\\n\", func_id_name(func_id), func_id,\n \t\t\tnon_sleepable_context_description(env));\n@@ -19235,12 +19267,13 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env,\n \t\t\treturn -EINVAL;\n \t\t}\n \t} else {\n-\t\tif (!btf_vmlinux) {\n+\t\t/* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */\n+\t\tbtf = bpf_get_btf_vmlinux();\n+\t\tif (IS_ERR_OR_NULL(btf)) {\n \t\t\tverbose(env, \"kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\\n\");\n \t\t\treturn -EINVAL;\n \t\t}\n-\t\tbtf_get(btf_vmlinux);\n-\t\tbtf = btf_vmlinux;\n+\t\tbtf_get(btf);\n \t}\n \n \terr = __check_pseudo_btf_id(env, insn, aux, btf);\n@@ -21130,29 +21163,72 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt\n \treturn 0;\n }\n \n+/*\n+ * Returns the parsed vmlinux BTF, NULL if the kernel has none, or an ERR_PTR\n+ * if it is malformed. With CONFIG_DEBUG_INFO_BTF=m the BTF lives in the\n+ * btf_vmlinux module; the first caller loads it, parses it and then registers\n+ * the BTF of the modules that were loaded before it. May sleep.\n+ */\n struct btf *bpf_get_btf_vmlinux(void)\n {\n \t/* Pairs with the smp_store_release() on the parse path below. */\n \tstruct btf *btf = smp_load_acquire(\u0026btf_vmlinux);\n+\tbool parsed = false;\n+\tu32 size;\n \n-\tif (!btf \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {\n-\t\tmutex_lock(\u0026btf_vmlinux_lock);\n-\t\tbtf = btf_vmlinux;\n-\t\tif (!btf) {\n-\t\t\tbtf = btf_parse_vmlinux();\n-\t\t\t/*\n-\t\t\t * Order the parsed BTF contents and the globals the\n-\t\t\t * parse populated (e.g. bpf_ctx_convert.t) before\n-\t\t\t * the pointer publication. Pairs with the acquire\n-\t\t\t * on the lockless fast path above.\n-\t\t\t */\n-\t\t\tsmp_store_release(\u0026btf_vmlinux, btf);\n+\tif (btf || !IS_ENABLED(CONFIG_DEBUG_INFO_BTF))\n+\t\treturn btf;\n+\n+\t/*\n+\t * Loading the module may take a while and its notifier must not be\n+\t * blocked by us, so do it outside btf_vmlinux_lock. Not available:\n+\t * behave like a kernel without BTF, and retry next time.\n+\t */\n+\tif (!btf_vmlinux_data(\u0026size, true))\n+\t\treturn NULL;\n+\n+\tmutex_lock(\u0026btf_vmlinux_lock);\n+\tbtf = btf_vmlinux;\n+\tif (!btf) {\n+\t\tbtf = btf_parse_vmlinux();\n+\t\t/*\n+\t\t * With =m the BTF was checked against the kernel when the\n+\t\t * module loaded, so a failure here is a resource problem\n+\t\t * (-ENOMEM) rather than a broken BTF: do not remember it,\n+\t\t * the next caller retries.\n+\t\t */\n+\t\tif (IS_MODULE(CONFIG_DEBUG_INFO_BTF) \u0026\u0026 IS_ERR(btf)) {\n+\t\t\tmutex_unlock(\u0026btf_vmlinux_lock);\n+\t\t\treturn btf;\n \t\t}\n-\t\tmutex_unlock(\u0026btf_vmlinux_lock);\n+\t\t/*\n+\t\t * Order the parsed BTF contents and the globals the\n+\t\t * parse populated (e.g. bpf_ctx_convert.t) before\n+\t\t * the pointer publication. Pairs with the acquire\n+\t\t * on the lockless fast path above.\n+\t\t */\n+\t\tsmp_store_release(\u0026btf_vmlinux, btf);\n+\t\tparsed = true;\n \t}\n+\tmutex_unlock(\u0026btf_vmlinux_lock);\n+\n+\tif (parsed \u0026\u0026 IS_MODULE(CONFIG_DEBUG_INFO_BTF))\n+\t\tbtf_parse_deferred_modules();\n+\n \treturn btf;\n }\n \n+/*\n+ * The vmlinux BTF if it has been parsed already, else NULL. Unlike\n+ * bpf_get_btf_vmlinux() this never loads or parses anything, so it is safe\n+ * to call from a running BPF program.\n+ */\n+struct btf *bpf_peek_btf_vmlinux(void)\n+{\n+\t/* Pairs with the smp_store_release() in bpf_get_btf_vmlinux() */\n+\treturn smp_load_acquire(\u0026btf_vmlinux);\n+}\n+\n /*\n * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In\n * this case expect that every file descriptor in the array is either a map or\n@@ -21724,7 +21800,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tif (ret)\n \t\tgoto err_prep;\n \n-\tbpf_get_btf_vmlinux();\n+\t/*\n+\t * The vmlinux BTF is not fetched up front: with CONFIG_DEBUG_INFO_BTF=m\n+\t * it is loaded on demand, at the points where kernel types enter the\n+\t * program (attach_btf, kfuncs, ksyms, map pointers, BTF-typed helpers).\n+\t */\n \n \t/* Serialize verification of unprivileged programs. */\n \tif (!is_priv)\n@@ -21745,10 +21825,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \n \tmark_verifier_state_clean(env);\n \n-\tif (IS_ERR(btf_vmlinux)) {\n+\tif (IS_ERR(bpf_peek_btf_vmlinux())) {\n \t\t/* Either gcc or pahole or kernel are broken. */\n \t\tverbose(env, \"in-kernel BTF is malformed\\n\");\n-\t\tret = PTR_ERR(btf_vmlinux);\n+\t\tret = PTR_ERR(bpf_peek_btf_vmlinux());\n \t\tgoto skip_full_check;\n \t}\n \ndiff --git a/kernel/module/main.c b/kernel/module/main.c\nindex d0e1e0bd2ad06..694c4bc7e6793 100644\n--- a/kernel/module/main.c\n+++ b/kernel/module/main.c\n@@ -2718,7 +2718,7 @@ static int find_module_sections(struct module *mod, struct load_info *info)\n \t\t\t\t\t sizeof(*mod-\u003ebpf_raw_events),\n \t\t\t\t\t \u0026mod-\u003enum_bpf_raw_events);\n #endif\n-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n \tmod-\u003ebtf_data = any_section_objs(info, \".BTF\", 1, \u0026mod-\u003ebtf_data_size);\n \tmod-\u003ebtf_base_data = any_section_objs(info, \".BTF.base\", 1,\n \t\t\t\t\t \u0026mod-\u003ebtf_base_data_size);\n@@ -3172,7 +3172,7 @@ static noinline int do_init_module(struct module *mod)\n \t\tmod-\u003emem[type].size = 0;\n \t}\n \n-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)\n \t/* .BTF is not SHF_ALLOC and will get removed, so sanitize pointers */\n \tmod-\u003ebtf_data = NULL;\n \tmod-\u003ebtf_base_data = NULL;\ndiff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c\nindex 195f78db9bdaf..c022b2877f0ba 100644\n--- a/kernel/trace/bpf_trace.c\n+++ b/kernel/trace/bpf_trace.c\n@@ -1015,7 +1015,8 @@ static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,\n \tif (btf_ptr_size != sizeof(struct btf_ptr))\n \t\treturn -EINVAL;\n \n-\t*btf = bpf_get_btf_vmlinux();\n+\t/* Called from a running program: only use the BTF if it is parsed. */\n+\t*btf = bpf_peek_btf_vmlinux();\n \n \tif (IS_ERR_OR_NULL(*btf))\n \t\treturn IS_ERR(*btf) ? PTR_ERR(*btf) : -EINVAL;\ndiff --git a/kernel/trace/trace_syscalls.c b/kernel/trace/trace_syscalls.c\nindex e35744049e3f2..7a0d59c308c29 100644\n--- a/kernel/trace/trace_syscalls.c\n+++ b/kernel/trace/trace_syscalls.c\n@@ -1304,7 +1304,7 @@ struct trace_event_functions exit_syscall_print_funcs = {\n \t.trace\t\t= print_syscall_exit,\n };\n \n-#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 defined(CONFIG_DEBUG_INFO_BTF)\n+#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF)\n /* BTF id lists for the shared sys_enter/sys_exit dispatcher tracepoints. */\n BTF_ID_LIST(syscall_enter_btf_ids)\n BTF_ID(func, __bpf_trace_sys_enter)\n@@ -1321,7 +1321,7 @@ struct trace_event_class __refdata event_class_syscall_enter = {\n \t.fields_array\t= syscall_enter_fields_array,\n \t.get_fields\t= syscall_get_enter_fields,\n \t.raw_init\t= init_syscall_trace,\n-#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 defined(CONFIG_DEBUG_INFO_BTF)\n+#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF)\n \t.btf_ids\t= syscall_enter_btf_ids,\n #endif\n };\n@@ -1336,7 +1336,7 @@ struct trace_event_class __refdata event_class_syscall_exit = {\n \t},\n \t.fields\t\t= LIST_HEAD_INIT(event_class_syscall_exit.fields),\n \t.raw_init\t= init_syscall_trace,\n-#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 defined(CONFIG_DEBUG_INFO_BTF)\n+#if defined(CONFIG_BPF_EVENTS) \u0026\u0026 IS_ENABLED(CONFIG_DEBUG_INFO_BTF)\n \t.btf_ids\t= syscall_exit_btf_ids,\n #endif\n };\ndiff --git a/lib/Kconfig.debug b/lib/Kconfig.debug\nindex 134b15a44625e..418025c5e6577 100644\n--- a/lib/Kconfig.debug\n+++ b/lib/Kconfig.debug\n@@ -396,7 +396,7 @@ config DEBUG_INFO_SPLIT\n \t Incompatible with older versions of ccache.\n \n config DEBUG_INFO_BTF\n-\tbool \"Generate BTF type information\"\n+\ttristate \"Generate BTF type information\"\n \tdepends on !DEBUG_INFO_SPLIT \u0026\u0026 !DEBUG_INFO_REDUCED\n \tdepends on !GCC_PLUGIN_RANDSTRUCT || COMPILE_TEST\n \tdepends on BPF_SYSCALL\n@@ -408,6 +408,26 @@ config DEBUG_INFO_BTF\n \t Turning this on requires pahole v1.22 or later, which will convert\n \t DWARF type info into equivalent deduplicated BTF type info.\n \n+\t If built as a module (=m), the vmlinux BTF is not part of the\n+\t kernel image. It is carried by the btf_vmlinux module, which is\n+\t loaded on demand the first time the BTF is needed: when a BPF\n+\t program requires kernel type information, or when\n+\t /sys/kernel/btf/vmlinux is opened. Until then, no memory is\n+\t spent on it. The vmlinux ELF file does not carry the BTF\n+\t either; module BTF is generated against vmlinux.unstripped, and\n+\t tools that read the BTF from a file can use that or\n+\t /sys/kernel/btf/vmlinux.\n+\n+\t Module BTF (DEBUG_INFO_BTF_MODULES) is kept when a module loads,\n+\t as with =y, and registered once the vmlinux BTF is available; the\n+\t saving is the vmlinux BTF only.\n+\n+\t If BPF programs that use kernel types run before the root file\n+\t system is mounted, put btf_vmlinux.ko into the initramfs: until\n+\t the module can be loaded, such programs fail as on a kernel\n+\t without BTF. Not compatible with BPF_PRELOAD, whose iterators\n+\t would load the BTF at every bpffs mount.\n+\n config PAHOLE_HAS_BTF_TAG\n \tdef_bool PAHOLE_VERSION \u003e= 123\n \tdepends on CC_IS_CLANG\ndiff --git a/net/netfilter/Makefile b/net/netfilter/Makefile\nindex 6bf74d488a292..a2c7f00794d22 100644\n--- a/net/netfilter/Makefile\n+++ b/net/netfilter/Makefile\n@@ -18,7 +18,7 @@ nf_conntrack-$(CONFIG_NF_CT_PROTO_GRE) += nf_conntrack_proto_gre.o\n ifeq ($(CONFIG_NF_CONNTRACK),m)\n nf_conntrack-$(CONFIG_DEBUG_INFO_BTF_MODULES) += nf_conntrack_bpf.o\n else ifeq ($(CONFIG_NF_CONNTRACK),y)\n-nf_conntrack-$(CONFIG_DEBUG_INFO_BTF) += nf_conntrack_bpf.o\n+nf_conntrack-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += nf_conntrack_bpf.o\n endif\n \n obj-$(CONFIG_NETFILTER) = netfilter.o\n@@ -65,7 +65,7 @@ nf_nat-$(CONFIG_NF_NAT_OVS) += nf_nat_ovs.o\n ifeq ($(CONFIG_NF_NAT),m)\n nf_nat-$(CONFIG_DEBUG_INFO_BTF_MODULES) += nf_nat_bpf.o\n else ifeq ($(CONFIG_NF_NAT),y)\n-nf_nat-$(CONFIG_DEBUG_INFO_BTF) += nf_nat_bpf.o\n+nf_nat-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += nf_nat_bpf.o\n endif\n \n # NAT helpers\n@@ -147,7 +147,7 @@ nf_flow_table-$(CONFIG_NF_FLOW_TABLE_PROCFS) += nf_flow_table_procfs.o\n ifeq ($(CONFIG_NF_FLOW_TABLE),m)\n nf_flow_table-$(CONFIG_DEBUG_INFO_BTF_MODULES) += nf_flow_table_bpf.o\n else ifeq ($(CONFIG_NF_FLOW_TABLE),y)\n-nf_flow_table-$(CONFIG_DEBUG_INFO_BTF) += nf_flow_table_bpf.o\n+nf_flow_table-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += nf_flow_table_bpf.o\n endif\n \n obj-$(CONFIG_NF_FLOW_TABLE_INET) += nf_flow_table_inet.o\ndiff --git a/net/xfrm/Makefile b/net/xfrm/Makefile\nindex 5a1787587cb35..b7f6e5046a0e9 100644\n--- a/net/xfrm/Makefile\n+++ b/net/xfrm/Makefile\n@@ -8,7 +8,7 @@ xfrm_interface-$(CONFIG_XFRM_INTERFACE) += xfrm_interface_core.o\n ifeq ($(CONFIG_XFRM_INTERFACE),m)\n xfrm_interface-$(CONFIG_DEBUG_INFO_BTF_MODULES) += xfrm_interface_bpf.o\n else ifeq ($(CONFIG_XFRM_INTERFACE),y)\n-xfrm_interface-$(CONFIG_DEBUG_INFO_BTF) += xfrm_interface_bpf.o\n+xfrm_interface-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += xfrm_interface_bpf.o\n endif\n \n obj-$(CONFIG_XFRM) := xfrm_policy.o xfrm_state.o xfrm_hash.o \\\n@@ -23,4 +23,4 @@ obj-$(CONFIG_XFRM_IPCOMP) += xfrm_ipcomp.o\n obj-$(CONFIG_XFRM_INTERFACE) += xfrm_interface.o\n obj-$(CONFIG_XFRM_IPTFS) += xfrm_iptfs.o\n obj-$(CONFIG_XFRM_ESPINTCP) += espintcp.o\n-obj-$(CONFIG_DEBUG_INFO_BTF) += xfrm_state_bpf.o\n+obj-$(subst m,y,$(CONFIG_DEBUG_INFO_BTF)) += xfrm_state_bpf.o\ndiff --git a/scripts/Makefile.modfinal b/scripts/Makefile.modfinal\nindex 01a37ec872b90..6a0958cf0e6f4 100644\n--- a/scripts/Makefile.modfinal\n+++ b/scripts/Makefile.modfinal\n@@ -38,20 +38,34 @@ quiet_cmd_ld_ko_o = LD [M] $@\n \t\t$(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE)\t\t\\\n \t\t-T $(objtree)/scripts/module.lds -o $@ $(filter %.o, $^)\n \n+# The ELF file with the vmlinux BTF: with CONFIG_DEBUG_INFO_BTF=m the BTF is\n+# stripped from vmlinux (scripts/Makefile.vmlinux), vmlinux.unstripped keeps it.\n+btf-vmlinux := $(objtree)/vmlinux$(if $(filter m,$(CONFIG_DEBUG_INFO_BTF)),.unstripped)\n+\n quiet_cmd_btf_ko = BTF [M] $@\n cmd_btf_ko = \t\t\t\t\t\t\t\\\n-\tif [ ! -f $(objtree)/vmlinux ]; then\t\t\t\t\\\n+\tif [ ! -f $(btf-vmlinux) ]; then\t\t\t\t\\\n \t\tprintf \"Skipping BTF generation for %s due to unavailability of vmlinux\\n\" $@ 1\u003e\u00262; \\\n \telse\t\\\n-\t\t$(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \\\n+\t\t$(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(btf-vmlinux) $@; \\\n \tfi;\n \n-# Re-generate module BTFs if either module's .ko or vmlinux changed\n-%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(objtree)/vmlinux) FORCE\n-\t+$(call if_changed,ld_ko_o)\n+# Modules that get a .BTF section: all of them with CONFIG_DEBUG_INFO_BTF_MODULES,\n+# otherwise only the vmlinux BTF carrier module with CONFIG_DEBUG_INFO_BTF=m.\n ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n-\t+$(if $(newer-prereqs),$(call cmd,btf_ko))\n+btf-modules := $(modules:%.o=%.ko)\n+else ifeq ($(CONFIG_DEBUG_INFO_BTF),m)\n+btf-modules := $(filter %/btf_vmlinux.ko,$(modules:%.o=%.ko))\n+# Only the carrier depends on vmlinux, not every module\n+ifdef KBUILD_BUILTIN\n+$(btf-modules): $(btf-vmlinux)\n+endif\n endif\n+\n+# Re-generate module BTFs if either module's .ko or vmlinux changed\n+%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(btf-vmlinux)) FORCE\n+\t+$(call if_changed,ld_ko_o)\n+\t+$(if $(and $(filter $@,$(btf-modules)),$(newer-prereqs)),$(call cmd,btf_ko))\n \t+$(call cmd,check_tracepoint)\n \n targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o\ndiff --git a/scripts/Makefile.vmlinux b/scripts/Makefile.vmlinux\nindex fcae1e432d9ad..557db1ee1f3b0 100644\n--- a/scripts/Makefile.vmlinux\n+++ b/scripts/Makefile.vmlinux\n@@ -86,6 +86,11 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel*' '!.rel*.dyn'\n # for compatibility with binutils \u003c 2.32\n # https://sourceware.org/git/?p=binutils-gdb.git;a=commit;h=c12d9fa2afe7abcbe407a00e15719e1a1350c2a7\n remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*'\n+# With CONFIG_DEBUG_INFO_BTF=m the btf_vmlinux module carries the vmlinux BTF;\n+# only vmlinux.unstripped keeps it, for module BTF generation.\n+ifeq ($(CONFIG_DEBUG_INFO_BTF),m)\n+remove-section-y += .BTF\n+endif\n \n remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*'\n \ndiff --git a/scripts/gen-btf.sh b/scripts/gen-btf.sh\nindex 8ca96eb10a69e..d808d0006d325 100755\n--- a/scripts/gen-btf.sh\n+++ b/scripts/gen-btf.sh\n@@ -22,16 +22,27 @@\n # - ${1}.btf.o ready for linking into vmlinux\n # - ${1}.BTF_ids with .BTF_ids data blob\n # This output is consumed by scripts/link-vmlinux.sh\n+#\n+# With CONFIG_DEBUG_INFO_BTF=m the .BTF section in ${1}.btf.o is not\n+# allocatable, so the kernel image does not carry the BTF; vmlinux.unstripped\n+# does, for module BTF generation, and scripts/Makefile.vmlinux strips it from\n+# vmlinux. ${1}.btf.o then also carries .BTF.meta, the size and SHA-256 of\n+# the BTF for the kernel (struct btf_vmlinux_meta); \"--placeholder ${1}\"\n+# produces a ${1}.btf.o with a zeroed .BTF.meta and no .BTF for the first\n+# vmlinux link, which the BTF is generated from. The btf_vmlinux module gets\n+# no BTF of its own; its .BTF section is a copy of the vmlinux BTF, extracted\n+# from --btf_base.\n \n set -e\n \n usage()\n {\n-\techo \"Usage: $0 [--btf_base \u003cfile\u003e] \u003ctarget ELF file\u003e\"\n+\techo \"Usage: $0 [--btf_base \u003cfile\u003e] [--placeholder] \u003ctarget ELF file\u003e\"\n \texit 1\n }\n \n BTF_BASE=\"\"\n+PLACEHOLDER=\"\"\n \n while [ $# -gt 0 ]; do\n \tcase \"$1\" in\n@@ -39,6 +50,10 @@ while [ $# -gt 0 ]; do\n \t\tBTF_BASE=\"$2\"\n \t\tshift 2\n \t\t;;\n+\t--placeholder)\n+\t\tPLACEHOLDER=1\n+\t\tshift\n+\t\t;;\n \t-*)\n \t\techo \"Unknown option: $1\" \u003e\u00262\n \t\tusage\n@@ -60,6 +75,10 @@ is_enabled() {\n \tgrep -q \"^$1=y\" ${objtree}/include/config/auto.conf\n }\n \n+is_module() {\n+\tgrep -q \"^$1=m\" ${objtree}/include/config/auto.conf\n+}\n+\n case \"${KBUILD_VERBOSE}\" in\n *1*)\n \tset -x\n@@ -79,6 +98,30 @@ gen_btf_data()\n \t\t--btf ${btf1} \"${ELF_FILE}\"\n }\n \n+# Write one byte with value $1 (0..255)\n+put_byte()\n+{\n+\tprintf \"\\\\$(printf '%03o' \"$1\")\"\n+}\n+\n+# CONFIG_DEBUG_INFO_BTF=m: write struct btf_vmlinux_meta { u32 size; u8\n+# sha256[32]; } for the BTF in $1 to $2, in the target's byte order.\n+gen_btf_meta()\n+{\n+\tsize=$(${CONFIG_SHELL} \"${srctree}/scripts/file-size.sh\" \"$1\")\n+\tsha256=$(sha256sum \u003c \"$1\" | cut -d' ' -f1)\n+\t{\n+\t\tif is_enabled CONFIG_CPU_BIG_ENDIAN; then\n+\t\t\tfor shift in 24 16 8 0; do put_byte $(( (size \u003e\u003e shift) \u0026 255 )); done\n+\t\telse\n+\t\t\tfor shift in 0 8 16 24; do put_byte $(( (size \u003e\u003e shift) \u0026 255 )); done\n+\t\tfi\n+\t\tfor byte in $(echo \"${sha256}\" | sed 's/../\u0026 /g'); do\n+\t\t\tput_byte $(( 0x${byte} ))\n+\t\tdone\n+\t} \u003e \"$2\"\n+}\n+\n gen_btf_o()\n {\n \tbtf_data=${ELF_FILE}.btf.o\n@@ -88,9 +131,23 @@ gen_btf_o()\n \t# deletes all symbols including __start_BTF and __stop_BTF, which will\n \t# be redefined in the linker script.\n \techo \"\" | ${CC} ${CLANG_FLAGS} ${KBUILD_CPPFLAGS} ${KBUILD_CFLAGS} -fno-lto -c -x c -o ${btf_data} -\n-\t${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \\\n-\t\t--set-section-flags .BTF=alloc,readonly ${btf_data}\n-\t${OBJCOPY} --only-section=.BTF --strip-all ${btf_data}\n+\tif is_module CONFIG_DEBUG_INFO_BTF; then\n+\t\t# CONFIG_DEBUG_INFO_BTF=m: .BTF stays non-allocatable, kept in\n+\t\t# vmlinux.unstripped for module BTF but not loaded; the btf_vmlinux\n+\t\t# module provides it at runtime. What is loaded is .BTF.meta,\n+\t\t# its size and hash, so that /sys/kernel/btf/vmlinux has the right\n+\t\t# size from boot and only the matching BTF is accepted.\n+\t\tgen_btf_meta ${ELF_FILE}.BTF ${ELF_FILE}.BTF.meta\n+\t\t${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \\\n+\t\t\t--set-section-flags .BTF=readonly \\\n+\t\t\t--add-section .BTF.meta=${ELF_FILE}.BTF.meta \\\n+\t\t\t--set-section-flags .BTF.meta=alloc,readonly ${btf_data}\n+\t\t${OBJCOPY} --only-section=.BTF --only-section=.BTF.meta --strip-all ${btf_data}\n+\telse\n+\t\t${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \\\n+\t\t\t--set-section-flags .BTF=alloc,readonly ${btf_data}\n+\t\t${OBJCOPY} --only-section=.BTF --strip-all ${btf_data}\n+\tfi\n \n \t# Change e_type to ET_REL so that it can be used to link final vmlinux.\n \t# GNU ld 2.35+ and lld do not allow an ET_EXEC input.\n@@ -121,6 +178,7 @@ cleanup()\n {\n \trm -f \"${ELF_FILE}.BTF.1\"\n \trm -f \"${ELF_FILE}.BTF\"\n+\trm -f \"${ELF_FILE}.BTF.meta\"\n \tif [ \"${BTFGEN_MODE}\" = \"module\" ]; then\n \t\trm -f \"${ELF_FILE}.BTF.base\"\n \t\trm -f \"${ELF_FILE}.BTF_ids\"\n@@ -133,6 +191,35 @@ if [ -n \"${BTF_BASE}\" ]; then\n \tBTFGEN_MODE=\"module\"\n fi\n \n+if [ -n \"${PLACEHOLDER}\" ]; then\n+\tbtf_data=${ELF_FILE}.btf.o\n+\techo \"\" | ${CC} ${CLANG_FLAGS} ${KBUILD_CPPFLAGS} ${KBUILD_CFLAGS} -fno-lto -c -x c -o ${btf_data} -\n+\tdd if=/dev/zero of=${ELF_FILE}.BTF.meta bs=36 count=1 2\u003e/dev/null\n+\t${OBJCOPY} --add-section .BTF.meta=${ELF_FILE}.BTF.meta \\\n+\t\t--set-section-flags .BTF.meta=alloc,readonly ${btf_data}\n+\t${OBJCOPY} --only-section=.BTF.meta --strip-all ${btf_data}\n+\texit 0\n+fi\n+\n+# CONFIG_DEBUG_INFO_BTF=m: the btf_vmlinux module carries the vmlinux BTF\n+# itself. Its own types are of no interest, so instead of generating split\n+# BTF for it, copy the (non-loadable) .BTF section of --btf_base\n+# (vmlinux.unstripped) into the module.\n+# The kernel recognizes the module by name and treats its .BTF as base BTF.\n+case \"${BTFGEN_MODE}:${ELF_FILE}\" in\n+module:*/btf_vmlinux.ko)\n+\tif is_module CONFIG_DEBUG_INFO_BTF; then\n+\t\t# -O binary only emits allocatable sections; make .BTF one for\n+\t\t# the extraction. ${BTF_BASE} itself is not modified.\n+\t\t${OBJCOPY} -O binary --only-section=.BTF\t\t\t\\\n+\t\t\t--set-section-flags .BTF=alloc,load,readonly\t\\\n+\t\t\t\"${BTF_BASE}\" \"${ELF_FILE}.BTF\"\n+\t\t${OBJCOPY} --add-section .BTF=\"${ELF_FILE}.BTF\" \"${ELF_FILE}\"\n+\t\texit 0\n+\tfi\n+\t;;\n+esac\n+\n gen_btf_data\n \n case \"${BTFGEN_MODE}\" in\ndiff --git a/scripts/link-vmlinux.sh b/scripts/link-vmlinux.sh\nindex ab0b8125c8cbc..a9a066267ef6e 100755\n--- a/scripts/link-vmlinux.sh\n+++ b/scripts/link-vmlinux.sh\n@@ -37,6 +37,15 @@ is_enabled() {\n \tgrep -q \"^$1=y\" include/config/auto.conf\n }\n \n+is_module() {\n+\tgrep -q \"^$1=m\" include/config/auto.conf\n+}\n+\n+# =y or =m\n+is_set() {\n+\tgrep -q \"^$1=[ym]\" include/config/auto.conf\n+}\n+\n # Nice output in kbuild format\n # Will be suppressed by \"make -s\"\n info()\n@@ -211,17 +220,25 @@ if is_enabled CONFIG_KALLSYMS; then\n \tkallsyms .tmp_vmlinux0.syms .tmp_vmlinux0.kallsyms\n fi\n \n-if is_enabled CONFIG_KALLSYMS || is_enabled CONFIG_DEBUG_INFO_BTF; then\n+if is_module CONFIG_DEBUG_INFO_BTF; then\n+\t# The kernel refers to the size and hash of its BTF, which only the\n+\t# BTF generated from the first link can provide; link a placeholder\n+\t# of the same layout until then.\n+\t${CONFIG_SHELL} ${srctree}/scripts/gen-btf.sh --placeholder .tmp_vmlinux0\n+\tbtf_vmlinux_bin_o=.tmp_vmlinux0.btf.o\n+fi\n+\n+if is_enabled CONFIG_KALLSYMS || is_set CONFIG_DEBUG_INFO_BTF; then\n \n \t# The kallsyms linking does not need debug symbols, but the BTF does.\n-\tif ! is_enabled CONFIG_DEBUG_INFO_BTF; then\n+\tif ! is_set CONFIG_DEBUG_INFO_BTF; then\n \t\tstrip_debug=1\n \tfi\n \n \tvmlinux_link .tmp_vmlinux1\n fi\n \n-if is_enabled CONFIG_DEBUG_INFO_BTF; then\n+if is_set CONFIG_DEBUG_INFO_BTF; then\n \tinfo BTF .tmp_vmlinux1\n \tif ! ${CONFIG_SHELL} ${srctree}/scripts/gen-btf.sh .tmp_vmlinux1; then\n \t\techo \u003e\u00262 \"Failed to generate BTF for vmlinux\"\n@@ -287,7 +304,7 @@ fi\n \n vmlinux_link \"${VMLINUX}\"\n \n-if is_enabled CONFIG_DEBUG_INFO_BTF; then\n+if is_set CONFIG_DEBUG_INFO_BTF; then\n \tinfo BTFIDS ${VMLINUX}\n \t${RESOLVE_BTFIDS} --patch_btfids ${btfids_vmlinux} ${VMLINUX}\n fi\n"
} |
| 2/1 | 2026/09/27 16:07 | agent | patch-evaluator |
0mModel:core Args: null Results: {
"EnableConfigs": [
"DEBUG_INFO_BTF",
"DEBUG_INFO_BTF_MODULES",
"BPF_SYSCALL",
"SYSFS",
"MODULES"
],
"FocusSymbols": [
"bpf_get_btf_vmlinux",
"btf_vmlinux_data",
"btf_parse_deferred_modules",
"btf_parse_vmlinux",
"btf_module_notify",
"btf_sysfs_vmlinux_read",
"btf_sysfs_vmlinux_mmap",
"btf_defer_reg"
],
"Reasoning": "The patch series adds support for building kernel BTF type information as a loadable module (CONFIG_DEBUG_INFO_BTF=m). It introduces significant logic and state handling across core BPF, BTF parsing, sysfs, verifier, and module notifier code paths, including on-demand loading of BTF, deferred module BTF parsing, queuing and draining of kfunc/struct_ops registrations, wait queue synchronization, SHA-256 integrity verification, and custom sysfs mmap/read handlers. These paths are directly exposed to userspace through sysfs and the BPF syscall.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit d1f4e4b40f45a48572f7ab842ce9ed972bf1576d
Author: syz-cluster <triage@syzkaller.com>
Date: Sun Sep 27 16:07:09 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/bpf/btf.rst b/Documentation/bpf/btf.rst
index 004aa1058d857..b637f83c85c4c 100644
--- a/Documentation/bpf/btf.rst
+++ b/Documentation/bpf/btf.rst
@@ -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
==========
diff --git a/Makefile b/Makefile
index 66654fa71655b..0a37decd9d013 100644
--- a/Makefile
+++ b/Makefile
@@ -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
@@ -1744,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
diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h
index b2988aa12f664..204a9ee171c6d 100644
--- a/include/asm-generic/vmlinux.lds.h
+++ b/include/asm-generic/vmlinux.lds.h
@@ -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) } \
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index e7c5e203edddb..a3c4caad5dfc6 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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;
diff --git a/include/linux/btf.h b/include/linux/btf.h
index ddd0f4f32d24b..586361fa03a0a 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -581,6 +581,12 @@ __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);
+#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);
diff --git a/include/linux/btf_ids.h b/include/linux/btf_ids.h
index 8b5a9ee92513d..c665afff100e7 100644
--- a/include/linux/btf_ids.h
+++ b/include/linux/btf_ids.h
@@ -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 */
diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h
index c5921f1390079..a90a99849ceed 100644
--- a/include/linux/compiler_types.h
+++ b/include/linux/compiler_types.h
@@ -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
diff --git a/include/linux/module.h b/include/linux/module.h
index 96cc98568eea5..82734996a862b 100644
--- a/include/linux/module.h
+++ b/include/linux/module.h
@@ -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;
diff --git a/include/trace/trace_events.h b/include/trace/trace_events.h
index 93011f800d0f7..2a0098929771b 100644
--- a/include/trace/trace_events.h
+++ b/include/trace/trace_events.h
@@ -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)
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index 9a92c348bbda6..8ab46f496fa48 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -41,7 +41,11 @@ 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
+# 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
diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c
index 1178acd72296e..bf3004908d15a 100644
--- a/kernel/bpf/bpf_struct_ops.c
+++ b/kernel/bpf/bpf_struct_ops.c
@@ -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",
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 4a1fa4fbdf4e8..00d65199b45e4 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -29,6 +29,7 @@
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/overflow.h>
+#include <crypto/sha2.h>
#include <linux/bitops.h>
#include <net/netfilter/nf_bpf_link.h>
@@ -6092,10 +6093,73 @@ static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,
return ERR_PTR(err);
}
+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)
extern char __start_BTF[];
extern char __stop_BTF[];
+#endif
extern struct btf *btf_vmlinux;
+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+/*
+ * With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF is not part of the kernel
+ * image. The btf_vmlinux module carries it in its .BTF section; when the
+ * module loads, btf_module_notify() copies the section here. The copy is
+ * made with vmalloc_user() so that /sys/kernel/btf/vmlinux can be mmap()ed
+ * as with the built-in BTF. Set once, never cleared: like the built-in
+ * BTF, once present it stays for the lifetime of the kernel.
+ *
+ * The size and SHA-256 of the BTF are linked into the kernel as .BTF.meta
+ * by scripts/gen-btf.sh: the size makes /sys/kernel/btf/vmlinux report its
+ * size before the BTF is loaded, the hash makes sure only the BTF this
+ * kernel was built with is accepted.
+ */
+struct btf_vmlinux_meta {
+ u32 size;
+ u8 sha256[SHA256_DIGEST_SIZE];
+} __packed;
+
+extern const struct btf_vmlinux_meta __start_BTF_meta[];
+#define btf_vmlinux_meta (__start_BTF_meta[0])
+
+static void *btf_vmlinux_raw;
+#endif
+
+/**
+ * btf_vmlinux_data - get the raw vmlinux BTF
+ * @size: where to store the size of the BTF, also when it is not loaded yet
+ * @load: with CONFIG_DEBUG_INFO_BTF=m, load the btf_vmlinux module if the
+ * BTF is not present yet; may sleep
+ *
+ * Return: the raw BTF, or NULL if it is not available.
+ */
+void *btf_vmlinux_data(u32 *size, bool load)
+{
+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)
+ *size = __stop_BTF - __start_BTF;
+ return __start_BTF;
+#elif IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+ /* Pairs with the smp_store_release() in btf_vmlinux_module_coming() */
+ void *data = smp_load_acquire(&btf_vmlinux_raw);
+
+ 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");
+ /* Same pairing as above */
+ data = smp_load_acquire(&btf_vmlinux_raw);
+ }
+ *size = btf_vmlinux_meta.size;
+ return data;
+#else
+ *size = 0;
+ return NULL;
+#endif
+}
+
#define BPF_MAP_TYPE(_id, _ops)
#define BPF_LINK_TYPE(_id, _name)
static union {
@@ -6126,12 +6190,25 @@ static u8 bpf_ctx_convert_map[] = {
#undef BPF_MAP_TYPE
#undef BPF_LINK_TYPE
+/*
+ * bpf_ctx_convert.t is filled in by btf_parse_vmlinux(). With
+ * CONFIG_DEBUG_INFO_BTF=m that may not have run yet: the program context
+ * types are kernel types too, so this is one of the places that loads the
+ * vmlinux BTF. Only called from the verifier, which may sleep.
+ */
+static const struct btf_type *bpf_ctx_convert_type(void)
+{
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+ return NULL;
+ return bpf_ctx_convert.t;
+}
+
static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
{
const struct btf_type *conv_struct;
const struct btf_member *ctx_type;
- conv_struct = bpf_ctx_convert.t;
+ conv_struct = bpf_ctx_convert_type();
if (!conv_struct)
return NULL;
/* prog_type is valid bpf program type. No need for bounds check. */
@@ -6147,7 +6224,7 @@ static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
const struct btf_type *conv_struct;
const struct btf_member *ctx_type;
- conv_struct = bpf_ctx_convert.t;
+ conv_struct = bpf_ctx_convert_type();
if (!conv_struct)
return -EFAULT;
/* prog_type is valid bpf program type. No need for bounds check. */
@@ -6406,7 +6483,11 @@ int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_ty
const struct btf_type *kctx_type;
u32 kctx_type_id;
- conv_struct = bpf_ctx_convert.t;
+ conv_struct = bpf_ctx_convert_type();
+ if (!conv_struct) {
+ bpf_log(log, "btf_vmlinux is malformed\n");
+ return -EINVAL;
+ }
/* get member for kernel ctx type */
kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
kctx_type_id = kctx_member->type;
@@ -6474,20 +6555,29 @@ static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name
return 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;
struct bpf_verifier_log *log;
struct btf *btf;
+ void *data;
+ u32 size;
int err;
+ /* The caller made sure the BTF is present, see bpf_get_btf_vmlinux() */
+ data = btf_vmlinux_data(&size, false);
+ if (!data)
+ return ERR_PTR(-ENOENT);
+
env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
if (!env)
return ERR_PTR(-ENOMEM);
log = &env->log;
log->level = BPF_LOG_KERNEL;
- btf = btf_parse_base(env, "vmlinux", __start_BTF, __stop_BTF - __start_BTF);
+ btf = btf_parse_base(env, "vmlinux", data, size);
if (IS_ERR(btf))
goto err_out;
@@ -6495,9 +6585,18 @@ struct btf *btf_parse_vmlinux(void)
bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
err = btf_alloc_id(btf);
if (err) {
+ 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;
@@ -6514,18 +6613,22 @@ __u32 btf_relocate_id(const struct btf *btf, __u32 id)
return btf->base_id_map[id];
}
-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)
-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 +6665,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,14 +6711,15 @@ 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);
}
return ERR_PTR(err);
}
-#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
+#endif /* CONFIG_DEBUG_INFO_BTF_MODULES || CONFIG_DEBUG_INFO_BTF=m */
struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
{
@@ -7876,6 +7983,13 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
t = btf_type_by_id(btf, t->type);
}
+ /* candidates are kernel types: load the vmlinux BTF, outside the mutex */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
+ bpf_log(log, "arg#%d reference type('%s %s') needs the vmlinux BTF\n",
+ arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
+ return -EINVAL;
+ }
+
mutex_lock(&cand_cache_mutex);
cc = bpf_core_find_cands(&ctx, type_id);
if (IS_ERR(cc)) {
@@ -8227,7 +8341,10 @@ int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
if (kern_type_id < 0)
return kern_type_id;
+ /* present: btf_get_ptr_to_btf_id() found the candidate in it */
vmlinux_btf = bpf_get_btf_vmlinux();
+ if (IS_ERR_OR_NULL(vmlinux_btf))
+ return -EINVAL;
ref_t = btf_type_by_id(vmlinux_btf, kern_type_id);
if (!btf_type_is_struct(ref_t)) {
tname = __btf_name_by_offset(vmlinux_btf, t->name_off);
@@ -8596,20 +8713,270 @@ enum {
BTF_MODULE_F_LIVE = (1 << 0),
};
-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+/*
+ * The module notifier registers module BTF (CONFIG_DEBUG_INFO_BTF_MODULES)
+ * and picks up the vmlinux BTF from the btf_vmlinux module
+ * (CONFIG_DEBUG_INFO_BTF=m).
+ */
+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+#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() and btf_apply_deferred_regs().
+ */
+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
+static void btf_free_deferred_regs(struct list_head *regs);
+static void btf_apply_deferred_regs(struct btf *btf, struct list_head *regs);
+
struct btf_module {
struct list_head list;
struct module *module;
struct btf *btf;
struct bin_attribute *sysfs_attr;
int flags;
+ /*
+ * CONFIG_DEBUG_INFO_BTF=m: a module loaded before the vmlinux BTF is
+ * available cannot have its BTF parsed yet. Its .BTF and .BTF.base
+ * sections are copied here and parsed once the vmlinux BTF arrives
+ * (btf_parse_deferred_modules()); @btf is NULL until then.
+ * Registrations of the module's kfuncs, dtor kfuncs and struct_ops
+ * wait in @deferred_regs.
+ */
+ void *data;
+ void *base_data;
+ u32 data_size;
+ u32 base_data_size;
+ struct list_head deferred_regs;
+ /*
+ * 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 *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;
+
+ 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 = size;
+ attr->private = private;
+ attr->read = 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;
+}
+
+/*
+ * 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) {
+ purge_cand_cache(btf_mod->btf);
+ btf_put(btf_mod->btf);
+ } else {
+ kvfree(btf_mod->data);
+ kvfree(btf_mod->base_data);
+ }
+ btf_free_deferred_regs(&btf_mod->deferred_regs);
+ kfree(btf_mod->sysfs_attr);
+ kfree(btf_mod);
+}
+
+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+/*
+ * The btf_vmlinux module carries the vmlinux BTF in its .BTF section
+ * (scripts/gen-btf.sh). Keep a copy; the module is only the carrier and
+ * has no BTF of its own.
+ */
+static int btf_vmlinux_module_coming(struct module *mod)
+{
+ u8 sha256sum[SHA256_DIGEST_SIZE];
+ void *data;
+
+ if (btf_vmlinux_raw)
+ return 0;
+
+ /*
+ * The verifier trusts the BTF as the description of this kernel's
+ * types, so a BTF from a different build must not get in even if
+ * the module otherwise loads (same release string, same vermagic).
+ */
+ if (mod->btf_data_size != btf_vmlinux_meta.size) {
+ pr_err("module [%s]: BTF size %u does not match this kernel (%u)\n",
+ mod->name, mod->btf_data_size, btf_vmlinux_meta.size);
+ return -EINVAL;
+ }
+ sha256(mod->btf_data, mod->btf_data_size, sha256sum);
+ if (memcmp(sha256sum, btf_vmlinux_meta.sha256, sizeof(sha256sum))) {
+ pr_err("module [%s]: BTF does not match this kernel\n", mod->name);
+ return -EINVAL;
+ }
+
+ data = vmalloc_user(mod->btf_data_size);
+ if (!data)
+ return -ENOMEM;
+ memcpy(data, mod->btf_data, mod->btf_data_size);
+
+ /* Pairs with the smp_load_acquire() in btf_vmlinux_data() */
+ smp_store_release(&btf_vmlinux_raw, data);
+ 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().
+ *
+ * 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)
+{
+ btf_mod->data = kvmemdup(mod->btf_data, mod->btf_data_size,
+ GFP_KERNEL | __GFP_NOWARN);
+ if (!btf_mod->data)
+ return -ENOMEM;
+ btf_mod->data_size = mod->btf_data_size;
+
+ if (mod->btf_base_data) {
+ btf_mod->base_data = kvmemdup(mod->btf_base_data,
+ mod->btf_base_data_size,
+ GFP_KERNEL | __GFP_NOWARN);
+ if (!btf_mod->base_data) {
+ kvfree(btf_mod->data);
+ return -ENOMEM;
+ }
+ btf_mod->base_data_size = mod->btf_base_data_size;
+ /* 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, sysfs_bin_attr_simple_read);
+ }
+
+ list_add(&btf_mod->list, &btf_modules);
+ return 0;
+}
+#else
+static int btf_vmlinux_module_coming(struct module *mod)
+{
+ return 0;
+}
+
+static int btf_module_defer(struct btf_module *btf_mod, struct module *mod)
+{
+ return 0;
+}
+#endif
+
static int btf_module_notify(struct notifier_block *nb, unsigned long op,
void *module)
{
@@ -8618,9 +8985,17 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
struct btf *btf;
int err = 0;
- if (mod->btf_data_size == 0 ||
- (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
- op != MODULE_STATE_GOING))
+ if (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
+ op != MODULE_STATE_GOING)
+ goto out;
+
+ if (IS_MODULE(CONFIG_DEBUG_INFO_BTF) && !strcmp(mod->name, "btf_vmlinux")) {
+ if (op == MODULE_STATE_COMING)
+ err = btf_vmlinux_module_coming(mod);
+ goto out;
+ }
+
+ if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || mod->btf_data_size == 0)
goto out;
switch (op) {
@@ -8630,7 +9005,28 @@ 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;
+ INIT_LIST_HEAD(&btf_mod->deferred_regs);
+
+ if (IS_MODULE(CONFIG_DEBUG_INFO_BTF)) {
+ mutex_lock(&btf_module_mutex);
+ /* Pairs with the publication in bpf_get_btf_vmlinux() */
+ if (!smp_load_acquire(&btf_vmlinux)) {
+ err = btf_module_defer(btf_mod, mod);
+ mutex_unlock(&btf_module_mutex);
+ if (err) {
+ pr_warn("failed to keep module [%s] BTF: %d\n",
+ mod->name, err);
+ kfree(btf_mod);
+ err = 0;
+ }
+ goto out;
+ }
+ mutex_unlock(&btf_module_mutex);
+ }
+
+ 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 +9048,13 @@ 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,
+ sysfs_bin_attr_simple_read);
break;
case MODULE_STATE_LIVE:
mutex_lock(&btf_module_mutex);
@@ -8691,6 +9063,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.
+ */
+ 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;
+ }
break;
}
mutex_unlock(&btf_module_mutex);
@@ -8707,15 +9099,13 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
* btf_try_get_module() on such BTFs will fail. This may
* be called again on btf_put(), but it's ok to do so.
*/
- btf_free_id(btf_mod->btf);
+ if (btf_mod->btf)
+ 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);
- break;
+ mutex_unlock(&btf_module_mutex);
+ /* off the list, nobody else can find it now */
+ btf_module_free(btf_mod);
+ goto out;
}
mutex_unlock(&btf_module_mutex);
break;
@@ -8735,7 +9125,107 @@ static int __init btf_module_init(void)
}
fs_initcall(btf_module_init);
-#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
+
+#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. 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)
+{
+ 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);
+ 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 -- 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
+ * its kfuncs and struct_ops, as with the vmlinux BTF. Applying walks
+ * btf_modules (btf_check_kfunc_name()) and so needs the mutex dropped; the
+ * module is pinned for that, and the scan restarts afterwards. A module
+ * that is still initializing is only published: its init is still queueing
+ * registrations, and MODULE_STATE_LIVE applies them once it is done.
+ */
+void btf_parse_deferred_modules(void)
+{
+ /* Pairs with the publication in bpf_get_btf_vmlinux() */
+ struct btf *vmlinux_btf = smp_load_acquire(&btf_vmlinux);
+ struct btf_module *btf_mod;
+ bool parsed = false;
+ LIST_HEAD(regs);
+ struct btf *btf;
+ int err;
+
+ if (IS_ERR_OR_NULL(vmlinux_btf))
+ return;
+
+ mutex_lock(&btf_module_mutex);
+restart:
+ list_for_each_entry(btf_mod, &btf_modules, list) {
+ if (btf_mod->btf || btf_mod->gone)
+ continue;
+
+ btf = btf_parse_module(btf_mod->module->name, vmlinux_btf,
+ btf_mod->data, btf_mod->data_size, true,
+ btf_mod->base_data, btf_mod->base_data_size);
+ if (IS_ERR(btf)) {
+ /* on failure the caller keeps the data */
+ btf_module_dead(btf_mod, "validate", PTR_ERR(btf));
+ continue;
+ }
+ /* btf->data is btf_mod->data now, the sysfs file keeps pointing at valid data */
+ kvfree(btf_mod->base_data);
+ btf_mod->base_data = NULL;
+
+ if ((btf_mod->flags & BTF_MODULE_F_LIVE) &&
+ try_module_get(btf_mod->module)) {
+ list_splice_init(&btf_mod->deferred_regs, ®s);
+ mutex_unlock(&btf_module_mutex);
+ btf_apply_deferred_regs(btf, ®s);
+ mutex_lock(&btf_module_mutex);
+ module_put(btf_mod->module);
+ }
+
+ err = btf_alloc_id(btf);
+ if (err) {
+ /* give the data back to the entry, the sysfs file may serve it */
+ btf->data = NULL;
+ btf_free(btf);
+ btf_module_dead(btf_mod, "register", err);
+ goto restart;
+ }
+
+ 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;
+ }
+ mutex_unlock(&btf_module_mutex);
+
+ if (parsed)
+ purge_cand_cache(NULL);
+}
+#endif /* IS_MODULE(CONFIG_DEBUG_INFO_BTF) */
+#endif /* BTF_MODULE_NOTIFIER */
struct module *btf_try_get_module(const struct btf *btf)
{
@@ -8787,8 +9277,11 @@ struct btf *btf_get_module_btf(const struct module *module)
if (btf_mod->module != module)
continue;
- btf_get(btf_mod->btf);
- btf = btf_mod->btf;
+ /* NULL while waiting for the vmlinux BTF (CONFIG_DEBUG_INFO_BTF=m) */
+ if (btf_mod->btf) {
+ btf_get(btf_mod->btf);
+ btf = btf_mod->btf;
+ }
break;
}
mutex_unlock(&btf_module_mutex);
@@ -8950,12 +9443,18 @@ static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind
#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
struct btf_module *btf_mod, *tmp;
#endif
+ struct btf *vmlinux_btf;
s32 id;
if (!btf_is_module(btf))
return 0;
- id = btf_find_by_name_kind(bpf_get_btf_vmlinux(), func_name, kind);
+ /* a module BTF only exists once the vmlinux BTF is parsed */
+ vmlinux_btf = bpf_get_btf_vmlinux();
+ if (IS_ERR_OR_NULL(vmlinux_btf))
+ return -EINVAL;
+
+ id = btf_find_by_name_kind(vmlinux_btf, func_name, kind);
if (id >= 0) {
pr_err("kfunc %s (id: %d) is already present in vmlinux.\n",
func_name, id);
@@ -8965,7 +9464,8 @@ static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind
#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
guard(mutex)(&btf_module_mutex);
list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
- if (btf_mod->btf == btf)
+ /* skip ourselves and, with CONFIG_DEBUG_INFO_BTF=m, unparsed BTF */
+ if (btf_mod->btf == btf || !btf_mod->btf)
continue;
id = btf_find_by_name_kind(btf_mod->btf, func_name, kind);
if (id >= 0) {
@@ -9290,11 +9790,36 @@ u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
return btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
}
+static int btf_kfunc_id_set_add(struct btf *btf, enum btf_kfunc_hook hook,
+ const struct btf_kfunc_id_set *kset)
+{
+ int ret, i;
+
+ for (i = 0; i < kset->set->cnt; i++) {
+ ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
+ kset->set->pairs[i].flags);
+ if (ret)
+ return ret;
+ }
+
+ 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, i;
+ 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)
@@ -9302,16 +9827,7 @@ static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
if (IS_ERR(btf))
return PTR_ERR(btf);
- for (i = 0; i < kset->set->cnt; i++) {
- ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
- kset->set->pairs[i].flags);
- if (ret)
- goto err_out;
- }
-
- ret = btf_populate_kfunc_set(btf, hook, kset);
-
-err_out:
+ ret = btf_kfunc_id_set_add(btf, hook, kset);
btf_put(btf);
return ret;
}
@@ -9403,21 +9919,13 @@ static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc
return 0;
}
-/* This function must be invoked only from initcalls/module init functions */
-int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
- struct module *owner)
+static int btf_dtor_kfuncs_add(struct btf *btf, const struct btf_id_dtor_kfunc *dtors,
+ u32 add_cnt)
{
struct btf_id_dtor_kfunc_tab *tab;
- struct btf *btf;
u32 tab_cnt, i;
int ret;
- btf = btf_get_module_btf(owner);
- if (!btf)
- return check_btf_kconfigs(owner, "dtor kfuncs");
- if (IS_ERR(btf))
- return PTR_ERR(btf);
-
if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
ret = -E2BIG;
@@ -9474,6 +9982,31 @@ int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_c
end:
if (ret)
btf_free_dtor_kfunc_tab(btf);
+ return ret;
+}
+
+/* This function must be invoked only from initcalls/module init functions */
+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");
+ if (IS_ERR(btf))
+ return PTR_ERR(btf);
+
+ ret = btf_dtor_kfuncs_add(btf, dtors, add_cnt);
btf_put(btf);
return ret;
}
@@ -9677,6 +10210,11 @@ static void purge_cand_cache(struct btf *btf)
__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
mutex_unlock(&cand_cache_mutex);
}
+#elif defined(BTF_MODULE_NOTIFIER)
+/* CONFIG_DEBUG_INFO_BTF=m without module BTF: nothing is ever cached */
+static void purge_cand_cache(struct btf *btf)
+{
+}
#endif
static struct bpf_cand_cache *
@@ -9740,9 +10278,11 @@ bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
const char *name;
int id;
- main_btf = bpf_get_btf_vmlinux();
- if (IS_ERR(main_btf))
- return ERR_CAST(main_btf);
+ /*
+ * Callers fetch the vmlinux BTF before taking cand_cache_mutex, so
+ * that loading it (CONFIG_DEBUG_INFO_BTF=m) happens outside the lock.
+ */
+ main_btf = bpf_peek_btf_vmlinux();
if (!main_btf)
return ERR_PTR(-EINVAL);
@@ -9845,6 +10385,13 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
struct bpf_cand_cache *cc;
int i;
+ /* candidates are kernel types: load the vmlinux BTF, outside the mutex */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
+ bpf_log(ctx->log, "relo #%u: needs the vmlinux BTF\n", relo_idx);
+ kfree(specs);
+ return -EINVAL;
+ }
+
mutex_lock(&cand_cache_mutex);
cc = bpf_core_find_cands(ctx, relo->type_id);
if (IS_ERR(cc)) {
@@ -10112,11 +10659,35 @@ bpf_struct_ops_find(struct btf *btf, u32 type_id)
return NULL;
}
-int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
+static int btf_struct_ops_register(struct btf *btf, struct bpf_struct_ops *st_ops)
{
struct bpf_verifier_log *log;
+ int err;
+
+ log = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);
+ if (!log)
+ return -ENOMEM;
+
+ log->level = BPF_LOG_KERNEL;
+
+ err = btf_add_struct_ops(btf, st_ops, log);
+
+ kfree(log);
+ return err;
+}
+
+int __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 = 0;
+ 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)
@@ -10124,24 +10695,183 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
if (IS_ERR(btf))
return PTR_ERR(btf);
- log = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);
- if (!log) {
- err = -ENOMEM;
- goto errout;
+ err = btf_struct_ops_register(btf, st_ops);
+ btf_put(btf);
+ 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 made before the BTF they apply to
+ * is available. Registrations for vmlinux wait in btf_vmlinux_deferred_regs
+ * until btf_parse_vmlinux() applies them; registrations for a module wait in
+ * its struct btf_module, under btf_module_mutex, until
+ * btf_parse_deferred_modules() does.
+ */
+#ifdef BTF_MODULE_NOTIFIER
+/*
+ * The vmlinux 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.
+ */
+static int btf_defer_reg(struct module *owner, const struct btf_deferred_reg *tmpl)
+{
+ struct list_head *head = NULL;
+ struct btf_deferred_reg *reg;
+ struct btf_module *btf_mod;
+
+ if (!IS_MODULE(CONFIG_DEBUG_INFO_BTF))
+ return 0;
+
+ guard(mutex)(owner ? &btf_module_mutex : &btf_vmlinux_regs_mutex);
+ if (!owner) {
+ if (!btf_vmlinux_regs_closed)
+ head = &btf_vmlinux_deferred_regs;
+ } else {
+ list_for_each_entry(btf_mod, &btf_modules, list) {
+ if (btf_mod->module != owner)
+ continue;
+ /* a dead entry has no BTF to register with, as with =y */
+ if (!btf_mod->btf && !btf_mod->gone)
+ head = &btf_mod->deferred_regs;
+ break;
+ }
}
+ if (!head)
+ return 0;
- log->level = BPF_LOG_KERNEL;
+ 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;
+}
- err = btf_add_struct_ops(btf, st_ops, log);
+static void btf_free_deferred_reg(struct btf_deferred_reg *reg)
+{
+ if (reg->kind == BTF_DEFERRED_DTOR_KFUNCS)
+ kfree(reg->dtor.dtors);
+ kfree(reg);
+}
-errout:
- kfree(log);
- btf_put(btf);
+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 "?";
+}
- return err;
+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;
}
-EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
-#endif
+
+/*
+ * Apply and free the registrations in @regs to @btf. For a module BTF the
+ * caller holds a reference on @btf and makes sure the owning module stays.
+ */
+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);
+ }
+}
+
+static void btf_free_deferred_regs(struct list_head *regs)
+{
+ struct btf_deferred_reg *reg, *tmp;
+
+ list_for_each_entry_safe(reg, tmp, regs, list) {
+ 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,
diff --git a/kernel/bpf/btf_vmlinux.c b/kernel/bpf/btf_vmlinux.c
new file mode 100644
index 0000000000000..8d89b4bb3c432
--- /dev/null
+++ b/kernel/bpf/btf_vmlinux.c
@@ -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");
diff --git a/kernel/bpf/preload/Kconfig b/kernel/bpf/preload/Kconfig
index aef7b0bc96d61..b1600bdce7a06 100644
--- a/kernel/bpf/preload/Kconfig
+++ b/kernel/bpf/preload/Kconfig
@@ -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
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 74496fd716d3b..9e9eaa7988138 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -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;
diff --git a/kernel/bpf/sysfs_btf.c b/kernel/bpf/sysfs_btf.c
index 9cbe15ce3540c..b2408878412a8 100644
--- a/kernel/bpf/sysfs_btf.c
+++ b/kernel/bpf/sysfs_btf.c
@@ -9,8 +9,13 @@
#include <linux/sysfs.h>
#include <linux/mm.h>
#include <linux/io.h>
+#include <linux/bpf.h>
#include <linux/btf.h>
+#include <linux/vmalloc.h>
+struct kobject *btf_kobj;
+
+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)
/* See scripts/link-vmlinux.sh, gen_btf() func for details */
extern char __start_BTF[];
extern char __stop_BTF[];
@@ -49,12 +54,86 @@ static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {
.mmap = btf_sysfs_vmlinux_mmap,
};
-struct kobject *btf_kobj;
-
-static int __init btf_vmlinux_init(void)
+static void __init btf_sysfs_vmlinux_init(void)
{
bin_attr_btf_vmlinux.private = __start_BTF;
bin_attr_btf_vmlinux.size = __stop_BTF - __start_BTF;
+}
+
+#else /* CONFIG_DEBUG_INFO_BTF=m */
+
+/*
+ * The BTF is carried by the btf_vmlinux module and only loaded when
+ * something needs it. Its size is known from the start, so the file has
+ * its final size from boot; the first read() or mmap() loads the BTF.
+ */
+static void *btf_sysfs_vmlinux_load(u32 *size)
+{
+ /* Loads the module, parses the BTF and registers module BTFs. */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+ return NULL;
+ return btf_vmlinux_data(size, false);
+}
+
+static ssize_t btf_sysfs_vmlinux_read(struct file *filp, struct kobject *kobj,
+ const struct bin_attribute *attr,
+ char *buf, loff_t off, size_t count)
+{
+ u32 size;
+ void *data = btf_sysfs_vmlinux_load(&size);
+
+ if (!data)
+ return -ENODEV;
+
+ /* sysfs clamps @off and @count to attr->size, which is @size */
+ memcpy(buf, data + off, count);
+ return count;
+}
+
+static int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,
+ const struct bin_attribute *attr,
+ struct vm_area_struct *vma)
+{
+ size_t vm_size = vma->vm_end - vma->vm_start;
+ u32 size;
+ void *data = btf_sysfs_vmlinux_load(&size);
+
+ if (!data)
+ return -ENODEV;
+
+ if (vma->vm_pgoff)
+ return -EINVAL;
+
+ if (vma->vm_flags & (VM_WRITE | VM_EXEC | VM_MAYSHARE))
+ return -EACCES;
+
+ if (vm_size > PAGE_ALIGN(size))
+ return -EINVAL;
+
+ vm_flags_mod(vma, VM_DONTDUMP, VM_MAYEXEC | VM_MAYWRITE);
+ /* the copy was made with vmalloc_user() for this purpose */
+ return remap_vmalloc_range(vma, data, 0);
+}
+
+static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {
+ .attr = { .name = "vmlinux", .mode = 0444, },
+ .read = btf_sysfs_vmlinux_read,
+ .mmap = btf_sysfs_vmlinux_mmap,
+};
+
+static void __init btf_sysfs_vmlinux_init(void)
+{
+ u32 size;
+
+ /* known before the BTF is loaded, see .BTF.meta */
+ btf_vmlinux_data(&size, false);
+ bin_attr_btf_vmlinux.size = size;
+}
+#endif
+
+static int __init btf_vmlinux_init(void)
+{
+ btf_sysfs_vmlinux_init();
if (bin_attr_btf_vmlinux.size == 0)
return 0;
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index a7c9e2d8965d5..72edabbc2db51 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -2873,7 +2873,8 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
tab = prog_aux->kfunc_tab;
btf_tab = prog_aux->kfunc_btf_tab;
if (!tab) {
- if (!btf_vmlinux) {
+ /* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
return -ENOTSUPP;
}
@@ -6257,7 +6258,8 @@ static int check_ptr_to_map_access(struct bpf_verifier_env *env,
u32 btf_id;
int ret;
- if (!btf_vmlinux) {
+ /* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
return -ENOTSUPP;
}
@@ -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)
+{
+ 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;
+ }
+ return false;
+}
+
static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
int *insn_idx_p)
{
@@ -11637,6 +11657,18 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
return err;
}
+ /*
+ * Helpers that take or return kernel BTF pointers need the vmlinux
+ * BTF; with CONFIG_DEBUG_INFO_BTF=m this is where it gets loaded.
+ * Without CONFIG_DEBUG_INFO_BTF they keep failing as they always did.
+ */
+ if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF) && helper_uses_vmlinux_btf(func_id, fn) &&
+ IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
+ verbose(env, "helper %s#%d is not supported without vmlinux BTF\n",
+ func_id_name(func_id), func_id);
+ return -ENOTSUPP;
+ }
+
if (fn->might_sleep && !in_sleepable_context(env)) {
verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
non_sleepable_context_description(env));
@@ -19235,12 +19267,13 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env,
return -EINVAL;
}
} else {
- if (!btf_vmlinux) {
+ /* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */
+ btf = bpf_get_btf_vmlinux();
+ if (IS_ERR_OR_NULL(btf)) {
verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
return -EINVAL;
}
- btf_get(btf_vmlinux);
- btf = btf_vmlinux;
+ btf_get(btf);
}
err = __check_pseudo_btf_id(env, insn, aux, btf);
@@ -21130,29 +21163,72 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt
return 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, 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)) {
- 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) {
+ 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;
}
- 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);
+ parsed = true;
}
+ mutex_unlock(&btf_vmlinux_lock);
+
+ if (parsed && IS_MODULE(CONFIG_DEBUG_INFO_BTF))
+ btf_parse_deferred_modules();
+
return btf;
}
+/*
+ * The vmlinux BTF if it has been parsed already, else NULL. Unlike
+ * bpf_get_btf_vmlinux() this never loads or parses anything, so it is safe
+ * to call from a running BPF program.
+ */
+struct btf *bpf_peek_btf_vmlinux(void)
+{
+ /* Pairs with the smp_store_release() in bpf_get_btf_vmlinux() */
+ return smp_load_acquire(&btf_vmlinux);
+}
+
/*
* The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
* this case expect that every file descriptor in the array is either a map or
@@ -21724,7 +21800,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret)
goto err_prep;
- bpf_get_btf_vmlinux();
+ /*
+ * The vmlinux BTF is not fetched up front: with CONFIG_DEBUG_INFO_BTF=m
+ * it is loaded on demand, at the points where kernel types enter the
+ * program (attach_btf, kfuncs, ksyms, map pointers, BTF-typed helpers).
+ */
/* Serialize verification of unprivileged programs. */
if (!is_priv)
@@ -21745,10 +21825,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())) {
/* 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;
}
diff --git a/kernel/module/main.c b/kernel/module/main.c
index d0e1e0bd2ad06..694c4bc7e6793 100644
--- a/kernel/module/main.c
+++ b/kernel/module/main.c
@@ -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;
diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c
index 195f78db9bdaf..c022b2877f0ba 100644
--- a/kernel/trace/bpf_trace.c
+++ b/kernel/trace/bpf_trace.c
@@ -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;
diff --git a/kernel/trace/trace_syscalls.c b/kernel/trace/trace_syscalls.c
index e35744049e3f2..7a0d59c308c29 100644
--- a/kernel/trace/trace_syscalls.c
+++ b/kernel/trace/trace_syscalls.c
@@ -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
};
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 134b15a44625e..418025c5e6577 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -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
diff --git a/net/netfilter/Makefile b/net/netfilter/Makefile
index 6bf74d488a292..a2c7f00794d22 100644
--- a/net/netfilter/Makefile
+++ b/net/netfilter/Makefile
@@ -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
diff --git a/net/xfrm/Makefile b/net/xfrm/Makefile
index 5a1787587cb35..b7f6e5046a0e9 100644
--- a/net/xfrm/Makefile
+++ b/net/xfrm/Makefile
@@ -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
diff --git a/scripts/Makefile.modfinal b/scripts/Makefile.modfinal
index 01a37ec872b90..6a0958cf0e6f4 100644
--- a/scripts/Makefile.modfinal
+++ b/scripts/Makefile.modfinal
@@ -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
diff --git a/scripts/Makefile.vmlinux b/scripts/Makefile.vmlinux
index fcae1e432d9ad..557db1ee1f3b0 100644
--- a/scripts/Makefile.vmlinux
+++ b/scripts/Makefile.vmlinux
@@ -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__*'
diff --git a/scripts/gen-btf.sh b/scripts/gen-btf.sh
index 8ca96eb10a69e..d808d0006d325 100755
--- a/scripts/gen-btf.sh
+++ b/scripts/gen-btf.sh
@@ -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}" in
diff --git a/scripts/link-vmlinux.sh b/scripts/link-vmlinux.sh
index ab0b8125c8cbc..a9a066267ef6e 100755
--- a/scripts/link-vmlinux.sh
+++ b/scripts/link-vmlinux.sh
@@ -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
|
| 3/2 | 2026/09/27 16:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34936 output: 24 thoughts: 1512 Thoughts: **Patch Analysis: Worthy of Fuzzing** Alright, let's dive into this patch with a critical eye. My initial assessment is that this introduces significant changes related to BTF (BPF Type Format) information and its handling within the kernel. The patch makes `CONFIG_DEBUG_INFO_BTF` tristate, allowing it to be built as a module (`=m`). When set to 'm', the vmlinux BTF data is no longer baked into the kernel image; instead, it's loaded dynamically via a `btf_vmlinux` module. This module is triggered on demand, specifically when `/sys/kernel/btf/vmlinux` is accessed (read or mmap), during BTF object enumeration, or when a BPF program needs kernel type information. I see that there are several deferred registrations, indicating a sophisticated dynamic loading approach. The code incorporates new functions and major logic additions, scattered throughout `kernel/bpf/btf.c`, `kernel/bpf/sysfs_btf.c`, `kernel/bpf/verifier.c`, `kernel/bpf/syscall.c`, and `kernel/module/main.c`, and potentially others. These include functions related to vmlinux data, BTF parsing (modules and vmlinux), sysfs interaction, and deferred module handling. Looking deeper, the changes reach core kernel subsystems. The patch touches the BPF subsystem, including the verifier and syscall handlers, as well as BTF mechanisms, module loading, and sysfs interfaces. Modifications are evident in how the verifier handles kernel type information. System calls, sysfs file interactions, and module loading are all reachable, even in a QEMU environment or standard fuzzing setup. I note that even if `CONFIG_DEBUG_INFO_BTF` is set to 'y', there are changes to core functions like `bpf_get_btf_vmlinux` and others, suggesting non-trivial logic changes. With 'm', we're seeing completely new code for dynamic module loading, deferred registration, sysfs mmap/read, and associated locking and synchronization primitives. Given the criteria for `WorthFuzzing`, this patch clearly fits the bill. It modifies core subsystems like BPF, which includes substantial logic modifications, and involves reachable code paths via syscalls and sysfs. That means we should be able to trigger the new code with some clever fuzzing, and it should be a priority. Now, let's determine the necessary configurations for enabling this feature. We need to check the `Kconfig` files and the patch diff to determine what needs to be enabled. I'll need to examine `lib/Kconfig.debug`, specifically: ``` config DEBUG_INFO_BTF tristate "Generate BTF type information" depends on !DEBUG_INFO_SPLIT && !DEBUG_INFO_REDUCED depends on !GCC_PLUGIN_RANDSTRUCT || COMPILE_TEST depends on BPF_SYSCALL ``` We also have `CONFIG_DEBUG_INFO_BTF_MODULES` to consider. A search using `grepper` across Kconfig files will be useful here. Based on this information, I will determine the `EnableConfigs` to prepare our fuzzing environment. |
| 4/2 | 2026/09/27 16:07 | tool | grepper |
0mArgs:{
"Expression": "config DEBUG_INFO_BTF_MODULES"
}Results: {
"Output": "lib/Kconfig.debug=439=config PAHOLE_HAS_LANG_EXCLUDE\n--\nlib/Kconfig.debug-447-\nlib/Kconfig.debug:448:config DEBUG_INFO_BTF_MODULES\nlib/Kconfig.debug-449-\tbool \"Generate BTF type information for kernel modules\"\n"
} |
| 5/2 | 2026/09/27 16:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37266 output: 34 thoughts: 19 Thoughts: Here's my take on the thought process, as requested: **Diving into Debugging Configuration** Okay, time to get to the heart of this. I need to understand something specific about the debugging configuration, so I'm going to jump into the `lib/Kconfig.debug` file. Let's start around line 448 – that's usually a good starting point for a section of code this size. I'm expecting to find the relevant configuration options or perhaps some conditional logic related to the debug features. I'll read around that line, see what the surrounding context says, and then move forward as needed. I'm ready to interpret the relevant Kconfig syntax and understand how it influences the build process, so I can get a better handle on the underlying mechanism. |
| 6/2 | 2026/09/27 16:07 | tool | read-file |
0mArgs:{
"File": "lib/Kconfig.debug",
"FirstLine": 440,
"LineCount": 40
}Results: {
"Contents": " 440:\t\tdef_bool PAHOLE_VERSION \u003e= 124\n 441:\t\thelp\n 442:\t\t Support for the --lang_exclude flag which makes pahole exclude\n 443:\t\t compilation units from the supplied language. Used in Kbuild to\n 444:\t\t omit Rust CUs which are not supported in version 1.24 of pahole,\n 445:\t\t otherwise it would emit malformed kernel and module binaries when\n 446:\t\t using DEBUG_INFO_BTF_MODULES.\n 447:\t\n 448:\tconfig DEBUG_INFO_BTF_MODULES\n 449:\t\tbool \"Generate BTF type information for kernel modules\"\n 450:\t\tdefault y\n 451:\t\tdepends on DEBUG_INFO_BTF \u0026\u0026 MODULES\n 452:\t\thelp\n 453:\t\t Generate compact split BTF type information for kernel modules.\n 454:\t\n 455:\tconfig MODULE_ALLOW_BTF_MISMATCH\n 456:\t\tbool \"Allow loading modules with non-matching BTF type info\"\n 457:\t\tdepends on DEBUG_INFO_BTF_MODULES\n 458:\t\thelp\n 459:\t\t For modules whose split BTF does not match vmlinux, load without\n 460:\t\t BTF rather than refusing to load. The default behavior with\n 461:\t\t module BTF enabled is to reject modules with such mismatches;\n 462:\t\t this option will still load module BTF where possible but ignore\n 463:\t\t it when a mismatch is found.\n 464:\t\n 465:\tconfig GDB_SCRIPTS\n 466:\t\tbool \"Provide GDB scripts for kernel debugging\"\n 467:\t\thelp\n 468:\t\t This creates the required links to GDB helper scripts in the\n 469:\t\t build directory. If you load vmlinux into gdb, the helper\n 470:\t\t scripts will be automatically imported by gdb as well, and\n 471:\t\t additional functions are available to analyze a Linux kernel\n 472:\t\t instance. See Documentation/process/debugging/gdb-kernel-debugging.rst\n 473:\t\t for further details.\n 474:\t\n 475:\tendif # DEBUG_INFO\n 476:\t\n 477:\tconfig FRAME_WARN\n 478:\t\tint \"Warn for stack frames larger than\"\n 479:\t\trange 0 8192\n"
} |
| 7/2 | 2026/09/27 16:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38130 output: 34 thoughts: 40 Thoughts: Here's my analysis of the provided snippet, framed as my own thought process: **Investigating the Dependency of `DEBUG_INFO_BTF`** Okay, so I need to figure out the dependencies of `DEBUG_INFO_BTF`. My first instinct, as always, is to dive into the Kconfig file. I'm going to navigate to `lib/Kconfig.debug`. I figure, based on experience, that the relevant configuration options will likely be in the vicinity of lines 390 to 420. This is where the core configuration options related to debug symbols and related functionality are usually defined. I'll focus my attention there and see what the relationships are. |
| 8/2 | 2026/09/27 16:07 | tool | read-file |
0mArgs:{
"File": "lib/Kconfig.debug",
"FirstLine": 380,
"LineCount": 45
}Results: {
"Contents": " 380:\t\tdepends on $(cc-option,-gsplit-dwarf)\n 381:\t\t# RISC-V linker relaxation + -gsplit-dwarf has issues with LLVM and GCC\n 382:\t\t# prior to 12.x:\n 383:\t\t# https://github.com/llvm/llvm-project/issues/56642\n 384:\t\t# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99090\n 385:\t\tdepends on !RISCV || GCC_VERSION \u003e= 120000\n 386:\t\thelp\n 387:\t\t Generate debug info into separate .dwo files. This significantly\n 388:\t\t reduces the build directory size for builds with DEBUG_INFO,\n 389:\t\t because it stores the information only once on disk in .dwo\n 390:\t\t files instead of multiple times in object files and executables.\n 391:\t\t In addition the debug information is also compressed.\n 392:\t\n 393:\t\t Requires recent gcc (4.7+) and recent gdb/binutils.\n 394:\t\t Any tool that packages or reads debug information would need\n 395:\t\t to know about the .dwo files and include them.\n 396:\t\t Incompatible with older versions of ccache.\n 397:\t\n 398:\tconfig DEBUG_INFO_BTF\n 399:\t\ttristate \"Generate BTF type information\"\n 400:\t\tdepends on !DEBUG_INFO_SPLIT \u0026\u0026 !DEBUG_INFO_REDUCED\n 401:\t\tdepends on !GCC_PLUGIN_RANDSTRUCT || COMPILE_TEST\n 402:\t\tdepends on BPF_SYSCALL\n 403:\t\tdepends on PAHOLE_VERSION \u003e= 122\n 404:\t\t# pahole uses elfutils, which does not have support for Hexagon relocations\n 405:\t\tdepends on !HEXAGON\n 406:\t\thelp\n 407:\t\t Generate deduplicated BTF type information from DWARF debug info.\n 408:\t\t Turning this on requires pahole v1.22 or later, which will convert\n 409:\t\t DWARF type info into equivalent deduplicated BTF type info.\n 410:\t\n 411:\t\t If built as a module (=m), the vmlinux BTF is not part of the\n 412:\t\t kernel image. It is carried by the btf_vmlinux module, which is\n 413:\t\t loaded on demand the first time the BTF is needed: when a BPF\n 414:\t\t program requires kernel type information, or when\n 415:\t\t /sys/kernel/btf/vmlinux is opened. Until then, no memory is\n 416:\t\t spent on it. The vmlinux ELF file does not carry the BTF\n 417:\t\t either; module BTF is generated against vmlinux.unstripped, and\n 418:\t\t tools that read the BTF from a file can use that or\n 419:\t\t /sys/kernel/btf/vmlinux.\n 420:\t\n 421:\t\t Module BTF (DEBUG_INFO_BTF_MODULES) is kept when a module loads,\n 422:\t\t as with =y, and registered once the vmlinux BTF is available; the\n 423:\t\t saving is the vmlinux BTF only.\n 424:\t\n"
} |
| 9/2 | 2026/09/27 16:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39238 output: 38 thoughts: 1018 Thoughts: **Focusing Our Fuzzing Efforts** Okay, so I'm looking at this patch and thinking about where to direct the fuzzing efforts. First, I see we have these relevant configurations enabled: `CONFIG_BPF_SYSCALL`, `CONFIG_DEBUG_INFO_BTF`, `CONFIG_DEBUG_INFO_BTF_MODULES`, `CONFIG_MODULES`, and `CONFIG_SYSFS`. That gives me some context. Now, the core of my thought process is: *where* should we fuzz? I need to identify specific kernel functions that are likely targets, especially those introduced or heavily modified by this patch. I'm aiming for focused, non-ubiquitous functions – things that are central to the new logic but not used everywhere in the kernel. Let's see what we have. I'm going through the files one by one. In `kernel/bpf/btf.c`, I've got a slew of candidates: `btf_vmlinux_data`, `btf_parse_vmlinux`, `btf_parse_module`, a lot of `btf_module_...` functions, and a bunch of others dealing with registration and deferral. Then in `kernel/bpf/sysfs_btf.c`, there's `btf_sysfs_vmlinux_load`, `btf_sysfs_vmlinux_read`, and `btf_sysfs_vmlinux_mmap`. In `kernel/bpf/verifier.c`, I see `bpf_get_btf_vmlinux`, `bpf_peek_btf_vmlinux`, and `helper_uses_vmlinux_btf`. And in `kernel/bpf/syscall.c`, there's `__sys_bpf` which calls `bpf_get_btf_vmlinux`. My next step is to filter these down. I need to figure out which of these functions actually exist in the compiled kernel. Are they non-static, or are they static and can be exported as symbols? This is important. So, let's go back through and categorize them. I note that `btf_parse_deferred_modules`, `btf_vmlinux_data`, `btf_parse_vmlinux`, `bpf_get_btf_vmlinux`, and `bpf_peek_btf_vmlinux` are non-static. The others are static, but some are module notifier callbacks or otherwise useful. Now, my goal is to select a good set of focus symbols, ideally between three and eight specific functions. I need to choose ones that are directly tied to the new logic. Based on this, I'm thinking about these as good choices: * `bpf_get_btf_vmlinux` * `btf_parse_deferred_modules` * `btf_vmlinux_data` * `btf_parse_vmlinux` * `btf_module_notify` * `btf_sysfs_vmlinux_read` * `btf_sysfs_vmlinux_mmap` * `btf_defer_reg` However, a question just popped into my head: I wonder if `btf_sysfs_vmlinux_read` and `btf_sysfs_vmlinux_mmap` are *only* present when `CONFIG_DEBUG_INFO_BTF=m`? I'd better double-check `kernel/bpf/sysfs_btf.c` to be sure. It could change how I rank these. |
| 10/2 | 2026/09/27 16:07 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/sysfs_btf.c",
"FirstLine": 1,
"LineCount": 80
}Results: {
"Contents": " 1:\t// SPDX-License-Identifier: GPL-2.0\n 2:\t/*\n 3:\t * Provide kernel BTF information for introspection and use by eBPF tools.\n 4:\t */\n 5:\t#include \u003clinux/kernel.h\u003e\n 6:\t#include \u003clinux/module.h\u003e\n 7:\t#include \u003clinux/kobject.h\u003e\n 8:\t#include \u003clinux/init.h\u003e\n 9:\t#include \u003clinux/sysfs.h\u003e\n 10:\t#include \u003clinux/mm.h\u003e\n 11:\t#include \u003clinux/io.h\u003e\n 12:\t#include \u003clinux/bpf.h\u003e\n 13:\t#include \u003clinux/btf.h\u003e\n 14:\t#include \u003clinux/vmalloc.h\u003e\n 15:\t\n 16:\tstruct kobject *btf_kobj;\n 17:\t\n 18:\t#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)\n 19:\t/* See scripts/link-vmlinux.sh, gen_btf() func for details */\n 20:\textern char __start_BTF[];\n 21:\textern char __stop_BTF[];\n 22:\t\n 23:\tstatic int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,\n 24:\t\t\t\t\t const struct bin_attribute *attr,\n 25:\t\t\t\t\t struct vm_area_struct *vma)\n 26:\t{\n 27:\t\tunsigned long pages = PAGE_ALIGN(attr-\u003esize) \u003e\u003e PAGE_SHIFT;\n 28:\t\tsize_t vm_size = vma-\u003evm_end - vma-\u003evm_start;\n 29:\t\tphys_addr_t addr = __pa_symbol(__start_BTF);\n 30:\t\tunsigned long pfn = addr \u003e\u003e PAGE_SHIFT;\n 31:\t\n 32:\t\tif (attr-\u003eprivate != __start_BTF || !PAGE_ALIGNED(addr))\n 33:\t\t\treturn -EINVAL;\n 34:\t\n 35:\t\tif (vma-\u003evm_pgoff)\n 36:\t\t\treturn -EINVAL;\n 37:\t\n 38:\t\tif (vma-\u003evm_flags \u0026 (VM_WRITE | VM_EXEC | VM_MAYSHARE))\n 39:\t\t\treturn -EACCES;\n 40:\t\n 41:\t\tif (pfn + pages \u003c pfn)\n 42:\t\t\treturn -EINVAL;\n 43:\t\n 44:\t\tif ((vm_size \u003e\u003e PAGE_SHIFT) \u003e pages)\n 45:\t\t\treturn -EINVAL;\n 46:\t\n 47:\t\tvm_flags_mod(vma, VM_DONTDUMP, VM_MAYEXEC | VM_MAYWRITE);\n 48:\t\treturn remap_pfn_range(vma, vma-\u003evm_start, pfn, vm_size, vma-\u003evm_page_prot);\n 49:\t}\n 50:\t\n 51:\tstatic struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {\n 52:\t\t.attr = { .name = \"vmlinux\", .mode = 0444, },\n 53:\t\t.read = sysfs_bin_attr_simple_read,\n 54:\t\t.mmap = btf_sysfs_vmlinux_mmap,\n 55:\t};\n 56:\t\n 57:\tstatic void __init btf_sysfs_vmlinux_init(void)\n 58:\t{\n 59:\t\tbin_attr_btf_vmlinux.private = __start_BTF;\n 60:\t\tbin_attr_btf_vmlinux.size = __stop_BTF - __start_BTF;\n 61:\t}\n 62:\t\n 63:\t#else /* CONFIG_DEBUG_INFO_BTF=m */\n 64:\t\n 65:\t/*\n 66:\t * The BTF is carried by the btf_vmlinux module and only loaded when\n 67:\t * something needs it. Its size is known from the start, so the file has\n 68:\t * its final size from boot; the first read() or mmap() loads the BTF.\n 69:\t */\n 70:\tstatic void *btf_sysfs_vmlinux_load(u32 *size)\n 71:\t{\n 72:\t\t/* Loads the module, parses the BTF and registers module BTFs. */\n 73:\t\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))\n 74:\t\t\treturn NULL;\n 75:\t\treturn btf_vmlinux_data(size, false);\n 76:\t}\n 77:\t\n 78:\tstatic ssize_t btf_sysfs_vmlinux_read(struct file *filp, struct kobject *kobj,\n 79:\t\t\t\t\t const struct bin_attribute *attr,\n 80:\t\t\t\t\t char *buf, loff_t off, size_t count)\n"
} |
| 11/2 | 2026/09/27 16:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 42398 output: 39 thoughts: 133 Thoughts: Here's my analysis of the `btf_sysfs_vmlinux_mmap` situation: **Understanding the `btf_sysfs_vmlinux_mmap` Implementation** Okay, so I see that `btf_sysfs_vmlinux_mmap` is actually *present* in both the `#if IS_BUILTIN` and the `#else` blocks of code. Interesting, I thought it was just one or the other based on the config. It's just implemented slightly differently. In the `#if IS_BUILTIN` case, good, it's the expected function, and it's been there for a while. However, when `CONFIG_DEBUG_INFO_BTF=m` (i.e., the `#else` case), it gets more complex. Now we have *both* `btf_sysfs_vmlinux_read` and `btf_sysfs_vmlinux_mmap` defined. I need to figure out how these two work together and what their relationship is. I need to fully understand this logic path. I should probably dig into the rest of `kernel/bpf/sysfs_btf.c` to understand how these functions fit into the overall picture. |
| 12/2 | 2026/09/27 16:07 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/sysfs_btf.c",
"FirstLine": 81,
"LineCount": 70
}Results: {
"Contents": " 81:\t{\n 82:\t\tu32 size;\n 83:\t\tvoid *data = btf_sysfs_vmlinux_load(\u0026size);\n 84:\t\n 85:\t\tif (!data)\n 86:\t\t\treturn -ENODEV;\n 87:\t\n 88:\t\t/* sysfs clamps @off and @count to attr-\u003esize, which is @size */\n 89:\t\tmemcpy(buf, data + off, count);\n 90:\t\treturn count;\n 91:\t}\n 92:\t\n 93:\tstatic int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,\n 94:\t\t\t\t\t const struct bin_attribute *attr,\n 95:\t\t\t\t\t struct vm_area_struct *vma)\n 96:\t{\n 97:\t\tsize_t vm_size = vma-\u003evm_end - vma-\u003evm_start;\n 98:\t\tu32 size;\n 99:\t\tvoid *data = btf_sysfs_vmlinux_load(\u0026size);\n 100:\t\n 101:\t\tif (!data)\n 102:\t\t\treturn -ENODEV;\n 103:\t\n 104:\t\tif (vma-\u003evm_pgoff)\n 105:\t\t\treturn -EINVAL;\n 106:\t\n 107:\t\tif (vma-\u003evm_flags \u0026 (VM_WRITE | VM_EXEC | VM_MAYSHARE))\n 108:\t\t\treturn -EACCES;\n 109:\t\n 110:\t\tif (vm_size \u003e PAGE_ALIGN(size))\n 111:\t\t\treturn -EINVAL;\n 112:\t\n 113:\t\tvm_flags_mod(vma, VM_DONTDUMP, VM_MAYEXEC | VM_MAYWRITE);\n 114:\t\t/* the copy was made with vmalloc_user() for this purpose */\n 115:\t\treturn remap_vmalloc_range(vma, data, 0);\n 116:\t}\n 117:\t\n 118:\tstatic struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {\n 119:\t\t.attr = { .name = \"vmlinux\", .mode = 0444, },\n 120:\t\t.read = btf_sysfs_vmlinux_read,\n 121:\t\t.mmap = btf_sysfs_vmlinux_mmap,\n 122:\t};\n 123:\t\n 124:\tstatic void __init btf_sysfs_vmlinux_init(void)\n 125:\t{\n 126:\t\tu32 size;\n 127:\t\n 128:\t\t/* known before the BTF is loaded, see .BTF.meta */\n 129:\t\tbtf_vmlinux_data(\u0026size, false);\n 130:\t\tbin_attr_btf_vmlinux.size = size;\n 131:\t}\n 132:\t#endif\n 133:\t\n 134:\tstatic int __init btf_vmlinux_init(void)\n 135:\t{\n 136:\t\tbtf_sysfs_vmlinux_init();\n 137:\t\n 138:\t\tif (bin_attr_btf_vmlinux.size == 0)\n 139:\t\t\treturn 0;\n 140:\t\n 141:\t\tbtf_kobj = kobject_create_and_add(\"btf\", kernel_kobj);\n 142:\t\tif (!btf_kobj)\n 143:\t\t\treturn -ENOMEM;\n 144:\t\n 145:\t\treturn sysfs_create_bin_file(btf_kobj, \u0026bin_attr_btf_vmlinux);\n 146:\t}\n 147:\t\n 148:\tsubsys_initcall(btf_vmlinux_init);\n"
} |
| 13/2 | 2026/09/27 16:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 43881 output: 286 thoughts: 1277 Thoughts: **Focus Symbol & Configuration Analysis for BTF Module Support** Alright, let's break this down. My goal is to determine the best focus symbols and configurations for fuzzing the new BTF module support. First, I need to identify the key functions involved. Starting with `btf_vmlinux_data` in `kernel/bpf/btf.c`, I see it's exported in `include/linux/btf.h` and used alongside `btf_parse_deferred_modules`, `bpf_get_btf_vmlinux`, `bpf_peek_btf_vmlinux`, and `btf_parse_vmlinux`. Then I checked for other relevant functions within `btf.c`, such as `btf_module_notify`, `btf_defer_reg`, and the static `btf_module_sysfs_read_deferred` and `btf_parse_module`. Now, keeping the FocusSymbols guidelines in mind – avoiding ubiquitous functions and targeting specific feature logic – I've listed these candidates: * `bpf_get_btf_vmlinux` * `btf_vmlinux_data` * `btf_parse_deferred_modules` * `btf_parse_vmlinux` * `btf_module_notify` * `btf_sysfs_vmlinux_read` * `btf_sysfs_vmlinux_mmap` * `btf_defer_reg` I've made sure to clarify if these are non-ubiquitous: and confirmed that `btf_defer_reg` and `btf_parse_deferred_modules` are specific to deferred BTF registrations with `CONFIG_DEBUG_INFO_BTF=m`, thus good focus symbol candidates. `bpf_get_btf_vmlinux` is involved in BPF verification and sysfs access for loading vmlinux BTF; `btf_vmlinux_data` accesses the raw BTF data; `btf_module_notify` handles module events for BTF; and `btf_sysfs_vmlinux_read` and `btf_sysfs_vmlinux_mmap` are related to the sysfs handlers for `/sys/kernel/btf/vmlinux`. Next, I've checked the required configurations. The following are required: `DEBUG_INFO_BTF`, `DEBUG_INFO_BTF_MODULES`, `BPF_SYSCALL`, `SYSFS`, and `MODULES`. I see in the Makefile that `sysfs_btf.o` depends on `CONFIG_SYSFS` and `CONFIG_DEBUG_INFO_BTF` and that `btf_vmlinux.o` depends on `CONFIG_DEBUG_INFO_BTF=m`. Finally, confirming the fuzzing strategy: Given the substantial new logic added – deferred BTF parsing, module notifications, synchronization primitives, SHA-256 integrity validation, and sysfs handlers – reaching the BPF syscall, sysfs BTF access, and module loading, `WorthFuzzing = true`. I can now call `set-results`. |
| 14/2 | 2026/09/27 16:07 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"DEBUG_INFO_BTF",
"DEBUG_INFO_BTF_MODULES",
"BPF_SYSCALL",
"SYSFS",
"MODULES"
],
"FocusSymbols": [
"bpf_get_btf_vmlinux",
"btf_vmlinux_data",
"btf_parse_deferred_modules",
"btf_parse_vmlinux",
"btf_module_notify",
"btf_sysfs_vmlinux_read",
"btf_sysfs_vmlinux_mmap",
"btf_defer_reg"
],
"Reasoning": "The patch series adds support for building kernel BTF type information as a loadable module (CONFIG_DEBUG_INFO_BTF=m). It introduces significant logic and state handling across core BPF, BTF parsing, sysfs, verifier, and module notifier code paths, including on-demand loading of BTF, deferred module BTF parsing, queuing and draining of kfunc/struct_ops registrations, wait queue synchronization, SHA-256 integrity verification, and custom sysfs mmap/read handlers. These paths are directly exposed to userspace through sysfs and the BPF syscall.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"DEBUG_INFO_BTF",
"DEBUG_INFO_BTF_MODULES",
"BPF_SYSCALL",
"SYSFS",
"MODULES"
],
"FocusSymbols": [
"bpf_get_btf_vmlinux",
"btf_vmlinux_data",
"btf_parse_deferred_modules",
"btf_parse_vmlinux",
"btf_module_notify",
"btf_sysfs_vmlinux_read",
"btf_sysfs_vmlinux_mmap",
"btf_defer_reg"
],
"Reasoning": "The patch series adds support for building kernel BTF type information as a loadable module (CONFIG_DEBUG_INFO_BTF=m). It introduces significant logic and state handling across core BPF, BTF parsing, sysfs, verifier, and module notifier code paths, including on-demand loading of BTF, deferred module BTF parsing, queuing and draining of kfunc/struct_ops registrations, wait queue synchronization, SHA-256 integrity verification, and custom sysfs mmap/read handlers. These paths are directly exposed to userspace through sysfs and the BPF syscall.",
"WorthFuzzing": true
} |
| 15/1 | 2026/09/27 16:07 | action | If |
0mArgs:{
"WorthFuzzing": true
}Results: null |
| 16/2 | 2026/09/27 16:07 | agent | kmsan-evaluator |
0mModel:core Args: null Results: {
"KMSANReasoning": "The patch series introduces support for building kernel BTF as an on-demand module (CONFIG_DEBUG_INFO_BTF=m). It adds on-demand module loading, deferred registration queues for kfuncs and struct_ops, and sysfs handling for unparsed/deferred BTF data.\n\nKMSAN vs KASAN applicability analysis:\n1. Heap and stack structures: All new data structures (such as struct btf_module, struct bin_attribute, and verifier logs) are allocated using kzalloc_obj() or vmalloc_user(), ensuring zero-initialization. Deferred registration entries and BTF data buffers are cloned via kmemdup()/kvmemdup() with explicit sizes.\n2. User space memory transfers: Sysfs binary file read() and mmap() handlers (/sys/kernel/btf/*) operate on buffers fully populated from the module ELF sections with bounds clamped to the validated section size, posing no risk of uninitialized memory info-leaks.\n3. No branching or logic depends on uninitialized memory.\n4. The risks introduced by this change center around module lifecycle, concurrency (lock ordering, waitqueue synchronization), and resource management (use-after-free, memory leaks), which are detectable by KASAN, LOCKDEP, and KMEMLEAK.\n\nTherefore, dedicated KMSAN fuzzing is not justified for these changes.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit d1f4e4b40f45a48572f7ab842ce9ed972bf1576d
Author: syz-cluster <triage@syzkaller.com>
Date: Sun Sep 27 16:07:09 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/bpf/btf.rst b/Documentation/bpf/btf.rst
index 004aa1058d857..b637f83c85c4c 100644
--- a/Documentation/bpf/btf.rst
+++ b/Documentation/bpf/btf.rst
@@ -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
==========
diff --git a/Makefile b/Makefile
index 66654fa71655b..0a37decd9d013 100644
--- a/Makefile
+++ b/Makefile
@@ -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
@@ -1744,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
diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h
index b2988aa12f664..204a9ee171c6d 100644
--- a/include/asm-generic/vmlinux.lds.h
+++ b/include/asm-generic/vmlinux.lds.h
@@ -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) } \
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index e7c5e203edddb..a3c4caad5dfc6 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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;
diff --git a/include/linux/btf.h b/include/linux/btf.h
index ddd0f4f32d24b..586361fa03a0a 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -581,6 +581,12 @@ __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);
+#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);
diff --git a/include/linux/btf_ids.h b/include/linux/btf_ids.h
index 8b5a9ee92513d..c665afff100e7 100644
--- a/include/linux/btf_ids.h
+++ b/include/linux/btf_ids.h
@@ -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 */
diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h
index c5921f1390079..a90a99849ceed 100644
--- a/include/linux/compiler_types.h
+++ b/include/linux/compiler_types.h
@@ -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
diff --git a/include/linux/module.h b/include/linux/module.h
index 96cc98568eea5..82734996a862b 100644
--- a/include/linux/module.h
+++ b/include/linux/module.h
@@ -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;
diff --git a/include/trace/trace_events.h b/include/trace/trace_events.h
index 93011f800d0f7..2a0098929771b 100644
--- a/include/trace/trace_events.h
+++ b/include/trace/trace_events.h
@@ -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)
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index 9a92c348bbda6..8ab46f496fa48 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -41,7 +41,11 @@ 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
+# 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
diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c
index 1178acd72296e..bf3004908d15a 100644
--- a/kernel/bpf/bpf_struct_ops.c
+++ b/kernel/bpf/bpf_struct_ops.c
@@ -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",
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 4a1fa4fbdf4e8..00d65199b45e4 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -29,6 +29,7 @@
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/overflow.h>
+#include <crypto/sha2.h>
#include <linux/bitops.h>
#include <net/netfilter/nf_bpf_link.h>
@@ -6092,10 +6093,73 @@ static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,
return ERR_PTR(err);
}
+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)
extern char __start_BTF[];
extern char __stop_BTF[];
+#endif
extern struct btf *btf_vmlinux;
+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+/*
+ * With CONFIG_DEBUG_INFO_BTF=m the vmlinux BTF is not part of the kernel
+ * image. The btf_vmlinux module carries it in its .BTF section; when the
+ * module loads, btf_module_notify() copies the section here. The copy is
+ * made with vmalloc_user() so that /sys/kernel/btf/vmlinux can be mmap()ed
+ * as with the built-in BTF. Set once, never cleared: like the built-in
+ * BTF, once present it stays for the lifetime of the kernel.
+ *
+ * The size and SHA-256 of the BTF are linked into the kernel as .BTF.meta
+ * by scripts/gen-btf.sh: the size makes /sys/kernel/btf/vmlinux report its
+ * size before the BTF is loaded, the hash makes sure only the BTF this
+ * kernel was built with is accepted.
+ */
+struct btf_vmlinux_meta {
+ u32 size;
+ u8 sha256[SHA256_DIGEST_SIZE];
+} __packed;
+
+extern const struct btf_vmlinux_meta __start_BTF_meta[];
+#define btf_vmlinux_meta (__start_BTF_meta[0])
+
+static void *btf_vmlinux_raw;
+#endif
+
+/**
+ * btf_vmlinux_data - get the raw vmlinux BTF
+ * @size: where to store the size of the BTF, also when it is not loaded yet
+ * @load: with CONFIG_DEBUG_INFO_BTF=m, load the btf_vmlinux module if the
+ * BTF is not present yet; may sleep
+ *
+ * Return: the raw BTF, or NULL if it is not available.
+ */
+void *btf_vmlinux_data(u32 *size, bool load)
+{
+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)
+ *size = __stop_BTF - __start_BTF;
+ return __start_BTF;
+#elif IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+ /* Pairs with the smp_store_release() in btf_vmlinux_module_coming() */
+ void *data = smp_load_acquire(&btf_vmlinux_raw);
+
+ 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");
+ /* Same pairing as above */
+ data = smp_load_acquire(&btf_vmlinux_raw);
+ }
+ *size = btf_vmlinux_meta.size;
+ return data;
+#else
+ *size = 0;
+ return NULL;
+#endif
+}
+
#define BPF_MAP_TYPE(_id, _ops)
#define BPF_LINK_TYPE(_id, _name)
static union {
@@ -6126,12 +6190,25 @@ static u8 bpf_ctx_convert_map[] = {
#undef BPF_MAP_TYPE
#undef BPF_LINK_TYPE
+/*
+ * bpf_ctx_convert.t is filled in by btf_parse_vmlinux(). With
+ * CONFIG_DEBUG_INFO_BTF=m that may not have run yet: the program context
+ * types are kernel types too, so this is one of the places that loads the
+ * vmlinux BTF. Only called from the verifier, which may sleep.
+ */
+static const struct btf_type *bpf_ctx_convert_type(void)
+{
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+ return NULL;
+ return bpf_ctx_convert.t;
+}
+
static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
{
const struct btf_type *conv_struct;
const struct btf_member *ctx_type;
- conv_struct = bpf_ctx_convert.t;
+ conv_struct = bpf_ctx_convert_type();
if (!conv_struct)
return NULL;
/* prog_type is valid bpf program type. No need for bounds check. */
@@ -6147,7 +6224,7 @@ static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
const struct btf_type *conv_struct;
const struct btf_member *ctx_type;
- conv_struct = bpf_ctx_convert.t;
+ conv_struct = bpf_ctx_convert_type();
if (!conv_struct)
return -EFAULT;
/* prog_type is valid bpf program type. No need for bounds check. */
@@ -6406,7 +6483,11 @@ int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_ty
const struct btf_type *kctx_type;
u32 kctx_type_id;
- conv_struct = bpf_ctx_convert.t;
+ conv_struct = bpf_ctx_convert_type();
+ if (!conv_struct) {
+ bpf_log(log, "btf_vmlinux is malformed\n");
+ return -EINVAL;
+ }
/* get member for kernel ctx type */
kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
kctx_type_id = kctx_member->type;
@@ -6474,20 +6555,29 @@ static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name
return 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;
struct bpf_verifier_log *log;
struct btf *btf;
+ void *data;
+ u32 size;
int err;
+ /* The caller made sure the BTF is present, see bpf_get_btf_vmlinux() */
+ data = btf_vmlinux_data(&size, false);
+ if (!data)
+ return ERR_PTR(-ENOENT);
+
env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
if (!env)
return ERR_PTR(-ENOMEM);
log = &env->log;
log->level = BPF_LOG_KERNEL;
- btf = btf_parse_base(env, "vmlinux", __start_BTF, __stop_BTF - __start_BTF);
+ btf = btf_parse_base(env, "vmlinux", data, size);
if (IS_ERR(btf))
goto err_out;
@@ -6495,9 +6585,18 @@ struct btf *btf_parse_vmlinux(void)
bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
err = btf_alloc_id(btf);
if (err) {
+ 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;
@@ -6514,18 +6613,22 @@ __u32 btf_relocate_id(const struct btf *btf, __u32 id)
return btf->base_id_map[id];
}
-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)
-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 +6665,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,14 +6711,15 @@ 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);
}
return ERR_PTR(err);
}
-#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
+#endif /* CONFIG_DEBUG_INFO_BTF_MODULES || CONFIG_DEBUG_INFO_BTF=m */
struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
{
@@ -7876,6 +7983,13 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
t = btf_type_by_id(btf, t->type);
}
+ /* candidates are kernel types: load the vmlinux BTF, outside the mutex */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
+ bpf_log(log, "arg#%d reference type('%s %s') needs the vmlinux BTF\n",
+ arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
+ return -EINVAL;
+ }
+
mutex_lock(&cand_cache_mutex);
cc = bpf_core_find_cands(&ctx, type_id);
if (IS_ERR(cc)) {
@@ -8227,7 +8341,10 @@ int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
if (kern_type_id < 0)
return kern_type_id;
+ /* present: btf_get_ptr_to_btf_id() found the candidate in it */
vmlinux_btf = bpf_get_btf_vmlinux();
+ if (IS_ERR_OR_NULL(vmlinux_btf))
+ return -EINVAL;
ref_t = btf_type_by_id(vmlinux_btf, kern_type_id);
if (!btf_type_is_struct(ref_t)) {
tname = __btf_name_by_offset(vmlinux_btf, t->name_off);
@@ -8596,20 +8713,270 @@ enum {
BTF_MODULE_F_LIVE = (1 << 0),
};
-#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+/*
+ * The module notifier registers module BTF (CONFIG_DEBUG_INFO_BTF_MODULES)
+ * and picks up the vmlinux BTF from the btf_vmlinux module
+ * (CONFIG_DEBUG_INFO_BTF=m).
+ */
+#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+#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() and btf_apply_deferred_regs().
+ */
+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
+static void btf_free_deferred_regs(struct list_head *regs);
+static void btf_apply_deferred_regs(struct btf *btf, struct list_head *regs);
+
struct btf_module {
struct list_head list;
struct module *module;
struct btf *btf;
struct bin_attribute *sysfs_attr;
int flags;
+ /*
+ * CONFIG_DEBUG_INFO_BTF=m: a module loaded before the vmlinux BTF is
+ * available cannot have its BTF parsed yet. Its .BTF and .BTF.base
+ * sections are copied here and parsed once the vmlinux BTF arrives
+ * (btf_parse_deferred_modules()); @btf is NULL until then.
+ * Registrations of the module's kfuncs, dtor kfuncs and struct_ops
+ * wait in @deferred_regs.
+ */
+ void *data;
+ void *base_data;
+ u32 data_size;
+ u32 base_data_size;
+ struct list_head deferred_regs;
+ /*
+ * 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 *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;
+
+ 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 = size;
+ attr->private = private;
+ attr->read = 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;
+}
+
+/*
+ * 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) {
+ purge_cand_cache(btf_mod->btf);
+ btf_put(btf_mod->btf);
+ } else {
+ kvfree(btf_mod->data);
+ kvfree(btf_mod->base_data);
+ }
+ btf_free_deferred_regs(&btf_mod->deferred_regs);
+ kfree(btf_mod->sysfs_attr);
+ kfree(btf_mod);
+}
+
+#if IS_MODULE(CONFIG_DEBUG_INFO_BTF)
+/*
+ * The btf_vmlinux module carries the vmlinux BTF in its .BTF section
+ * (scripts/gen-btf.sh). Keep a copy; the module is only the carrier and
+ * has no BTF of its own.
+ */
+static int btf_vmlinux_module_coming(struct module *mod)
+{
+ u8 sha256sum[SHA256_DIGEST_SIZE];
+ void *data;
+
+ if (btf_vmlinux_raw)
+ return 0;
+
+ /*
+ * The verifier trusts the BTF as the description of this kernel's
+ * types, so a BTF from a different build must not get in even if
+ * the module otherwise loads (same release string, same vermagic).
+ */
+ if (mod->btf_data_size != btf_vmlinux_meta.size) {
+ pr_err("module [%s]: BTF size %u does not match this kernel (%u)\n",
+ mod->name, mod->btf_data_size, btf_vmlinux_meta.size);
+ return -EINVAL;
+ }
+ sha256(mod->btf_data, mod->btf_data_size, sha256sum);
+ if (memcmp(sha256sum, btf_vmlinux_meta.sha256, sizeof(sha256sum))) {
+ pr_err("module [%s]: BTF does not match this kernel\n", mod->name);
+ return -EINVAL;
+ }
+
+ data = vmalloc_user(mod->btf_data_size);
+ if (!data)
+ return -ENOMEM;
+ memcpy(data, mod->btf_data, mod->btf_data_size);
+
+ /* Pairs with the smp_load_acquire() in btf_vmlinux_data() */
+ smp_store_release(&btf_vmlinux_raw, data);
+ 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().
+ *
+ * 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)
+{
+ btf_mod->data = kvmemdup(mod->btf_data, mod->btf_data_size,
+ GFP_KERNEL | __GFP_NOWARN);
+ if (!btf_mod->data)
+ return -ENOMEM;
+ btf_mod->data_size = mod->btf_data_size;
+
+ if (mod->btf_base_data) {
+ btf_mod->base_data = kvmemdup(mod->btf_base_data,
+ mod->btf_base_data_size,
+ GFP_KERNEL | __GFP_NOWARN);
+ if (!btf_mod->base_data) {
+ kvfree(btf_mod->data);
+ return -ENOMEM;
+ }
+ btf_mod->base_data_size = mod->btf_base_data_size;
+ /* 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, sysfs_bin_attr_simple_read);
+ }
+
+ list_add(&btf_mod->list, &btf_modules);
+ return 0;
+}
+#else
+static int btf_vmlinux_module_coming(struct module *mod)
+{
+ return 0;
+}
+
+static int btf_module_defer(struct btf_module *btf_mod, struct module *mod)
+{
+ return 0;
+}
+#endif
+
static int btf_module_notify(struct notifier_block *nb, unsigned long op,
void *module)
{
@@ -8618,9 +8985,17 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
struct btf *btf;
int err = 0;
- if (mod->btf_data_size == 0 ||
- (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
- op != MODULE_STATE_GOING))
+ if (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
+ op != MODULE_STATE_GOING)
+ goto out;
+
+ if (IS_MODULE(CONFIG_DEBUG_INFO_BTF) && !strcmp(mod->name, "btf_vmlinux")) {
+ if (op == MODULE_STATE_COMING)
+ err = btf_vmlinux_module_coming(mod);
+ goto out;
+ }
+
+ if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES) || mod->btf_data_size == 0)
goto out;
switch (op) {
@@ -8630,7 +9005,28 @@ 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;
+ INIT_LIST_HEAD(&btf_mod->deferred_regs);
+
+ if (IS_MODULE(CONFIG_DEBUG_INFO_BTF)) {
+ mutex_lock(&btf_module_mutex);
+ /* Pairs with the publication in bpf_get_btf_vmlinux() */
+ if (!smp_load_acquire(&btf_vmlinux)) {
+ err = btf_module_defer(btf_mod, mod);
+ mutex_unlock(&btf_module_mutex);
+ if (err) {
+ pr_warn("failed to keep module [%s] BTF: %d\n",
+ mod->name, err);
+ kfree(btf_mod);
+ err = 0;
+ }
+ goto out;
+ }
+ mutex_unlock(&btf_module_mutex);
+ }
+
+ 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 +9048,13 @@ 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,
+ sysfs_bin_attr_simple_read);
break;
case MODULE_STATE_LIVE:
mutex_lock(&btf_module_mutex);
@@ -8691,6 +9063,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.
+ */
+ 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;
+ }
break;
}
mutex_unlock(&btf_module_mutex);
@@ -8707,15 +9099,13 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
* btf_try_get_module() on such BTFs will fail. This may
* be called again on btf_put(), but it's ok to do so.
*/
- btf_free_id(btf_mod->btf);
+ if (btf_mod->btf)
+ 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);
- break;
+ mutex_unlock(&btf_module_mutex);
+ /* off the list, nobody else can find it now */
+ btf_module_free(btf_mod);
+ goto out;
}
mutex_unlock(&btf_module_mutex);
break;
@@ -8735,7 +9125,107 @@ static int __init btf_module_init(void)
}
fs_initcall(btf_module_init);
-#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
+
+#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. 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)
+{
+ 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);
+ 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 -- 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
+ * its kfuncs and struct_ops, as with the vmlinux BTF. Applying walks
+ * btf_modules (btf_check_kfunc_name()) and so needs the mutex dropped; the
+ * module is pinned for that, and the scan restarts afterwards. A module
+ * that is still initializing is only published: its init is still queueing
+ * registrations, and MODULE_STATE_LIVE applies them once it is done.
+ */
+void btf_parse_deferred_modules(void)
+{
+ /* Pairs with the publication in bpf_get_btf_vmlinux() */
+ struct btf *vmlinux_btf = smp_load_acquire(&btf_vmlinux);
+ struct btf_module *btf_mod;
+ bool parsed = false;
+ LIST_HEAD(regs);
+ struct btf *btf;
+ int err;
+
+ if (IS_ERR_OR_NULL(vmlinux_btf))
+ return;
+
+ mutex_lock(&btf_module_mutex);
+restart:
+ list_for_each_entry(btf_mod, &btf_modules, list) {
+ if (btf_mod->btf || btf_mod->gone)
+ continue;
+
+ btf = btf_parse_module(btf_mod->module->name, vmlinux_btf,
+ btf_mod->data, btf_mod->data_size, true,
+ btf_mod->base_data, btf_mod->base_data_size);
+ if (IS_ERR(btf)) {
+ /* on failure the caller keeps the data */
+ btf_module_dead(btf_mod, "validate", PTR_ERR(btf));
+ continue;
+ }
+ /* btf->data is btf_mod->data now, the sysfs file keeps pointing at valid data */
+ kvfree(btf_mod->base_data);
+ btf_mod->base_data = NULL;
+
+ if ((btf_mod->flags & BTF_MODULE_F_LIVE) &&
+ try_module_get(btf_mod->module)) {
+ list_splice_init(&btf_mod->deferred_regs, ®s);
+ mutex_unlock(&btf_module_mutex);
+ btf_apply_deferred_regs(btf, ®s);
+ mutex_lock(&btf_module_mutex);
+ module_put(btf_mod->module);
+ }
+
+ err = btf_alloc_id(btf);
+ if (err) {
+ /* give the data back to the entry, the sysfs file may serve it */
+ btf->data = NULL;
+ btf_free(btf);
+ btf_module_dead(btf_mod, "register", err);
+ goto restart;
+ }
+
+ 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;
+ }
+ mutex_unlock(&btf_module_mutex);
+
+ if (parsed)
+ purge_cand_cache(NULL);
+}
+#endif /* IS_MODULE(CONFIG_DEBUG_INFO_BTF) */
+#endif /* BTF_MODULE_NOTIFIER */
struct module *btf_try_get_module(const struct btf *btf)
{
@@ -8787,8 +9277,11 @@ struct btf *btf_get_module_btf(const struct module *module)
if (btf_mod->module != module)
continue;
- btf_get(btf_mod->btf);
- btf = btf_mod->btf;
+ /* NULL while waiting for the vmlinux BTF (CONFIG_DEBUG_INFO_BTF=m) */
+ if (btf_mod->btf) {
+ btf_get(btf_mod->btf);
+ btf = btf_mod->btf;
+ }
break;
}
mutex_unlock(&btf_module_mutex);
@@ -8950,12 +9443,18 @@ static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind
#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
struct btf_module *btf_mod, *tmp;
#endif
+ struct btf *vmlinux_btf;
s32 id;
if (!btf_is_module(btf))
return 0;
- id = btf_find_by_name_kind(bpf_get_btf_vmlinux(), func_name, kind);
+ /* a module BTF only exists once the vmlinux BTF is parsed */
+ vmlinux_btf = bpf_get_btf_vmlinux();
+ if (IS_ERR_OR_NULL(vmlinux_btf))
+ return -EINVAL;
+
+ id = btf_find_by_name_kind(vmlinux_btf, func_name, kind);
if (id >= 0) {
pr_err("kfunc %s (id: %d) is already present in vmlinux.\n",
func_name, id);
@@ -8965,7 +9464,8 @@ static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind
#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
guard(mutex)(&btf_module_mutex);
list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
- if (btf_mod->btf == btf)
+ /* skip ourselves and, with CONFIG_DEBUG_INFO_BTF=m, unparsed BTF */
+ if (btf_mod->btf == btf || !btf_mod->btf)
continue;
id = btf_find_by_name_kind(btf_mod->btf, func_name, kind);
if (id >= 0) {
@@ -9290,11 +9790,36 @@ u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
return btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
}
+static int btf_kfunc_id_set_add(struct btf *btf, enum btf_kfunc_hook hook,
+ const struct btf_kfunc_id_set *kset)
+{
+ int ret, i;
+
+ for (i = 0; i < kset->set->cnt; i++) {
+ ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
+ kset->set->pairs[i].flags);
+ if (ret)
+ return ret;
+ }
+
+ 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, i;
+ 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)
@@ -9302,16 +9827,7 @@ static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
if (IS_ERR(btf))
return PTR_ERR(btf);
- for (i = 0; i < kset->set->cnt; i++) {
- ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
- kset->set->pairs[i].flags);
- if (ret)
- goto err_out;
- }
-
- ret = btf_populate_kfunc_set(btf, hook, kset);
-
-err_out:
+ ret = btf_kfunc_id_set_add(btf, hook, kset);
btf_put(btf);
return ret;
}
@@ -9403,21 +9919,13 @@ static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc
return 0;
}
-/* This function must be invoked only from initcalls/module init functions */
-int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
- struct module *owner)
+static int btf_dtor_kfuncs_add(struct btf *btf, const struct btf_id_dtor_kfunc *dtors,
+ u32 add_cnt)
{
struct btf_id_dtor_kfunc_tab *tab;
- struct btf *btf;
u32 tab_cnt, i;
int ret;
- btf = btf_get_module_btf(owner);
- if (!btf)
- return check_btf_kconfigs(owner, "dtor kfuncs");
- if (IS_ERR(btf))
- return PTR_ERR(btf);
-
if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
ret = -E2BIG;
@@ -9474,6 +9982,31 @@ int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_c
end:
if (ret)
btf_free_dtor_kfunc_tab(btf);
+ return ret;
+}
+
+/* This function must be invoked only from initcalls/module init functions */
+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");
+ if (IS_ERR(btf))
+ return PTR_ERR(btf);
+
+ ret = btf_dtor_kfuncs_add(btf, dtors, add_cnt);
btf_put(btf);
return ret;
}
@@ -9677,6 +10210,11 @@ static void purge_cand_cache(struct btf *btf)
__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
mutex_unlock(&cand_cache_mutex);
}
+#elif defined(BTF_MODULE_NOTIFIER)
+/* CONFIG_DEBUG_INFO_BTF=m without module BTF: nothing is ever cached */
+static void purge_cand_cache(struct btf *btf)
+{
+}
#endif
static struct bpf_cand_cache *
@@ -9740,9 +10278,11 @@ bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
const char *name;
int id;
- main_btf = bpf_get_btf_vmlinux();
- if (IS_ERR(main_btf))
- return ERR_CAST(main_btf);
+ /*
+ * Callers fetch the vmlinux BTF before taking cand_cache_mutex, so
+ * that loading it (CONFIG_DEBUG_INFO_BTF=m) happens outside the lock.
+ */
+ main_btf = bpf_peek_btf_vmlinux();
if (!main_btf)
return ERR_PTR(-EINVAL);
@@ -9845,6 +10385,13 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
struct bpf_cand_cache *cc;
int i;
+ /* candidates are kernel types: load the vmlinux BTF, outside the mutex */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
+ bpf_log(ctx->log, "relo #%u: needs the vmlinux BTF\n", relo_idx);
+ kfree(specs);
+ return -EINVAL;
+ }
+
mutex_lock(&cand_cache_mutex);
cc = bpf_core_find_cands(ctx, relo->type_id);
if (IS_ERR(cc)) {
@@ -10112,11 +10659,35 @@ bpf_struct_ops_find(struct btf *btf, u32 type_id)
return NULL;
}
-int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
+static int btf_struct_ops_register(struct btf *btf, struct bpf_struct_ops *st_ops)
{
struct bpf_verifier_log *log;
+ int err;
+
+ log = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);
+ if (!log)
+ return -ENOMEM;
+
+ log->level = BPF_LOG_KERNEL;
+
+ err = btf_add_struct_ops(btf, st_ops, log);
+
+ kfree(log);
+ return err;
+}
+
+int __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 = 0;
+ 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)
@@ -10124,24 +10695,183 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
if (IS_ERR(btf))
return PTR_ERR(btf);
- log = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);
- if (!log) {
- err = -ENOMEM;
- goto errout;
+ err = btf_struct_ops_register(btf, st_ops);
+ btf_put(btf);
+ 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 made before the BTF they apply to
+ * is available. Registrations for vmlinux wait in btf_vmlinux_deferred_regs
+ * until btf_parse_vmlinux() applies them; registrations for a module wait in
+ * its struct btf_module, under btf_module_mutex, until
+ * btf_parse_deferred_modules() does.
+ */
+#ifdef BTF_MODULE_NOTIFIER
+/*
+ * The vmlinux 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.
+ */
+static int btf_defer_reg(struct module *owner, const struct btf_deferred_reg *tmpl)
+{
+ struct list_head *head = NULL;
+ struct btf_deferred_reg *reg;
+ struct btf_module *btf_mod;
+
+ if (!IS_MODULE(CONFIG_DEBUG_INFO_BTF))
+ return 0;
+
+ guard(mutex)(owner ? &btf_module_mutex : &btf_vmlinux_regs_mutex);
+ if (!owner) {
+ if (!btf_vmlinux_regs_closed)
+ head = &btf_vmlinux_deferred_regs;
+ } else {
+ list_for_each_entry(btf_mod, &btf_modules, list) {
+ if (btf_mod->module != owner)
+ continue;
+ /* a dead entry has no BTF to register with, as with =y */
+ if (!btf_mod->btf && !btf_mod->gone)
+ head = &btf_mod->deferred_regs;
+ break;
+ }
}
+ if (!head)
+ return 0;
- log->level = BPF_LOG_KERNEL;
+ 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;
+}
- err = btf_add_struct_ops(btf, st_ops, log);
+static void btf_free_deferred_reg(struct btf_deferred_reg *reg)
+{
+ if (reg->kind == BTF_DEFERRED_DTOR_KFUNCS)
+ kfree(reg->dtor.dtors);
+ kfree(reg);
+}
-errout:
- kfree(log);
- btf_put(btf);
+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 "?";
+}
- return err;
+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;
}
-EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
-#endif
+
+/*
+ * Apply and free the registrations in @regs to @btf. For a module BTF the
+ * caller holds a reference on @btf and makes sure the owning module stays.
+ */
+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);
+ }
+}
+
+static void btf_free_deferred_regs(struct list_head *regs)
+{
+ struct btf_deferred_reg *reg, *tmp;
+
+ list_for_each_entry_safe(reg, tmp, regs, list) {
+ 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,
diff --git a/kernel/bpf/btf_vmlinux.c b/kernel/bpf/btf_vmlinux.c
new file mode 100644
index 0000000000000..8d89b4bb3c432
--- /dev/null
+++ b/kernel/bpf/btf_vmlinux.c
@@ -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");
diff --git a/kernel/bpf/preload/Kconfig b/kernel/bpf/preload/Kconfig
index aef7b0bc96d61..b1600bdce7a06 100644
--- a/kernel/bpf/preload/Kconfig
+++ b/kernel/bpf/preload/Kconfig
@@ -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
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 74496fd716d3b..9e9eaa7988138 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -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;
diff --git a/kernel/bpf/sysfs_btf.c b/kernel/bpf/sysfs_btf.c
index 9cbe15ce3540c..b2408878412a8 100644
--- a/kernel/bpf/sysfs_btf.c
+++ b/kernel/bpf/sysfs_btf.c
@@ -9,8 +9,13 @@
#include <linux/sysfs.h>
#include <linux/mm.h>
#include <linux/io.h>
+#include <linux/bpf.h>
#include <linux/btf.h>
+#include <linux/vmalloc.h>
+struct kobject *btf_kobj;
+
+#if IS_BUILTIN(CONFIG_DEBUG_INFO_BTF)
/* See scripts/link-vmlinux.sh, gen_btf() func for details */
extern char __start_BTF[];
extern char __stop_BTF[];
@@ -49,12 +54,86 @@ static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {
.mmap = btf_sysfs_vmlinux_mmap,
};
-struct kobject *btf_kobj;
-
-static int __init btf_vmlinux_init(void)
+static void __init btf_sysfs_vmlinux_init(void)
{
bin_attr_btf_vmlinux.private = __start_BTF;
bin_attr_btf_vmlinux.size = __stop_BTF - __start_BTF;
+}
+
+#else /* CONFIG_DEBUG_INFO_BTF=m */
+
+/*
+ * The BTF is carried by the btf_vmlinux module and only loaded when
+ * something needs it. Its size is known from the start, so the file has
+ * its final size from boot; the first read() or mmap() loads the BTF.
+ */
+static void *btf_sysfs_vmlinux_load(u32 *size)
+{
+ /* Loads the module, parses the BTF and registers module BTFs. */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+ return NULL;
+ return btf_vmlinux_data(size, false);
+}
+
+static ssize_t btf_sysfs_vmlinux_read(struct file *filp, struct kobject *kobj,
+ const struct bin_attribute *attr,
+ char *buf, loff_t off, size_t count)
+{
+ u32 size;
+ void *data = btf_sysfs_vmlinux_load(&size);
+
+ if (!data)
+ return -ENODEV;
+
+ /* sysfs clamps @off and @count to attr->size, which is @size */
+ memcpy(buf, data + off, count);
+ return count;
+}
+
+static int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,
+ const struct bin_attribute *attr,
+ struct vm_area_struct *vma)
+{
+ size_t vm_size = vma->vm_end - vma->vm_start;
+ u32 size;
+ void *data = btf_sysfs_vmlinux_load(&size);
+
+ if (!data)
+ return -ENODEV;
+
+ if (vma->vm_pgoff)
+ return -EINVAL;
+
+ if (vma->vm_flags & (VM_WRITE | VM_EXEC | VM_MAYSHARE))
+ return -EACCES;
+
+ if (vm_size > PAGE_ALIGN(size))
+ return -EINVAL;
+
+ vm_flags_mod(vma, VM_DONTDUMP, VM_MAYEXEC | VM_MAYWRITE);
+ /* the copy was made with vmalloc_user() for this purpose */
+ return remap_vmalloc_range(vma, data, 0);
+}
+
+static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {
+ .attr = { .name = "vmlinux", .mode = 0444, },
+ .read = btf_sysfs_vmlinux_read,
+ .mmap = btf_sysfs_vmlinux_mmap,
+};
+
+static void __init btf_sysfs_vmlinux_init(void)
+{
+ u32 size;
+
+ /* known before the BTF is loaded, see .BTF.meta */
+ btf_vmlinux_data(&size, false);
+ bin_attr_btf_vmlinux.size = size;
+}
+#endif
+
+static int __init btf_vmlinux_init(void)
+{
+ btf_sysfs_vmlinux_init();
if (bin_attr_btf_vmlinux.size == 0)
return 0;
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index a7c9e2d8965d5..72edabbc2db51 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -2873,7 +2873,8 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
tab = prog_aux->kfunc_tab;
btf_tab = prog_aux->kfunc_btf_tab;
if (!tab) {
- if (!btf_vmlinux) {
+ /* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
return -ENOTSUPP;
}
@@ -6257,7 +6258,8 @@ static int check_ptr_to_map_access(struct bpf_verifier_env *env,
u32 btf_id;
int ret;
- if (!btf_vmlinux) {
+ /* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */
+ if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
return -ENOTSUPP;
}
@@ -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)
+{
+ 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;
+ }
+ return false;
+}
+
static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
int *insn_idx_p)
{
@@ -11637,6 +11657,18 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
return err;
}
+ /*
+ * Helpers that take or return kernel BTF pointers need the vmlinux
+ * BTF; with CONFIG_DEBUG_INFO_BTF=m this is where it gets loaded.
+ * Without CONFIG_DEBUG_INFO_BTF they keep failing as they always did.
+ */
+ if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF) && helper_uses_vmlinux_btf(func_id, fn) &&
+ IS_ERR_OR_NULL(bpf_get_btf_vmlinux())) {
+ verbose(env, "helper %s#%d is not supported without vmlinux BTF\n",
+ func_id_name(func_id), func_id);
+ return -ENOTSUPP;
+ }
+
if (fn->might_sleep && !in_sleepable_context(env)) {
verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
non_sleepable_context_description(env));
@@ -19235,12 +19267,13 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env,
return -EINVAL;
}
} else {
- if (!btf_vmlinux) {
+ /* with CONFIG_DEBUG_INFO_BTF=m this is where the vmlinux BTF gets loaded */
+ btf = bpf_get_btf_vmlinux();
+ if (IS_ERR_OR_NULL(btf)) {
verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
return -EINVAL;
}
- btf_get(btf_vmlinux);
- btf = btf_vmlinux;
+ btf_get(btf);
}
err = __check_pseudo_btf_id(env, insn, aux, btf);
@@ -21130,29 +21163,72 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt
return 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, 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)) {
- 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) {
+ 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;
}
- 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);
+ parsed = true;
}
+ mutex_unlock(&btf_vmlinux_lock);
+
+ if (parsed && IS_MODULE(CONFIG_DEBUG_INFO_BTF))
+ btf_parse_deferred_modules();
+
return btf;
}
+/*
+ * The vmlinux BTF if it has been parsed already, else NULL. Unlike
+ * bpf_get_btf_vmlinux() this never loads or parses anything, so it is safe
+ * to call from a running BPF program.
+ */
+struct btf *bpf_peek_btf_vmlinux(void)
+{
+ /* Pairs with the smp_store_release() in bpf_get_btf_vmlinux() */
+ return smp_load_acquire(&btf_vmlinux);
+}
+
/*
* The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
* this case expect that every file descriptor in the array is either a map or
@@ -21724,7 +21800,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret)
goto err_prep;
- bpf_get_btf_vmlinux();
+ /*
+ * The vmlinux BTF is not fetched up front: with CONFIG_DEBUG_INFO_BTF=m
+ * it is loaded on demand, at the points where kernel types enter the
+ * program (attach_btf, kfuncs, ksyms, map pointers, BTF-typed helpers).
+ */
/* Serialize verification of unprivileged programs. */
if (!is_priv)
@@ -21745,10 +21825,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())) {
/* 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;
}
diff --git a/kernel/module/main.c b/kernel/module/main.c
index d0e1e0bd2ad06..694c4bc7e6793 100644
--- a/kernel/module/main.c
+++ b/kernel/module/main.c
@@ -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;
diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c
index 195f78db9bdaf..c022b2877f0ba 100644
--- a/kernel/trace/bpf_trace.c
+++ b/kernel/trace/bpf_trace.c
@@ -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;
diff --git a/kernel/trace/trace_syscalls.c b/kernel/trace/trace_syscalls.c
index e35744049e3f2..7a0d59c308c29 100644
--- a/kernel/trace/trace_syscalls.c
+++ b/kernel/trace/trace_syscalls.c
@@ -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
};
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 134b15a44625e..418025c5e6577 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -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
diff --git a/net/netfilter/Makefile b/net/netfilter/Makefile
index 6bf74d488a292..a2c7f00794d22 100644
--- a/net/netfilter/Makefile
+++ b/net/netfilter/Makefile
@@ -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
diff --git a/net/xfrm/Makefile b/net/xfrm/Makefile
index 5a1787587cb35..b7f6e5046a0e9 100644
--- a/net/xfrm/Makefile
+++ b/net/xfrm/Makefile
@@ -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
diff --git a/scripts/Makefile.modfinal b/scripts/Makefile.modfinal
index 01a37ec872b90..6a0958cf0e6f4 100644
--- a/scripts/Makefile.modfinal
+++ b/scripts/Makefile.modfinal
@@ -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
diff --git a/scripts/Makefile.vmlinux b/scripts/Makefile.vmlinux
index fcae1e432d9ad..557db1ee1f3b0 100644
--- a/scripts/Makefile.vmlinux
+++ b/scripts/Makefile.vmlinux
@@ -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__*'
diff --git a/scripts/gen-btf.sh b/scripts/gen-btf.sh
index 8ca96eb10a69e..d808d0006d325 100755
--- a/scripts/gen-btf.sh
+++ b/scripts/gen-btf.sh
@@ -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}" in
diff --git a/scripts/link-vmlinux.sh b/scripts/link-vmlinux.sh
index ab0b8125c8cbc..a9a066267ef6e 100755
--- a/scripts/link-vmlinux.sh
+++ b/scripts/link-vmlinux.sh
@@ -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
|
| 17/3 | 2026/09/27 16:07 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34148 output: 35 thoughts: 3649 Thoughts: **KMSAN Assessment of BTF Module Support** Alright, let's break down this patch. My primary concern here is uninitialized memory, particularly where kernel data might leak to userspace or be used in conditional logic. The goal is to determine if `NeedsKMSAN` should be set to `true` or `false`. First, I see the addition of `CONFIG_DEBUG_INFO_BTF=m`, enabling the kernel to build BTF (BPF Type Format) as a module `btf_vmlinux`. I need to carefully scrutinize where this module data is created, used, and, most importantly, *exposed*. I'm starting by analyzing the structure `btf_vmlinux_meta`, which includes a size and SHA256 sum. This metadata is generated by `gen-btf.sh`, and the code uses a placeholder `dd` command to write zeros for the meta data initially. Then in `btf_vmlinux_module_coming`, I see the `sha256sum` is filled by `sha256()`. Also data is allocated with `vmalloc_user` which, crucially, zeroes memory on allocation, before copying the module data. Next, I examined the `btf_module_sysfs_read_deferred` function. Here, a sysfs read operation occurs. I tracked the flow and determined the data, `btf_mod->btf->data`, originates from the module's ELF section `.BTF`, loaded via `kvmemdup`. I confirmed that this section is loaded, via module loading, using `kvmemdup`. I had to look at `sysfs_btf.c`. I see the sysfs code for reading the vmlinux BTF. In this case, for `CONFIG_DEBUG_INFO_BTF=m`, there's a size in `btf_vmlinux_meta.size`, which is later read by `btf_sysfs_vmlinux_read`. This function calls `bpf_get_btf_vmlinux()` to load BTF data. The function also uses `vmalloc_user` followed by `memcpy` which is zeroed memory before copy from loaded data. If a user uses `mmap` on the sysfs file, the kernel calls `remap_vmalloc_range`. This is safe because `vmalloc_user` guarantees zeroed memory. I then dug into how `btf_defer_reg` works. A `btf_deferred_reg` structure is created, and populated in one of three ways, but importantly, by using designated initializers when it is allocated on the stack. My concern was padding bytes. However, designated initializers in C zero-initialize all unspecified fields. The structure is then copied with `kmemdup`. Further investigation determined that `kmemdup` is called, and `btf_apply_deferred_reg` is called. However, it's strictly an internal kernel mechanism and that structure is *never* sent to userspace. The active fields of this structure are read within the kernel. Finally, I checked `btf_module` allocation, which uses `kzalloc_obj`, which *zeroes* the memory. I also checked `sysfs_create_bin_file` and `btf_module_sysfs_add`, and these also use `kzalloc_obj`. The data read from `btf_parse_deferred_modules` using `btf_parse_module`, is safely copied using `kvmemdup`. After this thorough review, I'm confident that the code changes either initialize all structures before use, uses zeroing allocations or uses established zero-filling memory mapping primitives like `vmalloc_user` and `kzalloc`, before copying data. The data, in all cases, is well-handled. **Therefore, `NeedsKMSAN=false`.** |
| 18/3 | 2026/09/27 16:08 | tool | grepper |
0mArgs:{
"Expression": "btf_parse_module",
"PathPrefix": "kernel/bpf/btf.c"
}Results: {
"Output": "kernel/bpf/btf.c=6609=__u32 btf_relocate_id(const struct btf *btf, __u32 id)\n--\nkernel/bpf/btf.c-6622- */\nkernel/bpf/btf.c:6623:static struct btf *btf_parse_module(const char *module_name, struct btf *vmlinux_btf,\nkernel/bpf/btf.c-6624-\t\t\t\t void *data, unsigned int data_size, bool data_owned,\n--\nkernel/bpf/btf.c=8980=static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n--\nkernel/bpf/btf.c-9027-\nkernel/bpf/btf.c:9028:\t\tbtf = btf_parse_module(mod-\u003ename, bpf_get_btf_vmlinux(),\nkernel/bpf/btf.c-9029-\t\t\t\t mod-\u003ebtf_data, mod-\u003ebtf_data_size, false,\n--\nkernel/bpf/btf.c=9164=void btf_parse_deferred_modules(void)\n--\nkernel/bpf/btf.c-9182-\nkernel/bpf/btf.c:9183:\t\tbtf = btf_parse_module(btf_mod-\u003emodule-\u003ename, vmlinux_btf,\nkernel/bpf/btf.c-9184-\t\t\t\t btf_mod-\u003edata, btf_mod-\u003edata_size, true,\n"
} |
| 19/3 | 2026/09/27 16:08 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39085 output: 39 thoughts: 27 Thoughts: Okay, let's dive into this. Here's how I'd approach summarizing the thought process, as if I were considering the `btf_parse_module` function: **Analyzing the `btf_parse_module` Function** Alright, time to really get into `btf_parse_module` within `kernel/bpf/btf.c`. I need to fully understand how this function handles the parsing of BTF data for a specific module. I'm focusing on the core logic here, aiming to grasp the high-level flow and critical details. I'll need to pay close attention to the data structures involved: the `module` itself, the BTF data buffer, any error handling, and how the BTF data is interpreted to build up the in-kernel representation. I'll need to dissect how it walks through the BTF section, handling different type definitions, function definitions, and data sections. I'm particularly interested in any optimizations or potential bottlenecks within this function. I'll be keeping an eye out for how this function interacts with the BPF subsystem more broadly, what it does with the parsed BTF data, and how it handles potential errors during parsing. Does it have any implications for security or performance? What are the key validation steps it performs? I should also look for any edge cases it explicitly handles, or might miss. Ultimately, I'm trying to ensure I have a complete understanding of this critical function's role in the system. |
| 20/3 | 2026/09/27 16:08 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 6620,
"LineCount": 100
}Results: {
"Contents": "6620:\t * section; if @data_owned, it is an already kvmalloc()ed copy that the new\n6621:\t * btf takes ownership of on success (on failure the caller keeps it).\n6622:\t */\n6623:\tstatic struct btf *btf_parse_module(const char *module_name, struct btf *vmlinux_btf,\n6624:\t\t\t\t\t void *data, unsigned int data_size, bool data_owned,\n6625:\t\t\t\t\t void *base_data, unsigned int base_data_size)\n6626:\t{\n6627:\t\tstruct btf *btf = NULL, *base_btf = NULL;\n6628:\t\tstruct btf_verifier_env *env = NULL;\n6629:\t\tstruct bpf_verifier_log *log;\n6630:\t\tint err = 0;\n6631:\t\n6632:\t\tif (IS_ERR(vmlinux_btf))\n6633:\t\t\treturn vmlinux_btf;\n6634:\t\tif (!vmlinux_btf)\n6635:\t\t\treturn ERR_PTR(-EINVAL);\n6636:\t\n6637:\t\tenv = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);\n6638:\t\tif (!env)\n6639:\t\t\treturn ERR_PTR(-ENOMEM);\n6640:\t\n6641:\t\tlog = \u0026env-\u003elog;\n6642:\t\tlog-\u003elevel = BPF_LOG_KERNEL;\n6643:\t\n6644:\t\tif (base_data) {\n6645:\t\t\tbase_btf = btf_parse_base(env, \".BTF.base\", base_data, base_data_size);\n6646:\t\t\tif (IS_ERR(base_btf)) {\n6647:\t\t\t\terr = PTR_ERR(base_btf);\n6648:\t\t\t\tgoto errout;\n6649:\t\t\t}\n6650:\t\t} else {\n6651:\t\t\tbase_btf = vmlinux_btf;\n6652:\t\t}\n6653:\t\n6654:\t\tbtf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);\n6655:\t\tif (!btf) {\n6656:\t\t\terr = -ENOMEM;\n6657:\t\t\tgoto errout;\n6658:\t\t}\n6659:\t\tenv-\u003ebtf = btf;\n6660:\t\n6661:\t\tbtf-\u003ebase_btf = base_btf;\n6662:\t\tbtf-\u003estart_id = base_btf-\u003enr_types;\n6663:\t\tbtf-\u003estart_str_off = base_btf-\u003ehdr.str_len;\n6664:\t\tbtf-\u003ekernel_btf = true;\n6665:\t\tbtf-\u003enamed_start_id = 0;\n6666:\t\tstrscpy(btf-\u003ename, module_name);\n6667:\t\n6668:\t\tif (data_owned)\n6669:\t\t\tbtf-\u003edata = data;\n6670:\t\telse\n6671:\t\t\tbtf-\u003edata = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);\n6672:\t\tif (!btf-\u003edata) {\n6673:\t\t\terr = -ENOMEM;\n6674:\t\t\tgoto errout;\n6675:\t\t}\n6676:\t\tbtf-\u003edata_size = data_size;\n6677:\t\n6678:\t\terr = btf_parse_hdr(env);\n6679:\t\tif (err)\n6680:\t\t\tgoto errout;\n6681:\t\n6682:\t\tbtf-\u003enohdr_data = btf-\u003edata + btf-\u003ehdr.hdr_len;\n6683:\t\n6684:\t\terr = btf_parse_str_sec(env);\n6685:\t\tif (err)\n6686:\t\t\tgoto errout;\n6687:\t\n6688:\t\terr = btf_check_all_metas(env);\n6689:\t\tif (err)\n6690:\t\t\tgoto errout;\n6691:\t\n6692:\t\terr = btf_check_modifier_chain_length(env, btf, btf_nr_types(base_btf));\n6693:\t\tif (err)\n6694:\t\t\tgoto errout;\n6695:\t\n6696:\t\tif (base_btf != vmlinux_btf) {\n6697:\t\t\terr = btf_relocate(btf, vmlinux_btf, \u0026btf-\u003ebase_id_map);\n6698:\t\t\tif (err)\n6699:\t\t\t\tgoto errout;\n6700:\t\t\tbtf_free(base_btf);\n6701:\t\t\tbase_btf = vmlinux_btf;\n6702:\t\t}\n6703:\t\n6704:\t\tbtf_verifier_env_free(env);\n6705:\t\tbtf_check_sorted(btf);\n6706:\t\trefcount_set(\u0026btf-\u003erefcnt, 1);\n6707:\t\treturn btf;\n6708:\t\n6709:\terrout:\n6710:\t\tbtf_verifier_env_free(env);\n6711:\t\tif (!IS_ERR(base_btf) \u0026\u0026 base_btf != vmlinux_btf)\n6712:\t\t\tbtf_free(base_btf);\n6713:\t\tif (btf) {\n6714:\t\t\tif (!data_owned)\n6715:\t\t\t\tkvfree(btf-\u003edata);\n6716:\t\t\tkvfree(btf-\u003etypes);\n6717:\t\t\tkfree(btf);\n6718:\t\t}\n6719:\t\treturn ERR_PTR(err);\n"
} |
| 21/3 | 2026/09/27 16:08 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 41015 output: 38 thoughts: 44 Thoughts: Okay, let's dive into this. **Examining btf_parse_deferred_modules in kernel/bpf/btf.c** Alright, I need to understand how the `btf_parse_deferred_modules` function leverages this specific aspect. I'm going to jump into the code and focus on lines 9160 through 9225 within `kernel/bpf/btf.c`. This section should reveal the crucial details I need regarding its implementation and its role within the broader context of handling BTF (BPF Type Format) data, specifically with deferred modules. I need to see how the parsing function is architected and what considerations were used in its design. The lines should give context for my overall understanding. Let's see what we can find. |
| 22/3 | 2026/09/27 16:08 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 9160,
"LineCount": 80
}Results: {
"Contents": "9160:\t * module is pinned for that, and the scan restarts afterwards. A module\n9161:\t * that is still initializing is only published: its init is still queueing\n9162:\t * registrations, and MODULE_STATE_LIVE applies them once it is done.\n9163:\t */\n9164:\tvoid btf_parse_deferred_modules(void)\n9165:\t{\n9166:\t\t/* Pairs with the publication in bpf_get_btf_vmlinux() */\n9167:\t\tstruct btf *vmlinux_btf = smp_load_acquire(\u0026btf_vmlinux);\n9168:\t\tstruct btf_module *btf_mod;\n9169:\t\tbool parsed = false;\n9170:\t\tLIST_HEAD(regs);\n9171:\t\tstruct btf *btf;\n9172:\t\tint err;\n9173:\t\n9174:\t\tif (IS_ERR_OR_NULL(vmlinux_btf))\n9175:\t\t\treturn;\n9176:\t\n9177:\t\tmutex_lock(\u0026btf_module_mutex);\n9178:\trestart:\n9179:\t\tlist_for_each_entry(btf_mod, \u0026btf_modules, list) {\n9180:\t\t\tif (btf_mod-\u003ebtf || btf_mod-\u003egone)\n9181:\t\t\t\tcontinue;\n9182:\t\n9183:\t\t\tbtf = btf_parse_module(btf_mod-\u003emodule-\u003ename, vmlinux_btf,\n9184:\t\t\t\t\t btf_mod-\u003edata, btf_mod-\u003edata_size, true,\n9185:\t\t\t\t\t btf_mod-\u003ebase_data, btf_mod-\u003ebase_data_size);\n9186:\t\t\tif (IS_ERR(btf)) {\n9187:\t\t\t\t/* on failure the caller keeps the data */\n9188:\t\t\t\tbtf_module_dead(btf_mod, \"validate\", PTR_ERR(btf));\n9189:\t\t\t\tcontinue;\n9190:\t\t\t}\n9191:\t\t\t/* btf-\u003edata is btf_mod-\u003edata now, the sysfs file keeps pointing at valid data */\n9192:\t\t\tkvfree(btf_mod-\u003ebase_data);\n9193:\t\t\tbtf_mod-\u003ebase_data = NULL;\n9194:\t\n9195:\t\t\tif ((btf_mod-\u003eflags \u0026 BTF_MODULE_F_LIVE) \u0026\u0026\n9196:\t\t\t try_module_get(btf_mod-\u003emodule)) {\n9197:\t\t\t\tlist_splice_init(\u0026btf_mod-\u003edeferred_regs, \u0026regs);\n9198:\t\t\t\tmutex_unlock(\u0026btf_module_mutex);\n9199:\t\t\t\tbtf_apply_deferred_regs(btf, \u0026regs);\n9200:\t\t\t\tmutex_lock(\u0026btf_module_mutex);\n9201:\t\t\t\tmodule_put(btf_mod-\u003emodule);\n9202:\t\t\t}\n9203:\t\n9204:\t\t\terr = btf_alloc_id(btf);\n9205:\t\t\tif (err) {\n9206:\t\t\t\t/* give the data back to the entry, the sysfs file may serve it */\n9207:\t\t\t\tbtf-\u003edata = NULL;\n9208:\t\t\t\tbtf_free(btf);\n9209:\t\t\t\tbtf_module_dead(btf_mod, \"register\", err);\n9210:\t\t\t\tgoto restart;\n9211:\t\t\t}\n9212:\t\n9213:\t\t\tbtf_mod-\u003edata = NULL;\n9214:\t\t\tbtf_mod-\u003ebtf = btf;\n9215:\t\t\t/* Pairs with the smp_load_acquire() in btf_module_sysfs_read_deferred() */\n9216:\t\t\tsmp_store_release(\u0026btf_mod-\u003eready, true);\n9217:\t\t\twake_up_all(\u0026btf_module_wq);\n9218:\t\t\tparsed = true;\n9219:\t\t\t/* the list may have changed while the mutex was dropped */\n9220:\t\t\tgoto restart;\n9221:\t\t}\n9222:\t\tmutex_unlock(\u0026btf_module_mutex);\n9223:\t\n9224:\t\tif (parsed)\n9225:\t\t\tpurge_cand_cache(NULL);\n9226:\t}\n9227:\t#endif /* IS_MODULE(CONFIG_DEBUG_INFO_BTF) */\n9228:\t#endif /* BTF_MODULE_NOTIFIER */\n9229:\t\n9230:\tstruct module *btf_try_get_module(const struct btf *btf)\n9231:\t{\n9232:\t\tstruct module *res = NULL;\n9233:\t#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n9234:\t\tstruct btf_module *btf_mod, *tmp;\n9235:\t\n9236:\t\tmutex_lock(\u0026btf_module_mutex);\n9237:\t\tlist_for_each_entry_safe(btf_mod, tmp, \u0026btf_modules, list) {\n9238:\t\t\tif (btf_mod-\u003ebtf != btf)\n9239:\t\t\t\tcontinue;\n"
} |
| 23/3 | 2026/09/27 16:08 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 42630 output: 311 thoughts: 6145 Thoughts: **Analysis of BTF Module Loading and KMSAN Applicability** Okay, let's break this down. My goal here is to determine if this patch necessitates a KMSAN run. I'm seeing changes related to BTF (BPF Type Format) module loading, specifically when `CONFIG_DEBUG_INFO_BTF=m` is enabled. The core idea is to load the BTF data for the vmlinux image as a separate module, enabling on-demand loading and potentially saving memory. First, I looked closely at how the BTF data is handled. `btf_alloc_id` is followed by setting `btf_mod->btf`, which seems straightforward. The `btf_module_free` function looks like it handles freeing the resources, including the BTF data, and removing the sysfs entry. Key here is that if the module's BTF data is `NULL`, then `kvfree` is used. Otherwise `btf_put` is used. The logic is clear and seems fine. Then I get into `btf_vmlinux_data`, which is the workhorse for retrieving the BTF data. I need to be careful with the potential for uninitialized memory here. If `CONFIG_DEBUG_INFO_BTF` is a module, the code checks if `btf_vmlinux_raw` is NULL and requests the `btf_vmlinux` module to be loaded. My concern here is if there's a race, what happens if `btf_vmlinux_raw` is NULL. I went and investigated the `btf_sysfs_vmlinux_init` and `btf_sysfs_vmlinux_read` functions. Here is where the BTF data is exposed to userspace. In `btf_sysfs_vmlinux_init`, the size of `bin_attr_btf_vmlinux` is set using `btf_vmlinux_data`. The key is that `btf_vmlinux_data` can return NULL if the module is not loaded. I examined the `btf_sysfs_vmlinux_read` to see what happens when the user reads from the sysfs entry. The code calls `btf_sysfs_vmlinux_load`, which calls `bpf_get_btf_vmlinux()`. If the vmlinux BTF is not ready, then the read function exits. Then I need to examine what happens if the data is present and what is being read to the `buf` that is passed from the user space. I found that the data comes from `btf_vmlinux_module_coming`, where `vmalloc_user` is used to allocate memory and the data is copied. I realized that the size calculation in `btf_vmlinux_module_coming` is tied to `btf_vmlinux_meta.size`, which is calculated and generated using `scripts/gen-btf.sh`. It also contains a `sha256` value for verification. Thus, I concluded that the memory in `btf_vmlinux_module_coming` is correctly initialized. The `data` is then `vmalloc_user` initialized, which means the contents are zeroed, and filled with data from an ELF section. The data is validated through the `sha256` checksum before being exposed. The crucial point here is what happens in `btf_module_sysfs_read_deferred`. In this case, `btf_mod->btf->data` (which is copied using `kvmemdup`) is the source. Again, I need to make sure that the `attr->size` corresponds to how `btf_mod->btf->data` is copied and is accessible. By tracking the size calculations and allocations, it seems that there is a proper size match and the buffers are properly zeroed. The sysfs clamping (`off` and `count` are clamped to `attr->size`) further reinforces that we are only copying from initialized memory. I then did a sweep of the rest of the code for other calls to potentially unsafe code. I checked the code around the `BPF_BTF_GET_NEXT_ID` and other data structures. All memory operations seem safe because allocations are zeroed or the contents are copied from a known source. **KMSAN Determination** After thoroughly analyzing the memory access patterns, the various functions, and the use of sysfs, I'm confident that this patch does *not* introduce any uninitialized memory read vulnerabilities that KMSAN would specifically detect. My reasoning: 1. The patch enables loading and exposing vmlinux BTF data as a separate kernel module. It also includes adding deferring code. 2. All |
| 24/3 | 2026/09/27 16:08 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series introduces support for building kernel BTF as an on-demand module (CONFIG_DEBUG_INFO_BTF=m). It adds on-demand module loading, deferred registration queues for kfuncs and struct_ops, and sysfs handling for unparsed/deferred BTF data.\n\nKMSAN vs KASAN applicability analysis:\n1. Heap and stack structures: All new data structures (such as struct btf_module, struct bin_attribute, and verifier logs) are allocated using kzalloc_obj() or vmalloc_user(), ensuring zero-initialization. Deferred registration entries and BTF data buffers are cloned via kmemdup()/kvmemdup() with explicit sizes.\n2. User space memory transfers: Sysfs binary file read() and mmap() handlers (/sys/kernel/btf/*) operate on buffers fully populated from the module ELF sections with bounds clamped to the validated section size, posing no risk of uninitialized memory info-leaks.\n3. No branching or logic depends on uninitialized memory.\n4. The risks introduced by this change center around module lifecycle, concurrency (lock ordering, waitqueue synchronization), and resource management (use-after-free, memory leaks), which are detectable by KASAN, LOCKDEP, and KMEMLEAK.\n\nTherefore, dedicated KMSAN fuzzing is not justified for these changes.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series introduces support for building kernel BTF as an on-demand module (CONFIG_DEBUG_INFO_BTF=m). It adds on-demand module loading, deferred registration queues for kfuncs and struct_ops, and sysfs handling for unparsed/deferred BTF data.\n\nKMSAN vs KASAN applicability analysis:\n1. Heap and stack structures: All new data structures (such as struct btf_module, struct bin_attribute, and verifier logs) are allocated using kzalloc_obj() or vmalloc_user(), ensuring zero-initialization. Deferred registration entries and BTF data buffers are cloned via kmemdup()/kvmemdup() with explicit sizes.\n2. User space memory transfers: Sysfs binary file read() and mmap() handlers (/sys/kernel/btf/*) operate on buffers fully populated from the module ELF sections with bounds clamped to the validated section size, posing no risk of uninitialized memory info-leaks.\n3. No branching or logic depends on uninitialized memory.\n4. The risks introduced by this change center around module lifecycle, concurrency (lock ordering, waitqueue synchronization), and resource management (use-after-free, memory leaks), which are detectable by KASAN, LOCKDEP, and KMEMLEAK.\n\nTherefore, dedicated KMSAN fuzzing is not justified for these changes.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|