AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/01 08:10 flow patch-triage
4m Args:
null

Results:
{
  "EnableConfigs": [
    "DEBUG_INFO_BTF_LAZY",
    "DEBUG_INFO_BTF",
    "DEBUG_INFO_BTF_MODULES",
    "BPF_SYSCALL",
    "SYSFS"
  ],
  "FocusSymbols": [
    "bpf_get_btf_vmlinux",
    "bpf_peek_btf_vmlinux",
    "btf_vmlinux_data",
    "btf_parse_vmlinux",
    "btf_get_module_btf",
    "trace_btf_prepare",
    "__register_btf_kfunc_id_set",
    "register_btf_id_dtor_kfuncs",
    "__register_bpf_struct_ops"
  ],
  "KMSANReasoning": "The patch series introduces CONFIG_DEBUG_INFO_BTF_LAZY, which compresses the vmlinux BTF using zstd and lazily decompresses and parses it on first demand rather than at boot. It also implements deferred registration queues for kfuncs, dtor kfuncs, and struct_ops, as well as deferral for module split BTF loading.\n\n1. Analysis of Memory Allocation and Initialization:\n- All heap objects introduced or modified by the patch (such as `struct btf_deferred_reg` in btf_defer_reg() and `struct btf_module` in btf_module_notify()) are allocated using zero-initializing allocators (`kzalloc_obj`).\n- Buffer copies for deferred kfunc id sets, dtors, and module BTF data are cloned via `kmemdup`, `kmemdup_array`, and `kvmemdup`, duplicating already initialized data.\n- The vmlinux BTF raw buffer is allocated using `vmalloc_user()`, which zeroes allocated pages (`__GFP_ZERO`), and is populated by `zstd_decompress_dctx()`. The pointer is only published if decompression output exactly matches the expected size (`ret == *size`).\n- Stack variables (such as `zstd_frame_header hdr` in `btf_vmlinux_size()`) are guarded by error checks; `hdr.frameContentSize` is accessed only after `zstd_get_frame_header()` returns 0 (success). In `prog_ctx_tname()`, the out-pointer `*alt` is explicitly initialized to NULL before use.\n\n2. User Space Exposure and Info-leak Checks:\n- Data exposed to user space through `/sys/kernel/btf/vmlinux` via sysfs read and mmap operations maps or copies from the `vmalloc_user` buffer holding verified decompressed BTF data.\n- Similarly, trace events' BTF ID reads use `scnprintf` formatted into a stack buffer and copy only the formatted length via `simple_read_from_buffer`. There is no uninitialized memory or structure padding leaked to user space.\n\n3. KASAN vs KMSAN Applicability:\n- The risks introduced by this change involve synchronization, complex lock ordering (e.g., `btf_vmlinux_lock` vs `btf_module_mutex`, `cand_cache_mutex`, `event_mutex`), and object lifecycles across module load/unload transitions. These failure modes (deadlocks, use-after-free, double-free, NULL/ERR pointer dereferences) are detected by LOCKDEP and KASAN.\n- There are no uninitialized memory reads or uninitialized data leakage risks that uniquely require KMSAN.\n\nTherefore, dedicated KMSAN fuzzing is not justified.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch introduces CONFIG_DEBUG_INFO_BTF_LAZY, which implements on-demand zstd decompression and lazy parsing of the vmlinux BTF upon first use, as well as deferred registration of kfuncs, dtor kfuncs, and struct_ops. It also modifies module BTF handling, BPF verifier entrypoints, sysfs /sys/kernel/btf/vmlinux read/mmap interfaces, and ftrace BTF integrations. These changes introduce substantial new state management, memory management, and synchronization logic across core BPF, tracing, and module subsystems, which are reachable and readily exercisable via the bpf() syscall, sysfs, and tracefs in standard virtualized environments.",
  "WorthFuzzing": true
}

1/1 2026/11/01 08:10 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit d0d825401d8cf7610975e1842f2fd9fb6624bdbc\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Sun Nov 1 08:10:07 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/bpf/btf.rst b/Documentation/bpf/btf.rst\nindex 29de1222c3e73f..1ebce5cf578346 100644\n--- a/Documentation/bpf/btf.rst\n+++ b/Documentation/bpf/btf.rst\n@@ -1276,6 +1276,36 @@ format.::\n             .long   58\n             .long   8206                    # Line 8 Col 14\n \n+6.1 Compressed vmlinux BTF\n+--------------------------\n+\n+With ``CONFIG_DEBUG_INFO_BTF_LAZY``, the kernel image carries the vmlinux BTF\n+zstd-compressed, at about a quarter of its size, and the kernel decompresses\n+and parses it when something first needs it: a BPF program or map that uses\n+kernel types, ``BPF_BTF_GET_NEXT_ID``, tracing options that print arguments or\n+return values by their BTF types.\n+``/sys/kernel/btf/vmlinux`` has its full size from the start; reading or\n+mapping it decompresses the BTF but does not parse it. Systems that never use\n+BTF keep only the compressed copy in memory. The vmlinux file keeps the\n+uncompressed ``.BTF`` section, not loaded, for tools and module builds.\n+The option is available on x86 and arm64.\n+\n+Kernel function, destructor kfunc and struct_ops registrations made before the\n+first use, and the BTF of modules loaded before it, are kept and applied by the\n+task that parses the vmlinux BTF, before anyone else can see it. Errors of\n+those registrations then only show in the kernel log, and a module whose BTF\n+fails validation at that point stays loaded without BTF and without its files\n+in ``/sys/kernel/btf``. A first use that runs out of memory fails with\n+``-ENOMEM`` and leaves all of this as it was, for the next one to start over.\n+The vmlinux BTF gets the next free BTF id, not necessarily 1, and the image has\n+no ``__start_BTF``/``__stop_BTF`` symbols. The inline BTF\n+(``CONFIG_DEBUG_INFO_BTF_INLINE``) is not compressed.\n+\n+Users of kernel types during boot still parse it during boot, for example BPF\n+LSM programs, the iterators of ``CONFIG_BPF_PRELOAD`` (loaded at boot, or at the\n+first bpffs mount if ``bpf_preload`` is a module), or a module with a\n+``.BTF.base`` section.\n+\n 7. Testing\n ==========\n \ndiff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile\nindex 680ad803cba7df..58d05262dec82f 100644\n--- a/arch/x86/boot/compressed/Makefile\n+++ b/arch/x86/boot/compressed/Makefile\n@@ -116,7 +116,7 @@ endif\n $(obj)/vmlinux: $(vmlinux-objs-y) $(vmlinux-libs-y) FORCE\n \t$(call if_changed,ld)\n \n-OBJCOPYFLAGS_vmlinux.bin :=  -R .comment -S\n+OBJCOPYFLAGS_vmlinux.bin :=  -R .comment $(if $(CONFIG_DEBUG_INFO_BTF_LAZY),-R .BTF) -S\n $(obj)/vmlinux.bin: vmlinux FORCE\n \t$(call if_changed,objcopy)\n \ndiff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h\nindex 3eb732942d699c..7358aedab95cbc 100644\n--- a/include/asm-generic/vmlinux.lds.h\n+++ b/include/asm-generic/vmlinux.lds.h\n@@ -553,7 +553,7 @@\n \t\t\t\t\t\t\t\t\t\\\n \tRO_EXCEPTION_TABLE\t\t\t\t\t\t\\\n \tNOTES\t\t\t\t\t\t\t\t\\\n-\tBTF\t\t\t\t\t\t\t\t\\\n+\tRO_BTF\t\t\t\t\t\t\t\t\\\n \t\t\t\t\t\t\t\t\t\\\n \t. = ALIGN((align));\t\t\t\t\t\t\\\n \t__end_rodata = .;\n@@ -704,12 +704,24 @@\n #define BTF_INLINE_LINK\n #endif\n \n-#ifdef CONFIG_DEBUG_INFO_BTF\n-#define BTF\t\t\t\t\t\t\t\t\\\n+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY\n+/* compressed BTF in init data (see sysfs_btf.c), raw BTF not loaded */\n+#define BTF_LOADED\n+#define BTF_ZST\t\t. = ALIGN(8); BOUNDED_SECTION_BY(.init.BTF.zst, _BTF_zst)\n+#define BTF_RAW\t\t.BTF 0 : { *(.BTF) }\n+#else\n+#define BTF_LOADED\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 \t\tBOUNDED_SECTION_BY(.BTF, _BTF)\t\t\t\t\\\n-\t}\t\t\t\t\t\t\t\t\\\n+\t}\n+#define BTF_ZST\n+#define BTF_RAW\n+#endif\n+\n+#ifdef CONFIG_DEBUG_INFO_BTF\n+#define RO_BTF\t\t\t\t\t\t\t\t\\\n+\tBTF_LOADED\t\t\t\t\t\t\t\\\n \tBTF_INLINE\t\t\t\t\t\t\t\\\n \tBTF_INLINE_LINK\t\t\t\t\t\t\\\n \t. = ALIGN(PAGE_SIZE);\t\t\t\t\t\t\\\n@@ -717,7 +729,7 @@\n \t\t*(.BTF_ids)\t\t\t\t\t\t\\\n \t}\n #else\n-#define BTF\n+#define RO_BTF\n #endif\n \n /*\n@@ -748,6 +760,7 @@\n \tKERNEL_CTORS()\t\t\t\t\t\t\t\\\n \tMCOUNT_REC()\t\t\t\t\t\t\t\\\n \t*(.init.rodata .init.rodata.*)\t\t\t\t\t\\\n+\tBTF_ZST\t\t\t\t\t\t\t\t\\\n \tFTRACE_EVENTS()\t\t\t\t\t\t\t\\\n \tTRACE_SYSCALLS()\t\t\t\t\t\t\\\n \tKPROBE_BLACKLIST()\t\t\t\t\t\t\\\n@@ -880,6 +893,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_RAW\t\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 ff043678129358..c08b49e280d31f 100644\n--- a/include/linux/bpf.h\n+++ b/include/linux/bpf.h\n@@ -3259,6 +3259,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 a18254b7521bdd..ff6d4a1d2e6b60 100644\n--- a/include/linux/btf.h\n+++ b/include/linux/btf.h\n@@ -618,6 +618,11 @@ __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+#ifdef CONFIG_DEBUG_INFO_BTF\n+void *btf_vmlinux_data(u32 *size);\n+#else\n+static inline void *btf_vmlinux_data(u32 *size) { return ERR_PTR(-ENOENT); }\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/kernel/bpf/Makefile b/kernel/bpf/Makefile\nindex 269810b128c469..4f500927cec854 100644\n--- a/kernel/bpf/Makefile\n+++ b/kernel/bpf/Makefile\n@@ -40,8 +40,8 @@ obj-$(CONFIG_CGROUP_BPF) += cgroup.o\n 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+ifeq ($(CONFIG_SYSFS),y)\n obj-$(CONFIG_DEBUG_INFO_BTF_INLINE) += btf_vmlinux_inline.o\n endif\n ifeq ($(CONFIG_BPF_JIT),y)\ndiff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c\nindex 7c5cd6086e2735..5e753b7d532d35 100644\n--- a/kernel/bpf/bpf_struct_ops.c\n+++ b/kernel/bpf/bpf_struct_ops.c\n@@ -103,8 +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\t\t\t\t   st_ops_ids[IDX_ST_OPS_COMMON_VALUE_ID]);\n+\t/* a vmlinux id: btf may be the vmlinux BTF being published, or a module's */\n+\tcommon_value_type = btf_type_by_id(btf, 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\",\n \t\t\tvalue_name);\ndiff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c\nindex 1be30487a2fa75..c7234bcba87453 100644\n--- a/kernel/bpf/btf.c\n+++ b/kernel/bpf/btf.c\n@@ -1902,7 +1902,8 @@ static void btf_free(struct btf *btf)\n \tkvfree(btf-\u003eresolved_sizes);\n \tkvfree(btf-\u003eresolved_ids);\n \t/* vmlinux does not allocate btf-\u003edata, it simply points it at\n-\t * __start_BTF.\n+\t * __start_BTF, or at the decompressed copy with\n+\t * CONFIG_DEBUG_INFO_BTF_LAZY, which is never freed either.\n \t */\n \tif (!btf_is_vmlinux(btf))\n \t\tkvfree(btf-\u003edata);\n@@ -6524,8 +6525,6 @@ static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,\n \treturn ERR_PTR(err);\n }\n \n-extern char __start_BTF[];\n-extern char __stop_BTF[];\n extern struct btf *btf_vmlinux;\n \n #define BPF_MAP_TYPE(_id, _ops)\n@@ -6558,20 +6557,46 @@ static u8 bpf_ctx_convert_map[] = {\n #undef BPF_MAP_TYPE\n #undef BPF_LINK_TYPE\n \n-static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)\n+#define BPF_MAP_TYPE(_id, _ops)\n+#define BPF_LINK_TYPE(_id, _name)\n+#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \\\n+\t[_id] = #prog_ctx_type,\n+static const char * const bpf_prog_ctx_tname[] = {\n+#include \u003clinux/bpf_types.h\u003e\n+};\n+#undef BPF_PROG_TYPE\n+#undef BPF_MAP_TYPE\n+#undef BPF_LINK_TYPE\n+\n+struct user_regs_struct;\n+struct user_pt_regs;\n+\n+/*\n+ * Name of the context struct of @prog_type, as written in bpf_types.h, or NULL\n+ * if it has none (\"void *\").  Only names are compared against the program's\n+ * BTF, so the vmlinux BTF is not needed.  *@alt is set to the struct behind\n+ * the bpf_user_pt_regs_t typedef.  Typedefs of integers (__u64, __u32) never\n+ * match a struct name.\n+ */\n+static const char *prog_ctx_tname(enum bpf_prog_type prog_type, const char **alt)\n {\n-\tconst struct btf_type *conv_struct;\n-\tconst struct btf_member *ctx_type;\n+\tconst char *name = prog_type \u003c ARRAY_SIZE(bpf_prog_ctx_tname) ?\n+\t\t\t   bpf_prog_ctx_tname[prog_type] : NULL;\n \n-\tconv_struct = bpf_ctx_convert.t;\n-\tif (!conv_struct)\n+\t*alt = NULL;\n+\tif (!name || strchr(name, '*'))\n \t\treturn NULL;\n-\t/* prog_type is valid bpf program type. No need for bounds check. */\n-\tctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;\n-\t/* ctx_type is a pointer to prog_ctx_type in vmlinux.\n-\t * Like 'struct __sk_buff'\n-\t */\n-\treturn btf_type_by_id(btf_vmlinux, ctx_type-\u003etype);\n+\tif (str_has_prefix(name, \"struct \"))\n+\t\treturn name + strlen(\"struct \");\n+\tif (!strcmp(name, \"bpf_user_pt_regs_t\")) {\n+\t\tif (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs))\n+\t\t\t*alt = \"pt_regs\";\n+\t\telse if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs))\n+\t\t\t*alt = \"user_pt_regs\";\n+\t\telse if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct))\n+\t\t\t*alt = \"user_regs_struct\";\n+\t}\n+\treturn name;\n }\n \n static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)\n@@ -6579,9 +6604,10 @@ 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-\tif (!conv_struct)\n+\t/* bpf_ctx_convert.t is set when the vmlinux BTF is parsed */\n+\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))\n \t\treturn -EFAULT;\n+\tconv_struct = bpf_ctx_convert.t;\n \t/* prog_type is valid bpf program type. No need for bounds check. */\n \tctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;\n \t/* ctx_type is a pointer to prog_ctx_type in vmlinux.\n@@ -6603,8 +6629,7 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,\n \t\t\t  const struct btf_type *t, enum bpf_prog_type prog_type,\n \t\t\t  int arg)\n {\n-\tconst struct btf_type *ctx_type;\n-\tconst char *tname, *ctx_tname;\n+\tconst char *tname, *ctx_tname, *alt;\n \n \tt = btf_type_by_id(btf, t-\u003etype);\n \n@@ -6638,21 +6663,9 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,\n \t\treturn false;\n \t}\n \n-\tctx_type = find_canonical_prog_ctx_type(prog_type);\n-\tif (!ctx_type) {\n-\t\tbpf_log(log, \"btf_vmlinux is malformed\\n\");\n-\t\t/* should not happen */\n-\t\treturn false;\n-\t}\n-again:\n-\tctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type-\u003ename_off);\n-\tif (!ctx_tname) {\n-\t\t/* should not happen */\n-\t\tbpf_log(log, \"Please fix kernel include/linux/bpf_types.h\\n\");\n-\t\treturn false;\n-\t}\n \t/* program types without named context types work only with arg:ctx tag */\n-\tif (ctx_tname[0] == '\\0')\n+\tctx_tname = prog_ctx_tname(prog_type, \u0026alt);\n+\tif (!ctx_tname)\n \t\treturn false;\n \t/* only compare that prog's ctx type name is the same as\n \t * kernel expects. No need to compare field by field.\n@@ -6661,37 +6674,18 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,\n \t * int socket_filter_bpf_prog(struct __sk_buff *skb)\n \t * { // no fields of skb are ever used }\n \t */\n-\tif (btf_is_projection_of(ctx_tname, tname))\n+\tif (btf_is_projection_of(ctx_tname, tname) || !strcmp(ctx_tname, tname))\n \t\treturn true;\n-\tif (strcmp(ctx_tname, tname)) {\n-\t\t/* bpf_user_pt_regs_t is a typedef, so resolve it to\n-\t\t * underlying struct and check name again\n-\t\t */\n-\t\tif (!btf_type_is_modifier(ctx_type))\n-\t\t\treturn false;\n-\t\twhile (btf_type_is_modifier(ctx_type))\n-\t\t\tctx_type = btf_type_by_id(btf_vmlinux, ctx_type-\u003etype);\n-\t\tgoto again;\n-\t}\n-\treturn true;\n+\t/* bpf_user_pt_regs_t is a typedef, check the underlying struct too */\n+\treturn alt \u0026\u0026 !strcmp(alt, tname);\n }\n \n-/* forward declarations for arch-specific underlying types of\n- * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef\n- * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still\n- * works correctly with __builtin_types_compatible_p() on respective\n- * architectures\n- */\n-struct user_regs_struct;\n-struct user_pt_regs;\n-\n static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,\n \t\t\t\t      const struct btf_type *t, int arg,\n \t\t\t\t      enum bpf_prog_type prog_type,\n \t\t\t\t      enum bpf_attach_type attach_type)\n {\n-\tconst struct btf_type *ctx_type;\n-\tconst char *tname, *ctx_tname;\n+\tconst char *tname, *ctx_tname, *alt;\n \n \tif (!btf_is_ptr(t)) {\n \t\tbpf_log(log, \"arg#%d type isn't a pointer\\n\", arg);\n@@ -6791,27 +6785,20 @@ static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct\n \t\tbreak;\n \t}\n \n-\tctx_type = find_canonical_prog_ctx_type(prog_type);\n-\tif (!ctx_type) {\n-\t\t/* should not happen */\n-\t\tbpf_log(log, \"btf_vmlinux is malformed\\n\");\n-\t\treturn -EINVAL;\n-\t}\n-\n \t/* resolve typedefs and check that underlying structs are matching as well */\n-\twhile (btf_type_is_modifier(ctx_type))\n-\t\tctx_type = btf_type_by_id(btf_vmlinux, ctx_type-\u003etype);\n+\tctx_tname = prog_ctx_tname(prog_type, \u0026alt);\n+\tif (ctx_tname \u0026\u0026 !str_has_prefix(bpf_prog_ctx_tname[prog_type], \"struct \"))\n+\t\tctx_tname = alt;\n \n \t/* if program type doesn't have distinctly named struct type for\n \t * context, then __arg_ctx argument can only be `void *`, which we\n \t * already checked above\n \t */\n-\tif (!__btf_type_is_struct(ctx_type)) {\n+\tif (!ctx_tname) {\n \t\tbpf_log(log, \"arg#%d should be void pointer\\n\", arg);\n \t\treturn -EINVAL;\n \t}\n \n-\tctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type-\u003ename_off);\n \tif (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {\n \t\tbpf_log(log, \"arg#%d should be `struct %s *`\\n\", arg, ctx_tname);\n \t\treturn -EINVAL;\n@@ -6838,6 +6825,8 @@ 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+\tif (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))\n+\t\treturn -EINVAL;\n \tconv_struct = bpf_ctx_convert.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@@ -6911,15 +6900,21 @@ struct btf *btf_parse_vmlinux(void)\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+\tdata = btf_vmlinux_data(\u0026size);\n+\tif (IS_ERR(data))\n+\t\treturn ERR_CAST(data);\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@@ -6935,6 +6930,75 @@ struct btf *btf_parse_vmlinux(void)\n \treturn btf;\n }\n \n+static DEFINE_MUTEX(btf_vmlinux_lock);\n+/* CONFIG_DEBUG_INFO_BTF_LAZY: the task applying deferred work, and its BTF */\n+static struct task_struct *btf_vmlinux_builder;\n+static struct btf *btf_vmlinux_new;\n+static int btf_apply_deferred(void);\n+static void btf_drop_all_deferred(int err);\n+\n+static bool btf_vmlinux_building(void)\n+{\n+\treturn in_task() \u0026\u0026 READ_ONCE(btf_vmlinux_builder) == current;\n+}\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+\n+\t/* with CONFIG_DEBUG_INFO_BTF_LAZY any call may be the one that parses */\n+\tif (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))\n+\t\tmight_sleep();\n+\tif (btf || !IS_ENABLED(CONFIG_DEBUG_INFO_BTF))\n+\t\treturn btf;\n+\t/* the registrations btf_apply_deferred() applies see the new BTF */\n+\tif (btf_vmlinux_building())\n+\t\treturn btf_vmlinux_new;\n+\n+\tmutex_lock(\u0026btf_vmlinux_lock);\n+\tbtf = btf_vmlinux;\n+\tif (!btf) {\n+\t\tbtf = btf_parse_vmlinux();\n+\t\tif (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) \u0026\u0026 !IS_ERR(btf)) {\n+\t\t\tint err;\n+\n+\t\t\tbtf_vmlinux_new = btf;\n+\t\t\tWRITE_ONCE(btf_vmlinux_builder, current);\n+\t\t\terr = btf_apply_deferred();\n+\t\t\tWRITE_ONCE(btf_vmlinux_builder, NULL);\n+\t\t\tbtf_vmlinux_new = NULL;\n+\t\t\tif (err) {\n+\t\t\t\t/* nothing saw it: drop it with what was applied to it */\n+\t\t\t\tbpf_ctx_convert.t = NULL;\n+\t\t\t\tbtf_put(btf);\n+\t\t\t\tbtf = ERR_PTR(err);\n+\t\t\t}\n+\t\t}\n+\t\t/* a lazy parse that ran out of memory is retried by the next caller */\n+\t\tif (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || btf != ERR_PTR(-ENOMEM)) {\n+\t\t\tif (IS_ERR(btf))\n+\t\t\t\tbtf_drop_all_deferred(PTR_ERR(btf));\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+\t\t}\n+\t}\n+\tmutex_unlock(\u0026btf_vmlinux_lock);\n+\treturn btf;\n+}\n+\n+/* The vmlinux BTF if it is parsed already: for callers that cannot sleep */\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 /* If .BTF_ids section was created with distilled base BTF, both base and\n  * split BTF ids will need to be mapped to actual base/split ids for\n  * BTF now that it has been relocated.\n@@ -6948,8 +7012,9 @@ __u32 btf_relocate_id(const struct btf *btf, __u32 id)\n \n #ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n \n+/* @data is a copy owned by the returned BTF; the caller frees it on error */\n static struct btf *btf_parse_split(struct btf_verifier_env *env,\n-\t\t\t\t   const char *name, const void *data,\n+\t\t\t\t   const char *name, void *data,\n \t\t\t\t   unsigned int data_size, struct btf *base_btf)\n {\n \tstruct btf *btf;\n@@ -6965,11 +7030,7 @@ static struct btf *btf_parse_split(struct btf_verifier_env *env,\n \tbtf-\u003enamed_start_id = 0;\n \tstrscpy(btf-\u003ename, name);\n \n-\tbtf-\u003edata = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);\n-\tif (!btf-\u003edata) {\n-\t\terr = -ENOMEM;\n-\t\tgoto errout;\n-\t}\n+\tbtf-\u003edata = data;\n \tbtf-\u003edata_size = data_size;\n \n \terr = btf_parse_hdr(env);\n@@ -6993,6 +7054,7 @@ static struct btf *btf_parse_split(struct btf_verifier_env *env,\n \treturn btf;\n \n errout:\n+\tbtf-\u003edata = NULL;\n \tbtf_free(btf);\n \treturn ERR_PTR(err);\n }\n@@ -7064,10 +7126,16 @@ static int btf_rebase_inline(struct btf *inline_btf,\n \treturn 0;\n }\n \n-static struct btf *btf_parse_module(const char *module_name, const void *data,\n+/*\n+ * @data and @inline_data are copies made by the caller.  On success the\n+ * returned BTF owns @data, and *@relocated_inline_data is @inline_data,\n+ * relocated in place, unless the inline BTF is invalid.  The caller frees\n+ * the copies this does not take.\n+ */\n+static struct btf *btf_parse_module(const char *module_name, 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-\t\t\t\t    const void *inline_data,\n+\t\t\t\t    void *inline_data,\n \t\t\t\t    unsigned int inline_data_size,\n \t\t\t\t    void **relocated_inline_data)\n {\n@@ -7135,6 +7203,7 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,\n \t\tif (err) {\n \t\t\tpr_warn(\"failed to relocate module [%s] inline BTF: %d\\n\",\n \t\t\t\tmodule_name, err);\n+\t\t\tinline_btf-\u003edata = NULL;\n \t\t\tbtf_free(inline_btf);\n \t\t} else {\n \t\t\t*relocated_inline_data = inline_btf-\u003edata;\n@@ -7158,12 +7227,16 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,\n errout:\n \tkvfree(module_str_map);\n \tbtf_verifier_env_free(env);\n-\tif (inline_btf)\n+\tif (inline_btf) {\n+\t\tinline_btf-\u003edata = NULL;\n \t\tbtf_free(inline_btf);\n+\t}\n \tif (!IS_ERR(base_btf) \u0026\u0026 base_btf != vmlinux_btf)\n \t\tbtf_free(base_btf);\n-\tif (btf)\n+\tif (btf) {\n+\t\tbtf-\u003edata = NULL;\n \t\tbtf_free(btf);\n+\t}\n \treturn ERR_PTR(err);\n }\n \n@@ -8566,6 +8639,7 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,\n \t\t.btf = btf,\n \t\t.log = log,\n \t};\n+\tstruct btf *vmlinux_btf;\n \tu32 kern_type_id, type_id;\n \tint err = 0;\n \n@@ -8577,6 +8651,10 @@ 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/* parse it, if this is its first use, before taking cand_cache_mutex */\n+\tvmlinux_btf = bpf_get_btf_vmlinux();\n+\tif (IS_ERR(vmlinux_btf))\n+\t\treturn PTR_ERR(vmlinux_btf);\n \tmutex_lock(\u0026cand_cache_mutex);\n \tcc = bpf_core_find_cands(\u0026ctx, type_id);\n \tif (IS_ERR(cc)) {\n@@ -9262,6 +9340,10 @@ int btf_get_fd_by_id(u32 id)\n \tstruct btf *btf;\n \tint fd;\n \n+\t/* kernel BTFs get their ids while parsed, before they are published */\n+\tif (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))\n+\t\tbpf_get_btf_vmlinux();\n+\n \trcu_read_lock();\n \tbtf = idr_find(\u0026btf_idr, id);\n \tif (!btf || !refcount_inc_not_zero(\u0026btf-\u003erefcnt))\n@@ -9301,10 +9383,13 @@ enum {\n struct btf_module {\n \tstruct list_head list;\n \tstruct module *module;\n-\tstruct btf *btf;\n+\tstruct btf *btf;\t/* NULL while kept, see btf_module_keep() */\n+\tvoid *data;\t\t/* kept copy of .BTF, adopted by btf once parsed */\n+\tu32 data_size;\n \tstruct bin_attribute *sysfs_attr;\n \tstruct bin_attribute *sysfs_inline_attr;\n \tvoid *btf_inline_data;\n+\tu32 btf_inline_data_size;\n \tint flags;\n };\n \n@@ -9312,6 +9397,150 @@ static LIST_HEAD(btf_modules);\n static DEFINE_MUTEX(btf_module_mutex);\n \n static void purge_cand_cache(struct btf *btf);\n+static void btf_drop_deferred_regs(struct module *owner);\n+\n+/* /sys/kernel/btf/\u003cmodule\u003e and \u003cmodule\u003e.inline */\n+static void btf_module_add_files(struct btf_module *btf_mod, const char *name,\n+\t\t\t\t void *data, u32 data_size)\n+{\n+\tchar inline_name[MODULE_NAME_LEN + sizeof(\".inline\")];\n+\tstruct bin_attribute *attr;\n+\n+\tattr = sysfs_btf_add(name, data, data_size, false, NULL);\n+\tif (IS_ERR(attr))\n+\t\treturn;\n+\tbtf_mod-\u003esysfs_attr = attr;\n+\n+\tif (!btf_mod-\u003ebtf_inline_data)\n+\t\treturn;\n+\tsnprintf(inline_name, sizeof(inline_name), \"%s.inline\", name);\n+\tattr = sysfs_btf_add(inline_name, btf_mod-\u003ebtf_inline_data,\n+\t\t\t     btf_mod-\u003ebtf_inline_data_size, false, NULL);\n+\tif (IS_ERR(attr)) {\n+\t\tkvfree(btf_mod-\u003ebtf_inline_data);\n+\t\tbtf_mod-\u003ebtf_inline_data = NULL;\n+\t\treturn;\n+\t}\n+\tbtf_mod-\u003esysfs_inline_attr = attr;\n+}\n+\n+/*\n+ * CONFIG_DEBUG_INFO_BTF_LAZY: module BTF is split BTF on top of the vmlinux\n+ * BTF.  Until that is parsed, keep the module's copies of its BTF and inline\n+ * BTF as they are, serve them in sysfs, and let btf_parse_kept_modules()\n+ * parse them with the vmlinux BTF.  Distilled base BTF (.BTF.base) needs\n+ * relocation, which needs the vmlinux BTF, so it is parsed right away.\n+ *\n+ * TODO: defer modules with distilled base BTF as well: keep them here and\n+ * relocate them in btf_parse_kept_modules().  Their raw BTF is not usable\n+ * before that, so their sysfs files would have to wait for the first use.\n+ */\n+static bool btf_module_keep(struct btf_module *btf_mod, struct module *mod,\n+\t\t\t    void *data, void *inline_data, u32 inline_data_size)\n+{\n+\tif (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || mod-\u003ebtf_base_data)\n+\t\treturn false;\n+\tguard(mutex)(\u0026btf_vmlinux_lock);\n+\tif (btf_vmlinux)\n+\t\treturn false;\n+\tbtf_mod-\u003emodule = mod;\n+\tbtf_mod-\u003edata = data;\n+\tbtf_mod-\u003edata_size = mod-\u003ebtf_data_size;\n+\tbtf_mod-\u003ebtf_inline_data = inline_data;\n+\tbtf_mod-\u003ebtf_inline_data_size = inline_data ? inline_data_size : 0;\n+\t/* before btf_parse_kept_modules() can see the entry */\n+\tbtf_module_add_files(btf_mod, mod-\u003ename, data, mod-\u003ebtf_data_size);\n+\tmutex_lock(\u0026btf_module_mutex);\n+\tlist_add(\u0026btf_mod-\u003elist, \u0026btf_modules);\n+\tmutex_unlock(\u0026btf_module_mutex);\n+\treturn true;\n+}\n+\n+/* A kept module without BTF: no entry and no files, as if refused at load */\n+static void btf_module_drop_kept(struct btf_module *btf_mod)\n+{\n+\tlist_del(\u0026btf_mod-\u003elist);\n+\tif (btf_mod-\u003esysfs_attr)\n+\t\tsysfs_btf_remove(btf_mod-\u003esysfs_attr);\n+\tif (btf_mod-\u003esysfs_inline_attr)\n+\t\tsysfs_btf_remove(btf_mod-\u003esysfs_inline_attr);\n+\tkvfree(btf_mod-\u003ebtf_inline_data);\n+\tkvfree(btf_mod-\u003edata);\n+\tkfree(btf_mod);\n+}\n+\n+/* Undo btf_parse_kept_modules() of a round that is not published */\n+static void btf_unparse_kept_modules(void)\n+{\n+\tstruct btf_module *btf_mod;\n+\n+\tlockdep_assert_held(\u0026btf_module_mutex);\n+\tlist_for_each_entry(btf_mod, \u0026btf_modules, list) {\n+\t\tif (!btf_mod-\u003edata || !btf_mod-\u003ebtf)\n+\t\t\tcontinue;\n+\t\tbtf_mod-\u003ebtf-\u003edata = NULL;\t/* the kept copy */\n+\t\tbtf_put(btf_mod-\u003ebtf);\n+\t\tbtf_mod-\u003ebtf = NULL;\n+\t}\n+}\n+\n+/*\n+ * Called under btf_vmlinux_lock by the task that parses the vmlinux BTF,\n+ * before that is published.  Parses the kept module BTFs in place, oldest\n+ * first so that ids follow the load order as without\n+ * CONFIG_DEBUG_INFO_BTF_LAZY; in-tree module BTF and its inline BTF need no\n+ * relocation, so sysfs serves the same bytes before and after.  A module\n+ * whose BTF fails validation cannot be refused any more: it stays loaded\n+ * without BTF, and its files go away; an invalid inline BTF loses its file.\n+ * Returns -ENOMEM, with this round's module BTFs freed again, if memory ran\n+ * out.\n+ */\n+static int btf_parse_kept_modules(void)\n+{\n+\tstruct btf_module *btf_mod, *tmp;\n+\tvoid *inline_data;\n+\tstruct btf *btf;\n+\tint err;\n+\n+\tlockdep_assert_held(\u0026btf_vmlinux_lock);\n+\tguard(mutex)(\u0026btf_module_mutex);\n+\tlist_for_each_entry_safe_reverse(btf_mod, tmp, \u0026btf_modules, list) {\n+\t\tif (btf_mod-\u003ebtf || !btf_mod-\u003edata)\n+\t\t\tcontinue;\n+\t\tbtf = btf_parse_module(btf_mod-\u003emodule-\u003ename, btf_mod-\u003edata,\n+\t\t\t\t       btf_mod-\u003edata_size, NULL, 0,\n+\t\t\t\t       btf_mod-\u003ebtf_inline_data,\n+\t\t\t\t       btf_mod-\u003ebtf_inline_data_size, \u0026inline_data);\n+\t\tif (!IS_ERR(btf)) {\n+\t\t\terr = btf_alloc_id(btf);\n+\t\t\tif (err) {\n+\t\t\t\tbtf-\u003edata = NULL;\t/* the kept copy */\n+\t\t\t\tbtf_free(btf);\n+\t\t\t\tbtf = ERR_PTR(err);\n+\t\t\t}\n+\t\t}\n+\t\tif (btf == ERR_PTR(-ENOMEM)) {\n+\t\t\tbtf_unparse_kept_modules();\n+\t\t\treturn -ENOMEM;\n+\t\t}\n+\t\tif (IS_ERR(btf)) {\n+\t\t\tpr_warn(\"failed to validate module [%s] BTF: %ld\\n\",\n+\t\t\t\tbtf_mod-\u003emodule-\u003ename, PTR_ERR(btf));\n+\t\t\tbtf_module_drop_kept(btf_mod);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tbtf_mod-\u003ebtf = btf;\n+\t\tif (btf_mod-\u003ebtf_inline_data \u0026\u0026 !inline_data) {\n+\t\t\tif (btf_mod-\u003esysfs_inline_attr)\n+\t\t\t\tsysfs_btf_remove(btf_mod-\u003esysfs_inline_attr);\n+\t\t\tbtf_mod-\u003esysfs_inline_attr = NULL;\n+\t\t\tkvfree(btf_mod-\u003ebtf_inline_data);\n+\t\t\tbtf_mod-\u003ebtf_inline_data = NULL;\n+\t\t\tbtf_mod-\u003ebtf_inline_data_size = 0;\n+\t\t}\n+\t}\n+\treturn 0;\n+}\n \n #if IS_MODULE(CONFIG_DEBUG_INFO_BTF_INLINE)\n extern char __start_BTF_inline_link[];\n@@ -9422,9 +9651,8 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n {\n \tstruct btf_module *btf_mod, *tmp;\n \tstruct module *mod = module;\n-\tstruct bin_attribute *attr;\n \tstruct btf *btf;\n-\tvoid *inline_data = NULL, *relocated_inline_data = NULL;\n+\tvoid *data, *inline_data = NULL, *relocated_inline_data = NULL;\n \tunsigned int inline_data_size = 0;\n \tint err = 0;\n \n@@ -9452,11 +9680,26 @@ 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\tdata = kvmemdup(mod-\u003ebtf_data, mod-\u003ebtf_data_size, GFP_KERNEL | __GFP_NOWARN);\n+\t\tif (inline_data) {\n+\t\t\tinline_data = kvmemdup(inline_data, inline_data_size,\n+\t\t\t\t\t       GFP_KERNEL | __GFP_NOWARN);\n+\t\t\tif (!inline_data)\n+\t\t\t\tpr_warn(\"failed to validate module [%s] inline BTF: %d\\n\",\n+\t\t\t\t\tmod-\u003ename, -ENOMEM);\n+\t\t}\n+\t\tif (data \u0026\u0026 btf_module_keep(btf_mod, mod, data, inline_data,\n+\t\t\t\t\t    inline_data_size))\n+\t\t\tbreak;\n+\t\tbtf = !data ? ERR_PTR(-ENOMEM) :\n+\t\t      btf_parse_module(mod-\u003ename, data, mod-\u003ebtf_data_size,\n \t\t\t\t       mod-\u003ebtf_base_data, mod-\u003ebtf_base_data_size,\n-\t\t\t\t       inline_data, inline_data_size,\n+\t\t\t\t       inline_data, inline_data ? inline_data_size : 0,\n \t\t\t\t       \u0026relocated_inline_data);\n+\t\tif (inline_data != relocated_inline_data)\n+\t\t\tkvfree(inline_data);\n \t\tif (IS_ERR(btf)) {\n+\t\t\tkvfree(data);\n \t\t\tkfree(btf_mod);\n \t\t\tif (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {\n \t\t\t\tpr_warn(\"failed to validate module [%s] BTF: %ld\\n\",\n@@ -9480,30 +9723,12 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \t\tbtf_mod-\u003emodule = module;\n \t\tbtf_mod-\u003ebtf = btf;\n \t\tbtf_mod-\u003ebtf_inline_data = relocated_inline_data;\n+\t\tbtf_mod-\u003ebtf_inline_data_size = relocated_inline_data ? inline_data_size : 0;\n \t\tlist_add(\u0026btf_mod-\u003elist, \u0026btf_modules);\n \t\tmutex_unlock(\u0026btf_module_mutex);\n \n-\t\tattr = sysfs_btf_add(btf-\u003ename, btf-\u003edata, btf-\u003edata_size, false, NULL);\n-\t\tif (IS_ERR(attr)) {\n-\t\t\terr = 0;\n-\t\t\tgoto out;\n-\t\t}\n-\t\tbtf_mod-\u003esysfs_attr = attr;\n-\n-\t\tif (relocated_inline_data) {\n-\t\t\tchar name[MODULE_NAME_LEN + sizeof(\".inline\")];\n-\n-\t\t\tsnprintf(name, sizeof(name), \"%s.inline\", mod-\u003ename);\n-\t\t\tattr = sysfs_btf_add(name, relocated_inline_data,\n-\t\t\t\t\t     inline_data_size, false, NULL);\n-\t\t\tif (IS_ERR(attr)) {\n-\t\t\t\tkvfree(relocated_inline_data);\n-\t\t\t\tbtf_mod-\u003ebtf_inline_data = NULL;\n-\t\t\t\terr = 0;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t\tbtf_mod-\u003esysfs_inline_attr = attr;\n-\t\t}\n+\t\t/* data: the same as btf-\u003edata */\n+\t\tbtf_module_add_files(btf_mod, mod-\u003ename, data, mod-\u003ebtf_data_size);\n \t\tbreak;\n \tcase MODULE_STATE_LIVE:\n \t\tif (!mod-\u003ebtf_data_size)\n@@ -9521,11 +9746,17 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,\n \tcase MODULE_STATE_GOING:\n \t\tif (!mod-\u003ebtf_data_size)\n \t\t\tbreak;\n+\t\tbtf_drop_deferred_regs(module);\n \t\tmutex_lock(\u0026btf_module_mutex);\n \t\tlist_for_each_entry_safe(btf_mod, tmp, \u0026btf_modules, list) {\n \t\t\tif (btf_mod-\u003emodule != module)\n \t\t\t\tcontinue;\n \n+\t\t\tif (!btf_mod-\u003ebtf) {\t/* kept, see btf_module_keep() */\n+\t\t\t\tbtf_module_drop_kept(btf_mod);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\n \t\t\t/*\n \t\t\t * For modules, we do the freeing of BTF IDR as soon as\n \t\t\t * module goes away to disable BTF discovery, since the\n@@ -9610,9 +9841,12 @@ struct btf *btf_get_module_btf(const struct module *module)\n \t}\n \n #ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+\t/* kept module BTF is parsed together with the vmlinux BTF */\n+\tif (!module-\u003ebtf_data_size || IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))\n+\t\treturn NULL;\n \tmutex_lock(\u0026btf_module_mutex);\n \tlist_for_each_entry_safe(btf_mod, tmp, \u0026btf_modules, list) {\n-\t\tif (btf_mod-\u003emodule != module)\n+\t\tif (btf_mod-\u003emodule != module || !btf_mod-\u003ebtf)\n \t\t\tcontinue;\n \n \t\tbtf_get(btf_mod-\u003ebtf);\n@@ -9803,7 +10037,7 @@ 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\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@@ -10129,12 +10363,88 @@ 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+enum btf_deferred_kind { BTF_DEFER_KFUNCS, BTF_DEFER_DTORS, BTF_DEFER_ST_OPS };\n+\n+/* CONFIG_DEBUG_INFO_BTF_LAZY: a registration made before the vmlinux BTF is parsed */\n+struct btf_deferred_reg {\n+\tstruct list_head list;\n+\tstruct module *owner;\n+\tenum btf_deferred_kind kind;\n+\tenum btf_kfunc_hook hook;\n+\tvoid *data;\n+\tu32 cnt;\n+};\n+\n+/* protected by btf_vmlinux_lock */\n+static LIST_HEAD(btf_deferred_regs);\n+\n+/*\n+ * Does a registration by @owner need the vmlinux BTF?  Without module BTF a\n+ * module's registrations do nothing but warn (check_btf_kconfigs()), and\n+ * btf_module_notify(), which drops a going module's queued entries, does not\n+ * see such a module.\n+ */\n+static bool btf_reg_needs_vmlinux(const struct module *owner)\n+{\n+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+\treturn !owner || owner-\u003ebtf_data_size;\n+#else\n+\treturn !owner;\n+#endif\n+}\n+\n+/*\n+ * Initcalls and modules loaded early register kfuncs, dtor kfuncs and\n+ * struct_ops before anything needs the vmlinux BTF.  Queue these until it\n+ * is parsed (btf_apply_deferred()).  Returns true if the registration was\n+ * queued, with *err set to 0 or -ENOMEM.\n+ */\n+static bool btf_defer_reg(struct module *owner, enum btf_deferred_kind kind,\n+\t\t\t  enum btf_kfunc_hook hook, const void *data, u32 cnt, int *err)\n+{\n+\tstruct btf_deferred_reg *reg;\n+\n+\tif (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || bpf_peek_btf_vmlinux() ||\n+\t    btf_vmlinux_building() || !btf_reg_needs_vmlinux(owner))\n+\t\treturn false;\n+\tguard(mutex)(\u0026btf_vmlinux_lock);\n+\tif (btf_vmlinux)\n+\t\treturn false;\n+\n+\t*err = -ENOMEM;\n+\treg = kzalloc_obj(*reg);\n+\tif (!reg)\n+\t\treturn true;\n+\t/* callers may build kfunc sets and dtor arrays on the stack */\n+\tif (kind == BTF_DEFER_KFUNCS)\n+\t\treg-\u003edata = kmemdup(data, sizeof(struct btf_kfunc_id_set), GFP_KERNEL);\n+\telse if (kind == BTF_DEFER_DTORS)\n+\t\treg-\u003edata = kmemdup_array(data, cnt, sizeof(struct btf_id_dtor_kfunc),\n+\t\t\t\t\t  GFP_KERNEL);\n+\telse\n+\t\treg-\u003edata = (void *)data;\n+\tif (!reg-\u003edata) {\n+\t\tkfree(reg);\n+\t\treturn true;\n+\t}\n+\treg-\u003eowner = owner;\n+\treg-\u003ekind = kind;\n+\treg-\u003ehook = hook;\n+\treg-\u003ecnt = cnt;\n+\tlist_add_tail(\u0026reg-\u003elist, \u0026btf_deferred_regs);\n+\t*err = 0;\n+\treturn true;\n+}\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 *btf;\n \tint ret, i;\n \n+\tif (btf_defer_reg(kset-\u003eowner, BTF_DEFER_KFUNCS, hook, kset, 0, \u0026ret))\n+\t\treturn ret;\n+\n \tbtf = btf_get_module_btf(kset-\u003eowner);\n \tif (!btf)\n \t\treturn check_btf_kconfigs(kset-\u003eowner, \"kfunc\");\n@@ -10251,6 +10561,9 @@ int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_c\n \tu32 tab_cnt, i;\n \tint ret;\n \n+\tif (btf_defer_reg(owner, BTF_DEFER_DTORS, 0, dtors, add_cnt, \u0026ret))\n+\t\treturn ret;\n+\n \tbtf = btf_get_module_btf(owner);\n \tif (!btf)\n \t\treturn check_btf_kconfigs(owner, \"dtor kfuncs\");\n@@ -10579,7 +10892,8 @@ 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+\t/* callers parse it before taking cand_cache_mutex, see bpf_core_apply() */\n+\tmain_btf = bpf_peek_btf_vmlinux();\n \tif (IS_ERR(main_btf))\n \t\treturn ERR_CAST(main_btf);\n \tif (!main_btf)\n@@ -10682,8 +10996,18 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,\n \n \tif (need_cands) {\n \t\tstruct bpf_cand_cache *cc;\n+\t\tstruct btf *main_btf;\n \t\tint i;\n \n+\t\t/*\n+\t\t * Parsing the vmlinux BTF takes btf_module_mutex, which is\n+\t\t * taken before cand_cache_mutex when a module goes away.\n+\t\t */\n+\t\tmain_btf = bpf_get_btf_vmlinux();\n+\t\tif (IS_ERR(main_btf)) {\n+\t\t\tkfree(specs);\n+\t\t\treturn PTR_ERR(main_btf);\n+\t\t}\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@@ -10957,6 +11281,9 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n \tstruct btf *btf;\n \tint err = 0;\n \n+\tif (btf_defer_reg(st_ops-\u003eowner, BTF_DEFER_ST_OPS, 0, st_ops, 0, \u0026err))\n+\t\treturn err;\n+\n \tbtf = btf_get_module_btf(st_ops-\u003eowner);\n \tif (!btf)\n \t\treturn check_btf_kconfigs(st_ops-\u003eowner, \"struct_ops\");\n@@ -10982,6 +11309,103 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);\n #endif\n \n+static void btf_free_deferred_reg(struct btf_deferred_reg *reg)\n+{\n+\tlist_del(\u0026reg-\u003elist);\n+\tif (reg-\u003ekind != BTF_DEFER_ST_OPS)\n+\t\tkfree(reg-\u003edata);\n+\tkfree(reg);\n+}\n+\n+/*\n+ * Called under btf_vmlinux_lock, by the task that parsed the vmlinux BTF and\n+ * before it publishes it, so that nothing sees the BTF without its module\n+ * BTFs, kfuncs and struct_ops.  bpf_get_btf_vmlinux() returns the new BTF to\n+ * this task, so the registrations are applied as if they were made now, and\n+ * any they make in turn (a struct_ops -\u003einit() may register kfuncs) too.\n+ * They run in whichever task needs the BTF first, with the locks it holds:\n+ * they must not load modules or take locks that users of the BTF hold.\n+ *\n+ * Returns -ENOMEM if memory ran out, which may be only because that task is\n+ * being killed: the caller then drops the new BTF with whatever was applied\n+ * to it, and the next caller starts over with the queue intact, as for the\n+ * vmlinux BTF itself; a struct_ops -\u003einit() then runs again with the BTF of\n+ * that round.  Any other error of a registration is only logged.\n+ */\n+static int btf_apply_deferred(void)\n+{\n+\tstruct btf_deferred_reg *reg, *tmp;\n+\tint err;\n+\n+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+\terr = btf_parse_kept_modules();\n+\tif (err)\n+\t\treturn err;\n+#endif\n+\tlist_for_each_entry(reg, \u0026btf_deferred_regs, list) {\n+\t\t/* a going module's exit() runs before GOING drops its entries */\n+\t\tif (!try_module_get(reg-\u003eowner))\n+\t\t\tcontinue;\n+\t\terr = 0;\n+\t\tswitch (reg-\u003ekind) {\n+\t\tcase BTF_DEFER_KFUNCS:\n+\t\t\terr = __register_btf_kfunc_id_set(reg-\u003ehook, reg-\u003edata);\n+\t\t\tbreak;\n+\t\tcase BTF_DEFER_DTORS:\n+\t\t\terr = register_btf_id_dtor_kfuncs(reg-\u003edata, reg-\u003ecnt, reg-\u003eowner);\n+\t\t\tbreak;\n+\t\tcase BTF_DEFER_ST_OPS:\n+#if defined(CONFIG_BPF_JIT)\n+\t\t\terr = __register_bpf_struct_ops(reg-\u003edata);\n+#endif\n+\t\t\tbreak;\n+\t\t}\n+\t\tmodule_put(reg-\u003eowner);\n+\t\tif (err == -ENOMEM) {\n+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES\n+\t\t\tguard(mutex)(\u0026btf_module_mutex);\n+\t\t\tbtf_unparse_kept_modules();\n+#endif\n+\t\t\treturn err;\n+\t\t}\n+\t\tif (err)\n+\t\t\tpr_warn(\"failed to apply deferred BTF registration for %s: %d\\n\",\n+\t\t\t\treg-\u003eowner ? reg-\u003eowner-\u003ename : \"vmlinux\", err);\n+\t}\n+\tlist_for_each_entry_safe(reg, tmp, \u0026btf_deferred_regs, list)\n+\t\tbtf_free_deferred_reg(reg);\n+\treturn 0;\n+}\n+\n+/* The vmlinux BTF failed for good: nothing will apply what is queued */\n+static void btf_drop_all_deferred(int err)\n+{\n+\tstruct btf_deferred_reg *reg, *tmp;\n+\tint cnt = 0;\n+\n+\tlist_for_each_entry_safe(reg, tmp, \u0026btf_deferred_regs, list) {\n+\t\tbtf_free_deferred_reg(reg);\n+\t\tcnt++;\n+\t}\n+\tif (cnt)\n+\t\tpr_warn(\"vmlinux BTF unavailable (%d), dropped %d deferred BTF registrations\\n\",\n+\t\t\terr, cnt);\n+}\n+\n+/* @owner is going away: drop the registrations it queued */\n+static void __maybe_unused btf_drop_deferred_regs(struct module *owner)\n+{\n+\tstruct btf_deferred_reg *reg, *tmp;\n+\n+\tif (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))\n+\t\treturn;\n+\tguard(mutex)(\u0026btf_vmlinux_lock);\n+\tlist_for_each_entry_safe(reg, tmp, \u0026btf_deferred_regs, list) {\n+\t\tif (reg-\u003eowner == owner)\n+\t\t\tbtf_free_deferred_reg(reg);\n+\t}\n+}\n+\n bool btf_param_match_suffix(const struct btf *btf,\n \t\t\t    const struct btf_param *arg,\n \t\t\t    const char *suffix)\ndiff --git a/kernel/bpf/inode.c b/kernel/bpf/inode.c\nindex c6f328e4752e1d..39750d4ad401a7 100644\n--- a/kernel/bpf/inode.c\n+++ b/kernel/bpf/inode.c\n@@ -1059,6 +1059,13 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param)\n \t\tchar *p, *str;\n \t\tint val;\n \n+\t\t/*\n+\t\t * Setting delegation mount options requires privileges.  Check\n+\t\t * before the lookup, which may have to parse the vmlinux BTF.\n+\t\t */\n+\t\tif (!capable(CAP_SYS_ADMIN))\n+\t\t\treturn -EPERM;\n+\n \t\t/* ignore errors, fallback to hex */\n \t\t(void)find_bpffs_btf_enums(\u0026info);\n \n@@ -1100,10 +1107,6 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param)\n \t\t\t}\n \t\t}\n \n-\t\t/* Setting delegation mount options requires privileges */\n-\t\tif (msk \u0026\u0026 !capable(CAP_SYS_ADMIN))\n-\t\t\treturn -EPERM;\n-\n \t\t*delegate_msk |= msk;\n \t\tbreak;\n \t}\ndiff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c\nindex 02ed5368f05626..fefbb641692b21 100644\n--- a/kernel/bpf/syscall.c\n+++ b/kernel/bpf/syscall.c\n@@ -3048,8 +3048,12 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at\n \t\t\t\tgoto put_token;\n \t\t\t}\n \t\t}\n-\t} else if (attr-\u003eattach_btf_id || multi_func) {\n-\t\t/* fall back to vmlinux BTF, if BTF type ID is specified */\n+\t} else if ((attr-\u003eattach_btf_id || multi_func) \u0026\u0026 bpf_cap) {\n+\t\t/*\n+\t\t * fall back to vmlinux BTF, if BTF type ID is specified; only\n+\t\t * program types that need CAP_BPF take one, and\n+\t\t * bpf_prog_load_check_attach() refuses it for the others\n+\t\t */\n \t\tattach_btf = bpf_get_btf_vmlinux();\n \t\tif (IS_ERR(attach_btf)) {\n \t\t\terr = PTR_ERR(attach_btf);\n@@ -6511,6 +6515,10 @@ 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/* kernel BTFs have ids once parsed (CONFIG_DEBUG_INFO_BTF_LAZY) */\n+\t\tif (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) \u0026\u0026\n+\t\t    ns_capable_noaudit(\u0026init_user_ns, CAP_SYS_ADMIN))\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 556fe92c36495d..015cd82211541b 100644\n--- a/kernel/bpf/sysfs_btf.c\n+++ b/kernel/bpf/sysfs_btf.c\n@@ -12,11 +12,126 @@\n #include \u003clinux/vmalloc.h\u003e\n #include \u003clinux/io.h\u003e\n #include \u003clinux/btf.h\u003e\n+#include \u003clinux/zstd.h\u003e\n \n+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY\n+/* See scripts/gen-btf.sh, gen_btf_o() for details */\n+extern char __start_BTF_zst[];\n+extern char __stop_BTF_zst[];\n+\n+static DEFINE_MUTEX(btf_vmlinux_data_lock);\n+static void *btf_vmlinux_raw;\n+static u32 btf_vmlinux_raw_size;\n+static bool btf_vmlinux_broken;\n+/* Compressed BTF: init data until btf_vmlinux_keep_zst(), freed once decompressed */\n+static void *btf_zst = __start_BTF_zst;\n+\n+static u32 btf_vmlinux_size(void)\n+{\n+\tzstd_frame_header hdr;\n+\n+\tguard(mutex)(\u0026btf_vmlinux_data_lock);\n+\tif (!btf_vmlinux_raw_size \u0026\u0026 btf_zst \u0026\u0026\n+\t    !zstd_get_frame_header(\u0026hdr, btf_zst, __stop_BTF_zst - __start_BTF_zst) \u0026\u0026\n+\t    hdr.frameContentSize \u003c U32_MAX)\n+\t\tbtf_vmlinux_raw_size = hdr.frameContentSize;\n+\treturn btf_vmlinux_raw_size;\n+}\n+\n+static void btf_vmlinux_drop_zst(void)\n+{\n+\tif (btf_zst != __start_BTF_zst)\n+\t\tvfree(btf_zst);\n+\tbtf_zst = NULL;\n+}\n+\n+/*\n+ * The raw vmlinux BTF, decompressed on first use and never freed, or\n+ * ERR_PTR(-ENOMEM) if that cannot be done (now: memory; for good: no copy of\n+ * the compressed BTF), or ERR_PTR(-EINVAL) if it is broken.\n+ */\n+void *btf_vmlinux_data(u32 *size)\n+{\n+\tsize_t ret, ws_size = zstd_dctx_workspace_bound();\n+\tvoid *raw, *ws;\n+\n+\t/* Pairs with smp_store_release() below */\n+\traw = smp_load_acquire(\u0026btf_vmlinux_raw);\n+\tif (raw) {\n+\t\t*size = btf_vmlinux_raw_size;\n+\t\treturn raw;\n+\t}\n+\n+\t*size = btf_vmlinux_size();\n+\tguard(mutex)(\u0026btf_vmlinux_data_lock);\n+\tif (btf_vmlinux_raw)\n+\t\treturn btf_vmlinux_raw;\n+\tif (!btf_zst)\n+\t\treturn ERR_PTR(btf_vmlinux_broken ? -EINVAL : -ENOMEM);\n+\tif (!*size) {\n+\t\tpr_err(\"BTF: no size in the compressed vmlinux BTF\\n\");\n+\t\tbtf_vmlinux_broken = true;\n+\t\tbtf_vmlinux_drop_zst();\n+\t\treturn ERR_PTR(-EINVAL);\n+\t}\n+\t/* vmalloc_user(): btf_sysfs_vmlinux_mmap() maps it to user space */\n+\traw = vmalloc_user(*size);\n+\tws = kvmalloc(ws_size, GFP_KERNEL);\n+\tif (raw \u0026\u0026 ws) {\n+\t\tret = zstd_decompress_dctx(zstd_init_dctx(ws, ws_size), raw, *size,\n+\t\t\t\t\t   btf_zst, __stop_BTF_zst - __start_BTF_zst);\n+\t\tif (!zstd_is_error(ret) \u0026\u0026 ret == *size) {\n+\t\t\t/* Pairs with smp_load_acquire() above */\n+\t\t\tsmp_store_release(\u0026btf_vmlinux_raw, raw);\n+\t\t} else {\n+\t\t\tpr_err(\"BTF: cannot decompress the vmlinux BTF: %s\\n\",\n+\t\t\t       zstd_is_error(ret) ? zstd_get_error_name(ret) : \"size mismatch\");\n+\t\t\tbtf_vmlinux_broken = true;\n+\t\t}\n+\t\tbtf_vmlinux_drop_zst();\n+\t}\n+\tkvfree(ws);\n+\tif (btf_vmlinux_raw)\n+\t\treturn btf_vmlinux_raw;\n+\tvfree(raw);\n+\treturn ERR_PTR(btf_vmlinux_broken ? -EINVAL : -ENOMEM);\n+}\n+\n+/* Keep a copy of the compressed BTF before init memory is freed */\n+static int __init btf_vmlinux_keep_zst(void)\n+{\n+\tsize_t size = __stop_BTF_zst - __start_BTF_zst;\n+\n+\tguard(mutex)(\u0026btf_vmlinux_data_lock);\n+\tif (btf_zst) {\n+\t\t/* vmalloc(): kmalloc() would round up to a power of 2 */\n+\t\tbtf_zst = vmalloc(size);\n+\t\tif (btf_zst)\n+\t\t\tmemcpy(btf_zst, __start_BTF_zst, size);\n+\t\telse\n+\t\t\tpr_err(\"BTF: out of memory, vmlinux BTF unavailable\\n\");\n+\t}\n+\treturn 0;\n+}\n+late_initcall_sync(btf_vmlinux_keep_zst);\n+#else\n /* See scripts/link-vmlinux.sh, gen_btf() func for details */\n extern char __start_BTF[];\n extern char __stop_BTF[];\n \n+static u32 btf_vmlinux_size(void)\n+{\n+\treturn __stop_BTF - __start_BTF;\n+}\n+\n+void *btf_vmlinux_data(u32 *size)\n+{\n+\t*size = btf_vmlinux_size();\n+\treturn __start_BTF;\n+}\n+#endif\n+\n+#ifdef CONFIG_SYSFS\n static int btf_sysfs_mmap_check(void *data, size_t size, struct vm_area_struct *vma)\n {\n \tunsigned long pages = PAGE_ALIGN(size) \u003e\u003e PAGE_SHIFT;\n@@ -61,10 +176,49 @@ static int btf_sysfs_mmap_image(struct file *filp, struct kobject *kobj,\n \treturn remap_pfn_range(vma, vma-\u003evm_start, pfn, vm_size, vma-\u003evm_page_prot);\n }\n \n+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY\n+/* Reading or mapping the file decompresses the BTF but does not parse it */\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+\tvoid *data;\n+\tu32 size;\n+\tint err;\n+\n+\tdata = btf_vmlinux_data(\u0026size);\n+\tif (IS_ERR(data))\n+\t\treturn PTR_ERR(data);\n+\n+\terr = btf_sysfs_mmap_check(data, attr-\u003esize, vma);\n+\tif (err)\n+\t\treturn err;\n+\n+\treturn remap_vmalloc_range(vma, data, 0);\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, char *buf,\n+\t\t\t\t      loff_t off, size_t count)\n+{\n+\tvoid *data;\n+\tu32 size;\n+\n+\tdata = btf_vmlinux_data(\u0026size);\n+\tif (IS_ERR(data))\n+\t\treturn PTR_ERR(data);\n+\n+\treturn memory_read_from_buffer(buf, count, \u0026off, data, size);\n+}\n+#else\n+#define btf_sysfs_vmlinux_read\tsysfs_bin_attr_simple_read\n+#define btf_sysfs_vmlinux_mmap\tbtf_sysfs_mmap_image\n+#endif\n+\n static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {\n \t.attr = { .name = \"vmlinux\", .mode = 0444, },\n-\t.read = sysfs_bin_attr_simple_read,\n-\t.mmap = btf_sysfs_mmap_image,\n+\t.read = btf_sysfs_vmlinux_read,\n+\t.mmap = btf_sysfs_vmlinux_mmap,\n };\n \n struct kobject *btf_kobj;\n@@ -180,8 +334,12 @@ void sysfs_btf_remove(struct bin_attribute *attr)\n \n static int __init btf_vmlinux_init(void)\n {\n-\tbin_attr_btf_vmlinux.private = __start_BTF;\n-\tbin_attr_btf_vmlinux.size = __stop_BTF - __start_BTF;\n+\tu32 size;\n+\n+\t/* with CONFIG_DEBUG_INFO_BTF_LAZY the read and mmap handlers get it */\n+\tif (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))\n+\t\tbin_attr_btf_vmlinux.private = btf_vmlinux_data(\u0026size);\n+\tbin_attr_btf_vmlinux.size = btf_vmlinux_size();\n \n \tif (bin_attr_btf_vmlinux.size == 0)\n \t\treturn 0;\n@@ -194,3 +352,4 @@ static int __init btf_vmlinux_init(void)\n }\n \n subsys_initcall(btf_vmlinux_init);\n+#endif /* CONFIG_SYSFS */\ndiff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c\nindex 1b6c0674ff6a13..8606b97765e7eb 100644\n--- a/kernel/bpf/verifier.c\n+++ b/kernel/bpf/verifier.c\n@@ -320,7 +320,6 @@ static const char *btf_type_name(const struct btf *btf, u32 id)\n }\n \n static DEFINE_MUTEX(bpf_verifier_lock);\n-static DEFINE_MUTEX(btf_vmlinux_lock);\n static DEFINE_MUTEX(bpf_percpu_ma_lock);\n \n __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)\n@@ -3069,6 +3068,18 @@ static int fetch_kfunc_meta(struct bpf_verifier_env *env,\n static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n \t\t\t       const struct btf_func_model *fm, struct bpf_func_proto *proto);\n \n+/*\n+ * The vmlinux BTF failed to parse where a program first needs it: pass the\n+ * error on, as bpf_check() did when it fetched the BTF up front.  It need\n+ * not be for good: a parse on first use that runs out of memory is retried\n+ * by the next caller.\n+ */\n+static int vmlinux_btf_err(struct bpf_verifier_env *env, const struct btf *btf)\n+{\n+\tverbose(env, \"in-kernel BTF could not be parsed: %ld\\n\", PTR_ERR(btf));\n+\treturn PTR_ERR(btf);\n+}\n+\n int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n {\n \tstruct bpf_call_arg_meta meta;\n@@ -3085,7 +3096,11 @@ 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\tstruct btf *btf = bpf_get_btf_vmlinux();\n+\n+\t\tif (IS_ERR(btf))\n+\t\t\treturn vmlinux_btf_err(env, btf);\n+\t\tif (!btf) {\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@@ -6867,30 +6882,33 @@ static int check_ptr_to_map_access(struct bpf_verifier_env *env,\n \tenum bpf_type_flag flag = 0;\n \tconst struct btf_type *t;\n \tconst char *tname;\n+\tstruct btf *btf;\n \tu32 btf_id;\n \tint ret;\n \n-\tif (!btf_vmlinux) {\n-\t\tverbose(env, \"map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\\n\");\n-\t\treturn -ENOTSUPP;\n-\t}\n-\n \tif (!map-\u003eops-\u003emap_btf_id || !*map-\u003eops-\u003emap_btf_id) {\n \t\tverbose(env, \"map_ptr access not supported for map type %d\\n\",\n \t\t\tmap-\u003emap_type);\n \t\treturn -ENOTSUPP;\n \t}\n \n-\tt = btf_type_by_id(btf_vmlinux, *map-\u003eops-\u003emap_btf_id);\n-\ttname = btf_name_by_offset(btf_vmlinux, t-\u003ename_off);\n-\n+\t/* before the BTF fetch: unprivileged loads must not parse it */\n \tif (!env-\u003eallow_ptr_leaks) {\n-\t\tverbose(env,\n-\t\t\t\"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\\n\",\n-\t\t\ttname);\n+\t\tverbose(env, \"map_ptr access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\\n\");\n \t\treturn -EPERM;\n \t}\n \n+\tbtf = bpf_get_btf_vmlinux();\n+\tif (IS_ERR(btf))\n+\t\treturn vmlinux_btf_err(env, btf);\n+\tif (!btf) {\n+\t\tverbose(env, \"map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\\n\");\n+\t\treturn -ENOTSUPP;\n+\t}\n+\n+\tt = btf_type_by_id(btf, *map-\u003eops-\u003emap_btf_id);\n+\ttname = btf_name_by_offset(btf, t-\u003ename_off);\n+\n \tif (off \u003c 0) {\n \t\tverbose(env, \"%s is %s invalid negative access: off=%d\\n\",\n \t\t\treg_arg_name(env, argno), tname, off);\n@@ -12616,6 +12634,22 @@ static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n \treturn err;\n }\n \n+/* Does helper @fn bring kernel BTF types into the program? */\n+static bool helper_uses_vmlinux_btf(enum bpf_func_id func_id, const struct bpf_func_proto *fn)\n+{\n+\tint i;\n+\n+\t/* these take a kernel type id in struct btf_ptr */\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 ARRAY_SIZE(fn-\u003earg_type); i++)\n+\t\tif (base_type(fn-\u003earg_type[i]) == ARG_PTR_TO_BTF_ID)\n+\t\t\treturn true;\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@@ -12685,6 +12719,14 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn\n \t\treturn err;\n \t}\n \n+\tif (IS_ENABLED(CONFIG_DEBUG_INFO_BTF) \u0026\u0026 helper_uses_vmlinux_btf(func_id, fn)) {\n+\t\t/* never NULL with CONFIG_DEBUG_INFO_BTF */\n+\t\tstruct btf *btf = bpf_get_btf_vmlinux();\n+\n+\t\tif (IS_ERR(btf))\n+\t\t\treturn vmlinux_btf_err(env, btf);\n+\t}\n+\n \tif (fn-\u003emight_sleep \u0026\u0026 !in_sleepable_context(env)) {\n \t\tconst char *suggestion;\n \n@@ -13910,7 +13952,7 @@ BTF_SET_END(dynptr_write_kfuncs)\n \n static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta)\n {\n-\treturn meta-\u003ebtf == btf_vmlinux \u0026\u0026\n+\treturn is_kfunc(meta) \u0026\u0026 meta-\u003ebtf == btf_vmlinux \u0026\u0026\n \t       btf_id_set_contains(\u0026dynptr_write_kfuncs, meta-\u003efunc_id);\n }\n \n@@ -20960,12 +21002,14 @@ 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\tbtf = bpf_get_btf_vmlinux();\n+\t\tif (IS_ERR(btf))\n+\t\t\treturn vmlinux_btf_err(env, btf);\n+\t\tif (!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@@ -23182,29 +23226,6 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt\n \treturn 0;\n }\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-\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-\t\t}\n-\t\tmutex_unlock(\u0026btf_vmlinux_lock);\n-\t}\n-\treturn btf;\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@@ -23928,7 +23949,12 @@ 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 here but where kernel types enter\n+\t * the program (attach_btf, kfuncs, ksyms, map_ptr, BTF-typed helpers,\n+\t * CO-RE, kernel ctx types), so that programs which use none of them\n+\t * do not need it (CONFIG_DEBUG_INFO_BTF_LAZY).\n+\t */\n \n \t/* Serialize verification of unprivileged programs. */\n \tif (!is_priv)\n@@ -23949,13 +23975,6 @@ 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-\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\tgoto skip_full_check;\n-\t}\n-\n \tenv-\u003estrict_alignment = !!(attr-\u003eprog_flags \u0026 BPF_F_STRICT_ALIGNMENT);\n \tif (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))\n \t\tenv-\u003estrict_alignment = true;\ndiff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c\nindex 14adfb85fdb2be..92694d40c0c3e9 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/* fetched by the verifier, see helper_uses_vmlinux_btf() */\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_btf.c b/kernel/trace/trace_btf.c\nindex f0e0c04d58d99f..693c1a1083c55e 100644\n--- a/kernel/trace/trace_btf.c\n+++ b/kernel/trace/trace_btf.c\n@@ -1,4 +1,5 @@\n // SPDX-License-Identifier: GPL-2.0\n+#include \u003clinux/bpf.h\u003e\n #include \u003clinux/btf.h\u003e\n #include \u003clinux/kernel.h\u003e\n #include \u003clinux/slab.h\u003e\n@@ -141,6 +142,34 @@ const struct btf_member *btf_find_struct_member(struct btf *btf,\n \treturn member;\n }\n \n+static bool trace_btf_deferred;\n+\n+/*\n+ * func-args, funcgraph-args and funcgraph-retval print arguments and return\n+ * values by their BTF types, and the readers of the trace use the vmlinux\n+ * BTF only if it is parsed already: parse it when such output is enabled.\n+ * With CONFIG_DEBUG_INFO_BTF_LAZY that may be its first use, which should\n+ * not happen in a reader that holds the trace read locks while the tracer\n+ * records its work.\n+ */\n+void trace_btf_prepare(void)\n+{\n+\t/* trace_options= on the command line is applied by early_trace_init() */\n+\tif (system_state \u003c SYSTEM_SCHEDULING) {\n+\t\ttrace_btf_deferred = true;\n+\t\treturn;\n+\t}\n+\tbpf_get_btf_vmlinux();\n+}\n+\n+static int __init trace_btf_init(void)\n+{\n+\tif (trace_btf_deferred)\n+\t\tbpf_get_btf_vmlinux();\n+\treturn 0;\n+}\n+core_initcall(trace_btf_init);\n+\n void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retval,\n \t\t\tint *fmt, bool hex)\n {\n@@ -151,6 +180,9 @@ void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retv\n \tbool signed_type;\n \tint kind;\n \n+\t/* see trace_btf_prepare() */\n+\tif (IS_ERR_OR_NULL(bpf_peek_btf_vmlinux()))\n+\t\treturn;\n \tif (lookup_symbol_name(func, name))\n \t\treturn;\n \ndiff --git a/kernel/trace/trace_btf.h b/kernel/trace/trace_btf.h\nindex b3d408e6a7f6c4..47407eff1339b9 100644\n--- a/kernel/trace/trace_btf.h\n+++ b/kernel/trace/trace_btf.h\n@@ -23,9 +23,12 @@ const struct btf_member *btf_find_struct_member(struct btf *btf,\n #ifdef CONFIG_DEBUG_INFO_BTF\n void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retval,\n \t\t     int *fmt, bool hex);\n+void trace_btf_prepare(void);\n #else\n static inline void btf_trim_retval(unsigned long func, unsigned long *retval,\n \t\t\t\t   bool *print_retval, int *fmt, bool hex)\n {\n }\n+\n+static inline void trace_btf_prepare(void) { }\n #endif\ndiff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c\nindex 49d135bc2fbfcc..adc422fbe16eab 100644\n--- a/kernel/trace/trace_events.c\n+++ b/kernel/trace/trace_events.c\n@@ -23,6 +23,7 @@\n #include \u003clinux/sort.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/delay.h\u003e\n+#include \u003clinux/bpf.h\u003e\n #include \u003clinux/btf.h\u003e\n \n #include \u003ckunit/visibility.h\u003e\n@@ -2282,6 +2283,9 @@ event_btf_ids_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppo\n \tchar buf[128];\n \tint len;\n \n+\t/* parse the vmlinux BTF, if this is its first use, without event_mutex */\n+\tbpf_get_btf_vmlinux();\n+\n \t/* Module unload could free call-\u003eclass and ids[] mid-read. */\n \tscoped_guard(mutex, \u0026event_mutex) {\n \t\tfile = event_file_file(filp);\ndiff --git a/kernel/trace/trace_functions.c b/kernel/trace/trace_functions.c\nindex acaba990aaaa26..2cebaacda526f8 100644\n--- a/kernel/trace/trace_functions.c\n+++ b/kernel/trace/trace_functions.c\n@@ -18,6 +18,7 @@\n #include \u003clinux/fs.h\u003e\n \n #include \"trace.h\"\n+#include \"trace_btf.h\"\n \n static void tracing_start_function_trace(struct trace_array *tr);\n static void tracing_stop_function_trace(struct trace_array *tr);\n@@ -115,6 +116,9 @@ void ftrace_destroy_function_files(struct trace_array *tr)\n \n static ftrace_func_t select_trace_function(u32 flags_val)\n {\n+\tif (flags_val \u0026 TRACE_FUNC_OPT_ARGS)\n+\t\ttrace_btf_prepare();\n+\n \tswitch (flags_val \u0026 TRACE_FUNC_OPT_MASK) {\n \tcase TRACE_FUNC_NO_OPTS:\n \t\treturn function_trace_call;\ndiff --git a/kernel/trace/trace_functions_graph.c b/kernel/trace/trace_functions_graph.c\nindex 78a608315dd32b..cf5f433dd26e36 100644\n--- a/kernel/trace/trace_functions_graph.c\n+++ b/kernel/trace/trace_functions_graph.c\n@@ -474,6 +474,10 @@ static int graph_trace_init(struct trace_array *tr)\n {\n \tint ret;\n \n+\tif (tracer_flags_is_set(tr, TRACE_GRAPH_ARGS) ||\n+\t    tracer_flags_is_set(tr, TRACE_GRAPH_PRINT_RETVAL))\n+\t\ttrace_btf_prepare();\n+\n \tif (tracer_flags_is_set(tr, TRACE_GRAPH_ARGS))\n \t\ttr-\u003egops-\u003eentryfunc = trace_graph_entry_args;\n \telse\n@@ -507,10 +511,12 @@ static int ftrace_graph_trace_args(struct trace_array *tr, int set)\n {\n \ttrace_func_graph_ent_t entry;\n \n-\tif (set)\n+\tif (set) {\n+\t\ttrace_btf_prepare();\n \t\tentry = trace_graph_entry_args;\n-\telse\n+\t} else {\n \t\tentry = trace_graph_entry;\n+\t}\n \n \t/* See if there's any changes */\n \tif (tr-\u003egops-\u003eentryfunc == entry)\n@@ -1746,6 +1752,11 @@ func_graph_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set)\n \n \tcase TRACE_GRAPH_ARGS:\n \t\treturn ftrace_graph_trace_args(tr, set);\n+\n+\tcase TRACE_GRAPH_PRINT_RETVAL:\n+\t\tif (set)\n+\t\t\ttrace_btf_prepare();\n+\t\tbreak;\n \t}\n \n \treturn 0;\ndiff --git a/kernel/trace/trace_output.c b/kernel/trace/trace_output.c\nindex a5ad76175d10d4..cdb926c9d4e21d 100644\n--- a/kernel/trace/trace_output.c\n+++ b/kernel/trace/trace_output.c\n@@ -739,6 +739,9 @@ void print_function_args(struct trace_seq *s, unsigned long *args,\n \tif (lookup_symbol_name(func, name))\n \t\tgoto out;\n \n+\t/* see trace_btf_prepare() */\n+\tif (IS_ERR_OR_NULL(bpf_peek_btf_vmlinux()))\n+\t\tgoto out;\n \t/* TODO: Pass module name here too */\n \tt = btf_find_func_proto(name, \u0026btf);\n \tif (IS_ERR_OR_NULL(t))\ndiff --git a/lib/Kconfig.debug b/lib/Kconfig.debug\nindex 2d22638ec13a63..45b2bc4d9a9c75 100644\n--- a/lib/Kconfig.debug\n+++ b/lib/Kconfig.debug\n@@ -408,6 +408,30 @@ 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+config DEBUG_INFO_BTF_LAZY\n+\tbool \"Compress vmlinux BTF and parse it on first use\"\n+\tdepends on DEBUG_INFO_BTF\n+\tdepends on X86 || ARM64\n+\tselect ZSTD_DECOMPRESS\n+\thelp\n+\t  Keep the vmlinux BTF zstd-compressed in the kernel image, at about\n+\t  a quarter of its size, and decompress and parse it the first time\n+\t  something needs it instead of at boot.  Systems that never use BTF\n+\t  then keep only the compressed copy in memory, which saves about 80%\n+\t  of what the BTF costs; the first user pays a few tens of\n+\t  milliseconds once.  The vmlinux file keeps the uncompressed BTF as\n+\t  a non-loaded section for tools.  Building needs the zstd tool.\n+\n+\t  Users of kernel types at boot still parse it at boot: BPF LSM\n+\t  programs, the iterators of BPF_PRELOAD (loaded at boot, or at the\n+\t  first bpffs mount if bpf_preload is a module), and modules with\n+\t  distilled base BTF.  Kernel function and struct_ops registrations\n+\t  made before the first use are applied then and report errors only\n+\t  in the kernel log; a module BTF that fails validation then leaves\n+\t  the module loaded without BTF.\n+\n+\t  If unsure, say N.\n+\n config PAHOLE_HAS_BTF_TAG\n \tdef_bool PAHOLE_VERSION \u003e= 123\n \tdepends on CC_IS_CLANG\ndiff --git a/scripts/gen-btf.sh b/scripts/gen-btf.sh\nindex b17f1189298a55..c490b06306127e 100755\n--- a/scripts/gen-btf.sh\n+++ b/scripts/gen-btf.sh\n@@ -86,13 +86,24 @@ gen_btf_o()\n \tbtf_data=${ELF_FILE}.btf.o\n \n \t# Create ${btf_data} which contains just BTF sections but no symbols. Add\n-\t# SHF_ALLOC because .BTF will be part of the vmlinux image. --strip-all\n-\t# deletes all symbols including __start_BTF and __stop_BTF, which will\n-\t# be redefined in the linker script.\n+\t# SHF_ALLOC to the sections that will be part of the vmlinux image.\n+\t# --strip-all deletes all symbols including __start_BTF and __stop_BTF,\n+\t# which will 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-\tONLY_SEC=\"--only-section=.BTF\"\n+\tif is_enabled CONFIG_DEBUG_INFO_BTF_LAZY; then\n+\t\t# The image gets compressed BTF as init data, .BTF stays in\n+\t\t# the ELF file for tools.\n+\t\t${ZSTD} -q -f -19 ${ELF_FILE}.BTF -o ${ELF_FILE}.BTF.zst\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 .init.BTF.zst=${ELF_FILE}.BTF.zst \\\n+\t\t\t--set-section-flags .init.BTF.zst=alloc,readonly ${btf_data}\n+\t\tONLY_SEC=\"--only-section=.BTF --only-section=.init.BTF.zst\"\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\tONLY_SEC=\"--only-section=.BTF\"\n+\tfi\n \tbtf_inline=${ELF_FILE}.BTF.inline\n \tif [ \"${BTF_INLINE}\" = \"m\" ]; then\n \t\tif [ -f \"${btf_inline}\" ]; then\n@@ -145,7 +156,7 @@ embed_btf_data()\n cleanup()\n {\n \trm -f \"${ELF_FILE}.BTF.1\"\n-\trm -f \"${ELF_FILE}.BTF\"\n+\trm -f \"${ELF_FILE}.BTF\" \"${ELF_FILE}.BTF.zst\"\n \trm -f \"${ELF_FILE}.BTF.inline\"\n \trm -f \"${ELF_FILE}.BTF.inline.link\"\n \tif [ \"${BTFGEN_MODE}\" = \"module\" ]; then\ndiff --git a/tools/testing/selftests/bpf/prog_tests/ksyms.c b/tools/testing/selftests/bpf/prog_tests/ksyms.c\nindex dc7aab532fb147..fa97cc0ee3bf0d 100644\n--- a/tools/testing/selftests/bpf/prog_tests/ksyms.c\n+++ b/tools/testing/selftests/bpf/prog_tests/ksyms.c\n@@ -10,7 +10,7 @@ void test_ksyms(void)\n \tconst char *btf_path = \"/sys/kernel/btf/vmlinux\";\n \tstruct test_ksyms *skel;\n \tstruct test_ksyms__data *data;\n-\t__u64 link_fops_addr, per_cpu_start_addr;\n+\t__u64 link_fops_addr, per_cpu_start_addr, btf_start_addr;\n \tstruct stat st;\n \t__u64 btf_size;\n \tint err;\n@@ -30,6 +30,12 @@ void test_ksyms(void)\n \tif (!ASSERT_OK(stat(btf_path, \u0026st), \"stat_btf\"))\n \t\treturn;\n \tbtf_size = st.st_size;\n+\t/*\n+\t * With CONFIG_DEBUG_INFO_BTF_LAZY the image has the vmlinux BTF only\n+\t * compressed and no __start_BTF/__stop_BTF: the weak ksyms are 0.\n+\t */\n+\tif (kallsyms_find(\"__start_BTF\", \u0026btf_start_addr) == -ENOENT)\n+\t\tbtf_size = 0;\n \n \tskel = test_ksyms__open_and_load();\n \tif (!ASSERT_OK_PTR(skel, \"test_ksyms__open_and_load\"))\ndiff --git a/tools/testing/selftests/bpf/progs/linked_vars2.c b/tools/testing/selftests/bpf/progs/linked_vars2.c\nindex e4f5bd388a3c7a..bbdc3b25b4836e 100644\n--- a/tools/testing/selftests/bpf/progs/linked_vars2.c\n+++ b/tools/testing/selftests/bpf/progs/linked_vars2.c\n@@ -8,7 +8,7 @@\n extern int LINUX_KERNEL_VERSION __kconfig;\n /* when an extern is defined as both strong and weak, resulting symbol will be strong */\n extern bool CONFIG_BPF_SYSCALL __kconfig;\n-extern const void __start_BTF __ksym;\n+extern const void bpf_map_fops __ksym;\n \n int input_bss2;\n int input_data2 = 2;\n@@ -47,7 +47,7 @@ int BPF_PROG(handler2)\n \t */\n \toutput_sink2 = LINUX_KERNEL_VERSION\n \t\t       + CONFIG_BPF_SYSCALL\n-\t\t       + (long)\u0026__start_BTF;\n+\t\t       + (long)\u0026bpf_map_fops;\n \n \treturn 0;\n }\ndiff --git a/tools/testing/selftests/bpf/progs/test_ksyms.c b/tools/testing/selftests/bpf/progs/test_ksyms.c\nindex 6c9cbb5a3bdf46..0429430882252b 100644\n--- a/tools/testing/selftests/bpf/progs/test_ksyms.c\n+++ b/tools/testing/selftests/bpf/progs/test_ksyms.c\n@@ -11,8 +11,9 @@ __u64 out__btf_size = -1;\n __u64 out__per_cpu_start = -1;\n \n extern const void bpf_link_fops __ksym;\n-extern const void __start_BTF __ksym;\n-extern const void __stop_BTF __ksym;\n+/* weak: CONFIG_DEBUG_INFO_BTF_LAZY keeps no uncompressed BTF in the image */\n+extern const void __start_BTF __ksym __weak;\n+extern const void __stop_BTF __ksym __weak;\n extern const void __per_cpu_start __ksym;\n /* non-existing symbol, weak, default to zero */\n extern const void bpf_link_fops1 __ksym __weak;\n"
}

2/1 2026/11/01 08:10 agent patch-evaluator
0m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "DEBUG_INFO_BTF_LAZY",
    "DEBUG_INFO_BTF",
    "DEBUG_INFO_BTF_MODULES",
    "BPF_SYSCALL",
    "SYSFS"
  ],
  "FocusSymbols": [
    "bpf_get_btf_vmlinux",
    "bpf_peek_btf_vmlinux",
    "btf_vmlinux_data",
    "btf_parse_vmlinux",
    "btf_get_module_btf",
    "trace_btf_prepare",
    "__register_btf_kfunc_id_set",
    "register_btf_id_dtor_kfuncs",
    "__register_bpf_struct_ops"
  ],
  "Reasoning": "The patch introduces CONFIG_DEBUG_INFO_BTF_LAZY, which implements on-demand zstd decompression and lazy parsing of the vmlinux BTF upon first use, as well as deferred registration of kfuncs, dtor kfuncs, and struct_ops. It also modifies module BTF handling, BPF verifier entrypoints, sysfs /sys/kernel/btf/vmlinux read/mmap interfaces, and ftrace BTF integrations. These changes introduce substantial new state management, memory management, and synchronization logic across core BPF, tracing, and module subsystems, which are reachable and readily exercisable via the bpf() syscall, sysfs, and tracefs in standard virtualized environments.",
  "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 d0d825401d8cf7610975e1842f2fd9fb6624bdbc
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Nov 1 08:10:07 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/bpf/btf.rst b/Documentation/bpf/btf.rst
index 29de1222c3e73f..1ebce5cf578346 100644
--- a/Documentation/bpf/btf.rst
+++ b/Documentation/bpf/btf.rst
@@ -1276,6 +1276,36 @@ format.::
             .long   58
             .long   8206                    # Line 8 Col 14
 
+6.1 Compressed vmlinux BTF
+--------------------------
+
+With ``CONFIG_DEBUG_INFO_BTF_LAZY``, the kernel image carries the vmlinux BTF
+zstd-compressed, at about a quarter of its size, and the kernel decompresses
+and parses it when something first needs it: a BPF program or map that uses
+kernel types, ``BPF_BTF_GET_NEXT_ID``, tracing options that print arguments or
+return values by their BTF types.
+``/sys/kernel/btf/vmlinux`` has its full size from the start; reading or
+mapping it decompresses the BTF but does not parse it. Systems that never use
+BTF keep only the compressed copy in memory. The vmlinux file keeps the
+uncompressed ``.BTF`` section, not loaded, for tools and module builds.
+The option is available on x86 and arm64.
+
+Kernel function, destructor kfunc and struct_ops registrations made before the
+first use, and the BTF of modules loaded before it, are kept and applied by the
+task that parses the vmlinux BTF, before anyone else can see it. Errors of
+those registrations then only show in the kernel log, and a module whose BTF
+fails validation at that point stays loaded without BTF and without its files
+in ``/sys/kernel/btf``. A first use that runs out of memory fails with
+``-ENOMEM`` and leaves all of this as it was, for the next one to start over.
+The vmlinux BTF gets the next free BTF id, not necessarily 1, and the image has
+no ``__start_BTF``/``__stop_BTF`` symbols. The inline BTF
+(``CONFIG_DEBUG_INFO_BTF_INLINE``) is not compressed.
+
+Users of kernel types during boot still parse it during boot, for example BPF
+LSM programs, the iterators of ``CONFIG_BPF_PRELOAD`` (loaded at boot, or at the
+first bpffs mount if ``bpf_preload`` is a module), or a module with a
+``.BTF.base`` section.
+
 7. Testing
 ==========
 
diff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile
index 680ad803cba7df..58d05262dec82f 100644
--- a/arch/x86/boot/compressed/Makefile
+++ b/arch/x86/boot/compressed/Makefile
@@ -116,7 +116,7 @@ endif
 $(obj)/vmlinux: $(vmlinux-objs-y) $(vmlinux-libs-y) FORCE
 	$(call if_changed,ld)
 
-OBJCOPYFLAGS_vmlinux.bin :=  -R .comment -S
+OBJCOPYFLAGS_vmlinux.bin :=  -R .comment $(if $(CONFIG_DEBUG_INFO_BTF_LAZY),-R .BTF) -S
 $(obj)/vmlinux.bin: vmlinux FORCE
 	$(call if_changed,objcopy)
 
diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h
index 3eb732942d699c..7358aedab95cbc 100644
--- a/include/asm-generic/vmlinux.lds.h
+++ b/include/asm-generic/vmlinux.lds.h
@@ -553,7 +553,7 @@
 									\
 	RO_EXCEPTION_TABLE						\
 	NOTES								\
-	BTF								\
+	RO_BTF								\
 									\
 	. = ALIGN((align));						\
 	__end_rodata = .;
@@ -704,12 +704,24 @@
 #define BTF_INLINE_LINK
 #endif
 
-#ifdef CONFIG_DEBUG_INFO_BTF
-#define BTF								\
+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY
+/* compressed BTF in init data (see sysfs_btf.c), raw BTF not loaded */
+#define BTF_LOADED
+#define BTF_ZST		. = ALIGN(8); BOUNDED_SECTION_BY(.init.BTF.zst, _BTF_zst)
+#define BTF_RAW		.BTF 0 : { *(.BTF) }
+#else
+#define BTF_LOADED							\
 	. = ALIGN(PAGE_SIZE);						\
 	.BTF : AT(ADDR(.BTF) - LOAD_OFFSET) {				\
 		BOUNDED_SECTION_BY(.BTF, _BTF)				\
-	}								\
+	}
+#define BTF_ZST
+#define BTF_RAW
+#endif
+
+#ifdef CONFIG_DEBUG_INFO_BTF
+#define RO_BTF								\
+	BTF_LOADED							\
 	BTF_INLINE							\
 	BTF_INLINE_LINK						\
 	. = ALIGN(PAGE_SIZE);						\
@@ -717,7 +729,7 @@
 		*(.BTF_ids)						\
 	}
 #else
-#define BTF
+#define RO_BTF
 #endif
 
 /*
@@ -748,6 +760,7 @@
 	KERNEL_CTORS()							\
 	MCOUNT_REC()							\
 	*(.init.rodata .init.rodata.*)					\
+	BTF_ZST								\
 	FTRACE_EVENTS()							\
 	TRACE_SYSCALLS()						\
 	KPROBE_BLACKLIST()						\
@@ -880,6 +893,7 @@
 /* Required sections not related to debugging. */
 #define ELF_DETAILS							\
 		.comment 0 : { *(.comment) }				\
+		BTF_RAW							\
 		.symtab 0 : { *(.symtab) }				\
 		.strtab 0 : { *(.strtab) }				\
 		.shstrtab 0 : { *(.shstrtab) }				\
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index ff043678129358..c08b49e280d31f 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -3259,6 +3259,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 a18254b7521bdd..ff6d4a1d2e6b60 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -618,6 +618,11 @@ __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);
+#ifdef CONFIG_DEBUG_INFO_BTF
+void *btf_vmlinux_data(u32 *size);
+#else
+static inline void *btf_vmlinux_data(u32 *size) { return ERR_PTR(-ENOENT); }
+#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/kernel/bpf/Makefile b/kernel/bpf/Makefile
index 269810b128c469..4f500927cec854 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -40,8 +40,8 @@ obj-$(CONFIG_CGROUP_BPF) += cgroup.o
 ifeq ($(CONFIG_INET),y)
 obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o
 endif
-ifeq ($(CONFIG_SYSFS),y)
 obj-$(CONFIG_DEBUG_INFO_BTF) += sysfs_btf.o
+ifeq ($(CONFIG_SYSFS),y)
 obj-$(CONFIG_DEBUG_INFO_BTF_INLINE) += btf_vmlinux_inline.o
 endif
 ifeq ($(CONFIG_BPF_JIT),y)
diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c
index 7c5cd6086e2735..5e753b7d532d35 100644
--- a/kernel/bpf/bpf_struct_ops.c
+++ b/kernel/bpf/bpf_struct_ops.c
@@ -103,8 +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,
-					   st_ops_ids[IDX_ST_OPS_COMMON_VALUE_ID]);
+	/* a vmlinux id: btf may be the vmlinux BTF being published, or a module's */
+	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",
 			value_name);
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 1be30487a2fa75..c7234bcba87453 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -1902,7 +1902,8 @@ static void btf_free(struct btf *btf)
 	kvfree(btf->resolved_sizes);
 	kvfree(btf->resolved_ids);
 	/* vmlinux does not allocate btf->data, it simply points it at
-	 * __start_BTF.
+	 * __start_BTF, or at the decompressed copy with
+	 * CONFIG_DEBUG_INFO_BTF_LAZY, which is never freed either.
 	 */
 	if (!btf_is_vmlinux(btf))
 		kvfree(btf->data);
@@ -6524,8 +6525,6 @@ static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,
 	return ERR_PTR(err);
 }
 
-extern char __start_BTF[];
-extern char __stop_BTF[];
 extern struct btf *btf_vmlinux;
 
 #define BPF_MAP_TYPE(_id, _ops)
@@ -6558,20 +6557,46 @@ static u8 bpf_ctx_convert_map[] = {
 #undef BPF_MAP_TYPE
 #undef BPF_LINK_TYPE
 
-static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
+#define BPF_MAP_TYPE(_id, _ops)
+#define BPF_LINK_TYPE(_id, _name)
+#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
+	[_id] = #prog_ctx_type,
+static const char * const bpf_prog_ctx_tname[] = {
+#include <linux/bpf_types.h>
+};
+#undef BPF_PROG_TYPE
+#undef BPF_MAP_TYPE
+#undef BPF_LINK_TYPE
+
+struct user_regs_struct;
+struct user_pt_regs;
+
+/*
+ * Name of the context struct of @prog_type, as written in bpf_types.h, or NULL
+ * if it has none ("void *").  Only names are compared against the program's
+ * BTF, so the vmlinux BTF is not needed.  *@alt is set to the struct behind
+ * the bpf_user_pt_regs_t typedef.  Typedefs of integers (__u64, __u32) never
+ * match a struct name.
+ */
+static const char *prog_ctx_tname(enum bpf_prog_type prog_type, const char **alt)
 {
-	const struct btf_type *conv_struct;
-	const struct btf_member *ctx_type;
+	const char *name = prog_type < ARRAY_SIZE(bpf_prog_ctx_tname) ?
+			   bpf_prog_ctx_tname[prog_type] : NULL;
 
-	conv_struct = bpf_ctx_convert.t;
-	if (!conv_struct)
+	*alt = NULL;
+	if (!name || strchr(name, '*'))
 		return NULL;
-	/* prog_type is valid bpf program type. No need for bounds check. */
-	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
-	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
-	 * Like 'struct __sk_buff'
-	 */
-	return btf_type_by_id(btf_vmlinux, ctx_type->type);
+	if (str_has_prefix(name, "struct "))
+		return name + strlen("struct ");
+	if (!strcmp(name, "bpf_user_pt_regs_t")) {
+		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs))
+			*alt = "pt_regs";
+		else if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs))
+			*alt = "user_pt_regs";
+		else if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct))
+			*alt = "user_regs_struct";
+	}
+	return name;
 }
 
 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
@@ -6579,9 +6604,10 @@ 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;
-	if (!conv_struct)
+	/* bpf_ctx_convert.t is set when the vmlinux BTF is parsed */
+	if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
 		return -EFAULT;
+	conv_struct = bpf_ctx_convert.t;
 	/* prog_type is valid bpf program type. No need for bounds check. */
 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
@@ -6603,8 +6629,7 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 			  const struct btf_type *t, enum bpf_prog_type prog_type,
 			  int arg)
 {
-	const struct btf_type *ctx_type;
-	const char *tname, *ctx_tname;
+	const char *tname, *ctx_tname, *alt;
 
 	t = btf_type_by_id(btf, t->type);
 
@@ -6638,21 +6663,9 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 		return false;
 	}
 
-	ctx_type = find_canonical_prog_ctx_type(prog_type);
-	if (!ctx_type) {
-		bpf_log(log, "btf_vmlinux is malformed\n");
-		/* should not happen */
-		return false;
-	}
-again:
-	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
-	if (!ctx_tname) {
-		/* should not happen */
-		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
-		return false;
-	}
 	/* program types without named context types work only with arg:ctx tag */
-	if (ctx_tname[0] == '\0')
+	ctx_tname = prog_ctx_tname(prog_type, &alt);
+	if (!ctx_tname)
 		return false;
 	/* only compare that prog's ctx type name is the same as
 	 * kernel expects. No need to compare field by field.
@@ -6661,37 +6674,18 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
 	 * { // no fields of skb are ever used }
 	 */
-	if (btf_is_projection_of(ctx_tname, tname))
+	if (btf_is_projection_of(ctx_tname, tname) || !strcmp(ctx_tname, tname))
 		return true;
-	if (strcmp(ctx_tname, tname)) {
-		/* bpf_user_pt_regs_t is a typedef, so resolve it to
-		 * underlying struct and check name again
-		 */
-		if (!btf_type_is_modifier(ctx_type))
-			return false;
-		while (btf_type_is_modifier(ctx_type))
-			ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
-		goto again;
-	}
-	return true;
+	/* bpf_user_pt_regs_t is a typedef, check the underlying struct too */
+	return alt && !strcmp(alt, tname);
 }
 
-/* forward declarations for arch-specific underlying types of
- * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
- * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
- * works correctly with __builtin_types_compatible_p() on respective
- * architectures
- */
-struct user_regs_struct;
-struct user_pt_regs;
-
 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 				      const struct btf_type *t, int arg,
 				      enum bpf_prog_type prog_type,
 				      enum bpf_attach_type attach_type)
 {
-	const struct btf_type *ctx_type;
-	const char *tname, *ctx_tname;
+	const char *tname, *ctx_tname, *alt;
 
 	if (!btf_is_ptr(t)) {
 		bpf_log(log, "arg#%d type isn't a pointer\n", arg);
@@ -6791,27 +6785,20 @@ static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct
 		break;
 	}
 
-	ctx_type = find_canonical_prog_ctx_type(prog_type);
-	if (!ctx_type) {
-		/* should not happen */
-		bpf_log(log, "btf_vmlinux is malformed\n");
-		return -EINVAL;
-	}
-
 	/* resolve typedefs and check that underlying structs are matching as well */
-	while (btf_type_is_modifier(ctx_type))
-		ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
+	ctx_tname = prog_ctx_tname(prog_type, &alt);
+	if (ctx_tname && !str_has_prefix(bpf_prog_ctx_tname[prog_type], "struct "))
+		ctx_tname = alt;
 
 	/* if program type doesn't have distinctly named struct type for
 	 * context, then __arg_ctx argument can only be `void *`, which we
 	 * already checked above
 	 */
-	if (!__btf_type_is_struct(ctx_type)) {
+	if (!ctx_tname) {
 		bpf_log(log, "arg#%d should be void pointer\n", arg);
 		return -EINVAL;
 	}
 
-	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
 	if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
 		bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
 		return -EINVAL;
@@ -6838,6 +6825,8 @@ 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;
 
+	if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+		return -EINVAL;
 	conv_struct = bpf_ctx_convert.t;
 	/* get member for kernel ctx type */
 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
@@ -6911,15 +6900,21 @@ 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;
 
+	data = btf_vmlinux_data(&size);
+	if (IS_ERR(data))
+		return ERR_CAST(data);
+
 	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;
 
@@ -6935,6 +6930,75 @@ struct btf *btf_parse_vmlinux(void)
 	return btf;
 }
 
+static DEFINE_MUTEX(btf_vmlinux_lock);
+/* CONFIG_DEBUG_INFO_BTF_LAZY: the task applying deferred work, and its BTF */
+static struct task_struct *btf_vmlinux_builder;
+static struct btf *btf_vmlinux_new;
+static int btf_apply_deferred(void);
+static void btf_drop_all_deferred(int err);
+
+static bool btf_vmlinux_building(void)
+{
+	return in_task() && READ_ONCE(btf_vmlinux_builder) == current;
+}
+
+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);
+
+	/* with CONFIG_DEBUG_INFO_BTF_LAZY any call may be the one that parses */
+	if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		might_sleep();
+	if (btf || !IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
+		return btf;
+	/* the registrations btf_apply_deferred() applies see the new BTF */
+	if (btf_vmlinux_building())
+		return btf_vmlinux_new;
+
+	mutex_lock(&btf_vmlinux_lock);
+	btf = btf_vmlinux;
+	if (!btf) {
+		btf = btf_parse_vmlinux();
+		if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) && !IS_ERR(btf)) {
+			int err;
+
+			btf_vmlinux_new = btf;
+			WRITE_ONCE(btf_vmlinux_builder, current);
+			err = btf_apply_deferred();
+			WRITE_ONCE(btf_vmlinux_builder, NULL);
+			btf_vmlinux_new = NULL;
+			if (err) {
+				/* nothing saw it: drop it with what was applied to it */
+				bpf_ctx_convert.t = NULL;
+				btf_put(btf);
+				btf = ERR_PTR(err);
+			}
+		}
+		/* a lazy parse that ran out of memory is retried by the next caller */
+		if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || btf != ERR_PTR(-ENOMEM)) {
+			if (IS_ERR(btf))
+				btf_drop_all_deferred(PTR_ERR(btf));
+			/*
+			 * Order the parsed BTF contents and the globals the
+			 * parse populated (e.g. bpf_ctx_convert.t) before
+			 * the pointer publication. Pairs with the acquire
+			 * on the lockless fast path above.
+			 */
+			smp_store_release(&btf_vmlinux, btf);
+		}
+	}
+	mutex_unlock(&btf_vmlinux_lock);
+	return btf;
+}
+
+/* The vmlinux BTF if it is parsed already: for callers that cannot sleep */
+struct btf *bpf_peek_btf_vmlinux(void)
+{
+	/* Pairs with the smp_store_release() in bpf_get_btf_vmlinux() */
+	return smp_load_acquire(&btf_vmlinux);
+}
+
 /* If .BTF_ids section was created with distilled base BTF, both base and
  * split BTF ids will need to be mapped to actual base/split ids for
  * BTF now that it has been relocated.
@@ -6948,8 +7012,9 @@ __u32 btf_relocate_id(const struct btf *btf, __u32 id)
 
 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 
+/* @data is a copy owned by the returned BTF; the caller frees it on error */
 static struct btf *btf_parse_split(struct btf_verifier_env *env,
-				   const char *name, const void *data,
+				   const char *name, void *data,
 				   unsigned int data_size, struct btf *base_btf)
 {
 	struct btf *btf;
@@ -6965,11 +7030,7 @@ static struct btf *btf_parse_split(struct btf_verifier_env *env,
 	btf->named_start_id = 0;
 	strscpy(btf->name, name);
 
-	btf->data = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);
-	if (!btf->data) {
-		err = -ENOMEM;
-		goto errout;
-	}
+	btf->data = data;
 	btf->data_size = data_size;
 
 	err = btf_parse_hdr(env);
@@ -6993,6 +7054,7 @@ static struct btf *btf_parse_split(struct btf_verifier_env *env,
 	return btf;
 
 errout:
+	btf->data = NULL;
 	btf_free(btf);
 	return ERR_PTR(err);
 }
@@ -7064,10 +7126,16 @@ static int btf_rebase_inline(struct btf *inline_btf,
 	return 0;
 }
 
-static struct btf *btf_parse_module(const char *module_name, const void *data,
+/*
+ * @data and @inline_data are copies made by the caller.  On success the
+ * returned BTF owns @data, and *@relocated_inline_data is @inline_data,
+ * relocated in place, unless the inline BTF is invalid.  The caller frees
+ * the copies this does not take.
+ */
+static struct btf *btf_parse_module(const char *module_name, void *data,
 				    unsigned int data_size, void *base_data,
 				    unsigned int base_data_size,
-				    const void *inline_data,
+				    void *inline_data,
 				    unsigned int inline_data_size,
 				    void **relocated_inline_data)
 {
@@ -7135,6 +7203,7 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,
 		if (err) {
 			pr_warn("failed to relocate module [%s] inline BTF: %d\n",
 				module_name, err);
+			inline_btf->data = NULL;
 			btf_free(inline_btf);
 		} else {
 			*relocated_inline_data = inline_btf->data;
@@ -7158,12 +7227,16 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,
 errout:
 	kvfree(module_str_map);
 	btf_verifier_env_free(env);
-	if (inline_btf)
+	if (inline_btf) {
+		inline_btf->data = NULL;
 		btf_free(inline_btf);
+	}
 	if (!IS_ERR(base_btf) && base_btf != vmlinux_btf)
 		btf_free(base_btf);
-	if (btf)
+	if (btf) {
+		btf->data = NULL;
 		btf_free(btf);
+	}
 	return ERR_PTR(err);
 }
 
@@ -8566,6 +8639,7 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
 		.btf = btf,
 		.log = log,
 	};
+	struct btf *vmlinux_btf;
 	u32 kern_type_id, type_id;
 	int err = 0;
 
@@ -8577,6 +8651,10 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
 		t = btf_type_by_id(btf, t->type);
 	}
 
+	/* parse it, if this is its first use, before taking cand_cache_mutex */
+	vmlinux_btf = bpf_get_btf_vmlinux();
+	if (IS_ERR(vmlinux_btf))
+		return PTR_ERR(vmlinux_btf);
 	mutex_lock(&cand_cache_mutex);
 	cc = bpf_core_find_cands(&ctx, type_id);
 	if (IS_ERR(cc)) {
@@ -9262,6 +9340,10 @@ int btf_get_fd_by_id(u32 id)
 	struct btf *btf;
 	int fd;
 
+	/* kernel BTFs get their ids while parsed, before they are published */
+	if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		bpf_get_btf_vmlinux();
+
 	rcu_read_lock();
 	btf = idr_find(&btf_idr, id);
 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
@@ -9301,10 +9383,13 @@ enum {
 struct btf_module {
 	struct list_head list;
 	struct module *module;
-	struct btf *btf;
+	struct btf *btf;	/* NULL while kept, see btf_module_keep() */
+	void *data;		/* kept copy of .BTF, adopted by btf once parsed */
+	u32 data_size;
 	struct bin_attribute *sysfs_attr;
 	struct bin_attribute *sysfs_inline_attr;
 	void *btf_inline_data;
+	u32 btf_inline_data_size;
 	int flags;
 };
 
@@ -9312,6 +9397,150 @@ static LIST_HEAD(btf_modules);
 static DEFINE_MUTEX(btf_module_mutex);
 
 static void purge_cand_cache(struct btf *btf);
+static void btf_drop_deferred_regs(struct module *owner);
+
+/* /sys/kernel/btf/<module> and <module>.inline */
+static void btf_module_add_files(struct btf_module *btf_mod, const char *name,
+				 void *data, u32 data_size)
+{
+	char inline_name[MODULE_NAME_LEN + sizeof(".inline")];
+	struct bin_attribute *attr;
+
+	attr = sysfs_btf_add(name, data, data_size, false, NULL);
+	if (IS_ERR(attr))
+		return;
+	btf_mod->sysfs_attr = attr;
+
+	if (!btf_mod->btf_inline_data)
+		return;
+	snprintf(inline_name, sizeof(inline_name), "%s.inline", name);
+	attr = sysfs_btf_add(inline_name, btf_mod->btf_inline_data,
+			     btf_mod->btf_inline_data_size, false, NULL);
+	if (IS_ERR(attr)) {
+		kvfree(btf_mod->btf_inline_data);
+		btf_mod->btf_inline_data = NULL;
+		return;
+	}
+	btf_mod->sysfs_inline_attr = attr;
+}
+
+/*
+ * CONFIG_DEBUG_INFO_BTF_LAZY: module BTF is split BTF on top of the vmlinux
+ * BTF.  Until that is parsed, keep the module's copies of its BTF and inline
+ * BTF as they are, serve them in sysfs, and let btf_parse_kept_modules()
+ * parse them with the vmlinux BTF.  Distilled base BTF (.BTF.base) needs
+ * relocation, which needs the vmlinux BTF, so it is parsed right away.
+ *
+ * TODO: defer modules with distilled base BTF as well: keep them here and
+ * relocate them in btf_parse_kept_modules().  Their raw BTF is not usable
+ * before that, so their sysfs files would have to wait for the first use.
+ */
+static bool btf_module_keep(struct btf_module *btf_mod, struct module *mod,
+			    void *data, void *inline_data, u32 inline_data_size)
+{
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || mod->btf_base_data)
+		return false;
+	guard(mutex)(&btf_vmlinux_lock);
+	if (btf_vmlinux)
+		return false;
+	btf_mod->module = mod;
+	btf_mod->data = data;
+	btf_mod->data_size = mod->btf_data_size;
+	btf_mod->btf_inline_data = inline_data;
+	btf_mod->btf_inline_data_size = inline_data ? inline_data_size : 0;
+	/* before btf_parse_kept_modules() can see the entry */
+	btf_module_add_files(btf_mod, mod->name, data, mod->btf_data_size);
+	mutex_lock(&btf_module_mutex);
+	list_add(&btf_mod->list, &btf_modules);
+	mutex_unlock(&btf_module_mutex);
+	return true;
+}
+
+/* A kept module without BTF: no entry and no files, as if refused at load */
+static void btf_module_drop_kept(struct btf_module *btf_mod)
+{
+	list_del(&btf_mod->list);
+	if (btf_mod->sysfs_attr)
+		sysfs_btf_remove(btf_mod->sysfs_attr);
+	if (btf_mod->sysfs_inline_attr)
+		sysfs_btf_remove(btf_mod->sysfs_inline_attr);
+	kvfree(btf_mod->btf_inline_data);
+	kvfree(btf_mod->data);
+	kfree(btf_mod);
+}
+
+/* Undo btf_parse_kept_modules() of a round that is not published */
+static void btf_unparse_kept_modules(void)
+{
+	struct btf_module *btf_mod;
+
+	lockdep_assert_held(&btf_module_mutex);
+	list_for_each_entry(btf_mod, &btf_modules, list) {
+		if (!btf_mod->data || !btf_mod->btf)
+			continue;
+		btf_mod->btf->data = NULL;	/* the kept copy */
+		btf_put(btf_mod->btf);
+		btf_mod->btf = NULL;
+	}
+}
+
+/*
+ * Called under btf_vmlinux_lock by the task that parses the vmlinux BTF,
+ * before that is published.  Parses the kept module BTFs in place, oldest
+ * first so that ids follow the load order as without
+ * CONFIG_DEBUG_INFO_BTF_LAZY; in-tree module BTF and its inline BTF need no
+ * relocation, so sysfs serves the same bytes before and after.  A module
+ * whose BTF fails validation cannot be refused any more: it stays loaded
+ * without BTF, and its files go away; an invalid inline BTF loses its file.
+ * Returns -ENOMEM, with this round's module BTFs freed again, if memory ran
+ * out.
+ */
+static int btf_parse_kept_modules(void)
+{
+	struct btf_module *btf_mod, *tmp;
+	void *inline_data;
+	struct btf *btf;
+	int err;
+
+	lockdep_assert_held(&btf_vmlinux_lock);
+	guard(mutex)(&btf_module_mutex);
+	list_for_each_entry_safe_reverse(btf_mod, tmp, &btf_modules, list) {
+		if (btf_mod->btf || !btf_mod->data)
+			continue;
+		btf = btf_parse_module(btf_mod->module->name, btf_mod->data,
+				       btf_mod->data_size, NULL, 0,
+				       btf_mod->btf_inline_data,
+				       btf_mod->btf_inline_data_size, &inline_data);
+		if (!IS_ERR(btf)) {
+			err = btf_alloc_id(btf);
+			if (err) {
+				btf->data = NULL;	/* the kept copy */
+				btf_free(btf);
+				btf = ERR_PTR(err);
+			}
+		}
+		if (btf == ERR_PTR(-ENOMEM)) {
+			btf_unparse_kept_modules();
+			return -ENOMEM;
+		}
+		if (IS_ERR(btf)) {
+			pr_warn("failed to validate module [%s] BTF: %ld\n",
+				btf_mod->module->name, PTR_ERR(btf));
+			btf_module_drop_kept(btf_mod);
+			continue;
+		}
+		btf_mod->btf = btf;
+		if (btf_mod->btf_inline_data && !inline_data) {
+			if (btf_mod->sysfs_inline_attr)
+				sysfs_btf_remove(btf_mod->sysfs_inline_attr);
+			btf_mod->sysfs_inline_attr = NULL;
+			kvfree(btf_mod->btf_inline_data);
+			btf_mod->btf_inline_data = NULL;
+			btf_mod->btf_inline_data_size = 0;
+		}
+	}
+	return 0;
+}
 
 #if IS_MODULE(CONFIG_DEBUG_INFO_BTF_INLINE)
 extern char __start_BTF_inline_link[];
@@ -9422,9 +9651,8 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
 {
 	struct btf_module *btf_mod, *tmp;
 	struct module *mod = module;
-	struct bin_attribute *attr;
 	struct btf *btf;
-	void *inline_data = NULL, *relocated_inline_data = NULL;
+	void *data, *inline_data = NULL, *relocated_inline_data = NULL;
 	unsigned int inline_data_size = 0;
 	int err = 0;
 
@@ -9452,11 +9680,26 @@ 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,
+		data = kvmemdup(mod->btf_data, mod->btf_data_size, GFP_KERNEL | __GFP_NOWARN);
+		if (inline_data) {
+			inline_data = kvmemdup(inline_data, inline_data_size,
+					       GFP_KERNEL | __GFP_NOWARN);
+			if (!inline_data)
+				pr_warn("failed to validate module [%s] inline BTF: %d\n",
+					mod->name, -ENOMEM);
+		}
+		if (data && btf_module_keep(btf_mod, mod, data, inline_data,
+					    inline_data_size))
+			break;
+		btf = !data ? ERR_PTR(-ENOMEM) :
+		      btf_parse_module(mod->name, data, mod->btf_data_size,
 				       mod->btf_base_data, mod->btf_base_data_size,
-				       inline_data, inline_data_size,
+				       inline_data, inline_data ? inline_data_size : 0,
 				       &relocated_inline_data);
+		if (inline_data != relocated_inline_data)
+			kvfree(inline_data);
 		if (IS_ERR(btf)) {
+			kvfree(data);
 			kfree(btf_mod);
 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
 				pr_warn("failed to validate module [%s] BTF: %ld\n",
@@ -9480,30 +9723,12 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
 		btf_mod->module = module;
 		btf_mod->btf = btf;
 		btf_mod->btf_inline_data = relocated_inline_data;
+		btf_mod->btf_inline_data_size = relocated_inline_data ? inline_data_size : 0;
 		list_add(&btf_mod->list, &btf_modules);
 		mutex_unlock(&btf_module_mutex);
 
-		attr = sysfs_btf_add(btf->name, btf->data, btf->data_size, false, NULL);
-		if (IS_ERR(attr)) {
-			err = 0;
-			goto out;
-		}
-		btf_mod->sysfs_attr = attr;
-
-		if (relocated_inline_data) {
-			char name[MODULE_NAME_LEN + sizeof(".inline")];
-
-			snprintf(name, sizeof(name), "%s.inline", mod->name);
-			attr = sysfs_btf_add(name, relocated_inline_data,
-					     inline_data_size, false, NULL);
-			if (IS_ERR(attr)) {
-				kvfree(relocated_inline_data);
-				btf_mod->btf_inline_data = NULL;
-				err = 0;
-				break;
-			}
-			btf_mod->sysfs_inline_attr = attr;
-		}
+		/* data: the same as btf->data */
+		btf_module_add_files(btf_mod, mod->name, data, mod->btf_data_size);
 		break;
 	case MODULE_STATE_LIVE:
 		if (!mod->btf_data_size)
@@ -9521,11 +9746,17 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
 	case MODULE_STATE_GOING:
 		if (!mod->btf_data_size)
 			break;
+		btf_drop_deferred_regs(module);
 		mutex_lock(&btf_module_mutex);
 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
 			if (btf_mod->module != module)
 				continue;
 
+			if (!btf_mod->btf) {	/* kept, see btf_module_keep() */
+				btf_module_drop_kept(btf_mod);
+				break;
+			}
+
 			/*
 			 * For modules, we do the freeing of BTF IDR as soon as
 			 * module goes away to disable BTF discovery, since the
@@ -9610,9 +9841,12 @@ struct btf *btf_get_module_btf(const struct module *module)
 	}
 
 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+	/* kept module BTF is parsed together with the vmlinux BTF */
+	if (!module->btf_data_size || IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+		return NULL;
 	mutex_lock(&btf_module_mutex);
 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
-		if (btf_mod->module != module)
+		if (btf_mod->module != module || !btf_mod->btf)
 			continue;
 
 		btf_get(btf_mod->btf);
@@ -9803,7 +10037,7 @@ 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)
+		if (btf_mod->btf == btf || !btf_mod->btf)
 			continue;
 		id = btf_find_by_name_kind(btf_mod->btf, func_name, kind);
 		if (id >= 0) {
@@ -10129,12 +10363,88 @@ 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);
 }
 
+enum btf_deferred_kind { BTF_DEFER_KFUNCS, BTF_DEFER_DTORS, BTF_DEFER_ST_OPS };
+
+/* CONFIG_DEBUG_INFO_BTF_LAZY: a registration made before the vmlinux BTF is parsed */
+struct btf_deferred_reg {
+	struct list_head list;
+	struct module *owner;
+	enum btf_deferred_kind kind;
+	enum btf_kfunc_hook hook;
+	void *data;
+	u32 cnt;
+};
+
+/* protected by btf_vmlinux_lock */
+static LIST_HEAD(btf_deferred_regs);
+
+/*
+ * Does a registration by @owner need the vmlinux BTF?  Without module BTF a
+ * module's registrations do nothing but warn (check_btf_kconfigs()), and
+ * btf_module_notify(), which drops a going module's queued entries, does not
+ * see such a module.
+ */
+static bool btf_reg_needs_vmlinux(const struct module *owner)
+{
+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+	return !owner || owner->btf_data_size;
+#else
+	return !owner;
+#endif
+}
+
+/*
+ * Initcalls and modules loaded early register kfuncs, dtor kfuncs and
+ * struct_ops before anything needs the vmlinux BTF.  Queue these until it
+ * is parsed (btf_apply_deferred()).  Returns true if the registration was
+ * queued, with *err set to 0 or -ENOMEM.
+ */
+static bool btf_defer_reg(struct module *owner, enum btf_deferred_kind kind,
+			  enum btf_kfunc_hook hook, const void *data, u32 cnt, int *err)
+{
+	struct btf_deferred_reg *reg;
+
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || bpf_peek_btf_vmlinux() ||
+	    btf_vmlinux_building() || !btf_reg_needs_vmlinux(owner))
+		return false;
+	guard(mutex)(&btf_vmlinux_lock);
+	if (btf_vmlinux)
+		return false;
+
+	*err = -ENOMEM;
+	reg = kzalloc_obj(*reg);
+	if (!reg)
+		return true;
+	/* callers may build kfunc sets and dtor arrays on the stack */
+	if (kind == BTF_DEFER_KFUNCS)
+		reg->data = kmemdup(data, sizeof(struct btf_kfunc_id_set), GFP_KERNEL);
+	else if (kind == BTF_DEFER_DTORS)
+		reg->data = kmemdup_array(data, cnt, sizeof(struct btf_id_dtor_kfunc),
+					  GFP_KERNEL);
+	else
+		reg->data = (void *)data;
+	if (!reg->data) {
+		kfree(reg);
+		return true;
+	}
+	reg->owner = owner;
+	reg->kind = kind;
+	reg->hook = hook;
+	reg->cnt = cnt;
+	list_add_tail(&reg->list, &btf_deferred_regs);
+	*err = 0;
+	return true;
+}
+
 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
 				       const struct btf_kfunc_id_set *kset)
 {
 	struct btf *btf;
 	int ret, i;
 
+	if (btf_defer_reg(kset->owner, BTF_DEFER_KFUNCS, hook, kset, 0, &ret))
+		return ret;
+
 	btf = btf_get_module_btf(kset->owner);
 	if (!btf)
 		return check_btf_kconfigs(kset->owner, "kfunc");
@@ -10251,6 +10561,9 @@ int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_c
 	u32 tab_cnt, i;
 	int ret;
 
+	if (btf_defer_reg(owner, BTF_DEFER_DTORS, 0, dtors, add_cnt, &ret))
+		return ret;
+
 	btf = btf_get_module_btf(owner);
 	if (!btf)
 		return check_btf_kconfigs(owner, "dtor kfuncs");
@@ -10579,7 +10892,8 @@ bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
 	const char *name;
 	int id;
 
-	main_btf = bpf_get_btf_vmlinux();
+	/* callers parse it before taking cand_cache_mutex, see bpf_core_apply() */
+	main_btf = bpf_peek_btf_vmlinux();
 	if (IS_ERR(main_btf))
 		return ERR_CAST(main_btf);
 	if (!main_btf)
@@ -10682,8 +10996,18 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
 
 	if (need_cands) {
 		struct bpf_cand_cache *cc;
+		struct btf *main_btf;
 		int i;
 
+		/*
+		 * Parsing the vmlinux BTF takes btf_module_mutex, which is
+		 * taken before cand_cache_mutex when a module goes away.
+		 */
+		main_btf = bpf_get_btf_vmlinux();
+		if (IS_ERR(main_btf)) {
+			kfree(specs);
+			return PTR_ERR(main_btf);
+		}
 		mutex_lock(&cand_cache_mutex);
 		cc = bpf_core_find_cands(ctx, relo->type_id);
 		if (IS_ERR(cc)) {
@@ -10957,6 +11281,9 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
 	struct btf *btf;
 	int err = 0;
 
+	if (btf_defer_reg(st_ops->owner, BTF_DEFER_ST_OPS, 0, st_ops, 0, &err))
+		return err;
+
 	btf = btf_get_module_btf(st_ops->owner);
 	if (!btf)
 		return check_btf_kconfigs(st_ops->owner, "struct_ops");
@@ -10982,6 +11309,103 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
 #endif
 
+static void btf_free_deferred_reg(struct btf_deferred_reg *reg)
+{
+	list_del(&reg->list);
+	if (reg->kind != BTF_DEFER_ST_OPS)
+		kfree(reg->data);
+	kfree(reg);
+}
+
+/*
+ * Called under btf_vmlinux_lock, by the task that parsed the vmlinux BTF and
+ * before it publishes it, so that nothing sees the BTF without its module
+ * BTFs, kfuncs and struct_ops.  bpf_get_btf_vmlinux() returns the new BTF to
+ * this task, so the registrations are applied as if they were made now, and
+ * any they make in turn (a struct_ops ->init() may register kfuncs) too.
+ * They run in whichever task needs the BTF first, with the locks it holds:
+ * they must not load modules or take locks that users of the BTF hold.
+ *
+ * Returns -ENOMEM if memory ran out, which may be only because that task is
+ * being killed: the caller then drops the new BTF with whatever was applied
+ * to it, and the next caller starts over with the queue intact, as for the
+ * vmlinux BTF itself; a struct_ops ->init() then runs again with the BTF of
+ * that round.  Any other error of a registration is only logged.
+ */
+static int btf_apply_deferred(void)
+{
+	struct btf_deferred_reg *reg, *tmp;
+	int err;
+
+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+	err = btf_parse_kept_modules();
+	if (err)
+		return err;
+#endif
+	list_for_each_entry(reg, &btf_deferred_regs, list) {
+		/* a going module's exit() runs before GOING drops its entries */
+		if (!try_module_get(reg->owner))
+			continue;
+		err = 0;
+		switch (reg->kind) {
+		case BTF_DEFER_KFUNCS:
+			err = __register_btf_kfunc_id_set(reg->hook, reg->data);
+			break;
+		case BTF_DEFER_DTORS:
+			err = register_btf_id_dtor_kfuncs(reg->data, reg->cnt, reg->owner);
+			break;
+		case BTF_DEFER_ST_OPS:
+#if defined(CONFIG_BPF_JIT)
+			err = __register_bpf_struct_ops(reg->data);
+#endif
+			break;
+		}
+		module_put(reg->owner);
+		if (err == -ENOMEM) {
+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+			guard(mutex)(&btf_module_mutex);
+			btf_unparse_kept_modules();
+#endif
+			return err;
+		}
+		if (err)
+			pr_warn("failed to apply deferred BTF registration for %s: %d\n",
+				reg->owner ? reg->owner->name : "vmlinux", err);
+	}
+	list_for_each_entry_safe(reg, tmp, &btf_deferred_regs, list)
+		btf_free_deferred_reg(reg);
+	return 0;
+}
+
+/* The vmlinux BTF failed for good: nothing will apply what is queued */
+static void btf_drop_all_deferred(int err)
+{
+	struct btf_deferred_reg *reg, *tmp;
+	int cnt = 0;
+
+	list_for_each_entry_safe(reg, tmp, &btf_deferred_regs, list) {
+		btf_free_deferred_reg(reg);
+		cnt++;
+	}
+	if (cnt)
+		pr_warn("vmlinux BTF unavailable (%d), dropped %d deferred BTF registrations\n",
+			err, cnt);
+}
+
+/* @owner is going away: drop the registrations it queued */
+static void __maybe_unused btf_drop_deferred_regs(struct module *owner)
+{
+	struct btf_deferred_reg *reg, *tmp;
+
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		return;
+	guard(mutex)(&btf_vmlinux_lock);
+	list_for_each_entry_safe(reg, tmp, &btf_deferred_regs, list) {
+		if (reg->owner == owner)
+			btf_free_deferred_reg(reg);
+	}
+}
+
 bool btf_param_match_suffix(const struct btf *btf,
 			    const struct btf_param *arg,
 			    const char *suffix)
diff --git a/kernel/bpf/inode.c b/kernel/bpf/inode.c
index c6f328e4752e1d..39750d4ad401a7 100644
--- a/kernel/bpf/inode.c
+++ b/kernel/bpf/inode.c
@@ -1059,6 +1059,13 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param)
 		char *p, *str;
 		int val;
 
+		/*
+		 * Setting delegation mount options requires privileges.  Check
+		 * before the lookup, which may have to parse the vmlinux BTF.
+		 */
+		if (!capable(CAP_SYS_ADMIN))
+			return -EPERM;
+
 		/* ignore errors, fallback to hex */
 		(void)find_bpffs_btf_enums(&info);
 
@@ -1100,10 +1107,6 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param)
 			}
 		}
 
-		/* Setting delegation mount options requires privileges */
-		if (msk && !capable(CAP_SYS_ADMIN))
-			return -EPERM;
-
 		*delegate_msk |= msk;
 		break;
 	}
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 02ed5368f05626..fefbb641692b21 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -3048,8 +3048,12 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
 				goto put_token;
 			}
 		}
-	} else if (attr->attach_btf_id || multi_func) {
-		/* fall back to vmlinux BTF, if BTF type ID is specified */
+	} else if ((attr->attach_btf_id || multi_func) && bpf_cap) {
+		/*
+		 * fall back to vmlinux BTF, if BTF type ID is specified; only
+		 * program types that need CAP_BPF take one, and
+		 * bpf_prog_load_check_attach() refuses it for the others
+		 */
 		attach_btf = bpf_get_btf_vmlinux();
 		if (IS_ERR(attach_btf)) {
 			err = PTR_ERR(attach_btf);
@@ -6511,6 +6515,10 @@ 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:
+		/* kernel BTFs have ids once parsed (CONFIG_DEBUG_INFO_BTF_LAZY) */
+		if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) &&
+		    ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN))
+			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 556fe92c36495d..015cd82211541b 100644
--- a/kernel/bpf/sysfs_btf.c
+++ b/kernel/bpf/sysfs_btf.c
@@ -12,11 +12,126 @@
 #include <linux/vmalloc.h>
 #include <linux/io.h>
 #include <linux/btf.h>
+#include <linux/zstd.h>
 
+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY
+/* See scripts/gen-btf.sh, gen_btf_o() for details */
+extern char __start_BTF_zst[];
+extern char __stop_BTF_zst[];
+
+static DEFINE_MUTEX(btf_vmlinux_data_lock);
+static void *btf_vmlinux_raw;
+static u32 btf_vmlinux_raw_size;
+static bool btf_vmlinux_broken;
+/* Compressed BTF: init data until btf_vmlinux_keep_zst(), freed once decompressed */
+static void *btf_zst = __start_BTF_zst;
+
+static u32 btf_vmlinux_size(void)
+{
+	zstd_frame_header hdr;
+
+	guard(mutex)(&btf_vmlinux_data_lock);
+	if (!btf_vmlinux_raw_size && btf_zst &&
+	    !zstd_get_frame_header(&hdr, btf_zst, __stop_BTF_zst - __start_BTF_zst) &&
+	    hdr.frameContentSize < U32_MAX)
+		btf_vmlinux_raw_size = hdr.frameContentSize;
+	return btf_vmlinux_raw_size;
+}
+
+static void btf_vmlinux_drop_zst(void)
+{
+	if (btf_zst != __start_BTF_zst)
+		vfree(btf_zst);
+	btf_zst = NULL;
+}
+
+/*
+ * The raw vmlinux BTF, decompressed on first use and never freed, or
+ * ERR_PTR(-ENOMEM) if that cannot be done (now: memory; for good: no copy of
+ * the compressed BTF), or ERR_PTR(-EINVAL) if it is broken.
+ */
+void *btf_vmlinux_data(u32 *size)
+{
+	size_t ret, ws_size = zstd_dctx_workspace_bound();
+	void *raw, *ws;
+
+	/* Pairs with smp_store_release() below */
+	raw = smp_load_acquire(&btf_vmlinux_raw);
+	if (raw) {
+		*size = btf_vmlinux_raw_size;
+		return raw;
+	}
+
+	*size = btf_vmlinux_size();
+	guard(mutex)(&btf_vmlinux_data_lock);
+	if (btf_vmlinux_raw)
+		return btf_vmlinux_raw;
+	if (!btf_zst)
+		return ERR_PTR(btf_vmlinux_broken ? -EINVAL : -ENOMEM);
+	if (!*size) {
+		pr_err("BTF: no size in the compressed vmlinux BTF\n");
+		btf_vmlinux_broken = true;
+		btf_vmlinux_drop_zst();
+		return ERR_PTR(-EINVAL);
+	}
+	/* vmalloc_user(): btf_sysfs_vmlinux_mmap() maps it to user space */
+	raw = vmalloc_user(*size);
+	ws = kvmalloc(ws_size, GFP_KERNEL);
+	if (raw && ws) {
+		ret = zstd_decompress_dctx(zstd_init_dctx(ws, ws_size), raw, *size,
+					   btf_zst, __stop_BTF_zst - __start_BTF_zst);
+		if (!zstd_is_error(ret) && ret == *size) {
+			/* Pairs with smp_load_acquire() above */
+			smp_store_release(&btf_vmlinux_raw, raw);
+		} else {
+			pr_err("BTF: cannot decompress the vmlinux BTF: %s\n",
+			       zstd_is_error(ret) ? zstd_get_error_name(ret) : "size mismatch");
+			btf_vmlinux_broken = true;
+		}
+		btf_vmlinux_drop_zst();
+	}
+	kvfree(ws);
+	if (btf_vmlinux_raw)
+		return btf_vmlinux_raw;
+	vfree(raw);
+	return ERR_PTR(btf_vmlinux_broken ? -EINVAL : -ENOMEM);
+}
+
+/* Keep a copy of the compressed BTF before init memory is freed */
+static int __init btf_vmlinux_keep_zst(void)
+{
+	size_t size = __stop_BTF_zst - __start_BTF_zst;
+
+	guard(mutex)(&btf_vmlinux_data_lock);
+	if (btf_zst) {
+		/* vmalloc(): kmalloc() would round up to a power of 2 */
+		btf_zst = vmalloc(size);
+		if (btf_zst)
+			memcpy(btf_zst, __start_BTF_zst, size);
+		else
+			pr_err("BTF: out of memory, vmlinux BTF unavailable\n");
+	}
+	return 0;
+}
+late_initcall_sync(btf_vmlinux_keep_zst);
+#else
 /* See scripts/link-vmlinux.sh, gen_btf() func for details */
 extern char __start_BTF[];
 extern char __stop_BTF[];
 
+static u32 btf_vmlinux_size(void)
+{
+	return __stop_BTF - __start_BTF;
+}
+
+void *btf_vmlinux_data(u32 *size)
+{
+	*size = btf_vmlinux_size();
+	return __start_BTF;
+}
+#endif
+
+#ifdef CONFIG_SYSFS
 static int btf_sysfs_mmap_check(void *data, size_t size, struct vm_area_struct *vma)
 {
 	unsigned long pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
@@ -61,10 +176,49 @@ static int btf_sysfs_mmap_image(struct file *filp, struct kobject *kobj,
 	return remap_pfn_range(vma, vma->vm_start, pfn, vm_size, vma->vm_page_prot);
 }
 
+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY
+/* Reading or mapping the file decompresses the BTF but does not parse it */
+static int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,
+				  const struct bin_attribute *attr,
+				  struct vm_area_struct *vma)
+{
+	void *data;
+	u32 size;
+	int err;
+
+	data = btf_vmlinux_data(&size);
+	if (IS_ERR(data))
+		return PTR_ERR(data);
+
+	err = btf_sysfs_mmap_check(data, attr->size, vma);
+	if (err)
+		return err;
+
+	return remap_vmalloc_range(vma, data, 0);
+}
+
+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)
+{
+	void *data;
+	u32 size;
+
+	data = btf_vmlinux_data(&size);
+	if (IS_ERR(data))
+		return PTR_ERR(data);
+
+	return memory_read_from_buffer(buf, count, &off, data, size);
+}
+#else
+#define btf_sysfs_vmlinux_read	sysfs_bin_attr_simple_read
+#define btf_sysfs_vmlinux_mmap	btf_sysfs_mmap_image
+#endif
+
 static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {
 	.attr = { .name = "vmlinux", .mode = 0444, },
-	.read = sysfs_bin_attr_simple_read,
-	.mmap = btf_sysfs_mmap_image,
+	.read = btf_sysfs_vmlinux_read,
+	.mmap = btf_sysfs_vmlinux_mmap,
 };
 
 struct kobject *btf_kobj;
@@ -180,8 +334,12 @@ void sysfs_btf_remove(struct bin_attribute *attr)
 
 static int __init btf_vmlinux_init(void)
 {
-	bin_attr_btf_vmlinux.private = __start_BTF;
-	bin_attr_btf_vmlinux.size = __stop_BTF - __start_BTF;
+	u32 size;
+
+	/* with CONFIG_DEBUG_INFO_BTF_LAZY the read and mmap handlers get it */
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		bin_attr_btf_vmlinux.private = btf_vmlinux_data(&size);
+	bin_attr_btf_vmlinux.size = btf_vmlinux_size();
 
 	if (bin_attr_btf_vmlinux.size == 0)
 		return 0;
@@ -194,3 +352,4 @@ static int __init btf_vmlinux_init(void)
 }
 
 subsys_initcall(btf_vmlinux_init);
+#endif /* CONFIG_SYSFS */
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 1b6c0674ff6a13..8606b97765e7eb 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -320,7 +320,6 @@ static const char *btf_type_name(const struct btf *btf, u32 id)
 }
 
 static DEFINE_MUTEX(bpf_verifier_lock);
-static DEFINE_MUTEX(btf_vmlinux_lock);
 static DEFINE_MUTEX(bpf_percpu_ma_lock);
 
 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
@@ -3069,6 +3068,18 @@ static int fetch_kfunc_meta(struct bpf_verifier_env *env,
 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
 			       const struct btf_func_model *fm, struct bpf_func_proto *proto);
 
+/*
+ * The vmlinux BTF failed to parse where a program first needs it: pass the
+ * error on, as bpf_check() did when it fetched the BTF up front.  It need
+ * not be for good: a parse on first use that runs out of memory is retried
+ * by the next caller.
+ */
+static int vmlinux_btf_err(struct bpf_verifier_env *env, const struct btf *btf)
+{
+	verbose(env, "in-kernel BTF could not be parsed: %ld\n", PTR_ERR(btf));
+	return PTR_ERR(btf);
+}
+
 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 {
 	struct bpf_call_arg_meta meta;
@@ -3085,7 +3096,11 @@ 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) {
+		struct btf *btf = bpf_get_btf_vmlinux();
+
+		if (IS_ERR(btf))
+			return vmlinux_btf_err(env, btf);
+		if (!btf) {
 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
 			return -ENOTSUPP;
 		}
@@ -6867,30 +6882,33 @@ static int check_ptr_to_map_access(struct bpf_verifier_env *env,
 	enum bpf_type_flag flag = 0;
 	const struct btf_type *t;
 	const char *tname;
+	struct btf *btf;
 	u32 btf_id;
 	int ret;
 
-	if (!btf_vmlinux) {
-		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
-		return -ENOTSUPP;
-	}
-
 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
 		verbose(env, "map_ptr access not supported for map type %d\n",
 			map->map_type);
 		return -ENOTSUPP;
 	}
 
-	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
-	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
-
+	/* before the BTF fetch: unprivileged loads must not parse it */
 	if (!env->allow_ptr_leaks) {
-		verbose(env,
-			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
-			tname);
+		verbose(env, "map_ptr access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n");
 		return -EPERM;
 	}
 
+	btf = bpf_get_btf_vmlinux();
+	if (IS_ERR(btf))
+		return vmlinux_btf_err(env, btf);
+	if (!btf) {
+		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
+		return -ENOTSUPP;
+	}
+
+	t = btf_type_by_id(btf, *map->ops->map_btf_id);
+	tname = btf_name_by_offset(btf, t->name_off);
+
 	if (off < 0) {
 		verbose(env, "%s is %s invalid negative access: off=%d\n",
 			reg_arg_name(env, argno), tname, off);
@@ -12616,6 +12634,22 @@ static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
 	return err;
 }
 
+/* Does helper @fn 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 a kernel type id in struct btf_ptr */
+	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 < ARRAY_SIZE(fn->arg_type); 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)
 {
@@ -12685,6 +12719,14 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		return err;
 	}
 
+	if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF) && helper_uses_vmlinux_btf(func_id, fn)) {
+		/* never NULL with CONFIG_DEBUG_INFO_BTF */
+		struct btf *btf = bpf_get_btf_vmlinux();
+
+		if (IS_ERR(btf))
+			return vmlinux_btf_err(env, btf);
+	}
+
 	if (fn->might_sleep && !in_sleepable_context(env)) {
 		const char *suggestion;
 
@@ -13910,7 +13952,7 @@ BTF_SET_END(dynptr_write_kfuncs)
 
 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta)
 {
-	return meta->btf == btf_vmlinux &&
+	return is_kfunc(meta) && meta->btf == btf_vmlinux &&
 	       btf_id_set_contains(&dynptr_write_kfuncs, meta->func_id);
 }
 
@@ -20960,12 +21002,14 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env,
 			return -EINVAL;
 		}
 	} else {
-		if (!btf_vmlinux) {
+		btf = bpf_get_btf_vmlinux();
+		if (IS_ERR(btf))
+			return vmlinux_btf_err(env, btf);
+		if (!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);
@@ -23182,29 +23226,6 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt
 	return 0;
 }
 
-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);
-
-	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);
-		}
-		mutex_unlock(&btf_vmlinux_lock);
-	}
-	return btf;
-}
-
 /*
  * 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
@@ -23928,7 +23949,12 @@ 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 here but where kernel types enter
+	 * the program (attach_btf, kfuncs, ksyms, map_ptr, BTF-typed helpers,
+	 * CO-RE, kernel ctx types), so that programs which use none of them
+	 * do not need it (CONFIG_DEBUG_INFO_BTF_LAZY).
+	 */
 
 	/* Serialize verification of unprivileged programs. */
 	if (!is_priv)
@@ -23949,13 +23975,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 
 	mark_verifier_state_clean(env);
 
-	if (IS_ERR(btf_vmlinux)) {
-		/* Either gcc or pahole or kernel are broken. */
-		verbose(env, "in-kernel BTF is malformed\n");
-		ret = PTR_ERR(btf_vmlinux);
-		goto skip_full_check;
-	}
-
 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
 		env->strict_alignment = true;
diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c
index 14adfb85fdb2be..92694d40c0c3e9 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();
+	/* fetched by the verifier, see helper_uses_vmlinux_btf() */
+	*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_btf.c b/kernel/trace/trace_btf.c
index f0e0c04d58d99f..693c1a1083c55e 100644
--- a/kernel/trace/trace_btf.c
+++ b/kernel/trace/trace_btf.c
@@ -1,4 +1,5 @@
 // SPDX-License-Identifier: GPL-2.0
+#include <linux/bpf.h>
 #include <linux/btf.h>
 #include <linux/kernel.h>
 #include <linux/slab.h>
@@ -141,6 +142,34 @@ const struct btf_member *btf_find_struct_member(struct btf *btf,
 	return member;
 }
 
+static bool trace_btf_deferred;
+
+/*
+ * func-args, funcgraph-args and funcgraph-retval print arguments and return
+ * values by their BTF types, and the readers of the trace use the vmlinux
+ * BTF only if it is parsed already: parse it when such output is enabled.
+ * With CONFIG_DEBUG_INFO_BTF_LAZY that may be its first use, which should
+ * not happen in a reader that holds the trace read locks while the tracer
+ * records its work.
+ */
+void trace_btf_prepare(void)
+{
+	/* trace_options= on the command line is applied by early_trace_init() */
+	if (system_state < SYSTEM_SCHEDULING) {
+		trace_btf_deferred = true;
+		return;
+	}
+	bpf_get_btf_vmlinux();
+}
+
+static int __init trace_btf_init(void)
+{
+	if (trace_btf_deferred)
+		bpf_get_btf_vmlinux();
+	return 0;
+}
+core_initcall(trace_btf_init);
+
 void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retval,
 			int *fmt, bool hex)
 {
@@ -151,6 +180,9 @@ void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retv
 	bool signed_type;
 	int kind;
 
+	/* see trace_btf_prepare() */
+	if (IS_ERR_OR_NULL(bpf_peek_btf_vmlinux()))
+		return;
 	if (lookup_symbol_name(func, name))
 		return;
 
diff --git a/kernel/trace/trace_btf.h b/kernel/trace/trace_btf.h
index b3d408e6a7f6c4..47407eff1339b9 100644
--- a/kernel/trace/trace_btf.h
+++ b/kernel/trace/trace_btf.h
@@ -23,9 +23,12 @@ const struct btf_member *btf_find_struct_member(struct btf *btf,
 #ifdef CONFIG_DEBUG_INFO_BTF
 void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retval,
 		     int *fmt, bool hex);
+void trace_btf_prepare(void);
 #else
 static inline void btf_trim_retval(unsigned long func, unsigned long *retval,
 				   bool *print_retval, int *fmt, bool hex)
 {
 }
+
+static inline void trace_btf_prepare(void) { }
 #endif
diff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c
index 49d135bc2fbfcc..adc422fbe16eab 100644
--- a/kernel/trace/trace_events.c
+++ b/kernel/trace/trace_events.c
@@ -23,6 +23,7 @@
 #include <linux/sort.h>
 #include <linux/slab.h>
 #include <linux/delay.h>
+#include <linux/bpf.h>
 #include <linux/btf.h>
 
 #include <kunit/visibility.h>
@@ -2282,6 +2283,9 @@ event_btf_ids_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppo
 	char buf[128];
 	int len;
 
+	/* parse the vmlinux BTF, if this is its first use, without event_mutex */
+	bpf_get_btf_vmlinux();
+
 	/* Module unload could free call->class and ids[] mid-read. */
 	scoped_guard(mutex, &event_mutex) {
 		file = event_file_file(filp);
diff --git a/kernel/trace/trace_functions.c b/kernel/trace/trace_functions.c
index acaba990aaaa26..2cebaacda526f8 100644
--- a/kernel/trace/trace_functions.c
+++ b/kernel/trace/trace_functions.c
@@ -18,6 +18,7 @@
 #include <linux/fs.h>
 
 #include "trace.h"
+#include "trace_btf.h"
 
 static void tracing_start_function_trace(struct trace_array *tr);
 static void tracing_stop_function_trace(struct trace_array *tr);
@@ -115,6 +116,9 @@ void ftrace_destroy_function_files(struct trace_array *tr)
 
 static ftrace_func_t select_trace_function(u32 flags_val)
 {
+	if (flags_val & TRACE_FUNC_OPT_ARGS)
+		trace_btf_prepare();
+
 	switch (flags_val & TRACE_FUNC_OPT_MASK) {
 	case TRACE_FUNC_NO_OPTS:
 		return function_trace_call;
diff --git a/kernel/trace/trace_functions_graph.c b/kernel/trace/trace_functions_graph.c
index 78a608315dd32b..cf5f433dd26e36 100644
--- a/kernel/trace/trace_functions_graph.c
+++ b/kernel/trace/trace_functions_graph.c
@@ -474,6 +474,10 @@ static int graph_trace_init(struct trace_array *tr)
 {
 	int ret;
 
+	if (tracer_flags_is_set(tr, TRACE_GRAPH_ARGS) ||
+	    tracer_flags_is_set(tr, TRACE_GRAPH_PRINT_RETVAL))
+		trace_btf_prepare();
+
 	if (tracer_flags_is_set(tr, TRACE_GRAPH_ARGS))
 		tr->gops->entryfunc = trace_graph_entry_args;
 	else
@@ -507,10 +511,12 @@ static int ftrace_graph_trace_args(struct trace_array *tr, int set)
 {
 	trace_func_graph_ent_t entry;
 
-	if (set)
+	if (set) {
+		trace_btf_prepare();
 		entry = trace_graph_entry_args;
-	else
+	} else {
 		entry = trace_graph_entry;
+	}
 
 	/* See if there's any changes */
 	if (tr->gops->entryfunc == entry)
@@ -1746,6 +1752,11 @@ func_graph_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set)
 
 	case TRACE_GRAPH_ARGS:
 		return ftrace_graph_trace_args(tr, set);
+
+	case TRACE_GRAPH_PRINT_RETVAL:
+		if (set)
+			trace_btf_prepare();
+		break;
 	}
 
 	return 0;
diff --git a/kernel/trace/trace_output.c b/kernel/trace/trace_output.c
index a5ad76175d10d4..cdb926c9d4e21d 100644
--- a/kernel/trace/trace_output.c
+++ b/kernel/trace/trace_output.c
@@ -739,6 +739,9 @@ void print_function_args(struct trace_seq *s, unsigned long *args,
 	if (lookup_symbol_name(func, name))
 		goto out;
 
+	/* see trace_btf_prepare() */
+	if (IS_ERR_OR_NULL(bpf_peek_btf_vmlinux()))
+		goto out;
 	/* TODO: Pass module name here too */
 	t = btf_find_func_proto(name, &btf);
 	if (IS_ERR_OR_NULL(t))
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 2d22638ec13a63..45b2bc4d9a9c75 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -408,6 +408,30 @@ 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.
 
+config DEBUG_INFO_BTF_LAZY
+	bool "Compress vmlinux BTF and parse it on first use"
+	depends on DEBUG_INFO_BTF
+	depends on X86 || ARM64
+	select ZSTD_DECOMPRESS
+	help
+	  Keep the vmlinux BTF zstd-compressed in the kernel image, at about
+	  a quarter of its size, and decompress and parse it the first time
+	  something needs it instead of at boot.  Systems that never use BTF
+	  then keep only the compressed copy in memory, which saves about 80%
+	  of what the BTF costs; the first user pays a few tens of
+	  milliseconds once.  The vmlinux file keeps the uncompressed BTF as
+	  a non-loaded section for tools.  Building needs the zstd tool.
+
+	  Users of kernel types at boot still parse it at boot: BPF LSM
+	  programs, the iterators of BPF_PRELOAD (loaded at boot, or at the
+	  first bpffs mount if bpf_preload is a module), and modules with
+	  distilled base BTF.  Kernel function and struct_ops registrations
+	  made before the first use are applied then and report errors only
+	  in the kernel log; a module BTF that fails validation then leaves
+	  the module loaded without BTF.
+
+	  If unsure, say N.
+
 config PAHOLE_HAS_BTF_TAG
 	def_bool PAHOLE_VERSION >= 123
 	depends on CC_IS_CLANG
diff --git a/scripts/gen-btf.sh b/scripts/gen-btf.sh
index b17f1189298a55..c490b06306127e 100755
--- a/scripts/gen-btf.sh
+++ b/scripts/gen-btf.sh
@@ -86,13 +86,24 @@ gen_btf_o()
 	btf_data=${ELF_FILE}.btf.o
 
 	# Create ${btf_data} which contains just BTF sections but no symbols. Add
-	# SHF_ALLOC because .BTF will be part of the vmlinux image. --strip-all
-	# deletes all symbols including __start_BTF and __stop_BTF, which will
-	# be redefined in the linker script.
+	# SHF_ALLOC to the sections that will be part of the vmlinux image.
+	# --strip-all 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}
-	ONLY_SEC="--only-section=.BTF"
+	if is_enabled CONFIG_DEBUG_INFO_BTF_LAZY; then
+		# The image gets compressed BTF as init data, .BTF stays in
+		# the ELF file for tools.
+		${ZSTD} -q -f -19 ${ELF_FILE}.BTF -o ${ELF_FILE}.BTF.zst
+		${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \
+			--set-section-flags .BTF=readonly \
+			--add-section .init.BTF.zst=${ELF_FILE}.BTF.zst \
+			--set-section-flags .init.BTF.zst=alloc,readonly ${btf_data}
+		ONLY_SEC="--only-section=.BTF --only-section=.init.BTF.zst"
+	else
+		${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \
+			--set-section-flags .BTF=alloc,readonly ${btf_data}
+		ONLY_SEC="--only-section=.BTF"
+	fi
 	btf_inline=${ELF_FILE}.BTF.inline
 	if [ "${BTF_INLINE}" = "m" ]; then
 		if [ -f "${btf_inline}" ]; then
@@ -145,7 +156,7 @@ embed_btf_data()
 cleanup()
 {
 	rm -f "${ELF_FILE}.BTF.1"
-	rm -f "${ELF_FILE}.BTF"
+	rm -f "${ELF_FILE}.BTF" "${ELF_FILE}.BTF.zst"
 	rm -f "${ELF_FILE}.BTF.inline"
 	rm -f "${ELF_FILE}.BTF.inline.link"
 	if [ "${BTFGEN_MODE}" = "module" ]; then
diff --git a/tools/testing/selftests/bpf/prog_tests/ksyms.c b/tools/testing/selftests/bpf/prog_tests/ksyms.c
index dc7aab532fb147..fa97cc0ee3bf0d 100644
--- a/tools/testing/selftests/bpf/prog_tests/ksyms.c
+++ b/tools/testing/selftests/bpf/prog_tests/ksyms.c
@@ -10,7 +10,7 @@ void test_ksyms(void)
 	const char *btf_path = "/sys/kernel/btf/vmlinux";
 	struct test_ksyms *skel;
 	struct test_ksyms__data *data;
-	__u64 link_fops_addr, per_cpu_start_addr;
+	__u64 link_fops_addr, per_cpu_start_addr, btf_start_addr;
 	struct stat st;
 	__u64 btf_size;
 	int err;
@@ -30,6 +30,12 @@ void test_ksyms(void)
 	if (!ASSERT_OK(stat(btf_path, &st), "stat_btf"))
 		return;
 	btf_size = st.st_size;
+	/*
+	 * With CONFIG_DEBUG_INFO_BTF_LAZY the image has the vmlinux BTF only
+	 * compressed and no __start_BTF/__stop_BTF: the weak ksyms are 0.
+	 */
+	if (kallsyms_find("__start_BTF", &btf_start_addr) == -ENOENT)
+		btf_size = 0;
 
 	skel = test_ksyms__open_and_load();
 	if (!ASSERT_OK_PTR(skel, "test_ksyms__open_and_load"))
diff --git a/tools/testing/selftests/bpf/progs/linked_vars2.c b/tools/testing/selftests/bpf/progs/linked_vars2.c
index e4f5bd388a3c7a..bbdc3b25b4836e 100644
--- a/tools/testing/selftests/bpf/progs/linked_vars2.c
+++ b/tools/testing/selftests/bpf/progs/linked_vars2.c
@@ -8,7 +8,7 @@
 extern int LINUX_KERNEL_VERSION __kconfig;
 /* when an extern is defined as both strong and weak, resulting symbol will be strong */
 extern bool CONFIG_BPF_SYSCALL __kconfig;
-extern const void __start_BTF __ksym;
+extern const void bpf_map_fops __ksym;
 
 int input_bss2;
 int input_data2 = 2;
@@ -47,7 +47,7 @@ int BPF_PROG(handler2)
 	 */
 	output_sink2 = LINUX_KERNEL_VERSION
 		       + CONFIG_BPF_SYSCALL
-		       + (long)&__start_BTF;
+		       + (long)&bpf_map_fops;
 
 	return 0;
 }
diff --git a/tools/testing/selftests/bpf/progs/test_ksyms.c b/tools/testing/selftests/bpf/progs/test_ksyms.c
index 6c9cbb5a3bdf46..0429430882252b 100644
--- a/tools/testing/selftests/bpf/progs/test_ksyms.c
+++ b/tools/testing/selftests/bpf/progs/test_ksyms.c
@@ -11,8 +11,9 @@ __u64 out__btf_size = -1;
 __u64 out__per_cpu_start = -1;
 
 extern const void bpf_link_fops __ksym;
-extern const void __start_BTF __ksym;
-extern const void __stop_BTF __ksym;
+/* weak: CONFIG_DEBUG_INFO_BTF_LAZY keeps no uncompressed BTF in the image */
+extern const void __start_BTF __ksym __weak;
+extern const void __stop_BTF __ksym __weak;
 extern const void __per_cpu_start __ksym;
 /* non-existing symbol, weak, default to zero */
 extern const void bpf_link_fops1 __ksym __weak;

3/2 2026/11/01 08:10 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30411
							output: 35
							thoughts: 1030
						

Thoughts:
**Fuzzing Decision: BPF/BTF Lazy Initialization**

Okay, let's break this down. This patch introduces lazy loading for BTF data, compressing it with zstd and decompressing it on first use. This touches deep within the BPF/BTF subsystem, which is a prime target for fuzzing. The patch modifies a *significant* number of core BPF/BTF files: Documentation, arch, include, kernel, lib, scripts, and tools. This is a big area of the kernel.

My initial reaction is to immediately look at syzkaller.

The patch includes the introduction of lazy loading mechanisms: `btf_vmlinux_data()`, `zstd_decompress_dctx()`, `bpf_get_btf_vmlinux()`, `bpf_peek_btf_vmlinux()`, and `btf_vmlinux_builder`. Deferred registrations for kfuncs, dtors, struct_ops are now handled using `btf_defer_reg`, `btf_apply_deferred`, and `btf_parse_kept_modules`. There are also changes to the sysfs interface `/sys/kernel/btf/vmlinux` for mmap and read handling with dynamic decompression with `btf_sysfs_vmlinux_mmap` and `btf_sysfs_vmlinux_read`.

This is *definitely* reachable via standard QEMU/x86_64 virtualization. The patch touches the BPF subsystem, including `sys_bpf`, sysfs access, and tracing. I can easily reach this from userspace fuzzing, using syzkaller. This makes it a great target for fuzzing.

My primary concern is that this patch introduces substantial concurrency logic with lazy initialization and deferred list handling. The patch also includes memory allocation and error recovery paths. This kind of complexity is a perfect recipe for uncovering subtle bugs, especially race conditions. Verifier checks and locking changes are present. I need to pay close attention to the new `btf_vmlinux_lock`, `btf_vmlinux_builder`, and potential locking order issues, like between `btf_module_mutex`, `cand_cache_mutex`, and `btf_vmlinux_lock`.

**Therefore, WorthFuzzing = True.**

Now, before I kick off syzkaller, I *have* to nail down the configuration requirements. Let's make sure I know how to build the kernel to enable this functionality. I see a `CONFIG_DEBUG_INFO_BTF_LAZY` option. The Kconfig entry specifies: `DEBUG_INFO_BTF_LAZY depends on DEBUG_INFO_BTF`, `DEBUG_INFO_BTF`, and it also `selects ZSTD_DECOMPRESS` and depends on `X86 || ARM64`. Also, I need to enable `BPF_SYSCALL`.

Okay, I need to check `lib/Kconfig.debug`. I need to figure out what `DEBUG_INFO_BTF` depends on, and I'll need to double check any dependencies by reading the Kconfig file or using a utility like `grepper`. I will run these checks on the Kconfig files. This is my next step.



4/2 2026/11/01 08:10 tool grepper
0m Args:
{
  "Expression": "config DEBUG_INFO_BTF$",
  "PathPrefixes": [
    "lib/Kconfig.debug"
  ]
}

Results:
{
  "Output": "lib/Kconfig.debug=378=config DEBUG_INFO_SPLIT\n--\nlib/Kconfig.debug-397-\nlib/Kconfig.debug:398:config DEBUG_INFO_BTF\nlib/Kconfig.debug-399-\tbool \"Generate BTF type information\"\n"
}

5/2 2026/11/01 08:10 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32263
							output: 34
							thoughts: 19
						

Thoughts:
Here's my analysis of the provided text, rendered as a first-person expert summary:

**Digging into the Kconfig.debug file**

Okay, so we're looking at `lib/Kconfig.debug`. I know this file intimately – it's where we manage a lot of the low-level debug and instrumentation options for the kernel and related libraries. Now, the context here is critical. Where should I be focusing? Ah, they're suggesting line 398. That usually means something pretty specific. I'll need to remember to check for any relevant dependencies or conditional statements around that line, too. Let's get to it. Time to dive in.



6/2 2026/11/01 08:10 tool read-file
0m Args:
{
  "File": "lib/Kconfig.debug",
  "FirstLine": 395,
  "LineCount": 40
}

Results:
{
  "Contents": " 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\tbool \"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:\tconfig DEBUG_INFO_BTF_LAZY\n 412:\t\tbool \"Compress vmlinux BTF and parse it on first use\"\n 413:\t\tdepends on DEBUG_INFO_BTF\n 414:\t\tdepends on X86 || ARM64\n 415:\t\tselect ZSTD_DECOMPRESS\n 416:\t\thelp\n 417:\t\t  Keep the vmlinux BTF zstd-compressed in the kernel image, at about\n 418:\t\t  a quarter of its size, and decompress and parse it the first time\n 419:\t\t  something needs it instead of at boot.  Systems that never use BTF\n 420:\t\t  then keep only the compressed copy in memory, which saves about 80%\n 421:\t\t  of what the BTF costs; the first user pays a few tens of\n 422:\t\t  milliseconds once.  The vmlinux file keeps the uncompressed BTF as\n 423:\t\t  a non-loaded section for tools.  Building needs the zstd tool.\n 424:\t\n 425:\t\t  Users of kernel types at boot still parse it at boot: BPF LSM\n 426:\t\t  programs, the iterators of BPF_PRELOAD (loaded at boot, or at the\n 427:\t\t  first bpffs mount if bpf_preload is a module), and modules with\n 428:\t\t  distilled base BTF.  Kernel function and struct_ops registrations\n 429:\t\t  made before the first use are applied then and report errors only\n 430:\t\t  in the kernel log; a module BTF that fails validation then leaves\n 431:\t\t  the module loaded without BTF.\n 432:\t\n 433:\t\t  If unsure, say N.\n 434:\t\n"
}

7/2 2026/11/01 08:10 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33191
							output: 37
							thoughts: 18
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Investigating the BTF Modules**

Right, let's circle back and make absolutely sure we've covered all the bases. I was focusing on the main suspect, but I need to make sure we haven't overlooked any contributing factors. The primary issue could be stemming from somewhere else entirely. So, let's take a good, hard look at `DEBUG_INFO_BTF_MODULES`. It’s easy to get tunnel vision, especially when troubleshooting complex kernel-level issues. We have to be thorough, methodical, and eliminate all possibilities. I want to rule out any peripheral causes before diving deeper. Time to cross-check that specific configuration variable and see if it yields any useful insights, and if necessary, what specific issues are encountered when the variable is set to a specific value.



8/2 2026/11/01 08:10 tool grepper
0m Args:
{
  "Expression": "config DEBUG_INFO_BTF_MODULES",
  "PathPrefixes": [
    "lib/Kconfig.debug"
  ]
}

Results:
{
  "Output": "lib/Kconfig.debug=452=config PAHOLE_HAS_INLINE\n--\nlib/Kconfig.debug-457-\nlib/Kconfig.debug:458:config DEBUG_INFO_BTF_MODULES\nlib/Kconfig.debug-459-\tbool \"Generate BTF type information for kernel modules\"\n"
}

9/2 2026/11/01 08:10 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33532
							output: 337
							thoughts: 2064
						

Thoughts:
**Analysis of BTF Lazy Loading Implementation for Fuzzing**

Alright, let's break this down. We're dealing with a new config option, `CONFIG_DEBUG_INFO_BTF_LAZY`, and a handful of related ones, including `CONFIG_DEBUG_INFO_BTF`, `CONFIG_BPF_SYSCALL`, `CONFIG_DEBUG_INFO_BTF_MODULES`, and `CONFIG_SYSFS`. My primary goal here is to identify the critical functions, the "FocusSymbols," for targeted fuzzing and determine the necessary configurations.

First, I need to pinpoint the functions either newly introduced or heavily modified by this patch, while avoiding the usual suspects – those ubiquitous lifecycle hot-paths like allocators, trap handlers, and core locking primitives. Instead, I'm focusing on the code directly implementing the new lazy-loading logic or serving as direct entrypoints to the feature.

Examining the code, I've identified the following functions across `kernel/bpf/btf.c`, `kernel/bpf/sysfs_btf.c`, `kernel/bpf/verifier.c`, and `kernel/trace/trace_btf.c`, and `kernel/trace/trace_events.c`:

*   `bpf_get_btf_vmlinux`
*   `bpf_peek_btf_vmlinux`
*   `btf_parse_vmlinux`
*   `btf_vmlinux_data`
*   `btf_get_module_btf`
*   `__register_btf_kfunc_id_set`
*   `register_btf_id_dtor_kfuncs`
*   `__register_bpf_struct_ops`
*   `trace_btf_prepare`
*   `btf_trim_retval`

I also note `btf_sysfs_vmlinux_read` and `btf_sysfs_vmlinux_mmap` for their sysfs interaction, but they are static handlers. These are also related, but not the primary targets.

Now, let's determine the critical ones. `bpf_get_btf_vmlinux` sticks out immediately; it's the core of the lazy fetch. All lazy BTF accesses should go through it. `bpf_peek_btf_vmlinux` is also a key player when locking/sleeping is unavailable. `btf_vmlinux_data` provides the compressed BTF data from sysfs. I need to be sure the decompression is solid. `btf_parse_vmlinux` handles the now-decompressed data. Additionally, `trace_btf_prepare` prepares BTF for ftrace use. The `__register_btf_kfunc_id_set`, `register_btf_id_dtor_kfuncs`, and `__register_bpf_struct_ops` functions, are all interception points for deferred registrations. Finally, `btf_get_module_btf` will be key in handling modules.

I must check if the functions are likely ubiquitous or very specific. `bpf_get_btf_vmlinux` is *not* a ubiquitous function; it's specific to BPF operations that depend on kernel types, CO-RE, attach_btf, kfuncs, or BTF IDs. This makes it a great candidate. This, combined with the fact that these functions are accessible via the `bpf()` syscall, module loading, sysfs reads/mmaps, and tracefs nodes, makes it a prime fuzzing target.

Finally, the required configurations: `DEBUG_INFO_BTF_LAZY`, `DEBUG_INFO_BTF`, `DEBUG_INFO_BTF_MODULES`, `BPF_SYSCALL`, and `SYSFS` are all essential. As a side note, `DEBUG_INFO_BTF_LAZY` selects `ZSTD_DECOMPRESS`, which is important for the lazy decompression logic.

Therefore, this patch is definitely WorthFuzzing. The focus symbols are:
*   `bpf_get_btf_vmlinux`
*   `bpf_peek_btf_vmlinux`
*   `btf_vmlinux_data`
*   `btf_parse_vmlinux`
*   `btf_get_module_btf`
*   `trace_btf_prepare`
*   `__register_btf_kfunc_id_set`
*   `register_btf_id_dtor_kfuncs`
*   `__register_bpf_struct_ops`

The


10/2 2026/11/01 08:10 tool set-results
0m Args:
{
  "EnableConfigs": [
    "DEBUG_INFO_BTF_LAZY",
    "DEBUG_INFO_BTF",
    "DEBUG_INFO_BTF_MODULES",
    "BPF_SYSCALL",
    "SYSFS"
  ],
  "FocusSymbols": [
    "bpf_get_btf_vmlinux",
    "bpf_peek_btf_vmlinux",
    "btf_vmlinux_data",
    "btf_parse_vmlinux",
    "btf_get_module_btf",
    "trace_btf_prepare",
    "__register_btf_kfunc_id_set",
    "register_btf_id_dtor_kfuncs",
    "__register_bpf_struct_ops"
  ],
  "Reasoning": "The patch introduces CONFIG_DEBUG_INFO_BTF_LAZY, which implements on-demand zstd decompression and lazy parsing of the vmlinux BTF upon first use, as well as deferred registration of kfuncs, dtor kfuncs, and struct_ops. It also modifies module BTF handling, BPF verifier entrypoints, sysfs /sys/kernel/btf/vmlinux read/mmap interfaces, and ftrace BTF integrations. These changes introduce substantial new state management, memory management, and synchronization logic across core BPF, tracing, and module subsystems, which are reachable and readily exercisable via the bpf() syscall, sysfs, and tracefs in standard virtualized environments.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "DEBUG_INFO_BTF_LAZY",
    "DEBUG_INFO_BTF",
    "DEBUG_INFO_BTF_MODULES",
    "BPF_SYSCALL",
    "SYSFS"
  ],
  "FocusSymbols": [
    "bpf_get_btf_vmlinux",
    "bpf_peek_btf_vmlinux",
    "btf_vmlinux_data",
    "btf_parse_vmlinux",
    "btf_get_module_btf",
    "trace_btf_prepare",
    "__register_btf_kfunc_id_set",
    "register_btf_id_dtor_kfuncs",
    "__register_bpf_struct_ops"
  ],
  "Reasoning": "The patch introduces CONFIG_DEBUG_INFO_BTF_LAZY, which implements on-demand zstd decompression and lazy parsing of the vmlinux BTF upon first use, as well as deferred registration of kfuncs, dtor kfuncs, and struct_ops. It also modifies module BTF handling, BPF verifier entrypoints, sysfs /sys/kernel/btf/vmlinux read/mmap interfaces, and ftrace BTF integrations. These changes introduce substantial new state management, memory management, and synchronization logic across core BPF, tracing, and module subsystems, which are reachable and readily exercisable via the bpf() syscall, sysfs, and tracefs in standard virtualized environments.",
  "WorthFuzzing": true
}

11/1 2026/11/01 08:10 action If
3m Args:
{
  "WorthFuzzing": true
}

Results:
null

12/2 2026/11/01 08:10 agent kmsan-evaluator
3m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series introduces CONFIG_DEBUG_INFO_BTF_LAZY, which compresses the vmlinux BTF using zstd and lazily decompresses and parses it on first demand rather than at boot. It also implements deferred registration queues for kfuncs, dtor kfuncs, and struct_ops, as well as deferral for module split BTF loading.\n\n1. Analysis of Memory Allocation and Initialization:\n- All heap objects introduced or modified by the patch (such as `struct btf_deferred_reg` in btf_defer_reg() and `struct btf_module` in btf_module_notify()) are allocated using zero-initializing allocators (`kzalloc_obj`).\n- Buffer copies for deferred kfunc id sets, dtors, and module BTF data are cloned via `kmemdup`, `kmemdup_array`, and `kvmemdup`, duplicating already initialized data.\n- The vmlinux BTF raw buffer is allocated using `vmalloc_user()`, which zeroes allocated pages (`__GFP_ZERO`), and is populated by `zstd_decompress_dctx()`. The pointer is only published if decompression output exactly matches the expected size (`ret == *size`).\n- Stack variables (such as `zstd_frame_header hdr` in `btf_vmlinux_size()`) are guarded by error checks; `hdr.frameContentSize` is accessed only after `zstd_get_frame_header()` returns 0 (success). In `prog_ctx_tname()`, the out-pointer `*alt` is explicitly initialized to NULL before use.\n\n2. User Space Exposure and Info-leak Checks:\n- Data exposed to user space through `/sys/kernel/btf/vmlinux` via sysfs read and mmap operations maps or copies from the `vmalloc_user` buffer holding verified decompressed BTF data.\n- Similarly, trace events' BTF ID reads use `scnprintf` formatted into a stack buffer and copy only the formatted length via `simple_read_from_buffer`. There is no uninitialized memory or structure padding leaked to user space.\n\n3. KASAN vs KMSAN Applicability:\n- The risks introduced by this change involve synchronization, complex lock ordering (e.g., `btf_vmlinux_lock` vs `btf_module_mutex`, `cand_cache_mutex`, `event_mutex`), and object lifecycles across module load/unload transitions. These failure modes (deadlocks, use-after-free, double-free, NULL/ERR pointer dereferences) are detected by LOCKDEP and KASAN.\n- There are no uninitialized memory reads or uninitialized data leakage risks that uniquely require KMSAN.\n\nTherefore, dedicated KMSAN fuzzing is not justified.",
  "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 d0d825401d8cf7610975e1842f2fd9fb6624bdbc
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Nov 1 08:10:07 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/bpf/btf.rst b/Documentation/bpf/btf.rst
index 29de1222c3e73f..1ebce5cf578346 100644
--- a/Documentation/bpf/btf.rst
+++ b/Documentation/bpf/btf.rst
@@ -1276,6 +1276,36 @@ format.::
             .long   58
             .long   8206                    # Line 8 Col 14
 
+6.1 Compressed vmlinux BTF
+--------------------------
+
+With ``CONFIG_DEBUG_INFO_BTF_LAZY``, the kernel image carries the vmlinux BTF
+zstd-compressed, at about a quarter of its size, and the kernel decompresses
+and parses it when something first needs it: a BPF program or map that uses
+kernel types, ``BPF_BTF_GET_NEXT_ID``, tracing options that print arguments or
+return values by their BTF types.
+``/sys/kernel/btf/vmlinux`` has its full size from the start; reading or
+mapping it decompresses the BTF but does not parse it. Systems that never use
+BTF keep only the compressed copy in memory. The vmlinux file keeps the
+uncompressed ``.BTF`` section, not loaded, for tools and module builds.
+The option is available on x86 and arm64.
+
+Kernel function, destructor kfunc and struct_ops registrations made before the
+first use, and the BTF of modules loaded before it, are kept and applied by the
+task that parses the vmlinux BTF, before anyone else can see it. Errors of
+those registrations then only show in the kernel log, and a module whose BTF
+fails validation at that point stays loaded without BTF and without its files
+in ``/sys/kernel/btf``. A first use that runs out of memory fails with
+``-ENOMEM`` and leaves all of this as it was, for the next one to start over.
+The vmlinux BTF gets the next free BTF id, not necessarily 1, and the image has
+no ``__start_BTF``/``__stop_BTF`` symbols. The inline BTF
+(``CONFIG_DEBUG_INFO_BTF_INLINE``) is not compressed.
+
+Users of kernel types during boot still parse it during boot, for example BPF
+LSM programs, the iterators of ``CONFIG_BPF_PRELOAD`` (loaded at boot, or at the
+first bpffs mount if ``bpf_preload`` is a module), or a module with a
+``.BTF.base`` section.
+
 7. Testing
 ==========
 
diff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile
index 680ad803cba7df..58d05262dec82f 100644
--- a/arch/x86/boot/compressed/Makefile
+++ b/arch/x86/boot/compressed/Makefile
@@ -116,7 +116,7 @@ endif
 $(obj)/vmlinux: $(vmlinux-objs-y) $(vmlinux-libs-y) FORCE
 	$(call if_changed,ld)
 
-OBJCOPYFLAGS_vmlinux.bin :=  -R .comment -S
+OBJCOPYFLAGS_vmlinux.bin :=  -R .comment $(if $(CONFIG_DEBUG_INFO_BTF_LAZY),-R .BTF) -S
 $(obj)/vmlinux.bin: vmlinux FORCE
 	$(call if_changed,objcopy)
 
diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h
index 3eb732942d699c..7358aedab95cbc 100644
--- a/include/asm-generic/vmlinux.lds.h
+++ b/include/asm-generic/vmlinux.lds.h
@@ -553,7 +553,7 @@
 									\
 	RO_EXCEPTION_TABLE						\
 	NOTES								\
-	BTF								\
+	RO_BTF								\
 									\
 	. = ALIGN((align));						\
 	__end_rodata = .;
@@ -704,12 +704,24 @@
 #define BTF_INLINE_LINK
 #endif
 
-#ifdef CONFIG_DEBUG_INFO_BTF
-#define BTF								\
+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY
+/* compressed BTF in init data (see sysfs_btf.c), raw BTF not loaded */
+#define BTF_LOADED
+#define BTF_ZST		. = ALIGN(8); BOUNDED_SECTION_BY(.init.BTF.zst, _BTF_zst)
+#define BTF_RAW		.BTF 0 : { *(.BTF) }
+#else
+#define BTF_LOADED							\
 	. = ALIGN(PAGE_SIZE);						\
 	.BTF : AT(ADDR(.BTF) - LOAD_OFFSET) {				\
 		BOUNDED_SECTION_BY(.BTF, _BTF)				\
-	}								\
+	}
+#define BTF_ZST
+#define BTF_RAW
+#endif
+
+#ifdef CONFIG_DEBUG_INFO_BTF
+#define RO_BTF								\
+	BTF_LOADED							\
 	BTF_INLINE							\
 	BTF_INLINE_LINK						\
 	. = ALIGN(PAGE_SIZE);						\
@@ -717,7 +729,7 @@
 		*(.BTF_ids)						\
 	}
 #else
-#define BTF
+#define RO_BTF
 #endif
 
 /*
@@ -748,6 +760,7 @@
 	KERNEL_CTORS()							\
 	MCOUNT_REC()							\
 	*(.init.rodata .init.rodata.*)					\
+	BTF_ZST								\
 	FTRACE_EVENTS()							\
 	TRACE_SYSCALLS()						\
 	KPROBE_BLACKLIST()						\
@@ -880,6 +893,7 @@
 /* Required sections not related to debugging. */
 #define ELF_DETAILS							\
 		.comment 0 : { *(.comment) }				\
+		BTF_RAW							\
 		.symtab 0 : { *(.symtab) }				\
 		.strtab 0 : { *(.strtab) }				\
 		.shstrtab 0 : { *(.shstrtab) }				\
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index ff043678129358..c08b49e280d31f 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -3259,6 +3259,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 a18254b7521bdd..ff6d4a1d2e6b60 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -618,6 +618,11 @@ __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);
+#ifdef CONFIG_DEBUG_INFO_BTF
+void *btf_vmlinux_data(u32 *size);
+#else
+static inline void *btf_vmlinux_data(u32 *size) { return ERR_PTR(-ENOENT); }
+#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/kernel/bpf/Makefile b/kernel/bpf/Makefile
index 269810b128c469..4f500927cec854 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -40,8 +40,8 @@ obj-$(CONFIG_CGROUP_BPF) += cgroup.o
 ifeq ($(CONFIG_INET),y)
 obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o
 endif
-ifeq ($(CONFIG_SYSFS),y)
 obj-$(CONFIG_DEBUG_INFO_BTF) += sysfs_btf.o
+ifeq ($(CONFIG_SYSFS),y)
 obj-$(CONFIG_DEBUG_INFO_BTF_INLINE) += btf_vmlinux_inline.o
 endif
 ifeq ($(CONFIG_BPF_JIT),y)
diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c
index 7c5cd6086e2735..5e753b7d532d35 100644
--- a/kernel/bpf/bpf_struct_ops.c
+++ b/kernel/bpf/bpf_struct_ops.c
@@ -103,8 +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,
-					   st_ops_ids[IDX_ST_OPS_COMMON_VALUE_ID]);
+	/* a vmlinux id: btf may be the vmlinux BTF being published, or a module's */
+	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",
 			value_name);
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 1be30487a2fa75..c7234bcba87453 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -1902,7 +1902,8 @@ static void btf_free(struct btf *btf)
 	kvfree(btf->resolved_sizes);
 	kvfree(btf->resolved_ids);
 	/* vmlinux does not allocate btf->data, it simply points it at
-	 * __start_BTF.
+	 * __start_BTF, or at the decompressed copy with
+	 * CONFIG_DEBUG_INFO_BTF_LAZY, which is never freed either.
 	 */
 	if (!btf_is_vmlinux(btf))
 		kvfree(btf->data);
@@ -6524,8 +6525,6 @@ static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,
 	return ERR_PTR(err);
 }
 
-extern char __start_BTF[];
-extern char __stop_BTF[];
 extern struct btf *btf_vmlinux;
 
 #define BPF_MAP_TYPE(_id, _ops)
@@ -6558,20 +6557,46 @@ static u8 bpf_ctx_convert_map[] = {
 #undef BPF_MAP_TYPE
 #undef BPF_LINK_TYPE
 
-static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
+#define BPF_MAP_TYPE(_id, _ops)
+#define BPF_LINK_TYPE(_id, _name)
+#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
+	[_id] = #prog_ctx_type,
+static const char * const bpf_prog_ctx_tname[] = {
+#include <linux/bpf_types.h>
+};
+#undef BPF_PROG_TYPE
+#undef BPF_MAP_TYPE
+#undef BPF_LINK_TYPE
+
+struct user_regs_struct;
+struct user_pt_regs;
+
+/*
+ * Name of the context struct of @prog_type, as written in bpf_types.h, or NULL
+ * if it has none ("void *").  Only names are compared against the program's
+ * BTF, so the vmlinux BTF is not needed.  *@alt is set to the struct behind
+ * the bpf_user_pt_regs_t typedef.  Typedefs of integers (__u64, __u32) never
+ * match a struct name.
+ */
+static const char *prog_ctx_tname(enum bpf_prog_type prog_type, const char **alt)
 {
-	const struct btf_type *conv_struct;
-	const struct btf_member *ctx_type;
+	const char *name = prog_type < ARRAY_SIZE(bpf_prog_ctx_tname) ?
+			   bpf_prog_ctx_tname[prog_type] : NULL;
 
-	conv_struct = bpf_ctx_convert.t;
-	if (!conv_struct)
+	*alt = NULL;
+	if (!name || strchr(name, '*'))
 		return NULL;
-	/* prog_type is valid bpf program type. No need for bounds check. */
-	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
-	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
-	 * Like 'struct __sk_buff'
-	 */
-	return btf_type_by_id(btf_vmlinux, ctx_type->type);
+	if (str_has_prefix(name, "struct "))
+		return name + strlen("struct ");
+	if (!strcmp(name, "bpf_user_pt_regs_t")) {
+		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs))
+			*alt = "pt_regs";
+		else if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs))
+			*alt = "user_pt_regs";
+		else if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct))
+			*alt = "user_regs_struct";
+	}
+	return name;
 }
 
 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
@@ -6579,9 +6604,10 @@ 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;
-	if (!conv_struct)
+	/* bpf_ctx_convert.t is set when the vmlinux BTF is parsed */
+	if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
 		return -EFAULT;
+	conv_struct = bpf_ctx_convert.t;
 	/* prog_type is valid bpf program type. No need for bounds check. */
 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
@@ -6603,8 +6629,7 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 			  const struct btf_type *t, enum bpf_prog_type prog_type,
 			  int arg)
 {
-	const struct btf_type *ctx_type;
-	const char *tname, *ctx_tname;
+	const char *tname, *ctx_tname, *alt;
 
 	t = btf_type_by_id(btf, t->type);
 
@@ -6638,21 +6663,9 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 		return false;
 	}
 
-	ctx_type = find_canonical_prog_ctx_type(prog_type);
-	if (!ctx_type) {
-		bpf_log(log, "btf_vmlinux is malformed\n");
-		/* should not happen */
-		return false;
-	}
-again:
-	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
-	if (!ctx_tname) {
-		/* should not happen */
-		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
-		return false;
-	}
 	/* program types without named context types work only with arg:ctx tag */
-	if (ctx_tname[0] == '\0')
+	ctx_tname = prog_ctx_tname(prog_type, &alt);
+	if (!ctx_tname)
 		return false;
 	/* only compare that prog's ctx type name is the same as
 	 * kernel expects. No need to compare field by field.
@@ -6661,37 +6674,18 @@ bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
 	 * { // no fields of skb are ever used }
 	 */
-	if (btf_is_projection_of(ctx_tname, tname))
+	if (btf_is_projection_of(ctx_tname, tname) || !strcmp(ctx_tname, tname))
 		return true;
-	if (strcmp(ctx_tname, tname)) {
-		/* bpf_user_pt_regs_t is a typedef, so resolve it to
-		 * underlying struct and check name again
-		 */
-		if (!btf_type_is_modifier(ctx_type))
-			return false;
-		while (btf_type_is_modifier(ctx_type))
-			ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
-		goto again;
-	}
-	return true;
+	/* bpf_user_pt_regs_t is a typedef, check the underlying struct too */
+	return alt && !strcmp(alt, tname);
 }
 
-/* forward declarations for arch-specific underlying types of
- * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
- * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
- * works correctly with __builtin_types_compatible_p() on respective
- * architectures
- */
-struct user_regs_struct;
-struct user_pt_regs;
-
 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 				      const struct btf_type *t, int arg,
 				      enum bpf_prog_type prog_type,
 				      enum bpf_attach_type attach_type)
 {
-	const struct btf_type *ctx_type;
-	const char *tname, *ctx_tname;
+	const char *tname, *ctx_tname, *alt;
 
 	if (!btf_is_ptr(t)) {
 		bpf_log(log, "arg#%d type isn't a pointer\n", arg);
@@ -6791,27 +6785,20 @@ static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct
 		break;
 	}
 
-	ctx_type = find_canonical_prog_ctx_type(prog_type);
-	if (!ctx_type) {
-		/* should not happen */
-		bpf_log(log, "btf_vmlinux is malformed\n");
-		return -EINVAL;
-	}
-
 	/* resolve typedefs and check that underlying structs are matching as well */
-	while (btf_type_is_modifier(ctx_type))
-		ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
+	ctx_tname = prog_ctx_tname(prog_type, &alt);
+	if (ctx_tname && !str_has_prefix(bpf_prog_ctx_tname[prog_type], "struct "))
+		ctx_tname = alt;
 
 	/* if program type doesn't have distinctly named struct type for
 	 * context, then __arg_ctx argument can only be `void *`, which we
 	 * already checked above
 	 */
-	if (!__btf_type_is_struct(ctx_type)) {
+	if (!ctx_tname) {
 		bpf_log(log, "arg#%d should be void pointer\n", arg);
 		return -EINVAL;
 	}
 
-	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
 	if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
 		bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
 		return -EINVAL;
@@ -6838,6 +6825,8 @@ 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;
 
+	if (IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+		return -EINVAL;
 	conv_struct = bpf_ctx_convert.t;
 	/* get member for kernel ctx type */
 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
@@ -6911,15 +6900,21 @@ 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;
 
+	data = btf_vmlinux_data(&size);
+	if (IS_ERR(data))
+		return ERR_CAST(data);
+
 	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;
 
@@ -6935,6 +6930,75 @@ struct btf *btf_parse_vmlinux(void)
 	return btf;
 }
 
+static DEFINE_MUTEX(btf_vmlinux_lock);
+/* CONFIG_DEBUG_INFO_BTF_LAZY: the task applying deferred work, and its BTF */
+static struct task_struct *btf_vmlinux_builder;
+static struct btf *btf_vmlinux_new;
+static int btf_apply_deferred(void);
+static void btf_drop_all_deferred(int err);
+
+static bool btf_vmlinux_building(void)
+{
+	return in_task() && READ_ONCE(btf_vmlinux_builder) == current;
+}
+
+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);
+
+	/* with CONFIG_DEBUG_INFO_BTF_LAZY any call may be the one that parses */
+	if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		might_sleep();
+	if (btf || !IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
+		return btf;
+	/* the registrations btf_apply_deferred() applies see the new BTF */
+	if (btf_vmlinux_building())
+		return btf_vmlinux_new;
+
+	mutex_lock(&btf_vmlinux_lock);
+	btf = btf_vmlinux;
+	if (!btf) {
+		btf = btf_parse_vmlinux();
+		if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) && !IS_ERR(btf)) {
+			int err;
+
+			btf_vmlinux_new = btf;
+			WRITE_ONCE(btf_vmlinux_builder, current);
+			err = btf_apply_deferred();
+			WRITE_ONCE(btf_vmlinux_builder, NULL);
+			btf_vmlinux_new = NULL;
+			if (err) {
+				/* nothing saw it: drop it with what was applied to it */
+				bpf_ctx_convert.t = NULL;
+				btf_put(btf);
+				btf = ERR_PTR(err);
+			}
+		}
+		/* a lazy parse that ran out of memory is retried by the next caller */
+		if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || btf != ERR_PTR(-ENOMEM)) {
+			if (IS_ERR(btf))
+				btf_drop_all_deferred(PTR_ERR(btf));
+			/*
+			 * Order the parsed BTF contents and the globals the
+			 * parse populated (e.g. bpf_ctx_convert.t) before
+			 * the pointer publication. Pairs with the acquire
+			 * on the lockless fast path above.
+			 */
+			smp_store_release(&btf_vmlinux, btf);
+		}
+	}
+	mutex_unlock(&btf_vmlinux_lock);
+	return btf;
+}
+
+/* The vmlinux BTF if it is parsed already: for callers that cannot sleep */
+struct btf *bpf_peek_btf_vmlinux(void)
+{
+	/* Pairs with the smp_store_release() in bpf_get_btf_vmlinux() */
+	return smp_load_acquire(&btf_vmlinux);
+}
+
 /* If .BTF_ids section was created with distilled base BTF, both base and
  * split BTF ids will need to be mapped to actual base/split ids for
  * BTF now that it has been relocated.
@@ -6948,8 +7012,9 @@ __u32 btf_relocate_id(const struct btf *btf, __u32 id)
 
 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 
+/* @data is a copy owned by the returned BTF; the caller frees it on error */
 static struct btf *btf_parse_split(struct btf_verifier_env *env,
-				   const char *name, const void *data,
+				   const char *name, void *data,
 				   unsigned int data_size, struct btf *base_btf)
 {
 	struct btf *btf;
@@ -6965,11 +7030,7 @@ static struct btf *btf_parse_split(struct btf_verifier_env *env,
 	btf->named_start_id = 0;
 	strscpy(btf->name, name);
 
-	btf->data = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);
-	if (!btf->data) {
-		err = -ENOMEM;
-		goto errout;
-	}
+	btf->data = data;
 	btf->data_size = data_size;
 
 	err = btf_parse_hdr(env);
@@ -6993,6 +7054,7 @@ static struct btf *btf_parse_split(struct btf_verifier_env *env,
 	return btf;
 
 errout:
+	btf->data = NULL;
 	btf_free(btf);
 	return ERR_PTR(err);
 }
@@ -7064,10 +7126,16 @@ static int btf_rebase_inline(struct btf *inline_btf,
 	return 0;
 }
 
-static struct btf *btf_parse_module(const char *module_name, const void *data,
+/*
+ * @data and @inline_data are copies made by the caller.  On success the
+ * returned BTF owns @data, and *@relocated_inline_data is @inline_data,
+ * relocated in place, unless the inline BTF is invalid.  The caller frees
+ * the copies this does not take.
+ */
+static struct btf *btf_parse_module(const char *module_name, void *data,
 				    unsigned int data_size, void *base_data,
 				    unsigned int base_data_size,
-				    const void *inline_data,
+				    void *inline_data,
 				    unsigned int inline_data_size,
 				    void **relocated_inline_data)
 {
@@ -7135,6 +7203,7 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,
 		if (err) {
 			pr_warn("failed to relocate module [%s] inline BTF: %d\n",
 				module_name, err);
+			inline_btf->data = NULL;
 			btf_free(inline_btf);
 		} else {
 			*relocated_inline_data = inline_btf->data;
@@ -7158,12 +7227,16 @@ static struct btf *btf_parse_module(const char *module_name, const void *data,
 errout:
 	kvfree(module_str_map);
 	btf_verifier_env_free(env);
-	if (inline_btf)
+	if (inline_btf) {
+		inline_btf->data = NULL;
 		btf_free(inline_btf);
+	}
 	if (!IS_ERR(base_btf) && base_btf != vmlinux_btf)
 		btf_free(base_btf);
-	if (btf)
+	if (btf) {
+		btf->data = NULL;
 		btf_free(btf);
+	}
 	return ERR_PTR(err);
 }
 
@@ -8566,6 +8639,7 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
 		.btf = btf,
 		.log = log,
 	};
+	struct btf *vmlinux_btf;
 	u32 kern_type_id, type_id;
 	int err = 0;
 
@@ -8577,6 +8651,10 @@ static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
 		t = btf_type_by_id(btf, t->type);
 	}
 
+	/* parse it, if this is its first use, before taking cand_cache_mutex */
+	vmlinux_btf = bpf_get_btf_vmlinux();
+	if (IS_ERR(vmlinux_btf))
+		return PTR_ERR(vmlinux_btf);
 	mutex_lock(&cand_cache_mutex);
 	cc = bpf_core_find_cands(&ctx, type_id);
 	if (IS_ERR(cc)) {
@@ -9262,6 +9340,10 @@ int btf_get_fd_by_id(u32 id)
 	struct btf *btf;
 	int fd;
 
+	/* kernel BTFs get their ids while parsed, before they are published */
+	if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		bpf_get_btf_vmlinux();
+
 	rcu_read_lock();
 	btf = idr_find(&btf_idr, id);
 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
@@ -9301,10 +9383,13 @@ enum {
 struct btf_module {
 	struct list_head list;
 	struct module *module;
-	struct btf *btf;
+	struct btf *btf;	/* NULL while kept, see btf_module_keep() */
+	void *data;		/* kept copy of .BTF, adopted by btf once parsed */
+	u32 data_size;
 	struct bin_attribute *sysfs_attr;
 	struct bin_attribute *sysfs_inline_attr;
 	void *btf_inline_data;
+	u32 btf_inline_data_size;
 	int flags;
 };
 
@@ -9312,6 +9397,150 @@ static LIST_HEAD(btf_modules);
 static DEFINE_MUTEX(btf_module_mutex);
 
 static void purge_cand_cache(struct btf *btf);
+static void btf_drop_deferred_regs(struct module *owner);
+
+/* /sys/kernel/btf/<module> and <module>.inline */
+static void btf_module_add_files(struct btf_module *btf_mod, const char *name,
+				 void *data, u32 data_size)
+{
+	char inline_name[MODULE_NAME_LEN + sizeof(".inline")];
+	struct bin_attribute *attr;
+
+	attr = sysfs_btf_add(name, data, data_size, false, NULL);
+	if (IS_ERR(attr))
+		return;
+	btf_mod->sysfs_attr = attr;
+
+	if (!btf_mod->btf_inline_data)
+		return;
+	snprintf(inline_name, sizeof(inline_name), "%s.inline", name);
+	attr = sysfs_btf_add(inline_name, btf_mod->btf_inline_data,
+			     btf_mod->btf_inline_data_size, false, NULL);
+	if (IS_ERR(attr)) {
+		kvfree(btf_mod->btf_inline_data);
+		btf_mod->btf_inline_data = NULL;
+		return;
+	}
+	btf_mod->sysfs_inline_attr = attr;
+}
+
+/*
+ * CONFIG_DEBUG_INFO_BTF_LAZY: module BTF is split BTF on top of the vmlinux
+ * BTF.  Until that is parsed, keep the module's copies of its BTF and inline
+ * BTF as they are, serve them in sysfs, and let btf_parse_kept_modules()
+ * parse them with the vmlinux BTF.  Distilled base BTF (.BTF.base) needs
+ * relocation, which needs the vmlinux BTF, so it is parsed right away.
+ *
+ * TODO: defer modules with distilled base BTF as well: keep them here and
+ * relocate them in btf_parse_kept_modules().  Their raw BTF is not usable
+ * before that, so their sysfs files would have to wait for the first use.
+ */
+static bool btf_module_keep(struct btf_module *btf_mod, struct module *mod,
+			    void *data, void *inline_data, u32 inline_data_size)
+{
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || mod->btf_base_data)
+		return false;
+	guard(mutex)(&btf_vmlinux_lock);
+	if (btf_vmlinux)
+		return false;
+	btf_mod->module = mod;
+	btf_mod->data = data;
+	btf_mod->data_size = mod->btf_data_size;
+	btf_mod->btf_inline_data = inline_data;
+	btf_mod->btf_inline_data_size = inline_data ? inline_data_size : 0;
+	/* before btf_parse_kept_modules() can see the entry */
+	btf_module_add_files(btf_mod, mod->name, data, mod->btf_data_size);
+	mutex_lock(&btf_module_mutex);
+	list_add(&btf_mod->list, &btf_modules);
+	mutex_unlock(&btf_module_mutex);
+	return true;
+}
+
+/* A kept module without BTF: no entry and no files, as if refused at load */
+static void btf_module_drop_kept(struct btf_module *btf_mod)
+{
+	list_del(&btf_mod->list);
+	if (btf_mod->sysfs_attr)
+		sysfs_btf_remove(btf_mod->sysfs_attr);
+	if (btf_mod->sysfs_inline_attr)
+		sysfs_btf_remove(btf_mod->sysfs_inline_attr);
+	kvfree(btf_mod->btf_inline_data);
+	kvfree(btf_mod->data);
+	kfree(btf_mod);
+}
+
+/* Undo btf_parse_kept_modules() of a round that is not published */
+static void btf_unparse_kept_modules(void)
+{
+	struct btf_module *btf_mod;
+
+	lockdep_assert_held(&btf_module_mutex);
+	list_for_each_entry(btf_mod, &btf_modules, list) {
+		if (!btf_mod->data || !btf_mod->btf)
+			continue;
+		btf_mod->btf->data = NULL;	/* the kept copy */
+		btf_put(btf_mod->btf);
+		btf_mod->btf = NULL;
+	}
+}
+
+/*
+ * Called under btf_vmlinux_lock by the task that parses the vmlinux BTF,
+ * before that is published.  Parses the kept module BTFs in place, oldest
+ * first so that ids follow the load order as without
+ * CONFIG_DEBUG_INFO_BTF_LAZY; in-tree module BTF and its inline BTF need no
+ * relocation, so sysfs serves the same bytes before and after.  A module
+ * whose BTF fails validation cannot be refused any more: it stays loaded
+ * without BTF, and its files go away; an invalid inline BTF loses its file.
+ * Returns -ENOMEM, with this round's module BTFs freed again, if memory ran
+ * out.
+ */
+static int btf_parse_kept_modules(void)
+{
+	struct btf_module *btf_mod, *tmp;
+	void *inline_data;
+	struct btf *btf;
+	int err;
+
+	lockdep_assert_held(&btf_vmlinux_lock);
+	guard(mutex)(&btf_module_mutex);
+	list_for_each_entry_safe_reverse(btf_mod, tmp, &btf_modules, list) {
+		if (btf_mod->btf || !btf_mod->data)
+			continue;
+		btf = btf_parse_module(btf_mod->module->name, btf_mod->data,
+				       btf_mod->data_size, NULL, 0,
+				       btf_mod->btf_inline_data,
+				       btf_mod->btf_inline_data_size, &inline_data);
+		if (!IS_ERR(btf)) {
+			err = btf_alloc_id(btf);
+			if (err) {
+				btf->data = NULL;	/* the kept copy */
+				btf_free(btf);
+				btf = ERR_PTR(err);
+			}
+		}
+		if (btf == ERR_PTR(-ENOMEM)) {
+			btf_unparse_kept_modules();
+			return -ENOMEM;
+		}
+		if (IS_ERR(btf)) {
+			pr_warn("failed to validate module [%s] BTF: %ld\n",
+				btf_mod->module->name, PTR_ERR(btf));
+			btf_module_drop_kept(btf_mod);
+			continue;
+		}
+		btf_mod->btf = btf;
+		if (btf_mod->btf_inline_data && !inline_data) {
+			if (btf_mod->sysfs_inline_attr)
+				sysfs_btf_remove(btf_mod->sysfs_inline_attr);
+			btf_mod->sysfs_inline_attr = NULL;
+			kvfree(btf_mod->btf_inline_data);
+			btf_mod->btf_inline_data = NULL;
+			btf_mod->btf_inline_data_size = 0;
+		}
+	}
+	return 0;
+}
 
 #if IS_MODULE(CONFIG_DEBUG_INFO_BTF_INLINE)
 extern char __start_BTF_inline_link[];
@@ -9422,9 +9651,8 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
 {
 	struct btf_module *btf_mod, *tmp;
 	struct module *mod = module;
-	struct bin_attribute *attr;
 	struct btf *btf;
-	void *inline_data = NULL, *relocated_inline_data = NULL;
+	void *data, *inline_data = NULL, *relocated_inline_data = NULL;
 	unsigned int inline_data_size = 0;
 	int err = 0;
 
@@ -9452,11 +9680,26 @@ 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,
+		data = kvmemdup(mod->btf_data, mod->btf_data_size, GFP_KERNEL | __GFP_NOWARN);
+		if (inline_data) {
+			inline_data = kvmemdup(inline_data, inline_data_size,
+					       GFP_KERNEL | __GFP_NOWARN);
+			if (!inline_data)
+				pr_warn("failed to validate module [%s] inline BTF: %d\n",
+					mod->name, -ENOMEM);
+		}
+		if (data && btf_module_keep(btf_mod, mod, data, inline_data,
+					    inline_data_size))
+			break;
+		btf = !data ? ERR_PTR(-ENOMEM) :
+		      btf_parse_module(mod->name, data, mod->btf_data_size,
 				       mod->btf_base_data, mod->btf_base_data_size,
-				       inline_data, inline_data_size,
+				       inline_data, inline_data ? inline_data_size : 0,
 				       &relocated_inline_data);
+		if (inline_data != relocated_inline_data)
+			kvfree(inline_data);
 		if (IS_ERR(btf)) {
+			kvfree(data);
 			kfree(btf_mod);
 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
 				pr_warn("failed to validate module [%s] BTF: %ld\n",
@@ -9480,30 +9723,12 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
 		btf_mod->module = module;
 		btf_mod->btf = btf;
 		btf_mod->btf_inline_data = relocated_inline_data;
+		btf_mod->btf_inline_data_size = relocated_inline_data ? inline_data_size : 0;
 		list_add(&btf_mod->list, &btf_modules);
 		mutex_unlock(&btf_module_mutex);
 
-		attr = sysfs_btf_add(btf->name, btf->data, btf->data_size, false, NULL);
-		if (IS_ERR(attr)) {
-			err = 0;
-			goto out;
-		}
-		btf_mod->sysfs_attr = attr;
-
-		if (relocated_inline_data) {
-			char name[MODULE_NAME_LEN + sizeof(".inline")];
-
-			snprintf(name, sizeof(name), "%s.inline", mod->name);
-			attr = sysfs_btf_add(name, relocated_inline_data,
-					     inline_data_size, false, NULL);
-			if (IS_ERR(attr)) {
-				kvfree(relocated_inline_data);
-				btf_mod->btf_inline_data = NULL;
-				err = 0;
-				break;
-			}
-			btf_mod->sysfs_inline_attr = attr;
-		}
+		/* data: the same as btf->data */
+		btf_module_add_files(btf_mod, mod->name, data, mod->btf_data_size);
 		break;
 	case MODULE_STATE_LIVE:
 		if (!mod->btf_data_size)
@@ -9521,11 +9746,17 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op,
 	case MODULE_STATE_GOING:
 		if (!mod->btf_data_size)
 			break;
+		btf_drop_deferred_regs(module);
 		mutex_lock(&btf_module_mutex);
 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
 			if (btf_mod->module != module)
 				continue;
 
+			if (!btf_mod->btf) {	/* kept, see btf_module_keep() */
+				btf_module_drop_kept(btf_mod);
+				break;
+			}
+
 			/*
 			 * For modules, we do the freeing of BTF IDR as soon as
 			 * module goes away to disable BTF discovery, since the
@@ -9610,9 +9841,12 @@ struct btf *btf_get_module_btf(const struct module *module)
 	}
 
 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+	/* kept module BTF is parsed together with the vmlinux BTF */
+	if (!module->btf_data_size || IS_ERR_OR_NULL(bpf_get_btf_vmlinux()))
+		return NULL;
 	mutex_lock(&btf_module_mutex);
 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
-		if (btf_mod->module != module)
+		if (btf_mod->module != module || !btf_mod->btf)
 			continue;
 
 		btf_get(btf_mod->btf);
@@ -9803,7 +10037,7 @@ 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)
+		if (btf_mod->btf == btf || !btf_mod->btf)
 			continue;
 		id = btf_find_by_name_kind(btf_mod->btf, func_name, kind);
 		if (id >= 0) {
@@ -10129,12 +10363,88 @@ 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);
 }
 
+enum btf_deferred_kind { BTF_DEFER_KFUNCS, BTF_DEFER_DTORS, BTF_DEFER_ST_OPS };
+
+/* CONFIG_DEBUG_INFO_BTF_LAZY: a registration made before the vmlinux BTF is parsed */
+struct btf_deferred_reg {
+	struct list_head list;
+	struct module *owner;
+	enum btf_deferred_kind kind;
+	enum btf_kfunc_hook hook;
+	void *data;
+	u32 cnt;
+};
+
+/* protected by btf_vmlinux_lock */
+static LIST_HEAD(btf_deferred_regs);
+
+/*
+ * Does a registration by @owner need the vmlinux BTF?  Without module BTF a
+ * module's registrations do nothing but warn (check_btf_kconfigs()), and
+ * btf_module_notify(), which drops a going module's queued entries, does not
+ * see such a module.
+ */
+static bool btf_reg_needs_vmlinux(const struct module *owner)
+{
+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+	return !owner || owner->btf_data_size;
+#else
+	return !owner;
+#endif
+}
+
+/*
+ * Initcalls and modules loaded early register kfuncs, dtor kfuncs and
+ * struct_ops before anything needs the vmlinux BTF.  Queue these until it
+ * is parsed (btf_apply_deferred()).  Returns true if the registration was
+ * queued, with *err set to 0 or -ENOMEM.
+ */
+static bool btf_defer_reg(struct module *owner, enum btf_deferred_kind kind,
+			  enum btf_kfunc_hook hook, const void *data, u32 cnt, int *err)
+{
+	struct btf_deferred_reg *reg;
+
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) || bpf_peek_btf_vmlinux() ||
+	    btf_vmlinux_building() || !btf_reg_needs_vmlinux(owner))
+		return false;
+	guard(mutex)(&btf_vmlinux_lock);
+	if (btf_vmlinux)
+		return false;
+
+	*err = -ENOMEM;
+	reg = kzalloc_obj(*reg);
+	if (!reg)
+		return true;
+	/* callers may build kfunc sets and dtor arrays on the stack */
+	if (kind == BTF_DEFER_KFUNCS)
+		reg->data = kmemdup(data, sizeof(struct btf_kfunc_id_set), GFP_KERNEL);
+	else if (kind == BTF_DEFER_DTORS)
+		reg->data = kmemdup_array(data, cnt, sizeof(struct btf_id_dtor_kfunc),
+					  GFP_KERNEL);
+	else
+		reg->data = (void *)data;
+	if (!reg->data) {
+		kfree(reg);
+		return true;
+	}
+	reg->owner = owner;
+	reg->kind = kind;
+	reg->hook = hook;
+	reg->cnt = cnt;
+	list_add_tail(&reg->list, &btf_deferred_regs);
+	*err = 0;
+	return true;
+}
+
 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
 				       const struct btf_kfunc_id_set *kset)
 {
 	struct btf *btf;
 	int ret, i;
 
+	if (btf_defer_reg(kset->owner, BTF_DEFER_KFUNCS, hook, kset, 0, &ret))
+		return ret;
+
 	btf = btf_get_module_btf(kset->owner);
 	if (!btf)
 		return check_btf_kconfigs(kset->owner, "kfunc");
@@ -10251,6 +10561,9 @@ int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_c
 	u32 tab_cnt, i;
 	int ret;
 
+	if (btf_defer_reg(owner, BTF_DEFER_DTORS, 0, dtors, add_cnt, &ret))
+		return ret;
+
 	btf = btf_get_module_btf(owner);
 	if (!btf)
 		return check_btf_kconfigs(owner, "dtor kfuncs");
@@ -10579,7 +10892,8 @@ bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
 	const char *name;
 	int id;
 
-	main_btf = bpf_get_btf_vmlinux();
+	/* callers parse it before taking cand_cache_mutex, see bpf_core_apply() */
+	main_btf = bpf_peek_btf_vmlinux();
 	if (IS_ERR(main_btf))
 		return ERR_CAST(main_btf);
 	if (!main_btf)
@@ -10682,8 +10996,18 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
 
 	if (need_cands) {
 		struct bpf_cand_cache *cc;
+		struct btf *main_btf;
 		int i;
 
+		/*
+		 * Parsing the vmlinux BTF takes btf_module_mutex, which is
+		 * taken before cand_cache_mutex when a module goes away.
+		 */
+		main_btf = bpf_get_btf_vmlinux();
+		if (IS_ERR(main_btf)) {
+			kfree(specs);
+			return PTR_ERR(main_btf);
+		}
 		mutex_lock(&cand_cache_mutex);
 		cc = bpf_core_find_cands(ctx, relo->type_id);
 		if (IS_ERR(cc)) {
@@ -10957,6 +11281,9 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
 	struct btf *btf;
 	int err = 0;
 
+	if (btf_defer_reg(st_ops->owner, BTF_DEFER_ST_OPS, 0, st_ops, 0, &err))
+		return err;
+
 	btf = btf_get_module_btf(st_ops->owner);
 	if (!btf)
 		return check_btf_kconfigs(st_ops->owner, "struct_ops");
@@ -10982,6 +11309,103 @@ int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
 #endif
 
+static void btf_free_deferred_reg(struct btf_deferred_reg *reg)
+{
+	list_del(&reg->list);
+	if (reg->kind != BTF_DEFER_ST_OPS)
+		kfree(reg->data);
+	kfree(reg);
+}
+
+/*
+ * Called under btf_vmlinux_lock, by the task that parsed the vmlinux BTF and
+ * before it publishes it, so that nothing sees the BTF without its module
+ * BTFs, kfuncs and struct_ops.  bpf_get_btf_vmlinux() returns the new BTF to
+ * this task, so the registrations are applied as if they were made now, and
+ * any they make in turn (a struct_ops ->init() may register kfuncs) too.
+ * They run in whichever task needs the BTF first, with the locks it holds:
+ * they must not load modules or take locks that users of the BTF hold.
+ *
+ * Returns -ENOMEM if memory ran out, which may be only because that task is
+ * being killed: the caller then drops the new BTF with whatever was applied
+ * to it, and the next caller starts over with the queue intact, as for the
+ * vmlinux BTF itself; a struct_ops ->init() then runs again with the BTF of
+ * that round.  Any other error of a registration is only logged.
+ */
+static int btf_apply_deferred(void)
+{
+	struct btf_deferred_reg *reg, *tmp;
+	int err;
+
+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+	err = btf_parse_kept_modules();
+	if (err)
+		return err;
+#endif
+	list_for_each_entry(reg, &btf_deferred_regs, list) {
+		/* a going module's exit() runs before GOING drops its entries */
+		if (!try_module_get(reg->owner))
+			continue;
+		err = 0;
+		switch (reg->kind) {
+		case BTF_DEFER_KFUNCS:
+			err = __register_btf_kfunc_id_set(reg->hook, reg->data);
+			break;
+		case BTF_DEFER_DTORS:
+			err = register_btf_id_dtor_kfuncs(reg->data, reg->cnt, reg->owner);
+			break;
+		case BTF_DEFER_ST_OPS:
+#if defined(CONFIG_BPF_JIT)
+			err = __register_bpf_struct_ops(reg->data);
+#endif
+			break;
+		}
+		module_put(reg->owner);
+		if (err == -ENOMEM) {
+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+			guard(mutex)(&btf_module_mutex);
+			btf_unparse_kept_modules();
+#endif
+			return err;
+		}
+		if (err)
+			pr_warn("failed to apply deferred BTF registration for %s: %d\n",
+				reg->owner ? reg->owner->name : "vmlinux", err);
+	}
+	list_for_each_entry_safe(reg, tmp, &btf_deferred_regs, list)
+		btf_free_deferred_reg(reg);
+	return 0;
+}
+
+/* The vmlinux BTF failed for good: nothing will apply what is queued */
+static void btf_drop_all_deferred(int err)
+{
+	struct btf_deferred_reg *reg, *tmp;
+	int cnt = 0;
+
+	list_for_each_entry_safe(reg, tmp, &btf_deferred_regs, list) {
+		btf_free_deferred_reg(reg);
+		cnt++;
+	}
+	if (cnt)
+		pr_warn("vmlinux BTF unavailable (%d), dropped %d deferred BTF registrations\n",
+			err, cnt);
+}
+
+/* @owner is going away: drop the registrations it queued */
+static void __maybe_unused btf_drop_deferred_regs(struct module *owner)
+{
+	struct btf_deferred_reg *reg, *tmp;
+
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		return;
+	guard(mutex)(&btf_vmlinux_lock);
+	list_for_each_entry_safe(reg, tmp, &btf_deferred_regs, list) {
+		if (reg->owner == owner)
+			btf_free_deferred_reg(reg);
+	}
+}
+
 bool btf_param_match_suffix(const struct btf *btf,
 			    const struct btf_param *arg,
 			    const char *suffix)
diff --git a/kernel/bpf/inode.c b/kernel/bpf/inode.c
index c6f328e4752e1d..39750d4ad401a7 100644
--- a/kernel/bpf/inode.c
+++ b/kernel/bpf/inode.c
@@ -1059,6 +1059,13 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param)
 		char *p, *str;
 		int val;
 
+		/*
+		 * Setting delegation mount options requires privileges.  Check
+		 * before the lookup, which may have to parse the vmlinux BTF.
+		 */
+		if (!capable(CAP_SYS_ADMIN))
+			return -EPERM;
+
 		/* ignore errors, fallback to hex */
 		(void)find_bpffs_btf_enums(&info);
 
@@ -1100,10 +1107,6 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param)
 			}
 		}
 
-		/* Setting delegation mount options requires privileges */
-		if (msk && !capable(CAP_SYS_ADMIN))
-			return -EPERM;
-
 		*delegate_msk |= msk;
 		break;
 	}
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 02ed5368f05626..fefbb641692b21 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -3048,8 +3048,12 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
 				goto put_token;
 			}
 		}
-	} else if (attr->attach_btf_id || multi_func) {
-		/* fall back to vmlinux BTF, if BTF type ID is specified */
+	} else if ((attr->attach_btf_id || multi_func) && bpf_cap) {
+		/*
+		 * fall back to vmlinux BTF, if BTF type ID is specified; only
+		 * program types that need CAP_BPF take one, and
+		 * bpf_prog_load_check_attach() refuses it for the others
+		 */
 		attach_btf = bpf_get_btf_vmlinux();
 		if (IS_ERR(attach_btf)) {
 			err = PTR_ERR(attach_btf);
@@ -6511,6 +6515,10 @@ 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:
+		/* kernel BTFs have ids once parsed (CONFIG_DEBUG_INFO_BTF_LAZY) */
+		if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY) &&
+		    ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN))
+			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 556fe92c36495d..015cd82211541b 100644
--- a/kernel/bpf/sysfs_btf.c
+++ b/kernel/bpf/sysfs_btf.c
@@ -12,11 +12,126 @@
 #include <linux/vmalloc.h>
 #include <linux/io.h>
 #include <linux/btf.h>
+#include <linux/zstd.h>
 
+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY
+/* See scripts/gen-btf.sh, gen_btf_o() for details */
+extern char __start_BTF_zst[];
+extern char __stop_BTF_zst[];
+
+static DEFINE_MUTEX(btf_vmlinux_data_lock);
+static void *btf_vmlinux_raw;
+static u32 btf_vmlinux_raw_size;
+static bool btf_vmlinux_broken;
+/* Compressed BTF: init data until btf_vmlinux_keep_zst(), freed once decompressed */
+static void *btf_zst = __start_BTF_zst;
+
+static u32 btf_vmlinux_size(void)
+{
+	zstd_frame_header hdr;
+
+	guard(mutex)(&btf_vmlinux_data_lock);
+	if (!btf_vmlinux_raw_size && btf_zst &&
+	    !zstd_get_frame_header(&hdr, btf_zst, __stop_BTF_zst - __start_BTF_zst) &&
+	    hdr.frameContentSize < U32_MAX)
+		btf_vmlinux_raw_size = hdr.frameContentSize;
+	return btf_vmlinux_raw_size;
+}
+
+static void btf_vmlinux_drop_zst(void)
+{
+	if (btf_zst != __start_BTF_zst)
+		vfree(btf_zst);
+	btf_zst = NULL;
+}
+
+/*
+ * The raw vmlinux BTF, decompressed on first use and never freed, or
+ * ERR_PTR(-ENOMEM) if that cannot be done (now: memory; for good: no copy of
+ * the compressed BTF), or ERR_PTR(-EINVAL) if it is broken.
+ */
+void *btf_vmlinux_data(u32 *size)
+{
+	size_t ret, ws_size = zstd_dctx_workspace_bound();
+	void *raw, *ws;
+
+	/* Pairs with smp_store_release() below */
+	raw = smp_load_acquire(&btf_vmlinux_raw);
+	if (raw) {
+		*size = btf_vmlinux_raw_size;
+		return raw;
+	}
+
+	*size = btf_vmlinux_size();
+	guard(mutex)(&btf_vmlinux_data_lock);
+	if (btf_vmlinux_raw)
+		return btf_vmlinux_raw;
+	if (!btf_zst)
+		return ERR_PTR(btf_vmlinux_broken ? -EINVAL : -ENOMEM);
+	if (!*size) {
+		pr_err("BTF: no size in the compressed vmlinux BTF\n");
+		btf_vmlinux_broken = true;
+		btf_vmlinux_drop_zst();
+		return ERR_PTR(-EINVAL);
+	}
+	/* vmalloc_user(): btf_sysfs_vmlinux_mmap() maps it to user space */
+	raw = vmalloc_user(*size);
+	ws = kvmalloc(ws_size, GFP_KERNEL);
+	if (raw && ws) {
+		ret = zstd_decompress_dctx(zstd_init_dctx(ws, ws_size), raw, *size,
+					   btf_zst, __stop_BTF_zst - __start_BTF_zst);
+		if (!zstd_is_error(ret) && ret == *size) {
+			/* Pairs with smp_load_acquire() above */
+			smp_store_release(&btf_vmlinux_raw, raw);
+		} else {
+			pr_err("BTF: cannot decompress the vmlinux BTF: %s\n",
+			       zstd_is_error(ret) ? zstd_get_error_name(ret) : "size mismatch");
+			btf_vmlinux_broken = true;
+		}
+		btf_vmlinux_drop_zst();
+	}
+	kvfree(ws);
+	if (btf_vmlinux_raw)
+		return btf_vmlinux_raw;
+	vfree(raw);
+	return ERR_PTR(btf_vmlinux_broken ? -EINVAL : -ENOMEM);
+}
+
+/* Keep a copy of the compressed BTF before init memory is freed */
+static int __init btf_vmlinux_keep_zst(void)
+{
+	size_t size = __stop_BTF_zst - __start_BTF_zst;
+
+	guard(mutex)(&btf_vmlinux_data_lock);
+	if (btf_zst) {
+		/* vmalloc(): kmalloc() would round up to a power of 2 */
+		btf_zst = vmalloc(size);
+		if (btf_zst)
+			memcpy(btf_zst, __start_BTF_zst, size);
+		else
+			pr_err("BTF: out of memory, vmlinux BTF unavailable\n");
+	}
+	return 0;
+}
+late_initcall_sync(btf_vmlinux_keep_zst);
+#else
 /* See scripts/link-vmlinux.sh, gen_btf() func for details */
 extern char __start_BTF[];
 extern char __stop_BTF[];
 
+static u32 btf_vmlinux_size(void)
+{
+	return __stop_BTF - __start_BTF;
+}
+
+void *btf_vmlinux_data(u32 *size)
+{
+	*size = btf_vmlinux_size();
+	return __start_BTF;
+}
+#endif
+
+#ifdef CONFIG_SYSFS
 static int btf_sysfs_mmap_check(void *data, size_t size, struct vm_area_struct *vma)
 {
 	unsigned long pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
@@ -61,10 +176,49 @@ static int btf_sysfs_mmap_image(struct file *filp, struct kobject *kobj,
 	return remap_pfn_range(vma, vma->vm_start, pfn, vm_size, vma->vm_page_prot);
 }
 
+#ifdef CONFIG_DEBUG_INFO_BTF_LAZY
+/* Reading or mapping the file decompresses the BTF but does not parse it */
+static int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,
+				  const struct bin_attribute *attr,
+				  struct vm_area_struct *vma)
+{
+	void *data;
+	u32 size;
+	int err;
+
+	data = btf_vmlinux_data(&size);
+	if (IS_ERR(data))
+		return PTR_ERR(data);
+
+	err = btf_sysfs_mmap_check(data, attr->size, vma);
+	if (err)
+		return err;
+
+	return remap_vmalloc_range(vma, data, 0);
+}
+
+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)
+{
+	void *data;
+	u32 size;
+
+	data = btf_vmlinux_data(&size);
+	if (IS_ERR(data))
+		return PTR_ERR(data);
+
+	return memory_read_from_buffer(buf, count, &off, data, size);
+}
+#else
+#define btf_sysfs_vmlinux_read	sysfs_bin_attr_simple_read
+#define btf_sysfs_vmlinux_mmap	btf_sysfs_mmap_image
+#endif
+
 static struct bin_attribute bin_attr_btf_vmlinux __ro_after_init = {
 	.attr = { .name = "vmlinux", .mode = 0444, },
-	.read = sysfs_bin_attr_simple_read,
-	.mmap = btf_sysfs_mmap_image,
+	.read = btf_sysfs_vmlinux_read,
+	.mmap = btf_sysfs_vmlinux_mmap,
 };
 
 struct kobject *btf_kobj;
@@ -180,8 +334,12 @@ void sysfs_btf_remove(struct bin_attribute *attr)
 
 static int __init btf_vmlinux_init(void)
 {
-	bin_attr_btf_vmlinux.private = __start_BTF;
-	bin_attr_btf_vmlinux.size = __stop_BTF - __start_BTF;
+	u32 size;
+
+	/* with CONFIG_DEBUG_INFO_BTF_LAZY the read and mmap handlers get it */
+	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF_LAZY))
+		bin_attr_btf_vmlinux.private = btf_vmlinux_data(&size);
+	bin_attr_btf_vmlinux.size = btf_vmlinux_size();
 
 	if (bin_attr_btf_vmlinux.size == 0)
 		return 0;
@@ -194,3 +352,4 @@ static int __init btf_vmlinux_init(void)
 }
 
 subsys_initcall(btf_vmlinux_init);
+#endif /* CONFIG_SYSFS */
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 1b6c0674ff6a13..8606b97765e7eb 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -320,7 +320,6 @@ static const char *btf_type_name(const struct btf *btf, u32 id)
 }
 
 static DEFINE_MUTEX(bpf_verifier_lock);
-static DEFINE_MUTEX(btf_vmlinux_lock);
 static DEFINE_MUTEX(bpf_percpu_ma_lock);
 
 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
@@ -3069,6 +3068,18 @@ static int fetch_kfunc_meta(struct bpf_verifier_env *env,
 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
 			       const struct btf_func_model *fm, struct bpf_func_proto *proto);
 
+/*
+ * The vmlinux BTF failed to parse where a program first needs it: pass the
+ * error on, as bpf_check() did when it fetched the BTF up front.  It need
+ * not be for good: a parse on first use that runs out of memory is retried
+ * by the next caller.
+ */
+static int vmlinux_btf_err(struct bpf_verifier_env *env, const struct btf *btf)
+{
+	verbose(env, "in-kernel BTF could not be parsed: %ld\n", PTR_ERR(btf));
+	return PTR_ERR(btf);
+}
+
 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 {
 	struct bpf_call_arg_meta meta;
@@ -3085,7 +3096,11 @@ 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) {
+		struct btf *btf = bpf_get_btf_vmlinux();
+
+		if (IS_ERR(btf))
+			return vmlinux_btf_err(env, btf);
+		if (!btf) {
 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
 			return -ENOTSUPP;
 		}
@@ -6867,30 +6882,33 @@ static int check_ptr_to_map_access(struct bpf_verifier_env *env,
 	enum bpf_type_flag flag = 0;
 	const struct btf_type *t;
 	const char *tname;
+	struct btf *btf;
 	u32 btf_id;
 	int ret;
 
-	if (!btf_vmlinux) {
-		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
-		return -ENOTSUPP;
-	}
-
 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
 		verbose(env, "map_ptr access not supported for map type %d\n",
 			map->map_type);
 		return -ENOTSUPP;
 	}
 
-	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
-	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
-
+	/* before the BTF fetch: unprivileged loads must not parse it */
 	if (!env->allow_ptr_leaks) {
-		verbose(env,
-			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
-			tname);
+		verbose(env, "map_ptr access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n");
 		return -EPERM;
 	}
 
+	btf = bpf_get_btf_vmlinux();
+	if (IS_ERR(btf))
+		return vmlinux_btf_err(env, btf);
+	if (!btf) {
+		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
+		return -ENOTSUPP;
+	}
+
+	t = btf_type_by_id(btf, *map->ops->map_btf_id);
+	tname = btf_name_by_offset(btf, t->name_off);
+
 	if (off < 0) {
 		verbose(env, "%s is %s invalid negative access: off=%d\n",
 			reg_arg_name(env, argno), tname, off);
@@ -12616,6 +12634,22 @@ static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
 	return err;
 }
 
+/* Does helper @fn 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 a kernel type id in struct btf_ptr */
+	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 < ARRAY_SIZE(fn->arg_type); 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)
 {
@@ -12685,6 +12719,14 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		return err;
 	}
 
+	if (IS_ENABLED(CONFIG_DEBUG_INFO_BTF) && helper_uses_vmlinux_btf(func_id, fn)) {
+		/* never NULL with CONFIG_DEBUG_INFO_BTF */
+		struct btf *btf = bpf_get_btf_vmlinux();
+
+		if (IS_ERR(btf))
+			return vmlinux_btf_err(env, btf);
+	}
+
 	if (fn->might_sleep && !in_sleepable_context(env)) {
 		const char *suggestion;
 
@@ -13910,7 +13952,7 @@ BTF_SET_END(dynptr_write_kfuncs)
 
 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta)
 {
-	return meta->btf == btf_vmlinux &&
+	return is_kfunc(meta) && meta->btf == btf_vmlinux &&
 	       btf_id_set_contains(&dynptr_write_kfuncs, meta->func_id);
 }
 
@@ -20960,12 +21002,14 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env,
 			return -EINVAL;
 		}
 	} else {
-		if (!btf_vmlinux) {
+		btf = bpf_get_btf_vmlinux();
+		if (IS_ERR(btf))
+			return vmlinux_btf_err(env, btf);
+		if (!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);
@@ -23182,29 +23226,6 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt
 	return 0;
 }
 
-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);
-
-	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);
-		}
-		mutex_unlock(&btf_vmlinux_lock);
-	}
-	return btf;
-}
-
 /*
  * 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
@@ -23928,7 +23949,12 @@ 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 here but where kernel types enter
+	 * the program (attach_btf, kfuncs, ksyms, map_ptr, BTF-typed helpers,
+	 * CO-RE, kernel ctx types), so that programs which use none of them
+	 * do not need it (CONFIG_DEBUG_INFO_BTF_LAZY).
+	 */
 
 	/* Serialize verification of unprivileged programs. */
 	if (!is_priv)
@@ -23949,13 +23975,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 
 	mark_verifier_state_clean(env);
 
-	if (IS_ERR(btf_vmlinux)) {
-		/* Either gcc or pahole or kernel are broken. */
-		verbose(env, "in-kernel BTF is malformed\n");
-		ret = PTR_ERR(btf_vmlinux);
-		goto skip_full_check;
-	}
-
 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
 		env->strict_alignment = true;
diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c
index 14adfb85fdb2be..92694d40c0c3e9 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();
+	/* fetched by the verifier, see helper_uses_vmlinux_btf() */
+	*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_btf.c b/kernel/trace/trace_btf.c
index f0e0c04d58d99f..693c1a1083c55e 100644
--- a/kernel/trace/trace_btf.c
+++ b/kernel/trace/trace_btf.c
@@ -1,4 +1,5 @@
 // SPDX-License-Identifier: GPL-2.0
+#include <linux/bpf.h>
 #include <linux/btf.h>
 #include <linux/kernel.h>
 #include <linux/slab.h>
@@ -141,6 +142,34 @@ const struct btf_member *btf_find_struct_member(struct btf *btf,
 	return member;
 }
 
+static bool trace_btf_deferred;
+
+/*
+ * func-args, funcgraph-args and funcgraph-retval print arguments and return
+ * values by their BTF types, and the readers of the trace use the vmlinux
+ * BTF only if it is parsed already: parse it when such output is enabled.
+ * With CONFIG_DEBUG_INFO_BTF_LAZY that may be its first use, which should
+ * not happen in a reader that holds the trace read locks while the tracer
+ * records its work.
+ */
+void trace_btf_prepare(void)
+{
+	/* trace_options= on the command line is applied by early_trace_init() */
+	if (system_state < SYSTEM_SCHEDULING) {
+		trace_btf_deferred = true;
+		return;
+	}
+	bpf_get_btf_vmlinux();
+}
+
+static int __init trace_btf_init(void)
+{
+	if (trace_btf_deferred)
+		bpf_get_btf_vmlinux();
+	return 0;
+}
+core_initcall(trace_btf_init);
+
 void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retval,
 			int *fmt, bool hex)
 {
@@ -151,6 +180,9 @@ void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retv
 	bool signed_type;
 	int kind;
 
+	/* see trace_btf_prepare() */
+	if (IS_ERR_OR_NULL(bpf_peek_btf_vmlinux()))
+		return;
 	if (lookup_symbol_name(func, name))
 		return;
 
diff --git a/kernel/trace/trace_btf.h b/kernel/trace/trace_btf.h
index b3d408e6a7f6c4..47407eff1339b9 100644
--- a/kernel/trace/trace_btf.h
+++ b/kernel/trace/trace_btf.h
@@ -23,9 +23,12 @@ const struct btf_member *btf_find_struct_member(struct btf *btf,
 #ifdef CONFIG_DEBUG_INFO_BTF
 void btf_trim_retval(unsigned long func, unsigned long *retval, bool *print_retval,
 		     int *fmt, bool hex);
+void trace_btf_prepare(void);
 #else
 static inline void btf_trim_retval(unsigned long func, unsigned long *retval,
 				   bool *print_retval, int *fmt, bool hex)
 {
 }
+
+static inline void trace_btf_prepare(void) { }
 #endif
diff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c
index 49d135bc2fbfcc..adc422fbe16eab 100644
--- a/kernel/trace/trace_events.c
+++ b/kernel/trace/trace_events.c
@@ -23,6 +23,7 @@
 #include <linux/sort.h>
 #include <linux/slab.h>
 #include <linux/delay.h>
+#include <linux/bpf.h>
 #include <linux/btf.h>
 
 #include <kunit/visibility.h>
@@ -2282,6 +2283,9 @@ event_btf_ids_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppo
 	char buf[128];
 	int len;
 
+	/* parse the vmlinux BTF, if this is its first use, without event_mutex */
+	bpf_get_btf_vmlinux();
+
 	/* Module unload could free call->class and ids[] mid-read. */
 	scoped_guard(mutex, &event_mutex) {
 		file = event_file_file(filp);
diff --git a/kernel/trace/trace_functions.c b/kernel/trace/trace_functions.c
index acaba990aaaa26..2cebaacda526f8 100644
--- a/kernel/trace/trace_functions.c
+++ b/kernel/trace/trace_functions.c
@@ -18,6 +18,7 @@
 #include <linux/fs.h>
 
 #include "trace.h"
+#include "trace_btf.h"
 
 static void tracing_start_function_trace(struct trace_array *tr);
 static void tracing_stop_function_trace(struct trace_array *tr);
@@ -115,6 +116,9 @@ void ftrace_destroy_function_files(struct trace_array *tr)
 
 static ftrace_func_t select_trace_function(u32 flags_val)
 {
+	if (flags_val & TRACE_FUNC_OPT_ARGS)
+		trace_btf_prepare();
+
 	switch (flags_val & TRACE_FUNC_OPT_MASK) {
 	case TRACE_FUNC_NO_OPTS:
 		return function_trace_call;
diff --git a/kernel/trace/trace_functions_graph.c b/kernel/trace/trace_functions_graph.c
index 78a608315dd32b..cf5f433dd26e36 100644
--- a/kernel/trace/trace_functions_graph.c
+++ b/kernel/trace/trace_functions_graph.c
@@ -474,6 +474,10 @@ static int graph_trace_init(struct trace_array *tr)
 {
 	int ret;
 
+	if (tracer_flags_is_set(tr, TRACE_GRAPH_ARGS) ||
+	    tracer_flags_is_set(tr, TRACE_GRAPH_PRINT_RETVAL))
+		trace_btf_prepare();
+
 	if (tracer_flags_is_set(tr, TRACE_GRAPH_ARGS))
 		tr->gops->entryfunc = trace_graph_entry_args;
 	else
@@ -507,10 +511,12 @@ static int ftrace_graph_trace_args(struct trace_array *tr, int set)
 {
 	trace_func_graph_ent_t entry;
 
-	if (set)
+	if (set) {
+		trace_btf_prepare();
 		entry = trace_graph_entry_args;
-	else
+	} else {
 		entry = trace_graph_entry;
+	}
 
 	/* See if there's any changes */
 	if (tr->gops->entryfunc == entry)
@@ -1746,6 +1752,11 @@ func_graph_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set)
 
 	case TRACE_GRAPH_ARGS:
 		return ftrace_graph_trace_args(tr, set);
+
+	case TRACE_GRAPH_PRINT_RETVAL:
+		if (set)
+			trace_btf_prepare();
+		break;
 	}
 
 	return 0;
diff --git a/kernel/trace/trace_output.c b/kernel/trace/trace_output.c
index a5ad76175d10d4..cdb926c9d4e21d 100644
--- a/kernel/trace/trace_output.c
+++ b/kernel/trace/trace_output.c
@@ -739,6 +739,9 @@ void print_function_args(struct trace_seq *s, unsigned long *args,
 	if (lookup_symbol_name(func, name))
 		goto out;
 
+	/* see trace_btf_prepare() */
+	if (IS_ERR_OR_NULL(bpf_peek_btf_vmlinux()))
+		goto out;
 	/* TODO: Pass module name here too */
 	t = btf_find_func_proto(name, &btf);
 	if (IS_ERR_OR_NULL(t))
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 2d22638ec13a63..45b2bc4d9a9c75 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -408,6 +408,30 @@ 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.
 
+config DEBUG_INFO_BTF_LAZY
+	bool "Compress vmlinux BTF and parse it on first use"
+	depends on DEBUG_INFO_BTF
+	depends on X86 || ARM64
+	select ZSTD_DECOMPRESS
+	help
+	  Keep the vmlinux BTF zstd-compressed in the kernel image, at about
+	  a quarter of its size, and decompress and parse it the first time
+	  something needs it instead of at boot.  Systems that never use BTF
+	  then keep only the compressed copy in memory, which saves about 80%
+	  of what the BTF costs; the first user pays a few tens of
+	  milliseconds once.  The vmlinux file keeps the uncompressed BTF as
+	  a non-loaded section for tools.  Building needs the zstd tool.
+
+	  Users of kernel types at boot still parse it at boot: BPF LSM
+	  programs, the iterators of BPF_PRELOAD (loaded at boot, or at the
+	  first bpffs mount if bpf_preload is a module), and modules with
+	  distilled base BTF.  Kernel function and struct_ops registrations
+	  made before the first use are applied then and report errors only
+	  in the kernel log; a module BTF that fails validation then leaves
+	  the module loaded without BTF.
+
+	  If unsure, say N.
+
 config PAHOLE_HAS_BTF_TAG
 	def_bool PAHOLE_VERSION >= 123
 	depends on CC_IS_CLANG
diff --git a/scripts/gen-btf.sh b/scripts/gen-btf.sh
index b17f1189298a55..c490b06306127e 100755
--- a/scripts/gen-btf.sh
+++ b/scripts/gen-btf.sh
@@ -86,13 +86,24 @@ gen_btf_o()
 	btf_data=${ELF_FILE}.btf.o
 
 	# Create ${btf_data} which contains just BTF sections but no symbols. Add
-	# SHF_ALLOC because .BTF will be part of the vmlinux image. --strip-all
-	# deletes all symbols including __start_BTF and __stop_BTF, which will
-	# be redefined in the linker script.
+	# SHF_ALLOC to the sections that will be part of the vmlinux image.
+	# --strip-all 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}
-	ONLY_SEC="--only-section=.BTF"
+	if is_enabled CONFIG_DEBUG_INFO_BTF_LAZY; then
+		# The image gets compressed BTF as init data, .BTF stays in
+		# the ELF file for tools.
+		${ZSTD} -q -f -19 ${ELF_FILE}.BTF -o ${ELF_FILE}.BTF.zst
+		${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \
+			--set-section-flags .BTF=readonly \
+			--add-section .init.BTF.zst=${ELF_FILE}.BTF.zst \
+			--set-section-flags .init.BTF.zst=alloc,readonly ${btf_data}
+		ONLY_SEC="--only-section=.BTF --only-section=.init.BTF.zst"
+	else
+		${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \
+			--set-section-flags .BTF=alloc,readonly ${btf_data}
+		ONLY_SEC="--only-section=.BTF"
+	fi
 	btf_inline=${ELF_FILE}.BTF.inline
 	if [ "${BTF_INLINE}" = "m" ]; then
 		if [ -f "${btf_inline}" ]; then
@@ -145,7 +156,7 @@ embed_btf_data()
 cleanup()
 {
 	rm -f "${ELF_FILE}.BTF.1"
-	rm -f "${ELF_FILE}.BTF"
+	rm -f "${ELF_FILE}.BTF" "${ELF_FILE}.BTF.zst"
 	rm -f "${ELF_FILE}.BTF.inline"
 	rm -f "${ELF_FILE}.BTF.inline.link"
 	if [ "${BTFGEN_MODE}" = "module" ]; then
diff --git a/tools/testing/selftests/bpf/prog_tests/ksyms.c b/tools/testing/selftests/bpf/prog_tests/ksyms.c
index dc7aab532fb147..fa97cc0ee3bf0d 100644
--- a/tools/testing/selftests/bpf/prog_tests/ksyms.c
+++ b/tools/testing/selftests/bpf/prog_tests/ksyms.c
@@ -10,7 +10,7 @@ void test_ksyms(void)
 	const char *btf_path = "/sys/kernel/btf/vmlinux";
 	struct test_ksyms *skel;
 	struct test_ksyms__data *data;
-	__u64 link_fops_addr, per_cpu_start_addr;
+	__u64 link_fops_addr, per_cpu_start_addr, btf_start_addr;
 	struct stat st;
 	__u64 btf_size;
 	int err;
@@ -30,6 +30,12 @@ void test_ksyms(void)
 	if (!ASSERT_OK(stat(btf_path, &st), "stat_btf"))
 		return;
 	btf_size = st.st_size;
+	/*
+	 * With CONFIG_DEBUG_INFO_BTF_LAZY the image has the vmlinux BTF only
+	 * compressed and no __start_BTF/__stop_BTF: the weak ksyms are 0.
+	 */
+	if (kallsyms_find("__start_BTF", &btf_start_addr) == -ENOENT)
+		btf_size = 0;
 
 	skel = test_ksyms__open_and_load();
 	if (!ASSERT_OK_PTR(skel, "test_ksyms__open_and_load"))
diff --git a/tools/testing/selftests/bpf/progs/linked_vars2.c b/tools/testing/selftests/bpf/progs/linked_vars2.c
index e4f5bd388a3c7a..bbdc3b25b4836e 100644
--- a/tools/testing/selftests/bpf/progs/linked_vars2.c
+++ b/tools/testing/selftests/bpf/progs/linked_vars2.c
@@ -8,7 +8,7 @@
 extern int LINUX_KERNEL_VERSION __kconfig;
 /* when an extern is defined as both strong and weak, resulting symbol will be strong */
 extern bool CONFIG_BPF_SYSCALL __kconfig;
-extern const void __start_BTF __ksym;
+extern const void bpf_map_fops __ksym;
 
 int input_bss2;
 int input_data2 = 2;
@@ -47,7 +47,7 @@ int BPF_PROG(handler2)
 	 */
 	output_sink2 = LINUX_KERNEL_VERSION
 		       + CONFIG_BPF_SYSCALL
-		       + (long)&__start_BTF;
+		       + (long)&bpf_map_fops;
 
 	return 0;
 }
diff --git a/tools/testing/selftests/bpf/progs/test_ksyms.c b/tools/testing/selftests/bpf/progs/test_ksyms.c
index 6c9cbb5a3bdf46..0429430882252b 100644
--- a/tools/testing/selftests/bpf/progs/test_ksyms.c
+++ b/tools/testing/selftests/bpf/progs/test_ksyms.c
@@ -11,8 +11,9 @@ __u64 out__btf_size = -1;
 __u64 out__per_cpu_start = -1;
 
 extern const void bpf_link_fops __ksym;
-extern const void __start_BTF __ksym;
-extern const void __stop_BTF __ksym;
+/* weak: CONFIG_DEBUG_INFO_BTF_LAZY keeps no uncompressed BTF in the image */
+extern const void __start_BTF __ksym __weak;
+extern const void __stop_BTF __ksym __weak;
 extern const void __per_cpu_start __ksym;
 /* non-existing symbol, weak, default to zero */
 extern const void bpf_link_fops1 __ksym __weak;

13/3 2026/11/01 08:10 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29623
							output: 22
							thoughts: 1214
						

Thoughts:
**KMSAN Evaluation: CONFIG_DEBUG_INFO_BTF_LAZY Patch Series**

Okay, let's break this down. The question is, does this patch series warrant a dedicated KMSAN fuzzing session?  My primary concern is uninitialized memory reads and potential kernel-to-user info leaks, but only if they aren't already covered by KASAN or other standard detectors.  A KMSAN session is costly, so I want to avoid it unless absolutely necessary.

First, I need to understand the rules. KASAN already covers a lot of ground: out-of-bounds, UAF, double-frees, invalid frees, and memory corruption. LOCKDEP handles locking issues, and UB-sanitizers cover other undefined behavior. KMSAN focuses on *uninitialized memory reads* specifically, and kernel-to-user memory leaks that result from them.  The rule is: if it *could* be caught by KASAN or LOCKDEP, *don't* use KMSAN. KMSAN is for the *gaps*.

Now, the triggers: I need to consider cases where the patch *introduces* or *modifies* kernel structures that:

1.  Get sent to user space (via copy\_to\_user, put\_user, netlink, ioctl, sockets, BPF buffers) and might have uninitialized fields.
2.  Involve conditional logic dependent on potentially uninitialized variables.
3.  Allocate complex data structures where uninitialized fields could be read later.
4.  Relate to bounds checks or lengths that could lead to uninitialized byte access.

Conversely, I can avoid KMSAN if:

*   The risk is mainly out-of-bounds, overflows, NULL pointer derefs, locking bugs, or UAFs (KASAN will get those).
*   All touched structures are zeroed or initialized *before* being used.
*   The patch doesn't introduce any new uninitialized memory risks.

Alright, let's dive into this patch... "Compress vmlinux BTF and parse it on first use." I'm looking at `kernel/bpf/sysfs_btf.c`.

Okay, so `btf_vmlinux_size` calls `zstd_get_frame_header` and reads `hdr.frameContentSize`. Now, does `zstd_get_frame_header` initialize `hdr`? That's the first question. *I need to check the implementation of `zstd_get_frame_header` itself* to be sure. It could be a source of uninitialized reads.

Then, `btf_vmlinux_data` allocates `raw = vmalloc_user(*size);`. *Wait a minute!* `vmalloc_user` specifies `GFP_KERNEL | __GFP_ZERO`. Good! That *should* zero the memory, so `raw` *should* be initialized. However, the subsequent `zstd_decompress_dctx` call decompresses *into* `raw`. So I need to ensure that the logic correctly handles cases where the decompression is incomplete, *but* the allocation succeeded. `ret` contains the size written. If `ret == *size`, then everything is good and `raw` is made available via `smp_store_release`. But what if `ret < *size`?  In that case, we hit the error branch, where the `raw` buffer is freed.

The critical logic is in that error branch! The code checks if `ret` is an error *and* that `ret == *size`. If *both* are false, the decompression failed and a message is printed, the associated data is dropped, and `raw` is freed.

So, *as long as* `zstd_get_frame_header` *initializes* `hdr`, the code appears to be safe.  `vmalloc_user` initializes `raw`, and if decompression fails, `raw` is freed.  The sysfs reads and mmap operations don't expose uninitialized memory, since `raw` is only passed to those functions if the decompression succeeds.

Now I need to check `zstd_get_frame_header` very carefully! But based on my initial analysis, this *doesn't* scream KMSAN to me *unless* `zstd_get_frame_header` has an initialization issue.  I think it might be OK, but that `zstd_get_frame_header` check is essential. I'm leaning towards `NeedsKMSAN = false`, contingent on that implementation check.



14/3 2026/11/01 08:11 tool grepper
0m Args:
{
  "Expression": "zstd_get_frame_header"
}

Results:
{
  "Output": "drivers/base/firmware_loader/main.c=311=static int fw_decompress_zstd(struct device *dev, struct fw_priv *fw_priv,\n--\ndrivers/base/firmware_loader/main.c-324-\ndrivers/base/firmware_loader/main.c:325:\t\tif (zstd_get_frame_header(\u0026params, in_buffer, in_size) ||\ndrivers/base/firmware_loader/main.c-326-\t\t    params.frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN) {\n--\ndrivers/crypto/intel/qat/qat_common/qat_comp_algs.c=360=static int qat_comp_alg_zstd_decompress(struct acomp_req *req)\n--\ndrivers/crypto/intel/qat/qat_common/qat_comp_algs.c-370-\tbuffer = kmap_local_page(sg_page(req-\u003esrc)) + req-\u003esrc-\u003eoffset;\ndrivers/crypto/intel/qat/qat_common/qat_comp_algs.c:371:\tzret = zstd_get_frame_header(\u0026header, buffer, req-\u003esrc-\u003elength);\ndrivers/crypto/intel/qat/qat_common/qat_comp_algs.c-372-\tkunmap_local(buffer);\n--\ninclude/linux/zstd.h=645=typedef ZSTD_FrameHeader zstd_frame_header;\n--\ninclude/linux/zstd.h-647-/**\ninclude/linux/zstd.h:648: * zstd_get_frame_header() - extracts parameters from a zstd or skippable frame\ninclude/linux/zstd.h-649- * @params:   On success the frame parameters are written here.\n--\ninclude/linux/zstd.h-656- */\ninclude/linux/zstd.h:657:size_t zstd_get_frame_header(zstd_frame_header *params, const void *src,\ninclude/linux/zstd.h-658-\tsize_t src_size);\n--\nkernel/bpf/sysfs_btf.c=29=static u32 btf_vmlinux_size(void)\n--\nkernel/bpf/sysfs_btf.c-34-\tif (!btf_vmlinux_raw_size \u0026\u0026 btf_zst \u0026\u0026\nkernel/bpf/sysfs_btf.c:35:\t    !zstd_get_frame_header(\u0026hdr, btf_zst, __stop_BTF_zst - __start_BTF_zst) \u0026\u0026\nkernel/bpf/sysfs_btf.c-36-\t    hdr.frameContentSize \u003c U32_MAX)\n--\nkernel/module/decompress.c=207=static ssize_t module_zstd_decompress(struct load_info *info,\n--\nkernel/module/decompress.c-230-\nkernel/module/decompress.c:231:\tret = zstd_get_frame_header(\u0026header, zstd_buf.src, zstd_buf.size);\nkernel/module/decompress.c-232-\tif (ret != 0) {\n--\nlib/decompress_unzstd.c=165=static int INIT __unzstd(unsigned char *in_buf, long in_len,\n--\nlib/decompress_unzstd.c-248-\t */\nlib/decompress_unzstd.c:249:\tret = zstd_get_frame_header(\u0026header, in.src, in.size);\nlib/decompress_unzstd.c-250-\terr = handle_zstd_error(ret, error);\n--\nlib/zstd/zstd_decompress_module.c=131=EXPORT_SYMBOL(zstd_find_frame_compressed_size);\nlib/zstd/zstd_decompress_module.c-132-\nlib/zstd/zstd_decompress_module.c:133:size_t zstd_get_frame_header(zstd_frame_header *header, const void *src,\nlib/zstd/zstd_decompress_module.c-134-\tsize_t src_size)\n--\nlib/zstd/zstd_decompress_module.c-137-}\nlib/zstd/zstd_decompress_module.c:138:EXPORT_SYMBOL(zstd_get_frame_header);\nlib/zstd/zstd_decompress_module.c-139-\n--\nsecurity/apparmor/apparmorfs.c=538=static struct aa_loaddata *aa_get_data_from_compressed(const char __user *userbuf,\n--\nsecurity/apparmor/apparmorfs.c-558-\t}\nsecurity/apparmor/apparmorfs.c:559:\terror = zstd_get_frame_header(\u0026header, *compressed_data, buffer_size);\nsecurity/apparmor/apparmorfs.c-560-\tif (error || header.frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN ||\n"
}

15/3 2026/11/01 08:11 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33106
							output: 38
							thoughts: 347
						

Thoughts:
**Analyzing BTF Deferred Registration and Module Structures**

Okay, let's dive into the code and dissect these structures. First, I need to get a clear picture of how `btf_defer_reg` and related structures are being handled. Looking at `kernel/bpf/btf.c`, I see the `btf_deferred_reg` structure:

Right, standard list head for management, `owner` pointing to the module, `kind`, `hook`, `data`, and a count. The crucial question is how the `reg` instance is allocated. Ah, it's `reg = kzalloc_obj(*reg);` which means `kzalloc` is being used, so this memory is initialized to zero. Excellent, that's important for security and predictable initialization. Now, the `reg->data` member is allocated using either `kmemdup` or `kmemdup_array`. These functions are safe choices because they duplicate from existing valid data, meaning there's no risk of uninitialized memory being copied or the potential for a buffer overflow. Good, so far, so good.

Next, I need to examine the `btf_module` structure:

This structure looks like it manages the relationship between the module and its associated BTF data. The module pointer is there, along with the BTF itself which is initially `NULL` before being "adopted". We have a `data` field holding a copy of the `.BTF` data, and associated size and sysfs attributes. Now, where is this `btf_module` structure actually allocated? I'll quickly look in `kernel/bpf/btf.c` around lines 9450-9480 to trace its usage.


16/3 2026/11/01 08:11 tool read-file
0m Args:
{
  "File": "kernel/bpf/btf.c",
  "FirstLine": 9670,
  "LineCount": 70
}

Results:
{
  "Contents": "9670:\t#if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_INLINE)\n9671:\t\t\tif (mod-\u003ebtf_inline_data_size) {\n9672:\t\t\t\tinline_data = mod-\u003ebtf_inline_data;\n9673:\t\t\t\tinline_data_size = mod-\u003ebtf_inline_data_size;\n9674:\t\t\t}\n9675:\t#endif\n9676:\t\t\tif (!mod-\u003ebtf_data_size)\n9677:\t\t\t\tbreak;\n9678:\t\t\tbtf_mod = kzalloc_obj(*btf_mod);\n9679:\t\t\tif (!btf_mod) {\n9680:\t\t\t\terr = -ENOMEM;\n9681:\t\t\t\tgoto out;\n9682:\t\t\t}\n9683:\t\t\tdata = kvmemdup(mod-\u003ebtf_data, mod-\u003ebtf_data_size, GFP_KERNEL | __GFP_NOWARN);\n9684:\t\t\tif (inline_data) {\n9685:\t\t\t\tinline_data = kvmemdup(inline_data, inline_data_size,\n9686:\t\t\t\t\t\t       GFP_KERNEL | __GFP_NOWARN);\n9687:\t\t\t\tif (!inline_data)\n9688:\t\t\t\t\tpr_warn(\"failed to validate module [%s] inline BTF: %d\\n\",\n9689:\t\t\t\t\t\tmod-\u003ename, -ENOMEM);\n9690:\t\t\t}\n9691:\t\t\tif (data \u0026\u0026 btf_module_keep(btf_mod, mod, data, inline_data,\n9692:\t\t\t\t\t\t    inline_data_size))\n9693:\t\t\t\tbreak;\n9694:\t\t\tbtf = !data ? ERR_PTR(-ENOMEM) :\n9695:\t\t\t      btf_parse_module(mod-\u003ename, data, mod-\u003ebtf_data_size,\n9696:\t\t\t\t\t       mod-\u003ebtf_base_data, mod-\u003ebtf_base_data_size,\n9697:\t\t\t\t\t       inline_data, inline_data ? inline_data_size : 0,\n9698:\t\t\t\t\t       \u0026relocated_inline_data);\n9699:\t\t\tif (inline_data != relocated_inline_data)\n9700:\t\t\t\tkvfree(inline_data);\n9701:\t\t\tif (IS_ERR(btf)) {\n9702:\t\t\t\tkvfree(data);\n9703:\t\t\t\tkfree(btf_mod);\n9704:\t\t\t\tif (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {\n9705:\t\t\t\t\tpr_warn(\"failed to validate module [%s] BTF: %ld\\n\",\n9706:\t\t\t\t\t\tmod-\u003ename, PTR_ERR(btf));\n9707:\t\t\t\t\terr = PTR_ERR(btf);\n9708:\t\t\t\t} else {\n9709:\t\t\t\t\tpr_warn_once(\"Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\\n\");\n9710:\t\t\t\t}\n9711:\t\t\t\tgoto out;\n9712:\t\t\t}\n9713:\t\t\terr = btf_alloc_id(btf);\n9714:\t\t\tif (err) {\n9715:\t\t\t\tbtf_free(btf);\n9716:\t\t\t\tkvfree(relocated_inline_data);\n9717:\t\t\t\tkfree(btf_mod);\n9718:\t\t\t\tgoto out;\n9719:\t\t\t}\n9720:\t\n9721:\t\t\tpurge_cand_cache(NULL);\n9722:\t\t\tmutex_lock(\u0026btf_module_mutex);\n9723:\t\t\tbtf_mod-\u003emodule = module;\n9724:\t\t\tbtf_mod-\u003ebtf = btf;\n9725:\t\t\tbtf_mod-\u003ebtf_inline_data = relocated_inline_data;\n9726:\t\t\tbtf_mod-\u003ebtf_inline_data_size = relocated_inline_data ? inline_data_size : 0;\n9727:\t\t\tlist_add(\u0026btf_mod-\u003elist, \u0026btf_modules);\n9728:\t\t\tmutex_unlock(\u0026btf_module_mutex);\n9729:\t\n9730:\t\t\t/* data: the same as btf-\u003edata */\n9731:\t\t\tbtf_module_add_files(btf_mod, mod-\u003ename, data, mod-\u003ebtf_data_size);\n9732:\t\t\tbreak;\n9733:\t\tcase MODULE_STATE_LIVE:\n9734:\t\t\tif (!mod-\u003ebtf_data_size)\n9735:\t\t\t\tbreak;\n9736:\t\t\tmutex_lock(\u0026btf_module_mutex);\n9737:\t\t\tlist_for_each_entry_safe(btf_mod, tmp, \u0026btf_modules, list) {\n9738:\t\t\t\tif (btf_mod-\u003emodule != module)\n9739:\t\t\t\t\tcontinue;\n"
}

17/3 2026/11/01 08:11 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35105
							output: 21
							thoughts: 217
						

Thoughts:
Here's my thought process, as it stands:

**Analyzing BTF Module Addition**

Okay, so I've just allocated a `btf_mod` using `kzalloc_obj`, and I see the code is copying `btf_data` and potentially some inline data with `kvmemdup`.  I'm noting the use of `GFP_KERNEL | __GFP_NOWARN` – this suggests a kernel-level allocation, which is standard, and the `__GFP_NOWARN` implies an absence of allocation failure warnings. Makes sense in a kernel context where we may not want to spam logs, but still want to handle failures.

Now, let's dive into this `btf_module_add_files` function. I see it's taking the `btf_mod`, a name, and the data/size of the data. The important part I think is how it's adding the BTF data to sysfs through the function `sysfs_btf_add`. A file named `<name>.inline` is possibly created using `sysfs_btf_add` to add it to the sysfs, and then the function `sysfs_btf_add` itself is of interest. Let's see what that does. That's the key to understanding how these BTF modules are exposed and managed within the system.



18/3 2026/11/01 08:11 tool grepper
0m Args:
{
  "Expression": "sysfs_btf_add"
}

Results:
{
  "Output": "include/linux/btf.h=646=int btf_check_iter_arg(struct btf *btf, const struct btf_type *func, int arg_idx);\n--\ninclude/linux/btf.h-648-#if IS_ENABLED(CONFIG_SYSFS)\ninclude/linux/btf.h:649:struct bin_attribute *sysfs_btf_add(const char *name, void *data, size_t data_size,\ninclude/linux/btf.h-650-\t\t\t\t    bool mmap, const char *lazy_module_name);\n--\ninclude/linux/btf.h=654=static inline struct bin_attribute *\ninclude/linux/btf.h:655:sysfs_btf_add(const char *name, void *data, size_t data_size, bool mmap,\ninclude/linux/btf.h-656-\t      const char *lazy_module_name)\n--\nkernel/bpf/btf.c=9403=static void btf_module_add_files(struct btf_module *btf_mod, const char *name,\n--\nkernel/bpf/btf.c-9408-\nkernel/bpf/btf.c:9409:\tattr = sysfs_btf_add(name, data, data_size, false, NULL);\nkernel/bpf/btf.c-9410-\tif (IS_ERR(attr))\n--\nkernel/bpf/btf.c-9416-\tsnprintf(inline_name, sizeof(inline_name), \"%s.inline\", name);\nkernel/bpf/btf.c:9417:\tattr = sysfs_btf_add(inline_name, btf_mod-\u003ebtf_inline_data,\nkernel/bpf/btf.c-9418-\t\t\t     btf_mod-\u003ebtf_inline_data_size, false, NULL);\n--\nkernel/bpf/btf.c=9586=static void btf_vmlinux_inline_lazy_init(void)\n--\nkernel/bpf/btf.c-9594-\t}\nkernel/bpf/btf.c:9595:\tvmlinux_inline_attr = sysfs_btf_add(\"vmlinux.inline\", NULL,\nkernel/bpf/btf.c-9596-\t\t\t\t\t    vmlinux_inline_link-\u003ebtf_size, true,\n--\nkernel/bpf/btf_vmlinux_inline.c=16=static int __init btf_vmlinux_inline_init(void)\n--\nkernel/bpf/btf_vmlinux_inline.c-21-\tif (data_size)\nkernel/bpf/btf_vmlinux_inline.c:22:\t\tsysfs_btf_add(\"vmlinux.inline\", __start_BTF_inline, data_size, true, NULL);\nkernel/bpf/btf_vmlinux_inline.c-23-#endif\n--\nkernel/bpf/sysfs_btf.c=256=static int btf_sysfs_mmap_lazy(struct file *filp, struct kobject *kobj,\n--\nkernel/bpf/sysfs_btf.c-272-\nkernel/bpf/sysfs_btf.c:273:struct bin_attribute *sysfs_btf_add(const char *name, void *data, size_t data_size,\nkernel/bpf/sysfs_btf.c-274-\t\t\t\t    bool mmap, const char *lazy_module_name)\n"
}

19/3 2026/11/01 08:11 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36537
							output: 40
							thoughts: 38
						

Thoughts:
Here's my understanding, as if I were thinking it:

**Diving into BTF Sysfs Implementation**

Okay, so I need to get a handle on how the kernel exposes and handles BTF data through sysfs, specifically the read and mmap operations. My hunch is that the `btf_sysfs_add` function in `kernel/bpf/sysfs_btf.c` is the key entry point here. That's the logical place to start digging into the details of how the BTF type information gets exposed and what mechanisms are involved. Understanding this function should give me a good baseline for how the data is read by userspace, and perhaps more importantly, how it's made available for memory mapping, if that's even supported in this specific context. Let's see what `btf_sysfs_add` and its surrounding code reveals... I'm hoping to clarify if there are any subtle interactions or potential gotchas in how this BTF data is handled at the sysfs interface.



20/3 2026/11/01 08:11 tool read-file
0m Args:
{
  "File": "kernel/bpf/sysfs_btf.c",
  "FirstLine": 270,
  "LineCount": 70
}

Results:
{
  "Contents": " 270:\t\treturn remap_vmalloc_range(vma, data, 0);\n 271:\t}\n 272:\t\n 273:\tstruct bin_attribute *sysfs_btf_add(const char *name, void *data, size_t data_size,\n 274:\t\t\t\t\t    bool mmap, const char *lazy_module_name)\n 275:\t{\n 276:\t\tstruct btf_sysfs_entry *entry;\n 277:\t\tstruct bin_attribute *attr;\n 278:\t\tint err;\n 279:\t\n 280:\t\tentry = kzalloc_obj(*entry);\n 281:\t\tif (!entry)\n 282:\t\t\treturn ERR_PTR(-ENOMEM);\n 283:\t\n 284:\t\tattr = \u0026entry-\u003eattr;\n 285:\t\tsysfs_bin_attr_init(attr);\n 286:\t\tattr-\u003eattr.mode = 0444;\n 287:\t\tattr-\u003esize = data_size;\n 288:\t\tattr-\u003eprivate = data;\n 289:\t\tattr-\u003eread = lazy_module_name ? btf_sysfs_read_lazy : sysfs_bin_attr_simple_read;\n 290:\t\tif (mmap)\n 291:\t\t\tattr-\u003emmap = lazy_module_name ? btf_sysfs_mmap_lazy : btf_sysfs_mmap_image;\n 292:\t\tattr-\u003eattr.name = kstrdup(name, GFP_KERNEL);\n 293:\t\tif (!attr-\u003eattr.name) {\n 294:\t\t\terr = -ENOMEM;\n 295:\t\t\tgoto err_free;\n 296:\t\t}\n 297:\t\tif (lazy_module_name) {\n 298:\t\t\tentry-\u003emodule_name = kstrdup(lazy_module_name, GFP_KERNEL);\n 299:\t\t\tif (!entry-\u003emodule_name) {\n 300:\t\t\t\terr = -ENOMEM;\n 301:\t\t\t\tgoto err_free;\n 302:\t\t\t}\n 303:\t\t}\n 304:\t\n 305:\t\terr = sysfs_create_bin_file(btf_kobj, attr);\n 306:\t\tif (err) {\n 307:\t\t\tpr_warn(\"failed to register [%s] BTF in sysfs: %d\\n\", name, err);\n 308:\t\t\tgoto err_free;\n 309:\t\t}\n 310:\t\n 311:\t\treturn attr;\n 312:\t\n 313:\terr_free:\n 314:\t\tkfree(entry-\u003emodule_name);\n 315:\t\tkfree(attr-\u003eattr.name);\n 316:\t\tkfree(entry);\n 317:\t\treturn ERR_PTR(err);\n 318:\t}\n 319:\t\n 320:\tbool sysfs_btf_update(struct bin_attribute *attr, void *data)\n 321:\t{\n 322:\t\treturn attr \u0026\u0026 !cmpxchg(\u0026attr-\u003eprivate, NULL, data);\n 323:\t}\n 324:\t\n 325:\tvoid sysfs_btf_remove(struct bin_attribute *attr)\n 326:\t{\n 327:\t\tstruct btf_sysfs_entry *entry = container_of(attr, struct btf_sysfs_entry, attr);\n 328:\t\n 329:\t\tsysfs_remove_bin_file(btf_kobj, attr);\n 330:\t\tkfree(entry-\u003emodule_name);\n 331:\t\tkfree(attr-\u003eattr.name);\n 332:\t\tkfree(entry);\n 333:\t}\n 334:\t\n 335:\tstatic int __init btf_vmlinux_init(void)\n 336:\t{\n 337:\t\tu32 size;\n 338:\t\n 339:\t\t/* with CONFIG_DEBUG_INFO_BTF_LAZY the read and mmap handlers get it */\n"
}

21/3 2026/11/01 08:11 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37901
							output: 24
							thoughts: 1566
						

Thoughts:
**Analyzing BTF vmlinux Data Retrieval**

Okay, let's break this down. I'm looking at `sysfs_btf.c`, specifically how the vmlinux BTF data is handled for mmap and read operations. The functions `btf_sysfs_vmlinux_read` and `btf_sysfs_vmlinux_mmap` are the key.

First, I need to get the data, which is where `btf_vmlinux_data` comes in. This is where things get interesting. The function first attempts to load the raw data via an `smp_load_acquire`. If that's successful, it uses a cached copy and returns. Otherwise it needs to decompress the data.

Crucially, when the data *isn't* cached, `btf_vmlinux_data` calculates the size via `btf_vmlinux_size()`, grabs a mutex, and checks again if another thread has done the hard work. If not, it allocates memory with `vmalloc_user`, which I'm noting is *user-accessible* memory, and critically, initializes it with zeros. This allocated memory, `raw`, is then decompressed.

Now, a couple of things here. First, if I see `smp_store_release` on `btf_vmlinux_raw`, I know the data is getting cached, and a size is getting set. Second, I need to understand that the size is derived from a Zstandard header. The `btf_vmlinux_size` function checks the header to determine the *uncompressed* size, *before* allocating the user-accessible memory.

Aha! Now I see. When the data isn't cached (the first time the data is being made available to user-space): the original size of the compressed data is read from the Zstandard header (using `zstd_get_frame_header`) and stored in `btf_vmlinux_raw_size`. That size then gets passed to `vmalloc_user`, but *before* that point, the mutex must be obtained. This ensures that the decompressed size is correctly used, and that the value `btf_vmlinux_raw_size` is always valid.

Okay, let's step through a read in another thread. A subsequent call to `btf_vmlinux_data` will see `btf_vmlinux_raw` as non-null, and directly return the already-decompressed data. At this point, the initial allocation size, and the contents of that memory, have been written by the original decompressor. The subsequent reader is using the same size, which has been correctly derived from the Zstandard header.

Now let's step through a write to the user-space mapped memory. The allocation is sized according to the size derived from the Zstandard header. Then the data is decompressed, overwriting any previous zero-filled data. *Finally*, `remap_vmalloc_range` maps this, in its entirety, to user space. Therefore, the memory mapped to user space contains all of the contents from the decompression of the BTF data. Crucially, the size of the mapped range is correctly passed from the caller. 



22/3 2026/11/01 08:12 tool grepper
0m Args:
{
  "Expression": "btf_sysfs_mmap_check"
}

Results:
{
  "Output": "kernel/bpf/sysfs_btf.c=127=void *btf_vmlinux_data(u32 *size)\n--\nkernel/bpf/sysfs_btf.c-134-#ifdef CONFIG_SYSFS\nkernel/bpf/sysfs_btf.c:135:static int btf_sysfs_mmap_check(void *data, size_t size, struct vm_area_struct *vma)\nkernel/bpf/sysfs_btf.c-136-{\n--\nkernel/bpf/sysfs_btf.c=156=static int btf_sysfs_mmap_image(struct file *filp, struct kobject *kobj,\n--\nkernel/bpf/sysfs_btf.c-165-\nkernel/bpf/sysfs_btf.c:166:\terr = btf_sysfs_mmap_check(data, attr-\u003esize, vma);\nkernel/bpf/sysfs_btf.c-167-\tif (err)\n--\nkernel/bpf/sysfs_btf.c=181=static int btf_sysfs_vmlinux_mmap(struct file *filp, struct kobject *kobj,\n--\nkernel/bpf/sysfs_btf.c-192-\nkernel/bpf/sysfs_btf.c:193:\terr = btf_sysfs_mmap_check(data, attr-\u003esize, vma);\nkernel/bpf/sysfs_btf.c-194-\tif (err)\n--\nkernel/bpf/sysfs_btf.c=256=static int btf_sysfs_mmap_lazy(struct file *filp, struct kobject *kobj,\n--\nkernel/bpf/sysfs_btf.c-265-\nkernel/bpf/sysfs_btf.c:266:\terr = btf_sysfs_mmap_check(data, attr-\u003esize, vma);\nkernel/bpf/sysfs_btf.c-267-\tif (err)\n"
}

23/3 2026/11/01 08:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40723
							output: 40
							thoughts: 31
						

Thoughts:
Okay, here's my interpretation of what's going on, thinking like a kernel expert:

**Diving into `btf_sysfs_mmap_check`**

Alright, let's get down to brass tacks. I'm taking a look at `btf_sysfs_mmap_check` within `kernel/bpf/sysfs_btf.c`. Given the naming, my immediate assumption is that this function is responsible for validating some aspect of memory mapping related to BTF (BPF Type Format) data that's being accessed through sysfs. It's likely involved in guarding against malicious input or ensuring data integrity when a user-space application attempts to mmap a BTF file, which is a common pattern for interacting with kernel-provided BPF data. I bet this check ensures that the requested mapping is safe, perhaps by validating permissions, offset, size, or other crucial parameters before allowing the user to read or write to the BTF metadata. I need to understand what specific checks it performs, to properly design this.



24/3 2026/11/01 08:12 tool read-file
0m Args:
{
  "File": "kernel/bpf/sysfs_btf.c",
  "FirstLine": 135,
  "LineCount": 30
}

Results:
{
  "Contents": " 135:\tstatic int btf_sysfs_mmap_check(void *data, size_t size, struct vm_area_struct *vma)\n 136:\t{\n 137:\t\tunsigned long pages = PAGE_ALIGN(size) \u003e\u003e PAGE_SHIFT;\n 138:\t\tsize_t vm_size = vma-\u003evm_end - vma-\u003evm_start;\n 139:\t\n 140:\t\tif (!data || !PAGE_ALIGNED((unsigned long)data))\n 141:\t\t\treturn -EINVAL;\n 142:\t\n 143:\t\tif (vma-\u003evm_pgoff)\n 144:\t\t\treturn -EINVAL;\n 145:\t\n 146:\t\tif (vma-\u003evm_flags \u0026 (VM_WRITE | VM_EXEC | VM_MAYSHARE))\n 147:\t\t\treturn -EACCES;\n 148:\t\n 149:\t\tif ((vm_size \u003e\u003e PAGE_SHIFT) \u003e pages)\n 150:\t\t\treturn -EINVAL;\n 151:\t\n 152:\t\tvm_flags_mod(vma, VM_DONTDUMP, VM_MAYEXEC | VM_MAYWRITE);\n 153:\t\treturn 0;\n 154:\t}\n 155:\t\n 156:\tstatic int btf_sysfs_mmap_image(struct file *filp, struct kobject *kobj,\n 157:\t\t\t\t\tconst struct bin_attribute *attr,\n 158:\t\t\t\t\tstruct vm_area_struct *vma)\n 159:\t{\n 160:\t\tvoid *data = READ_ONCE(attr-\u003eprivate);\n 161:\t\tphys_addr_t addr;\n 162:\t\tunsigned long pfn;\n 163:\t\tsize_t vm_size = vma-\u003evm_end - vma-\u003evm_start;\n 164:\t\tint err;\n"
}

25/3 2026/11/01 08:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41517
							output: 38
							thoughts: 1502
						

Thoughts:
**Analyzing BTF and BPF Context Validation**

Alright, let's break this down systematically. I'm focusing on the code related to BTF (BPF Type Format) and the validation of program contexts within the BPF framework. First, I looked at `btf_validate_prog_ctx_type` and its supporting function `prog_ctx_tname`. `prog_ctx_tname` is straightforward; it retrieves the expected context type name based on the BPF program type. It handles some special cases, like `bpf_user_pt_regs_t`, and attempts to find a compatible type if necessary. It primarily works with static strings and compile-time constants, which is generally good for stability.

Next, I examined `btf_is_prog_ctx_type`, which is used for context type checking. It uses `prog_ctx_tname` to get the expected context type, and then compares it against the provided type using `btf_is_projection_of` or direct string comparison. The special handling for `bpf_user_pt_regs_t` is retained here too. Interestingly, `btf_validate_prog_ctx_type` handles `struct` prefixes in a slightly different manner, only using `alt` if the original name doesn't have the prefix, meaning it might use the alternate name in cases where it is `bpf_user_pt_regs_t`.

I then shifted my attention to `kernel/bpf/inode.c`, specifically around the `bpf_parse_param` function. A critical change here involves moving the capability check (`CAP_SYS_ADMIN`) *before* any potentially expensive BTF parsing. This is a very prudent optimization, as parsing the vmlinux BTF could be quite resource intensive. The original version could be susceptible to a DOS attack.

In `kernel/bpf/syscall.c`, I examined the `bpf_prog_load` function. There's a refinement concerning the fallback to vmlinux BTF when `attach_btf_id` or `multi_func` is specified. Now, it explicitly checks `bpf_cap`, ensuring that the fallback only happens for program types that actually require the `CAP_BPF` capability. This is an important security measure.

Finally, I checked `kernel/trace/trace_events.c`, specifically `event_btf_ids_read`. This function now includes a call to `bpf_get_btf_vmlinux()` *before* acquiring `event_mutex`. This implies that the vmlinux BTF might be parsed lazily, the first time this function is used. The subsequent reading of `buf` in the `scoped_guard` looks safe as it's a stack-allocated buffer and should be properly initialized by the code. The lock is also handled appropriately. I did a quick check on the full `event_btf_ids_read` to be certain there weren't any information leaks, and it seems fine.



26/3 2026/11/01 08:12 tool read-file
0m Args:
{
  "File": "kernel/trace/trace_events.c",
  "FirstLine": 2280,
  "LineCount": 40
}

Results:
{
  "Contents": "2280:\t\tu32 raw_id = 0, tp_id = 0, obj_id = 0;\n2281:\t\tconst u32 *ids;\n2282:\t\tstruct btf *btf;\n2283:\t\tchar buf[128];\n2284:\t\tint len;\n2285:\t\n2286:\t\t/* parse the vmlinux BTF, if this is its first use, without event_mutex */\n2287:\t\tbpf_get_btf_vmlinux();\n2288:\t\n2289:\t\t/* Module unload could free call-\u003eclass and ids[] mid-read. */\n2290:\t\tscoped_guard(mutex, \u0026event_mutex) {\n2291:\t\t\tfile = event_file_file(filp);\n2292:\t\t\tif (!file)\n2293:\t\t\t\treturn -ENODEV;\n2294:\t\n2295:\t\t\tcall = file-\u003eevent_call;\n2296:\t\t\tids = call-\u003eclass-\u003ebtf_ids;\n2297:\t\t\tif (!ids)\n2298:\t\t\t\treturn -ENOENT;\n2299:\t\t\tif (!(call-\u003eflags \u0026 TRACE_EVENT_FL_DYNAMIC))\n2300:\t\t\t\tmod = (struct module *)call-\u003emodule;\n2301:\t\n2302:\t\t\tbtf = btf_get_module_btf(mod);\n2303:\t\t\tif (IS_ERR_OR_NULL(btf))\n2304:\t\t\t\treturn -ENOENT;\n2305:\t\n2306:\t\t\t/* Module-local ids in ids[] need base+local relocation. */\n2307:\t\t\ttp_id = btf_relocate_id(btf, ids[1]);\n2308:\t\n2309:\t\t\t/*\n2310:\t\t\t * Without FL_TRACEPOINT the dispatcher is shared (e.g. all\n2311:\t\t\t * per-syscall events fan out from __bpf_trace_sys_enter), so\n2312:\t\t\t * raw_btf_id has no per-event attach point — report 0.\n2313:\t\t\t */\n2314:\t\t\tif (call-\u003eflags \u0026 TRACE_EVENT_FL_TRACEPOINT) {\n2315:\t\t\t\tt = btf_type_by_id(btf, btf_relocate_id(btf, ids[0]));\n2316:\t\t\t\traw_id = t ? t-\u003etype : 0;\n2317:\t\t\t}\n2318:\t\t\tobj_id = btf_obj_id(btf);\n2319:\t\t\tbtf_put(btf);\n"
}

27/3 2026/11/01 08:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44382
							output: 38
							thoughts: 45
						

Thoughts:
Here's my summary, as though I were thinking through the process:

**Diving into the Trace Events Code**

Okay, so I'm looking at how this `buf` variable is being handled, specifically in the context of `snprintf` and `simple_read_from_buffer`. Since I need to understand this better, let's zero in on the relevant code. My thought is that the best starting point is line 2320 through 2335 of `kernel/trace/trace_events.c`. This section likely contains the direct manipulation or usage of `buf` with these functions, and understanding it will give me the context I need to get a handle on what the code is doing.



28/3 2026/11/01 08:12 tool read-file
0m Args:
{
  "File": "kernel/trace/trace_events.c",
  "FirstLine": 2320,
  "LineCount": 20
}

Results:
{
  "Contents": "2320:\t\t}\n2321:\t\n2322:\t\tlen = scnprintf(buf, sizeof(buf),\n2323:\t\t\t\t\"btf_obj_id: %u\\nraw_btf_id: %u\\ntp_btf_id: %u\\n\",\n2324:\t\t\t\tobj_id, raw_id, tp_id);\n2325:\t\n2326:\t\treturn simple_read_from_buffer(ubuf, cnt, ppos, buf, len);\n2327:\t}\n2328:\t#endif\n2329:\t\n2330:\tstatic ssize_t\n2331:\tevent_filter_read(struct file *filp, char __user *ubuf, size_t cnt,\n2332:\t\t\t  loff_t *ppos)\n2333:\t{\n2334:\t\tstruct trace_event_file *file;\n2335:\t\tstruct trace_seq *s;\n2336:\t\tint r = -ENODEV;\n2337:\t\n2338:\t\tif (*ppos)\n2339:\t\t\treturn 0;\n"
}

29/3 2026/11/01 08:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44925
							output: 20
							thoughts: 128
						

Thoughts:
Okay, let's break this down.

**Diving into the btf_parse_base Function**

Alright, so I see a standard pattern here: `scnprintf` followed by `simple_read_from_buffer(ubuf, cnt, ppos, buf, len)`. That's completely expected and, from what I can see at a glance, safe. No immediate red flags there.

Now, I'm more interested in what's happening with `btf_parse_base`. Let me see... in `kernel/bpf/btf.c`, I see `btf = btf_parse_base(env, "vmlinux", data, size);`. Okay, `btf_parse_base` is the key function. Now, where is `data` coming from? It looks like it's from `btf_vmlinux_data(&size);`. Time to dig into how `btf_parse_base` is using this `data`. Gotta understand how that data is being handled. This is where the potential vulnerabilities often lie.



30/3 2026/11/01 08:12 tool grepper
0m Args:
{
  "Expression": "btf_parse_base"
}

Results:
{
  "Output": "kernel/bpf/btf.c=6843=BTF_ID_LIST_SINGLE(bpf_ctx_convert_btf_id, struct, bpf_ctx_convert)\nkernel/bpf/btf.c-6844-\nkernel/bpf/btf.c:6845:static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name,\nkernel/bpf/btf.c-6846-\t\t\t\t  void *data, unsigned int data_size)\n--\nkernel/bpf/btf.c=6898=struct btf *btf_parse_vmlinux(void)\n--\nkernel/bpf/btf.c-6916-\tlog-\u003elevel = BPF_LOG_KERNEL;\nkernel/bpf/btf.c:6917:\tbtf = btf_parse_base(env, \"vmlinux\", data, size);\nkernel/bpf/btf.c-6918-\tif (IS_ERR(btf))\n--\nkernel/bpf/btf.c=7135=static struct btf *btf_parse_module(const char *module_name, void *data,\n--\nkernel/bpf/btf.c-7163-\tif (base_data) {\nkernel/bpf/btf.c:7164:\t\tbase_btf = btf_parse_base(env, \".BTF.base\", base_data, base_data_size);\nkernel/bpf/btf.c-7165-\t\tif (IS_ERR(base_btf)) {\n"
}

31/3 2026/11/01 08:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45720
							output: 38
							thoughts: 12
						

Thoughts:
Okay, here's my interpretation of "Let's read `btf_parse_base`," presented as though it's my own thought process, assuming I'm an expert in this field.

**Diving into `btf_parse_base`**

Alright, time to crack this open. "Let's read `btf_parse_base`..." That's the command, and I'm ready to comply. This function, `btf_parse_base`, immediately tells me we're dealing with the foundational parsing logic for the BTF (BPF Type Format) data. Given the name, I'd expect it handles the core structure of the BTF data, likely dealing with things like the header, versioning, size checks, and possibly the initial metadata that establishes the framework for everything else. It's almost certain it needs to process the "base" of the BTF data that is then interpreted by other helper functions.

I anticipate it will be relatively low-level code that sets the stage for type extraction. I'll be looking for things like memory mapping of the BTF data, error handling at the very beginning of the parsing process and sanity checks on the input buffer. Probably checks for the correct magic number and version. Let's see what gems are contained.



32/3 2026/11/01 08:12 tool read-file
0m Args:
{
  "File": "kernel/bpf/btf.c",
  "FirstLine": 6845,
  "LineCount": 40
}

Results:
{
  "Contents": "6845:\tstatic struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name,\n6846:\t\t\t\t\t  void *data, unsigned int data_size)\n6847:\t{\n6848:\t\tstruct btf *btf = NULL;\n6849:\t\tint err;\n6850:\t\n6851:\t\tif (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))\n6852:\t\t\treturn ERR_PTR(-ENOENT);\n6853:\t\n6854:\t\tbtf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);\n6855:\t\tif (!btf) {\n6856:\t\t\terr = -ENOMEM;\n6857:\t\t\tgoto errout;\n6858:\t\t}\n6859:\t\tenv-\u003ebtf = btf;\n6860:\t\n6861:\t\tbtf-\u003edata = data;\n6862:\t\tbtf-\u003edata_size = data_size;\n6863:\t\tbtf-\u003ekernel_btf = true;\n6864:\t\tbtf-\u003enamed_start_id = 0;\n6865:\t\tstrscpy(btf-\u003ename, name);\n6866:\t\n6867:\t\terr = btf_parse_hdr(env);\n6868:\t\tif (err)\n6869:\t\t\tgoto errout;\n6870:\t\n6871:\t\tbtf-\u003enohdr_data = btf-\u003edata + btf-\u003ehdr.hdr_len;\n6872:\t\n6873:\t\terr = btf_parse_str_sec(env);\n6874:\t\tif (err)\n6875:\t\t\tgoto errout;\n6876:\t\n6877:\t\terr = btf_check_all_metas(env);\n6878:\t\tif (err)\n6879:\t\t\tgoto errout;\n6880:\t\n6881:\t\terr = btf_check_modifier_chain_length(env, btf, 1);\n6882:\t\tif (err)\n6883:\t\t\tgoto errout;\n6884:\t\n"
}

33/3 2026/11/01 08:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 46623
							output: 22
							thoughts: 1230
						

Thoughts:
**Analyzing BTF Data Management**

Okay, let's trace the lifecycle of `btf` structures, specifically focusing on how `btf->data` is handled, given my understanding of the implications for the broader BPF ecosystem. I'm keen on catching any potential memory leaks or incorrect usage patterns. It seems that `btf_free` is the central function for releasing resources, and I'm noting that `btf->types`, `btf->resolved_sizes`, and `btf->resolved_ids` are all freed using `kvfree`. That's standard and expected.

The crucial bit, however, is the handling of `btf->data`.  It looks like, in the vmlinux case (and with lazy BTF enabled), it often points directly at the read-only section (e.g., `__start_BTF`) or a decompressed copy.  This suggests no freeing is *necessary* in those scenarios, which makes sense. I see consistent `kvfree` calls for `btf->data` when the BTF isn't the vmlinux version, which is what I'd expect.

Looking at `btf_parse_split` and `btf_parse_module`, I see how `btf->data` is assigned from a provided `data` pointer.  Crucially, it is explicitly set to `NULL` before calling `btf_free` in the `errout` paths and in other error scenarios. This ensures that a double-free is avoided if an error occurs during parsing. The `btf_unparse_kept_modules` function has an interesting pattern where the maintained copy is handled.

However, I'm getting a little uneasy about `btf_defer_reg`. I'm seeing an unusual handling of the `data` pointer that's concerning. It looks like it is possible to bypass the memory copy in cases where the `kind` of deferred registration is `BTF_DEFER_ST_OPS`. Where does `st_ops` come from? What are the caller scenarios for `__register_bpf_struct_ops` and `register_bpf_struct_ops`? That seems like an area that needs some closer investigation. We could be looking at a scenario where a stack-allocated or temporary buffer is being deferred and then being freed before being consumed, which sounds like trouble, I should check the callers of those functions to see if that's the case. It is important to make sure the data in this case is valid until `btf_apply_deferred` is called.



34/3 2026/11/01 08:13 tool grepper
0m Args:
{
  "Expression": "register_bpf_struct_ops"
}

Results:
{
  "Output": "drivers/hid/bpf/hid_bpf_struct_ops.c=337=static int __init hid_bpf_struct_ops_init(void)\ndrivers/hid/bpf/hid_bpf_struct_ops.c-338-{\ndrivers/hid/bpf/hid_bpf_struct_ops.c:339:\treturn register_bpf_struct_ops(\u0026bpf_hid_bpf_ops, hid_bpf_ops);\ndrivers/hid/bpf/hid_bpf_struct_ops.c-340-}\n--\nfs/binfmt_misc_bpf.c=459=static int __init bm_bpf_struct_ops_init(void)\nfs/binfmt_misc_bpf.c-460-{\nfs/binfmt_misc_bpf.c:461:\treturn register_bpf_struct_ops(\u0026bpf_binfmt_misc_ops, binfmt_misc_ops);\nfs/binfmt_misc_bpf.c-462-}\n--\ninclude/linux/bpf.h=2348=static inline bool is_struct_ops_tramp(const struct bpf_tramp_nodes *fentry_nodes)\n--\ninclude/linux/bpf.h-2356- * type information correctly. Developers should use this macro to register\ninclude/linux/bpf.h:2357: * a struct_ops type instead of calling __register_bpf_struct_ops() directly.\ninclude/linux/bpf.h-2358- */\ninclude/linux/bpf.h:2359:#define register_bpf_struct_ops(st_ops, type)\t\t\t\t\\\ninclude/linux/bpf.h-2360-\t({\t\t\t\t\t\t\t\t\\\n--\ninclude/linux/bpf.h-2365-\t\tBTF_TYPE_EMIT(struct bpf_struct_ops_##type);\t\t\\\ninclude/linux/bpf.h:2366:\t\t__register_bpf_struct_ops(st_ops);\t\t\t\\\ninclude/linux/bpf.h-2367-\t})\n--\ninclude/linux/bpf.h=2430=void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc);\ninclude/linux/bpf.h-2431-#else\ninclude/linux/bpf.h:2432:#define register_bpf_struct_ops(st_ops, type) ({ (void *)(st_ops); 0; })\ninclude/linux/bpf.h-2433-static inline bool bpf_try_module_get(const void *data, struct module *owner)\n--\ninclude/linux/btf.h=576=struct bpf_struct_ops;\ninclude/linux/btf.h:577:int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops);\ninclude/linux/btf.h-578-const struct bpf_struct_ops_desc *bpf_struct_ops_find_value(struct btf *btf, u32 value_id);\n--\nio_uring/bpf-ops.c=263=static int __init io_uring_bpf_init(void)\n--\nio_uring/bpf-ops.c-266-\nio_uring/bpf-ops.c:267:\tret = register_bpf_struct_ops(\u0026bpf_ring_ops, io_uring_bpf_ops);\nio_uring/bpf-ops.c-268-\tif (ret) {\n--\nkernel/bpf/btf.c=11257=bpf_struct_ops_find(struct btf *btf, u32 type_id)\n--\nkernel/bpf/btf.c-11277-\nkernel/bpf/btf.c:11278:int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\nkernel/bpf/btf.c-11279-{\n--\nkernel/bpf/btf.c-11308-}\nkernel/bpf/btf.c:11309:EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);\nkernel/bpf/btf.c-11310-#endif\n--\nkernel/bpf/btf.c=11335=static int btf_apply_deferred(void)\n--\nkernel/bpf/btf.c-11358-#if defined(CONFIG_BPF_JIT)\nkernel/bpf/btf.c:11359:\t\t\terr = __register_bpf_struct_ops(reg-\u003edata);\nkernel/bpf/btf.c-11360-#endif\n--\nkernel/sched/ext/ext.c=12331=static int __init scx_init(void)\n--\nkernel/sched/ext/ext.c-12453-\nkernel/sched/ext/ext.c:12454:\tret = register_bpf_struct_ops(\u0026bpf_sched_ext_ops, sched_ext_ops);\nkernel/sched/ext/ext.c-12455-\tif (ret) {\n--\nkernel/sched/ext/ext.c-12459-\nkernel/sched/ext/ext.c:12460:\tret = register_bpf_struct_ops(\u0026bpf_sched_ext_ops_cid, sched_ext_ops_cid);\nkernel/sched/ext/ext.c-12461-\tif (ret) {\n--\nnet/bpf/bpf_dummy_struct_ops.c=319=static int __init bpf_dummy_struct_ops_init(void)\nnet/bpf/bpf_dummy_struct_ops.c-320-{\nnet/bpf/bpf_dummy_struct_ops.c:321:\treturn register_bpf_struct_ops(\u0026bpf_bpf_dummy_ops, bpf_dummy_ops);\nnet/bpf/bpf_dummy_struct_ops.c-322-}\n--\nnet/ipv4/bpf_tcp_ca.c=362=static int __init bpf_tcp_ca_kfunc_init(void)\n--\nnet/ipv4/bpf_tcp_ca.c-366-\tret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, \u0026bpf_tcp_ca_kfunc_set);\nnet/ipv4/bpf_tcp_ca.c:367:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_tcp_congestion_ops, tcp_congestion_ops);\nnet/ipv4/bpf_tcp_ca.c-368-\n--\nnet/ipv4/bpf_tcp_ops.c=437=static int __init __bpf_tcp_ops_init(void)\n--\nnet/ipv4/bpf_tcp_ops.c-447-\t\t\t\t\t       \u0026bpf_tcp_ops_set_rcvlowat_kfunc_id_set);\nnet/ipv4/bpf_tcp_ops.c:448:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_tcp_ops, bpf_tcp_ops);\nnet/ipv4/bpf_tcp_ops.c-449-\n--\nnet/sched/bpf_qdisc.c=458=static int __init bpf_qdisc_kfunc_init(void)\n--\nnet/sched/bpf_qdisc.c-471-\t\t\t\t\t\t THIS_MODULE);\nnet/sched/bpf_qdisc.c:472:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_Qdisc_ops, Qdisc_ops);\nnet/sched/bpf_qdisc.c-473-\n--\nnet/smc/smc_hs_bpf.c=137=int bpf_smc_hs_ctrl_init(void)\nnet/smc/smc_hs_bpf.c-138-{\nnet/smc/smc_hs_bpf.c:139:\treturn register_bpf_struct_ops(\u0026bpf_smc_hs_ctrl_ops, smc_hs_ctrl);\nnet/smc/smc_hs_bpf.c-140-}\n--\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c=59=static int bpf_test_no_cfi_init(void)\n--\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-62-\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c:63:\tret = register_bpf_struct_ops(\u0026test_no_cif_ops,\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-64-\t\t\t\t      bpf_test_no_cfi_ops);\n--\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-68-\ttest_no_cif_ops.cfi_stubs = \u0026__test_no_cif_ops;\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c:69:\tret = register_bpf_struct_ops(\u0026test_no_cif_ops,\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-70-\t\t\t\t      bpf_test_no_cfi_ops);\n--\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c=2610=static int bpf_testmod_init(void)\n--\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c-2626-\tret = ret ?: register_btf_fmodret_id_set(\u0026bpf_testmod_trampoline_count_fmodret_set);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2627:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_bpf_testmod_ops, bpf_testmod_ops);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2628:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_testmod_ops2, bpf_testmod_ops2);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2629:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_testmod_ops3, bpf_testmod_ops3);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2630:\tret = ret ?: register_bpf_struct_ops(\u0026testmod_st_ops, bpf_testmod_st_ops);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2631:\tret = ret ?: register_bpf_struct_ops(\u0026testmod_multi_st_ops, bpf_testmod_multi_st_ops);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c-2632-\tret = ret ?: register_btf_id_dtor_kfuncs(bpf_testmod_dtors,\n"
}

35/3 2026/11/01 08:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 51345
							output: 24
							thoughts: 1118
						

Thoughts:
**Analyzing Potential KMSAN Triggers in BTF Handling**

Okay, let's break this down. My initial thought is that the assignment `reg->data = (void *)data;` is safe since `st_ops` structures are statically allocated and global.  No stack allocation issues here. I did note the explicit `kmemdup` calls for kfuncs and dtors which is a good defensive measure.

Now, I'm digging into `is_valid_value_type` in `bpf_struct_ops.c`.  The key point is the change to `btf_type_by_id`: it now takes the `btf` struct as an argument instead of always using `btf_vmlinux`. This is important because `btf` could be the vmlinux BTF or a module's BTF.

Next, I'm examining `btf_get_ptr_to_btf_id`.  I see the introduction of `vmlinux_btf` via `bpf_get_btf_vmlinux()` before acquiring `cand_cache_mutex`. This implies that `vmlinux_btf` is being parsed before taking the lock, which likely handles the case where it’s the first use.

Then I checked `btf_get_fd_by_id`. The check for `CONFIG_DEBUG_INFO_BTF_LAZY` and the call to `bpf_get_btf_vmlinux()` if enabled indicates that kernel BTFs have their IDs assigned during parsing, which happens before the BTFs are published. This is likely an optimization for lazy loading.

Finally, I'm reviewing the KMSAN triggers.  Specifically, the focus is on the four KMSAN triggers.

*   **Trigger 1 (Kernel data sent to user space):**  I'm looking closely at how `/sys/kernel/btf/vmlinux` and module BTF files are handled.  The use of `vmalloc_user` (zeroes pages), `zstd_decompress_dctx` (strict size check) in the sysfs case and `kvmemdup` (no new uninitialized data) in the module BTF files is reassuring. Trace events using `scnprintf` followed by `simple_read_from_buffer` seems like a normal flow, so nothing is highlighted.

*   **Trigger 2 (Conditional logic with uninitialized variables):**  My main concern here is `zstd_get_frame_header(&hdr, ...)` since the condition `!zstd_get_frame_header(&hdr, ...) && hdr.frameContentSize < U32_MAX` has the potential to lead to a KMSAN trigger. The `&&` short-circuiting ensures `hdr` is only used if `zstd_get_frame_header` succeeds (returns 0) which is good.  I will verify `zstd_get_frame_header` in kernel `lib/zstd/zstd_decompress_module.c`.



36/3 2026/11/01 08:13 tool grepper
0m Args:
{
  "Expression": "zstd_get_frame_header.*\\{"
}

Results:
{
  "Output": "no matches"
}

37/3 2026/11/01 08:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 53154
							output: 25
							thoughts: 16
						

Thoughts:
Okay, here's my attempt at summarizing that thought process, keeping in mind the expert user and aiming for a fulsome rendering:

**Locating the Frame Header Function**

Alright, I'm thinking I need to get to the heart of how Zstandard handles its frame headers. That likely means tracking down the definition of the `zstd_get_frame_header` function. I need to understand what that function expects as input, what data it returns, and ultimately, how it's used within the broader decompression and compression flow. I'm assuming it's part of the standard Zstandard library, but it wouldn't hurt to quickly verify the exact name and maybe even the namespace within the headers. The goal is a clear understanding of the data structure the function uses and how it accesses the underlying compressed data. I need this to be the base for further investigation of the Zstandard algorithm. Time to get digging through those header files and source code!



38/3 2026/11/01 08:13 tool grepper
0m Args:
{
  "Expression": "size_t zstd_get_frame_header"
}

Results:
{
  "Output": "include/linux/zstd.h=645=typedef ZSTD_FrameHeader zstd_frame_header;\n--\ninclude/linux/zstd.h-656- */\ninclude/linux/zstd.h:657:size_t zstd_get_frame_header(zstd_frame_header *params, const void *src,\ninclude/linux/zstd.h-658-\tsize_t src_size);\n--\nlib/zstd/zstd_decompress_module.c=131=EXPORT_SYMBOL(zstd_find_frame_compressed_size);\nlib/zstd/zstd_decompress_module.c-132-\nlib/zstd/zstd_decompress_module.c:133:size_t zstd_get_frame_header(zstd_frame_header *header, const void *src,\nlib/zstd/zstd_decompress_module.c-134-\tsize_t src_size)\n"
}

39/3 2026/11/01 08:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 53643
							output: 42
							thoughts: 26
						

Thoughts:
Okay, here's my interpretation of what's going on, thinking through this as a senior-level expert:

**Deconstructing `zstd_decompress_module.c` Line 133**

Alright, I'm heading over to `lib/zstd/zstd_decompress_module.c`, specifically line 133. Given the context of decompression, my initial thought is this likely resides somewhere within the core decompression logic. Considering it's a module, I'm assuming we are at the intersection of a higher level function, perhaps a method related to handling the various "chunks" or "frames" of data within a Zstandard stream. It could be related to decoding a specific symbol, an offset value, or potentially managing the internal state of the decompressor. The fact that the line is being brought up suggests that something there is noteworthy – either a subtle optimization, a potential performance bottleneck, or, perhaps, a critical state transition. I'm mentally preparing for it to be a bit-level operation, a conditional branch based on some internal data structure or maybe a call to an embedded function within the module. Let's see what's actually there.



40/3 2026/11/01 08:13 tool read-file
0m Args:
{
  "File": "lib/zstd/zstd_decompress_module.c",
  "FirstLine": 130,
  "LineCount": 20
}

Results:
{
  "Contents": " 130:\t}\n 131:\tEXPORT_SYMBOL(zstd_find_frame_compressed_size);\n 132:\t\n 133:\tsize_t zstd_get_frame_header(zstd_frame_header *header, const void *src,\n 134:\t\tsize_t src_size)\n 135:\t{\n 136:\t\treturn ZSTD_getFrameHeader(header, src, src_size);\n 137:\t}\n 138:\tEXPORT_SYMBOL(zstd_get_frame_header);\n 139:\t\n 140:\tMODULE_LICENSE(\"Dual BSD/GPL\");\n 141:\tMODULE_DESCRIPTION(\"Zstd Decompressor\");\n"
}

41/3 2026/11/01 08:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 54158
							output: 620
							thoughts: 2996
						

Thoughts:
**KMSAN Applicability Analysis for BTF Lazy Loading Patch**

Alright, let's break this down. My goal is to determine if this patch necessitates a KMSAN (Kernel Memory Sanitizer) check. The core change here is the introduction of a lazy-loading mechanism for vmlinux BTF (Berkeley Packet Filter Type Format) data using ZSTD compression. The vmlinux BTF is now decompressed on-demand, which also introduces deferred registrations (kfuncs, dtors, struct_ops) and module BTF loading. My focus has to be: does this potentially expose or create a new avenue for uninitialized memory reads or information leaks that would only be caught by KMSAN?

First, I meticulously examine all memory allocations. The newly introduced structures – `btf_deferred_reg`, `btf_module`, `btf`, `btf_verifier_env` – are all allocated using `kzalloc_obj`, which is a zeroing allocator. This means all their fields start clean, which is good. Data copied into these structures comes from `kvmemdup`, `kmemdup`, or `kmemdup_array`. These are important; `kvmemdup` copies from kernel memory, `kmemdup` from a kernel memory, and `kmemdup_array` from an array of kernel memory – all of which I *know* are initialized because they're part of how the caller is using it. Furthermore, the vmlinux BTF buffer itself is allocated using `vmalloc_user` which *also* zeroes memory. Crucially, the decompressed size is verified against the *expected* size. Any failure, and the buffer is freed. The decompressed data is then *only* exposed if the check passes.

Next, I check any stack variables. Variables like `hdr` in `btf_vmlinux_size` and `alt` in `prog_ctx_tname` are either fully initialized by the calls themselves or guarded by error checks/short-circuiting logic. If there's an issue with the call, it bails out *before* the value gets read.

Now, consider user-space exposure. The BTF data is exposed via `/sys/kernel/btf/vmlinux` and `/sys/kernel/btf/<module>`. The data *there* comes from the vmalloc and kvmemdup buffers which hold the decompressed BTF data. Therefore, there's no possibility of uninitialized kernel memory being leaked to user space via the sysfs interface. There isn't any uninitialized struct padding either.

Finally, I contrast the potential risks here with the strengths of KASAN (Kernel Address Sanitizer) and LOCKDEP. The primary risks of this patch are concurrency problems, race conditions, potential deadlocks involving the `btf_vmlinux_lock`, `btf_module_mutex`, `cand_cache_mutex`, and `event_mutex` locks, problems due to module unload and deferred registrations, or the handling of errors. These concerns are precisely the kinds of issues that KASAN, LOCKDEP, and standard kernel debugging tools are designed to catch.  There's no risk here of uninitialized memory reads or an info-leak that would *only* be caught by KMSAN.

Therefore, `NeedsKMSAN = false`. I am confident that the current kernel debugging infrastructure is sufficient.



42/3 2026/11/01 08:14 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series introduces CONFIG_DEBUG_INFO_BTF_LAZY, which compresses the vmlinux BTF using zstd and lazily decompresses and parses it on first demand rather than at boot. It also implements deferred registration queues for kfuncs, dtor kfuncs, and struct_ops, as well as deferral for module split BTF loading.\n\n1. Analysis of Memory Allocation and Initialization:\n- All heap objects introduced or modified by the patch (such as `struct btf_deferred_reg` in btf_defer_reg() and `struct btf_module` in btf_module_notify()) are allocated using zero-initializing allocators (`kzalloc_obj`).\n- Buffer copies for deferred kfunc id sets, dtors, and module BTF data are cloned via `kmemdup`, `kmemdup_array`, and `kvmemdup`, duplicating already initialized data.\n- The vmlinux BTF raw buffer is allocated using `vmalloc_user()`, which zeroes allocated pages (`__GFP_ZERO`), and is populated by `zstd_decompress_dctx()`. The pointer is only published if decompression output exactly matches the expected size (`ret == *size`).\n- Stack variables (such as `zstd_frame_header hdr` in `btf_vmlinux_size()`) are guarded by error checks; `hdr.frameContentSize` is accessed only after `zstd_get_frame_header()` returns 0 (success). In `prog_ctx_tname()`, the out-pointer `*alt` is explicitly initialized to NULL before use.\n\n2. User Space Exposure and Info-leak Checks:\n- Data exposed to user space through `/sys/kernel/btf/vmlinux` via sysfs read and mmap operations maps or copies from the `vmalloc_user` buffer holding verified decompressed BTF data.\n- Similarly, trace events' BTF ID reads use `scnprintf` formatted into a stack buffer and copy only the formatted length via `simple_read_from_buffer`. There is no uninitialized memory or structure padding leaked to user space.\n\n3. KASAN vs KMSAN Applicability:\n- The risks introduced by this change involve synchronization, complex lock ordering (e.g., `btf_vmlinux_lock` vs `btf_module_mutex`, `cand_cache_mutex`, `event_mutex`), and object lifecycles across module load/unload transitions. These failure modes (deadlocks, use-after-free, double-free, NULL/ERR pointer dereferences) are detected by LOCKDEP and KASAN.\n- There are no uninitialized memory reads or uninitialized data leakage risks that uniquely require KMSAN.\n\nTherefore, dedicated KMSAN fuzzing is not justified.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series introduces CONFIG_DEBUG_INFO_BTF_LAZY, which compresses the vmlinux BTF using zstd and lazily decompresses and parses it on first demand rather than at boot. It also implements deferred registration queues for kfuncs, dtor kfuncs, and struct_ops, as well as deferral for module split BTF loading.\n\n1. Analysis of Memory Allocation and Initialization:\n- All heap objects introduced or modified by the patch (such as `struct btf_deferred_reg` in btf_defer_reg() and `struct btf_module` in btf_module_notify()) are allocated using zero-initializing allocators (`kzalloc_obj`).\n- Buffer copies for deferred kfunc id sets, dtors, and module BTF data are cloned via `kmemdup`, `kmemdup_array`, and `kvmemdup`, duplicating already initialized data.\n- The vmlinux BTF raw buffer is allocated using `vmalloc_user()`, which zeroes allocated pages (`__GFP_ZERO`), and is populated by `zstd_decompress_dctx()`. The pointer is only published if decompression output exactly matches the expected size (`ret == *size`).\n- Stack variables (such as `zstd_frame_header hdr` in `btf_vmlinux_size()`) are guarded by error checks; `hdr.frameContentSize` is accessed only after `zstd_get_frame_header()` returns 0 (success). In `prog_ctx_tname()`, the out-pointer `*alt` is explicitly initialized to NULL before use.\n\n2. User Space Exposure and Info-leak Checks:\n- Data exposed to user space through `/sys/kernel/btf/vmlinux` via sysfs read and mmap operations maps or copies from the `vmalloc_user` buffer holding verified decompressed BTF data.\n- Similarly, trace events' BTF ID reads use `scnprintf` formatted into a stack buffer and copy only the formatted length via `simple_read_from_buffer`. There is no uninitialized memory or structure padding leaked to user space.\n\n3. KASAN vs KMSAN Applicability:\n- The risks introduced by this change involve synchronization, complex lock ordering (e.g., `btf_vmlinux_lock` vs `btf_module_mutex`, `cand_cache_mutex`, `event_mutex`), and object lifecycles across module load/unload transitions. These failure modes (deadlocks, use-after-free, double-free, NULL/ERR pointer dereferences) are detected by LOCKDEP and KASAN.\n- There are no uninitialized memory reads or uninitialized data leakage risks that uniquely require KMSAN.\n\nTherefore, dedicated KMSAN fuzzing is not justified.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)