AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/05 14:28 flow patch-triage
48m Args:
null

Results:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BPF_INSN_KFUNCS"
  ],
  "FocusSymbols": [
    "bpf_inline_kfunc_bodies",
    "bpf_restore_kfunc_calls",
    "bpf_mark_kfunc_body_regs",
    "bpf_jit_inline_kfunc",
    "kfunc_copy",
    "kfunc_copy_insn",
    "kfunc_bind",
    "btf_check_kfunc_body",
    "bpf_rol64",
    "bpf_select64",
    "bpf_extract64",
    "bpf_load_be64",
    "bpf_lea64"
  ],
  "KMSANReasoning": "The patch series introduces BPF inline kfuncs, allowing kfuncs to provide BPF instruction bodies and native x86-64 inline/copied implementations.\n\n1. Analysis of Memory Allocation and Initialization:\n- In `bpf_inline_kfunc_bodies()`, `env-\u003ekfunc_inlines` is allocated using `kvzalloc_objs`, ensuring all inline descriptors are zero-initialized.\n- In `bpf_add_kfunc_call()`, descriptor allocations are zeroed with `memset(desc, 0, sizeof(*desc))`.\n- When expanding `insn_aux_data` in `bpf_patch_insn_data()`, memory is allocated with `__GFP_ZERO`.\n- Stack buffers such as `code` in `bpf_restore_kfunc_calls()` and `kfunc_copy()` are written sequentially and completely up to the returned `len` bytes prior to `kmemdup()` and copying into the JIT image.\n\n2. Absence of Kernel-to-User Info-Leaks or Uninitialized Reads:\n- No new or modified kernel data structures are exposed to userspace via `copy_to_user`, netlink, socket options, or syscalls without full initialization.\n- Control flow and branching logic throughout the new verifier passes (`bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `kfunc_bind`, `bpf_restore_kfunc_calls`) depend only on initialized state fields, instruction opcodes, and BTF metadata.\n\n3. KASAN vs KMSAN Applicability:\n- Potential failure modes in this patch involve bounds checking during x86 instruction decoding/copying (`kfunc_copy`, `kfunc_copy_insn`), out-of-bounds indexing in `kfunc_bind()`, or invalid JIT native code generation. These are out-of-bounds access or control-flow bugs that fall within the scope of KASAN and standard kernel debuggers.\n- Furthermore, BPF JIT generated instructions are not instrumented by KMSAN.\n- As there are no uninitialized memory risks or kernel-to-user info-leak vectors unique to KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series introduces inline kfuncs in the BPF subsystem and the x86-64 BPF JIT compiler. The verifier inlines kfunc bodies during verification and restores calls or emits/copies native machine code during JIT compilation. This modifies core BPF verifier behavior, register state/liveness tracking, and x86 machine code generation/copying, which is directly reachable from unprivileged or privileged userspace via the bpf() syscall. Fuzzing is essential to test for verifier inconsistencies, register binding issues, and JIT instruction generation bugs.",
  "WorthFuzzing": true
}

1/1 2026/10/05 14:28 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit b05094a96f90fd89caede9601c328198860eabdc\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Mon Oct 5 14:28:34 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/bpf/kfuncs.rst b/Documentation/bpf/kfuncs.rst\nindex 73578a4c3b1fb..432e61a82aa9d 100644\n--- a/Documentation/bpf/kfuncs.rst\n+++ b/Documentation/bpf/kfuncs.rst\n@@ -695,6 +695,59 @@ verified inline, so an unassigned R2 is simply passed back to the caller as\n uninitialized and only a caller that reads it fails. A stack pointer left in\n R2 is still rejected there, just as one in R0 is.\n \n+2.10 Inline kfuncs\n+------------------\n+\n+A kfunc can come with a body: a few BPF instructions that compute it from its\n+arguments in R1-R5 into R0. The verifier then checks each call of the kfunc as\n+its body, so it knows as much about the result as if the program had computed\n+it in BPF, and the JIT puts native code in place of the call. Where the JIT has\n+no native code, the body runs in place of the call. BPF programs call such\n+kfuncs like any other, and arguments whose names end in ``__k`` must be known\n+constants (see section 2.3.2). ``CONFIG_BPF_INSN_KFUNCS`` provides\n+``bpf_rol64()``, ``bpf_select64()``, ``bpf_extract64()``, ``bpf_load_be64()``,\n+``bpf_prefetch()``, ``bpf_copy16()`` and ``bpf_lea64()``.\n+\n+The verifier replaces each call with the body before it analyzes the program.\n+Only the arguments are readable at the entry of the body, and R1-R5 are not\n+readable after it, as after a call. After the analysis, a call goes back into\n+the program if the JIT has native code for it, with its operands bound to the\n+registers that the moves around the call copied them from or to. The body stays\n+when the verifier rewrites it later, for example with speculation barriers,\n+when it accesses memory other than the stack, map values, memory and packets,\n+and when constant blinding is on.\n+\n+The native code comes from the kfunc set: an ``emit`` callback writes it for\n+the architecture, such as ``rol $13`` or ``movbe 8(%rdi)`` on x86-64. Without\n+``emit``, or when it has no code for the CPU, the x86-64 JIT copies the\n+compiled kfunc with its registers renamed. It copies only straight-line moves,\n+ALU instructions and address computations on the registers of a call, without\n+division or rip-relative addressing. Native code is trusted like the rest of\n+the JIT: it has to compute what the body computes, with the same memory\n+accesses.\n+\n+A kfunc set gives bodies to some of its kfuncs::\n+\n+        static const struct bpf_insn rol64_body[] = { ... };\n+\n+        static const struct bpf_kfunc_body bodies[] = {\n+                { \u0026body_ids[0], rol64_body, ARRAY_SIZE(rol64_body), rol64_emit },\n+        };\n+\n+        static const struct btf_kfunc_id_set kfunc_set = {\n+                .set      = \u0026kfunc_ids,\n+                .bodies   = bodies,\n+                .body_cnt = ARRAY_SIZE(bodies),\n+        };\n+\n+Registration checks each body: it may use R0-R5, ALU instructions, loads and\n+stores, and forward jumps that land within it, so that it ends by falling\n+through its last instruction, but not the sign extension, signed division and\n+byte swap of cpu v4, which not every JIT has. Each argument and the result must\n+fit in one register, and the kfunc may have no kfunc flags. ``emit`` writes at\n+most ``BPF_KFUNC_INLINE_MAX`` bytes. Modules give their kfuncs bodies and\n+native code in the same way.\n+\n .. _BPF_kfunc_lifecycle_expectations:\n \n 3. kfunc lifecycle expectations\ndiff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c\nindex 083fcd6cf15b7..6a57109caa97a 100644\n--- a/arch/x86/net/bpf_jit_comp.c\n+++ b/arch/x86/net/bpf_jit_comp.c\n@@ -15,8 +15,12 @@\n #include \u003clinux/memory.h\u003e\n #include \u003clinux/sort.h\u003e\n #include \u003clinux/execmem.h\u003e\n+#include \u003clinux/kallsyms.h\u003e\n+#include \u003clinux/uaccess.h\u003e\n #include \u003casm/extable.h\u003e\n #include \u003casm/ftrace.h\u003e\n+#include \u003casm/insn.h\u003e\n+#include \u003casm/insn-eval.h\u003e\n #include \u003casm/set_memory.h\u003e\n #include \u003casm/nospec-branch.h\u003e\n #include \u003casm/text-patching.h\u003e\n@@ -2000,6 +2004,174 @@ static int emit_kfunc_arena_args(struct bpf_prog *bpf_prog,\n \treturn prog - start;\n }\n \n+/*\n+ * Registers that copied kfunc code may use: those of R0-R5, which hold the\n+ * arguments and the result as for a call, and the scratch registers r10 and\n+ * r11. r9 can hold the private frame pointer.\n+ */\n+#define KFUNC_COPY_REGS\t(BIT(0) | BIT(1) | BIT(2) | BIT(6) | BIT(7) | BIT(8) | \\\n+\t\t\t BIT(10) | BIT(11))\n+\n+/*\n+ * Write an instruction of a compiled kfunc with the registers of R0-R5\n+ * renamed by @map to those that the verifier bound them to. It must be a\n+ * move, ALU or address computation without control flow, prefixes other than\n+ * operand size, rip-relative addressing or registers other than\n+ * KFUNC_COPY_REGS, and no division, which can trap.\n+ */\n+static u8 *kfunc_copy_insn(u8 *p, const struct insn *insn, const u8 *c, const u8 *map)\n+{\n+\tu8 op = insn-\u003eopcode.bytes[insn-\u003eopcode.nbytes - 1], rex = insn-\u003erex_prefix.bytes[0];\n+\tu8 modrm = insn-\u003emodrm.value, sib = insn-\u003esib.value, ext = X86_MODRM_REG(modrm);\n+\tu8 mod = X86_MODRM_MOD(modrm), reg = ext, rm = 0, idx = 4;\n+\tbool two = insn-\u003eopcode.nbytes == 2, group, opreg, disp8, implicit;\n+\tu16 regs = 0;\n+\tint head;\n+\n+\tif (insn-\u003evex_prefix.nbytes || insn-\u003eopcode.nbytes \u003e 2 || insn-\u003eprefixes.nbytes \u003e 1 ||\n+\t    (insn-\u003eprefixes.nbytes \u0026\u0026 insn-\u003eprefixes.bytes[0] != 0x66))\n+\t\treturn NULL;\n+\tif (two) {\n+\t\t/* cmovcc, imul, movzx/movsx of words, bswap, prefetch */\n+\t\tgroup = op == 0x18;\n+\t\tif ((op \u0026 0xf0) != 0x40 \u0026\u0026 op != 0xaf \u0026\u0026 op != 0xb7 \u0026\u0026 op != 0xbf \u0026\u0026\n+\t\t    (op \u0026 0xf8) != 0xc8 \u0026\u0026 !(group \u0026\u0026 ext \u003c 4))\n+\t\t\treturn NULL;\n+\t} else {\n+\t\t/* add, or, and, sub, xor, cmp, mov, lea, test, imul, shifts, not, neg, mul */\n+\t\tgroup = op == 0x81 || op == 0x83 || op == 0xc1 || op == 0xc7 ||\n+\t\t\top == 0xd1 || op == 0xd3 || op == 0xf7;\n+\t\tif (!(op \u003c 0x40 \u0026\u0026 (op \u0026 0xf0) != 0x10 \u0026\u0026 (op \u0026 7) % 2 \u0026\u0026 (op \u0026 7) \u003c 6) \u0026\u0026\n+\t\t    op != 0x63 \u0026\u0026 op != 0x69 \u0026\u0026 op != 0x6b \u0026\u0026 op != 0x85 \u0026\u0026 op != 0x89 \u0026\u0026\n+\t\t    op != 0x8b \u0026\u0026 op != 0x8d \u0026\u0026 op != 0x98 \u0026\u0026 op != 0x99 \u0026\u0026 op != 0xa9 \u0026\u0026\n+\t\t    (op \u0026 0xf8) != 0xb8 \u0026\u0026\n+\t\t    !(group \u0026\u0026 op != 0xc7 \u0026\u0026 op != 0xf7 \u0026\u0026 ext != 2 \u0026\u0026 ext != 3) \u0026\u0026\n+\t\t    !(op == 0xc7 \u0026\u0026 !ext) \u0026\u0026 !(op == 0xf7 \u0026\u0026 ext != 1 \u0026\u0026 ext \u003c 6))\n+\t\t\treturn NULL;\n+\t}\n+\n+\t/* uses %rax, %rcx or %rdx without naming it, as in \"and $imm, %eax\" */\n+\timplicit = !two \u0026\u0026 ((op \u003c 0x40 \u0026\u0026 (op \u0026 7) == 5) || op == 0x98 || op == 0x99 ||\n+\t\t\t    op == 0xa9 || op == 0xd3 || (op == 0xf7 \u0026\u0026 (ext == 4 || ext == 5)));\n+\n+\topreg = (op \u0026 0xf8) == (two ? 0xc8 : 0xb8);\n+\tif (opreg)\n+\t\trm = (op \u0026 7) + (X86_REX_B(rex) ? 8 : 0);\n+\tif (insn-\u003emodrm.nbytes) {\n+\t\treg = group ? ext : ext + (X86_REX_R(rex) ? 8 : 0);\n+\t\trm = (insn-\u003esib.nbytes ? X86_SIB_BASE(sib) : X86_MODRM_RM(modrm)) +\n+\t\t     (X86_REX_B(rex) ? 8 : 0);\n+\t\tif (insn-\u003esib.nbytes)\n+\t\t\tidx = X86_SIB_INDEX(sib) + (X86_REX_X(rex) ? 8 : 0);\n+\t\t/* rip-relative or absolute */\n+\t\tif (!mod \u0026\u0026 (rm \u0026 7) == 5)\n+\t\t\treturn NULL;\n+\t\tregs = (group ? 0 : BIT(reg)) | (idx != 4 ? BIT(idx) : 0);\n+\t}\n+\tif ((regs | (opreg || insn-\u003emodrm.nbytes ? BIT(rm) : 0)) \u0026 ~KFUNC_COPY_REGS)\n+\t\treturn NULL;\n+\t/* which cannot be renamed, so they must hold their operands as for a call */\n+\tif (implicit \u0026\u0026 (map[0] != 0 || map[1] != 1 || map[2] != 2))\n+\t\treturn NULL;\n+\n+\t/* the instruction again, with the registers renamed */\n+\tif (!group)\n+\t\treg = map[reg];\n+\trm = map[rm];\n+\tidx = idx != 4 ? map[idx] : 4;\n+\tif (insn-\u003eprefixes.nbytes)\n+\t\t*p++ = 0x66;\n+\trex = 0x40 | X86_REX_W(rex) | (reg \u0026 8 ? 4 : 0) | (idx \u0026 8 ? 2 : 0) | (rm \u0026 8 ? 1 : 0);\n+\tif (rex != 0x40)\n+\t\t*p++ = rex;\n+\tif (two)\n+\t\t*p++ = 0x0f;\n+\t*p++ = opreg ? (op \u0026 0xf8) | (rm \u0026 7) : op;\n+\tif (insn-\u003emodrm.nbytes) {\n+\t\t/* a base of r13 needs a displacement */\n+\t\tdisp8 = !mod \u0026\u0026 (rm \u0026 7) == 5;\n+\t\t*p++ = (disp8 ? 1 : mod) \u003c\u003c 6 | (reg \u0026 7) \u003c\u003c 3 | (insn-\u003esib.nbytes ? 4 : rm \u0026 7);\n+\t\tif (insn-\u003esib.nbytes)\n+\t\t\t*p++ = (sib \u0026 0xc0) | (idx \u0026 7) \u003c\u003c 3 | (rm \u0026 7);\n+\t\tif (disp8)\n+\t\t\t*p++ = 0;\n+\t}\n+\thead = insn-\u003eprefixes.nbytes + insn-\u003erex_prefix.nbytes + insn-\u003eopcode.nbytes +\n+\t       insn-\u003emodrm.nbytes + insn-\u003esib.nbytes;\n+\tmemcpy(p, c + head, insn-\u003elength - head);\n+\treturn p + insn-\u003elength - head;\n+}\n+\n+/*\n+ * Copy the compiled kfunc of an inlined call up to its return, without the\n+ * ENDBR and NOPs at its entry, with the operands renamed by @map.\n+ */\n+static int kfunc_copy(const struct bpf_kfunc_inline *in, const u8 *map, u8 *buf)\n+{\n+\tu8 code[BPF_KFUNC_INLINE_MAX + MAX_INSN_SIZE], *c, *p = buf;\n+\tunsigned long size, off, ret;\n+\tstruct insn insn;\n+\tint pos;\n+\n+\tif (!kallsyms_lookup_size_offset(in-\u003eaddr, \u0026size, \u0026off) || off)\n+\t\treturn -EINVAL;\n+\tsize = min(size, sizeof(code));\n+\tif (copy_from_kernel_nofault(code, (void *)in-\u003eaddr, size))\n+\t\treturn -EFAULT;\n+\tfor (pos = 0; pos \u003c size; pos += insn.length) {\n+\t\tif (insn_decode(\u0026insn, code + pos, size - pos, INSN_MODE_64))\n+\t\t\treturn -EINVAL;\n+\t\tc = code + pos;\n+\t\t/* ret, or a jump to the return thunk */\n+\t\tret = in-\u003eaddr + pos + insn.length + insn.immediate.value;\n+\t\tif ((insn.length == 1 \u0026\u0026 c[0] == 0xc3) ||\n+\t\t    (c[0] == 0xe9 \u0026\u0026 (ret == (unsigned long)x86_return_thunk ||\n+\t\t\t\t      ret == (unsigned long)__x86_return_thunk)))\n+\t\t\treturn p \u003e buf ? p - buf : -EINVAL;\n+\t\tif ((insn.length == 4 \u0026\u0026 is_endbr((u32 *)c)) || insn_is_nop(\u0026insn))\n+\t\t\tcontinue;\n+\t\tif (insn_is_rex2(\u0026insn))\n+\t\t\treturn -EINVAL;\n+\t\t/* renaming adds at most a REX prefix and a displacement */\n+\t\tif (p - buf + insn.length + 2 \u003e BPF_KFUNC_INLINE_MAX)\n+\t\t\treturn -E2BIG;\n+\t\tp = kfunc_copy_insn(p, \u0026insn, c, map);\n+\t\tif (!p)\n+\t\t\treturn -EINVAL;\n+\t}\n+\treturn -EINVAL;\n+}\n+\n+static u8 x86_reg(u32 reg)\n+{\n+\treturn reg2hex[reg] + (is_ereg(reg) ? 8 : 0);\n+}\n+\n+/*\n+ * Get native code for an inlined kfunc call, with the operands in the x86\n+ * registers that the verifier bound them to: the code from the emit callback\n+ * of the kfunc's body, or else a copy of the compiled kfunc.\n+ */\n+int bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf)\n+{\n+\tu8 reg[MAX_BPF_FUNC_REG_ARGS + 1], map[16];\n+\tint i, len;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(map); i++)\n+\t\tmap[i] = i;\n+\tfor (i = BPF_REG_0; i \u003c= BPF_REG_5; i++) {\n+\t\treg[i] = x86_reg(in-\u003ereg[i]);\n+\t\tmap[x86_reg(i)] = reg[i];\n+\t}\n+\t/* copying needs the instruction decoder */\n+\tif (in-\u003ecopy \u0026\u0026 IS_ENABLED(CONFIG_INSTRUCTION_DECODER))\n+\t\treturn kfunc_copy(in, map, buf);\n+\tif (in-\u003ecopy || !in-\u003ebody-\u003eemit)\n+\t\treturn -EOPNOTSUPP;\n+\tlen = in-\u003ebody-\u003eemit(reg, in-\u003eimm, buf);\n+\treturn len \u003e 0 \u0026\u0026 len \u003c= BPF_KFUNC_INLINE_MAX ? len : -EINVAL;\n+}\n+\n static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *addrs, u8 *image,\n \t\t  u8 *rw_image, int oldproglen, struct jit_context *ctx, bool jmp_padding)\n {\n@@ -2952,6 +3124,15 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *\n \t\t\tif (!imm32)\n \t\t\t\treturn -EINVAL;\n \t\t\tif (src_reg == BPF_PSEUDO_KFUNC_CALL) {\n+\t\t\t\tconst struct bpf_kfunc_inline *in;\n+\n+\t\t\t\t/* an inlined kfunc call gets its native code */\n+\t\t\t\tin = bpf_kfunc_native(env, insn_idx);\n+\t\t\t\tif (in) {\n+\t\t\t\t\tmemcpy(prog, in-\u003eimage, in-\u003eimage_len);\n+\t\t\t\t\tprog += in-\u003eimage_len;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n \t\t\t\tfm = bpf_jit_find_kfunc_model(bpf_prog, insn);\n \t\t\t\tif (!fm)\n \t\t\t\t\treturn -EINVAL;\ndiff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h\nindex c51083c761cf2..571c8d4da3271 100644\n--- a/include/linux/bpf_verifier.h\n+++ b/include/linux/bpf_verifier.h\n@@ -634,6 +634,7 @@ struct bpf_insn_aux_data {\n \t\tenum bpf_reg_type ptr_type;\t/* pointer type for load/store insns */\n \t\tstruct bpf_map_ptr_state map_ptr_state;\n \t\ts32 call_imm;\t\t\t/* saved imm field of call insn */\n+\t\tu32 kfunc_inline;\t\t/* 1 + index into env-\u003ekfunc_inlines, at a call */\n \t\tu32 alu_limit;\t\t\t/* limit for add/sub register with pointer */\n \t\tstruct {\n \t\t\tu32 map_index;\t\t/* index into used_maps[] */\n@@ -683,6 +684,9 @@ struct bpf_insn_aux_data {\n \t */\n \tu8 fastcall_spills_num:3;\n \tu8 arg_prog:4;\n+\t/* insn belongs to the body of a kfunc call, see bpf_inline_kfunc_bodies() */\n+\tu8 kfunc_body:1;\n+\tu8 kfunc_body_entry:1;\n \n \t/* below fields are initialized once */\n \tunsigned int orig_idx; /* original instruction index */\n@@ -1083,6 +1087,8 @@ struct bpf_verifier_env {\n \tu32 scc_cnt;\n \tstruct bpf_iarray *succ;\n \tstruct bpf_iarray *gotox_tmp_buf;\n+\tstruct bpf_kfunc_inline *kfunc_inlines;\n+\tu32 kfunc_inline_cnt;\n };\n \n static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)\n@@ -1794,14 +1800,42 @@ enum bpf_reg_arg_type {\n #define MAX_KFUNC_CALL_DESCS (MAX_KFUNC_DESCS * 2)\n static_assert(MAX_KFUNC_CALL_DESCS \u003c= S16_MAX + 1);\n \n+/* A call of a kfunc with a body, which the verifier replaced by the body */\n+struct bpf_kfunc_inline {\n+\tstruct bpf_insn call;\n+\tconst struct bpf_kfunc_body *body;\n+\tunsigned long addr;\t\t/* of the compiled kfunc */\n+\tu8 *image;\t\t\t/* native code for the JIT */\n+\tu32 start;\n+\t/* the BPF registers that R0-R5 are bound to, and the constant arguments */\n+\tu8 reg[MAX_BPF_FUNC_REG_ARGS + 1];\n+\ts32 imm[MAX_BPF_FUNC_REG_ARGS + 1];\n+\tu8 image_len;\n+\tu8 nargs;\n+\tu8 imm_mask;\t/* R1-R5 that hold constant (__k) arguments */\n+\tbool entered;\t/* the verifier reached the body */\n+\tbool ret;\t/* the kfunc returns a value */\n+\tbool copy;\t/* the native code is a copy of the compiled kfunc */\n+};\n+\n struct bpf_kfunc_desc {\n \tstruct btf_func_model func_model;\n \tstruct bpf_func_proto proto;\n+\tconst struct bpf_kfunc_body *body;\n \tu32 func_id;\n \tu16 offset;\n+\tu8 body_imm;\t/* R1-R5 that are constant (__k) arguments of the body */\n \tunsigned long addr;\n };\n \n+struct bpf_kfunc_desc *bpf_find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset);\n+int bpf_inline_kfunc_bodies(struct bpf_verifier_env *env);\n+int bpf_mark_kfunc_body_regs(struct bpf_verifier_env *env, int prev_insn_idx,\n+\t\t\t     const struct bpf_insn_aux_data *aux);\n+void bpf_restore_kfunc_calls(struct bpf_verifier_env *env);\n+void bpf_free_kfunc_inlines(struct bpf_verifier_env *env);\n+const struct bpf_kfunc_inline *bpf_kfunc_native(const struct bpf_verifier_env *env, int idx);\n+\n struct bpf_kfunc_desc_tab {\n \tu32 nr_descs;\n \tu32 nr_base_descs;\ndiff --git a/include/linux/btf.h b/include/linux/btf.h\nindex 4b63bb91550a1..1e7e52e778d82 100644\n--- a/include/linux/btf.h\n+++ b/include/linux/btf.h\n@@ -120,10 +120,36 @@ struct bpf_prog;\n \n typedef int (*btf_kfunc_filter_t)(const struct bpf_prog *prog, u32 kfunc_id);\n \n+#define BPF_KFUNC_BODY_MAX_INSNS\t32\n+#define BPF_KFUNC_INLINE_MAX\t\t128\n+\n+/*\n+ * The body of a kfunc: len BPF instructions that compute the kfunc from its\n+ * arguments in R1-R5 into R0. The verifier analyzes each call of the kfunc as\n+ * the body, and the body runs in place of the call unless the JIT has native\n+ * code for it, see kernel/bpf/kfunc_inline.c.\n+ *\n+ * emit, if set, writes native code for a call to buf, at most\n+ * BPF_KFUNC_INLINE_MAX bytes, and returns its length, or an error if it has\n+ * no code, for example because the CPU lacks a feature; the JIT then copies\n+ * the compiled kfunc. reg[i] is the native register that the verifier bound\n+ * Ri to, for R0-R5, and those of R1-R5 that are not arguments are free to\n+ * use. imm[i] is the value of Ri if it is a constant (__k) argument. Like the\n+ * rest of the JIT, native code is trusted to compute what the body computes.\n+ */\n+struct bpf_kfunc_body {\n+\tconst u32 *id;\n+\tconst struct bpf_insn *insns;\n+\tu32 len;\n+\tint (*emit)(const u8 *reg, const s32 *imm, u8 *buf);\n+};\n+\n struct btf_kfunc_id_set {\n \tstruct module *owner;\n \tstruct btf_id_set8 *set;\n \tbtf_kfunc_filter_t filter;\n+\tconst struct bpf_kfunc_body *bodies;\n+\tu32 body_cnt;\n };\n \n struct btf_id_dtor_kfunc {\n@@ -604,6 +630,7 @@ const char *btf_str_by_offset(const struct btf *btf, u32 offset);\n struct btf *btf_parse_vmlinux(void);\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+const struct bpf_kfunc_body *btf_find_kfunc_body(const struct btf *btf, u32 kfunc_btf_id);\n int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag);\n bool btf_kfunc_is_allowed(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog);\n u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,\ndiff --git a/include/linux/filter.h b/include/linux/filter.h\nindex 9339c6131f8ff..d93629eb40cd3 100644\n--- a/include/linux/filter.h\n+++ b/include/linux/filter.h\n@@ -1239,6 +1239,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr\n void bpf_jit_compile(struct bpf_prog *prog);\n bool bpf_jit_needs_zext(void);\n bool bpf_jit_inlines_helper_call(s32 imm);\n+struct bpf_kfunc_inline;\n+int bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf);\n bool bpf_jit_supports_subprog_tailcalls(void);\n bool bpf_jit_supports_percpu_insn(void);\n bool bpf_jit_supports_kfunc_call(void);\ndiff --git a/kernel/bpf/Kconfig b/kernel/bpf/Kconfig\nindex 98493e32db2ad..ca0dbfa1f81c5 100644\n--- a/kernel/bpf/Kconfig\n+++ b/kernel/bpf/Kconfig\n@@ -101,6 +101,7 @@ config BPF_CRYPTO\n \t  data. The supported algorithms are AES-CBC and AES-ECB.\n \n source \"kernel/bpf/preload/Kconfig\"\n+source \"kernel/bpf/insn_kfuncs/Kconfig\"\n \n config BPF_LSM\n \tbool \"Enable BPF LSM Instrumentation\"\ndiff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile\nindex c1f9b0d3468d3..94c81491a8e65 100644\n--- a/kernel/bpf/Makefile\n+++ b/kernel/bpf/Makefile\n@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_\n obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o\n obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o\n obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o\n-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o\n+obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o kfunc_inline.o\n obj-${CONFIG_BPF_LSM}\t  += bpf_inode_storage.o\n obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o\n obj-$(CONFIG_BPF_JIT) += trampoline.o\n@@ -60,6 +60,7 @@ obj-${CONFIG_BPF_LSM} += bpf_lsm_proto.o bpf_lsm.o\n endif\n obj-$(CONFIG_BPF_CRYPTO) += crypto.o\n obj-$(CONFIG_BPF_PRELOAD) += preload/\n+obj-$(CONFIG_BPF_INSN_KFUNCS) += insn_kfuncs/\n \n obj-$(CONFIG_BPF_SYSCALL) += relo_core.o\n obj-$(CONFIG_BPF_SYSCALL) += btf_iter.o\ndiff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c\nindex 0630675377aaa..4b729d0367bb2 100644\n--- a/kernel/bpf/btf.c\n+++ b/kernel/bpf/btf.c\n@@ -246,6 +246,14 @@ struct btf_id_dtor_kfunc_tab {\n \tstruct btf_id_dtor_kfunc dtors[];\n };\n \n+struct btf_kfunc_body_tab {\n+\tu32 cnt;\n+\tstruct {\n+\t\tu32 id;\n+\t\tconst struct bpf_kfunc_body *body;\n+\t} bodies[];\n+};\n+\n struct btf_struct_ops_tab {\n \tu32 cnt;\n \tu32 capacity;\n@@ -269,6 +277,7 @@ struct btf {\n \tstruct rcu_head rcu;\n \tstruct btf_kfunc_set_tab *kfunc_set_tab;\n \tstruct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;\n+\tstruct btf_kfunc_body_tab *kfunc_body_tab;\n \tstruct btf_struct_metas *struct_meta_tab;\n \tstruct btf_struct_ops_tab *struct_ops_tab;\n \tstruct btf_layout *layout;\n@@ -1883,6 +1892,7 @@ static void btf_free(struct btf *btf)\n \tbtf_free_struct_meta_tab(btf);\n \tbtf_free_dtor_kfunc_tab(btf);\n \tbtf_free_kfunc_set_tab(btf);\n+\tkfree(btf-\u003ekfunc_body_tab);\n \tbtf_free_struct_ops_tab(btf);\n \tkvfree(btf-\u003etypes);\n \tkvfree(btf-\u003eresolved_sizes);\n@@ -9695,6 +9705,118 @@ 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+const struct bpf_kfunc_body *btf_find_kfunc_body(const struct btf *btf, u32 kfunc_btf_id)\n+{\n+\tconst struct btf_kfunc_body_tab *tab = btf-\u003ekfunc_body_tab;\n+\tu32 i;\n+\n+\tfor (i = 0; tab \u0026\u0026 i \u003c tab-\u003ecnt; i++)\n+\t\tif (tab-\u003ebodies[i].id == kfunc_btf_id)\n+\t\t\treturn tab-\u003ebodies[i].body;\n+\treturn NULL;\n+}\n+\n+/* a scalar or a pointer of one register */\n+static bool btf_kfunc_reg_type(const struct btf *btf, u32 id)\n+{\n+\tconst struct btf_type *t = btf_type_skip_modifiers(btf, id, NULL);\n+\n+\treturn btf_type_is_ptr(t) ||\n+\t       ((btf_type_is_int(t) || btf_is_any_enum(t)) \u0026\u0026 t-\u003esize \u003c= sizeof(u64));\n+}\n+\n+/*\n+ * A kfunc with a body takes each argument in one of R1-R5, constant (__k)\n+ * ones in 32 bits for native code, and returns in R0. Its body uses R0-R5,\n+ * no instruction of cpu v4, which not every JIT has, and jumps only forward\n+ * within it, so that it ends by falling through the last instruction. The\n+ * verifier checks the rest.\n+ */\n+static bool btf_check_kfunc_body(const struct btf *btf, const struct btf_type *func,\n+\t\t\t\t const struct bpf_kfunc_body *b)\n+{\n+\tconst struct btf_type *proto = btf_type_by_id(btf, func-\u003etype);\n+\tconst struct btf_param *args = btf_params(proto);\n+\tint i, n = btf_type_vlen(proto), len = b-\u003elen;\n+\tconst struct bpf_insn *insn;\n+\tu8 op;\n+\n+\tif (n \u003e MAX_BPF_FUNC_REG_ARGS || !b-\u003einsns || !len || len \u003e BPF_KFUNC_BODY_MAX_INSNS ||\n+\t    (proto-\u003etype \u0026\u0026 !btf_kfunc_reg_type(btf, proto-\u003etype)))\n+\t\treturn false;\n+\tfor (i = 0; i \u003c n; i++)\n+\t\tif (!btf_kfunc_reg_type(btf, args[i].type) ||\n+\t\t    (btf_param_match_suffix(btf, \u0026args[i], \"__k\") \u0026\u0026\n+\t\t     btf_type_skip_modifiers(btf, args[i].type, NULL)-\u003esize \u003e sizeof(s32)))\n+\t\t\treturn false;\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tinsn = \u0026b-\u003einsns[i];\n+\t\top = BPF_OP(insn-\u003ecode);\n+\t\tif (insn-\u003edst_reg \u003e BPF_REG_5 || insn-\u003esrc_reg \u003e BPF_REG_5)\n+\t\t\treturn false;\n+\t\tswitch (BPF_CLASS(insn-\u003ecode)) {\n+\t\tcase BPF_ALU:\n+\t\tcase BPF_ALU64:\t\t/* not movsx, sdiv, smod or bswap */\n+\t\t\tif (insn-\u003eoff || (BPF_CLASS(insn-\u003ecode) == BPF_ALU64 \u0026\u0026 op == BPF_END))\n+\t\t\t\treturn false;\n+\t\t\tbreak;\n+\t\tcase BPF_LDX:\n+\t\tcase BPF_ST:\n+\t\tcase BPF_STX:\t\t/* not ldsx or atomics */\n+\t\t\tif (BPF_MODE(insn-\u003ecode) != BPF_MEM)\n+\t\t\t\treturn false;\n+\t\t\tbreak;\n+\t\tcase BPF_JMP:\n+\t\tcase BPF_JMP32:\t\t/* forward jumps within the body, not gotol */\n+\t\t\tif (op == BPF_CALL || op == BPF_EXIT || op == BPF_JCOND ||\n+\t\t\t    (op == BPF_JA \u0026\u0026 insn-\u003ecode != (BPF_JMP | BPF_JA)) ||\n+\t\t\t    insn-\u003eoff \u003c 0 || insn-\u003eoff \u003e= len - i - 1)\n+\t\t\t\treturn false;\n+\t\t\tbreak;\n+\t\tdefault:\t\t/* not ld_imm64 */\n+\t\t\treturn false;\n+\t\t}\n+\t}\n+\treturn true;\n+}\n+\n+static int btf_add_kfunc_bodies(struct btf *btf, const struct btf_kfunc_id_set *kset)\n+{\n+\tu32 i, id, cnt = btf-\u003ekfunc_body_tab ? btf-\u003ekfunc_body_tab-\u003ecnt : 0;\n+\tstruct btf_kfunc_body_tab *tab;\n+\tconst struct bpf_kfunc_body *b;\n+\tconst struct btf_type *t;\n+\tu32 *pair;\n+\n+\tif (!kset-\u003ebody_cnt)\n+\t\treturn 0;\n+\ttab = krealloc(btf-\u003ekfunc_body_tab, struct_size(tab, bodies, cnt + kset-\u003ebody_cnt),\n+\t\t       GFP_KERNEL | __GFP_NOWARN);\n+\tif (!tab)\n+\t\treturn -ENOMEM;\n+\ttab-\u003ecnt = cnt;\n+\tbtf-\u003ekfunc_body_tab = tab;\n+\tfor (i = 0; i \u003c kset-\u003ebody_cnt; i++) {\n+\t\tb = \u0026kset-\u003ebodies[i];\n+\t\tid = btf_relocate_id(btf, *b-\u003eid);\n+\t\tt = btf_type_by_id(btf, id);\n+\t\tpair = btf_id_set8_contains(kset-\u003eset, *b-\u003eid);\n+\t\t/* the body stands for the call, so no kfunc flags apply */\n+\t\tif (!pair || pair[1] || !t || !btf_type_is_func(t) ||\n+\t\t    !btf_check_kfunc_body(btf, t, b)) {\n+\t\t\t/* a set that fails to register leaves no bodies */\n+\t\t\ttab-\u003ecnt = cnt;\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\t/* a set registered for several hooks adds its bodies once */\n+\t\tif (!btf_find_kfunc_body(btf, id)) {\n+\t\t\ttab-\u003ebodies[tab-\u003ecnt].id = id;\n+\t\t\ttab-\u003ebodies[tab-\u003ecnt++].body = b;\n+\t\t}\n+\t}\n+\treturn 0;\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@@ -9714,6 +9836,10 @@ static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,\n \t\t\tgoto err_out;\n \t}\n \n+\tret = btf_add_kfunc_bodies(btf, kset);\n+\tif (ret)\n+\t\tgoto err_out;\n+\n \tret = btf_populate_kfunc_set(btf, hook, kset);\n \n err_out:\ndiff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c\nindex b1528adbeb79d..8fa745e62e7ee 100644\n--- a/kernel/bpf/const_fold.c\n+++ b/kernel/bpf/const_fold.c\n@@ -268,6 +268,10 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)\n \t\tmemcpy(ci_out, ci, sizeof(ci_out));\n \n \t\tconst_reg_xfer(env, ci_out, insn, insns, idx);\n+\t\t/* the body of a kfunc call leaves R0-R5 unknown, like the call */\n+\t\tif (insn_aux[idx].kfunc_body)\n+\t\t\tfor (r = BPF_REG_0; r \u003c= BPF_REG_5; r++)\n+\t\t\t\tci_out[r] = unknown;\n \n \t\tsucc = bpf_insn_successors(env, idx);\n \t\tfor (int s = 0; s \u003c succ-\u003ecnt; s++)\ndiff --git a/kernel/bpf/core.c b/kernel/bpf/core.c\nindex 05c89396119ad..68665ea2499e9 100644\n--- a/kernel/bpf/core.c\n+++ b/kernel/bpf/core.c\n@@ -3299,6 +3299,15 @@ bool __weak bpf_jit_inlines_helper_call(s32 imm)\n \treturn false;\n }\n \n+/* Write native code for an inlined kfunc call, see struct bpf_kfunc_inline,\n+ * to @buf for the JIT to copy. Return its length, or an error to keep the\n+ * body of the kfunc.\n+ */\n+int __weak bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf)\n+{\n+\treturn -EOPNOTSUPP;\n+}\n+\n /* Return TRUE if the JIT backend supports mixing bpf2bpf and tailcalls. */\n bool __weak bpf_jit_supports_subprog_tailcalls(void)\n {\ndiff --git a/kernel/bpf/insn_kfuncs/Kconfig b/kernel/bpf/insn_kfuncs/Kconfig\nnew file mode 100644\nindex 0000000000000..179236855d652\n--- /dev/null\n+++ b/kernel/bpf/insn_kfuncs/Kconfig\n@@ -0,0 +1,16 @@\n+# SPDX-License-Identifier: GPL-2.0-only\n+config BPF_INSN_KFUNCS\n+\ttristate \"Kfuncs for CPU instructions that BPF lacks\"\n+\tdepends on BPF_SYSCALL \u0026\u0026 BPF_JIT \u0026\u0026 DEBUG_INFO_BTF\n+\thelp\n+\t  Provide kfuncs for rotate, conditional select, bit field extract,\n+\t  big-endian load, prefetch, 16-byte copy and address computation.\n+\t  The verifier checks each call as the kfunc's BPF body, and the JIT\n+\t  puts native code in its place where it can.\n+\n+\t  If unsure, say N.\n+\n+config BPF_INSN_KFUNCS_ARCH\n+\tbool\n+\tdepends on BPF_INSN_KFUNCS\n+\tdefault y if X86_64\ndiff --git a/kernel/bpf/insn_kfuncs/Makefile b/kernel/bpf/insn_kfuncs/Makefile\nnew file mode 100644\nindex 0000000000000..31e7ef567c90f\n--- /dev/null\n+++ b/kernel/bpf/insn_kfuncs/Makefile\n@@ -0,0 +1,5 @@\n+# SPDX-License-Identifier: GPL-2.0\n+obj-$(CONFIG_BPF_INSN_KFUNCS) += bpf_insn_kfuncs.o\n+ifeq ($(CONFIG_BPF_INSN_KFUNCS_ARCH),y)\n+CFLAGS_bpf_insn_kfuncs.o += -I$(src)/$(SRCARCH)\n+endif\ndiff --git a/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c b/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c\nnew file mode 100644\nindex 0000000000000..1fcd0d7d0690c\n--- /dev/null\n+++ b/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c\n@@ -0,0 +1,184 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Kfuncs for CPU instructions that BPF lacks, with BPF bodies, see struct\n+ * bpf_kfunc_body. Arguments named __k must be known constants.\n+ */\n+#include \u003clinux/bitops.h\u003e\n+#include \u003clinux/btf.h\u003e\n+#include \u003clinux/btf_ids.h\u003e\n+#include \u003clinux/filter.h\u003e\n+#include \u003clinux/module.h\u003e\n+#include \u003clinux/unaligned.h\u003e\n+\n+__bpf_kfunc_start_defs();\n+\n+__bpf_kfunc u64 bpf_rol64(u64 x, u32 n__k)\n+{\n+\treturn rol64(x, n__k);\n+}\n+\n+__bpf_kfunc u64 bpf_select64(u64 cond, u64 a, u64 b)\n+{\n+\treturn cond ? a : b;\n+}\n+\n+__bpf_kfunc u64 bpf_extract64(u64 x, u32 start__k, u32 len__k)\n+{\n+\treturn x \u003c\u003c (64 - start__k - len__k) \u003e\u003e (64 - len__k);\n+}\n+\n+__bpf_kfunc u64 bpf_load_be64(const void *p, s32 off__k)\n+{\n+\treturn get_unaligned_be64(p + off__k);\n+}\n+\n+__bpf_kfunc void bpf_prefetch(const void *p)\n+{\n+\t/* not prefetch(), which boot-time alternatives may rewrite */\n+\t__builtin_prefetch(p);\n+}\n+\n+__bpf_kfunc void bpf_copy16(void *dst, const void *src)\n+{\n+\t/* both loads first, as in the body, in case the buffers overlap */\n+\tu64 lo = get_unaligned((const u64 *)src);\n+\tu64 hi = get_unaligned((const u64 *)(src + 8));\n+\n+\tput_unaligned(lo, (u64 *)dst);\n+\tput_unaligned(hi, (u64 *)(dst + 8));\n+}\n+\n+__bpf_kfunc u64 bpf_lea64(u64 base, u64 index, u32 scale__k, s32 disp__k)\n+{\n+\treturn base + index * scale__k + disp__k;\n+}\n+\n+__bpf_kfunc_end_defs();\n+\n+/* x \u003c\u003c n | x \u003e\u003e (-n \u0026 63) */\n+static const struct bpf_insn rol64_body[] = {\n+\tBPF_ALU64_IMM(BPF_AND, BPF_REG_2, 63),\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+\tBPF_ALU64_REG(BPF_LSH, BPF_REG_0, BPF_REG_2),\n+\tBPF_ALU64_IMM(BPF_NEG, BPF_REG_2, 0),\n+\tBPF_ALU64_IMM(BPF_AND, BPF_REG_2, 63),\n+\tBPF_ALU64_REG(BPF_RSH, BPF_REG_1, BPF_REG_2),\n+\tBPF_ALU64_REG(BPF_OR, BPF_REG_0, BPF_REG_1),\n+};\n+\n+/* the jump lands within the body, here on its last instruction */\n+static const struct bpf_insn select64_body[] = {\n+\tBPF_JMP_IMM(BPF_JNE, BPF_REG_1, 0, 1),\n+\tBPF_MOV64_REG(BPF_REG_2, BPF_REG_3),\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_2),\n+};\n+\n+/* x \u003c\u003c (64 - start - len) \u003e\u003e (64 - len) */\n+static const struct bpf_insn extract64_body[] = {\n+\tBPF_MOV32_IMM(BPF_REG_4, 64),\n+\tBPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_2),\n+\tBPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_3),\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+\tBPF_ALU64_REG(BPF_LSH, BPF_REG_0, BPF_REG_4),\n+\tBPF_MOV32_IMM(BPF_REG_4, 64),\n+\tBPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_3),\n+\tBPF_ALU64_REG(BPF_RSH, BPF_REG_0, BPF_REG_4),\n+};\n+\n+/* the offset is an s32 */\n+static const struct bpf_insn load_be64_body[] = {\n+\tBPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 32),\n+\tBPF_ALU64_IMM(BPF_ARSH, BPF_REG_2, 32),\n+\tBPF_ALU64_REG(BPF_ADD, BPF_REG_1, BPF_REG_2),\n+\tBPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, 0),\n+\tBPF_ENDIAN(BPF_TO_BE, BPF_REG_0, 64),\n+};\n+\n+/* a load whose value is not used, of memory that the program may read */\n+static const struct bpf_insn prefetch_body[] = {\n+\tBPF_LDX_MEM(BPF_B, BPF_REG_1, BPF_REG_1, 0),\n+};\n+\n+/* two loads, then two stores */\n+static const struct bpf_insn copy16_body[] = {\n+\tBPF_LDX_MEM(BPF_DW, BPF_REG_4, BPF_REG_2, 0),\n+\tBPF_LDX_MEM(BPF_DW, BPF_REG_5, BPF_REG_2, 8),\n+\tBPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_4, 0),\n+\tBPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_5, 8),\n+};\n+\n+/* base + index * scale + disp, scale a u32 and disp an s32 */\n+static const struct bpf_insn lea64_body[] = {\n+\tBPF_MOV32_REG(BPF_REG_3, BPF_REG_3),\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_2),\n+\tBPF_ALU64_REG(BPF_MUL, BPF_REG_0, BPF_REG_3),\n+\tBPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1),\n+\tBPF_ALU64_IMM(BPF_LSH, BPF_REG_4, 32),\n+\tBPF_ALU64_IMM(BPF_ARSH, BPF_REG_4, 32),\n+\tBPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_4),\n+};\n+\n+#ifdef CONFIG_BPF_INSN_KFUNCS_ARCH\n+#include \"insn_kfuncs.h\" /* $(SRCARCH)/insn_kfuncs.h */\n+#else\n+#define rol64_emit\tNULL\n+#define select64_emit\tNULL\n+#define extract64_emit\tNULL\n+#define load_be64_emit\tNULL\n+#define lea64_emit\tNULL\n+#endif\n+\n+BTF_KFUNCS_START(insn_kfunc_ids)\n+BTF_ID_FLAGS(func, bpf_rol64)\n+BTF_ID_FLAGS(func, bpf_select64)\n+BTF_ID_FLAGS(func, bpf_extract64)\n+BTF_ID_FLAGS(func, bpf_load_be64)\n+BTF_ID_FLAGS(func, bpf_prefetch)\n+BTF_ID_FLAGS(func, bpf_copy16)\n+BTF_ID_FLAGS(func, bpf_lea64)\n+BTF_KFUNCS_END(insn_kfunc_ids)\n+\n+BTF_ID_LIST(body_ids)\n+BTF_ID(func, bpf_rol64)\n+BTF_ID(func, bpf_select64)\n+BTF_ID(func, bpf_extract64)\n+BTF_ID(func, bpf_load_be64)\n+BTF_ID(func, bpf_prefetch)\n+BTF_ID(func, bpf_copy16)\n+BTF_ID(func, bpf_lea64)\n+\n+#define BODY(i, op, emit)\t{ \u0026body_ids[i], op##_body, ARRAY_SIZE(op##_body), emit }\n+\n+/* without emit, the JIT copies the kfunc, whose code is the instruction itself */\n+static const struct bpf_kfunc_body bodies[] = {\n+\tBODY(0, rol64, rol64_emit),\n+\tBODY(1, select64, select64_emit),\n+\tBODY(2, extract64, extract64_emit),\n+\tBODY(3, load_be64, load_be64_emit),\n+\tBODY(4, prefetch, NULL),\n+\tBODY(5, copy16, NULL),\n+\tBODY(6, lea64, lea64_emit),\n+};\n+\n+static const struct btf_kfunc_id_set insn_kfunc_set = {\n+\t.owner    = THIS_MODULE,\n+\t.set      = \u0026insn_kfunc_ids,\n+\t.bodies   = bodies,\n+\t.body_cnt = ARRAY_SIZE(bodies),\n+};\n+\n+static int __init insn_kfuncs_init(void)\n+{\n+\treturn register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, \u0026insn_kfunc_set);\n+}\n+\n+/* the kfunc set goes away with the module's BTF */\n+static void __exit insn_kfuncs_exit(void)\n+{\n+}\n+\n+module_init(insn_kfuncs_init);\n+module_exit(insn_kfuncs_exit);\n+\n+MODULE_DESCRIPTION(\"Kfuncs for CPU instructions that BPF lacks\");\n+MODULE_LICENSE(\"GPL\");\ndiff --git a/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h b/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h\nnew file mode 100644\nindex 0000000000000..5809bb69b4cd6\n--- /dev/null\n+++ b/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h\n@@ -0,0 +1,155 @@\n+/* SPDX-License-Identifier: GPL-2.0 */\n+/* x86-64 code for the kfuncs in bpf_insn_kfuncs.c, see struct bpf_kfunc_body */\n+#include \u003clinux/cpufeature.h\u003e\n+#include \u003clinux/log2.h\u003e\n+#include \u003clinux/unaligned.h\u003e\n+\n+static u8 *x86_rex(u8 *p, bool w, u8 reg, u8 rm)\n+{\n+\tu8 b = 0x40 | (w ? 8 : 0) | (reg \u0026 8 ? 4 : 0) | (rm \u0026 8 ? 1 : 0);\n+\n+\tif (b != 0x40)\n+\t\t*p++ = b;\n+\treturn p;\n+}\n+\n+/* 64-bit op %reg, %rm */\n+static u8 *x86_op_rr(u8 *p, u8 op, u8 reg, u8 rm)\n+{\n+\tp = x86_rex(p, true, reg, rm);\n+\t*p++ = op;\n+\t*p++ = 0xc0 | (reg \u0026 7) \u003c\u003c 3 | (rm \u0026 7);\n+\treturn p;\n+}\n+\n+/*\n+ * ModRM, SIB and displacement of disp(%base, %index, 1 \u003c\u003c scale), with @reg in\n+ * the reg field. An @index of 4 (%rsp) is none.\n+ */\n+static u8 *x86_mem(u8 *p, u8 reg, u8 base, u8 index, u8 scale, s32 disp)\n+{\n+\tu8 mod = !disp \u0026\u0026 (base \u0026 7) != 5 ? 0 : disp == (s8)disp ? 1 : 2;\n+\tbool sib = index != 4 || (base \u0026 7) == 4;\n+\n+\t*p++ = mod \u003c\u003c 6 | (reg \u0026 7) \u003c\u003c 3 | (sib ? 4 : base \u0026 7);\n+\tif (sib)\n+\t\t*p++ = scale \u003c\u003c 6 | (index \u0026 7) \u003c\u003c 3 | (base \u0026 7);\n+\tif (mod == 1)\n+\t\t*p++ = disp;\n+\tif (mod == 2) {\n+\t\tput_unaligned_le32(disp, p);\n+\t\tp += 4;\n+\t}\n+\treturn p;\n+}\n+\n+static int rol64_emit(const u8 *reg, const s32 *imm, u8 *buf)\n+{\n+\tu8 dst = reg[0], src = reg[1], n = imm[BPF_REG_2] \u0026 63, *p = buf;\n+\n+\tif (n \u0026\u0026 dst != src \u0026\u0026 cpu_feature_enabled(X86_FEATURE_BMI2)) {\n+\t\t/* rorx $(64 - n), %src, %dst */\n+\t\t*p++ = 0xc4;\n+\t\t*p++ = (dst \u0026 8 ? 0 : 0x80) | 0x40 | (src \u0026 8 ? 0 : 0x20) | 0x03;\n+\t\t*p++ = 0xfb;\n+\t\t*p++ = 0xf0;\n+\t\t*p++ = 0xc0 | (dst \u0026 7) \u003c\u003c 3 | (src \u0026 7);\n+\t\t*p++ = 64 - n;\n+\t\treturn p - buf;\n+\t}\n+\tif (dst != src || !n)\n+\t\tp = x86_op_rr(p, 0x89, src, dst);\t/* mov %src, %dst */\n+\tif (n) {\n+\t\t/* rol $n, %dst */\n+\t\tp = x86_rex(p, true, 0, dst);\n+\t\t*p++ = 0xc1;\n+\t\t*p++ = 0xc0 | (dst \u0026 7);\n+\t\t*p++ = n;\n+\t}\n+\treturn p - buf;\n+}\n+\n+/* cmovcc %src, %dst */\n+static u8 *x86_cmov(u8 *p, u8 cc, u8 dst, u8 src)\n+{\n+\tp = x86_rex(p, true, dst, src);\n+\t*p++ = 0x0f;\n+\t*p++ = 0x40 | cc;\n+\t*p++ = 0xc0 | (dst \u0026 7) \u003c\u003c 3 | (src \u0026 7);\n+\treturn p;\n+}\n+\n+/*\n+ * dst = cc ? a : b, after the test or compare at @p. The flags come first, so\n+ * the result may take the register of an operand they read. A result in the\n+ * register of a takes b with the inverse condition, which a copy of the\n+ * compiled kfunc cannot do.\n+ */\n+static int x86_select(u8 *buf, u8 *p, u8 cc, u8 dst, u8 a, u8 b)\n+{\n+\tif (dst == a)\n+\t\treturn x86_cmov(p, cc ^ 1, dst, b) - buf;\n+\tif (dst != b)\n+\t\tp = x86_op_rr(p, 0x89, b, dst);\t/* mov %b, %dst */\n+\treturn x86_cmov(p, cc, dst, a) - buf;\n+}\n+\n+static int select64_emit(const u8 *reg, const s32 *imm, u8 *buf)\n+{\n+\tu8 cond = reg[1];\n+\n+\t/* test %cond, %cond; cmovne */\n+\treturn x86_select(buf, x86_op_rr(buf, 0x85, cond, cond), 0x5, reg[0],\n+\t\t\t   reg[2], reg[3]);\n+}\n+\n+/* R4 is free for the control word, as there are three arguments */\n+static int extract64_emit(const u8 *reg, const s32 *imm, u8 *buf)\n+{\n+\tu8 dst = reg[0], src = reg[1], ctl = dst != src ? dst : reg[4];\n+\tu32 start = imm[BPF_REG_2], len = imm[BPF_REG_3];\n+\tu8 *p = buf;\n+\n+\tif (!cpu_feature_enabled(X86_FEATURE_BMI1) || start \u003e 63 || !len || len \u003e 64 - start)\n+\t\treturn -EOPNOTSUPP;\n+\t/* mov $(start | len \u003c\u003c 8), %ctl */\n+\tp = x86_rex(p, false, 0, ctl);\n+\t*p++ = 0xb8 | (ctl \u0026 7);\n+\tput_unaligned_le32(start | len \u003c\u003c 8, p);\n+\tp += 4;\n+\t/* bextr %ctl, %src, %dst */\n+\t*p++ = 0xc4;\n+\t*p++ = (dst \u0026 8 ? 0 : 0x80) | 0x40 | (src \u0026 8 ? 0 : 0x20) | 0x02;\n+\t*p++ = 0x80 | (~ctl \u0026 0xf) \u003c\u003c 3;\n+\t*p++ = 0xf7;\n+\t*p++ = 0xc0 | (dst \u0026 7) \u003c\u003c 3 | (src \u0026 7);\n+\treturn p - buf;\n+}\n+\n+static int load_be64_emit(const u8 *reg, const s32 *imm, u8 *buf)\n+{\n+\tu8 dst = reg[0], base = reg[1], *p = buf;\n+\n+\tif (!cpu_feature_enabled(X86_FEATURE_MOVBE))\n+\t\treturn -EOPNOTSUPP;\n+\t/* movbe off(%base), %dst */\n+\tp = x86_rex(p, true, dst, base);\n+\t*p++ = 0x0f;\n+\t*p++ = 0x38;\n+\t*p++ = 0xf0;\n+\treturn x86_mem(p, dst, base, 4, 0, imm[BPF_REG_2]) - buf;\n+}\n+\n+static int lea64_emit(const u8 *reg, const s32 *imm, u8 *buf)\n+{\n+\tu8 dst = reg[0], base = reg[1], index = reg[2], *p = buf;\n+\tu32 scale = imm[BPF_REG_3];\n+\n+\t/* %rsp cannot be an index, and the scale is 1, 2, 4 or 8 */\n+\tif (index == 4 || !is_power_of_2(scale) || scale \u003e 8)\n+\t\treturn -EOPNOTSUPP;\n+\t/* lea disp(%base, %index, scale), %dst */\n+\t*p++ = 0x48 | (dst \u0026 8 ? 4 : 0) | (index \u0026 8 ? 2 : 0) | (base \u0026 8 ? 1 : 0);\n+\t*p++ = 0x8d;\n+\treturn x86_mem(p, dst, base, index, ilog2(scale), imm[BPF_REG_4]) - buf;\n+}\ndiff --git a/kernel/bpf/kfunc_inline.c b/kernel/bpf/kfunc_inline.c\nnew file mode 100644\nindex 0000000000000..daf92c3ad512c\n--- /dev/null\n+++ b/kernel/bpf/kfunc_inline.c\n@@ -0,0 +1,273 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/* Calls of kfuncs that have a BPF body, see struct bpf_kfunc_body */\n+#include \u003clinux/bpf.h\u003e\n+#include \u003clinux/bpf_verifier.h\u003e\n+#include \u003clinux/filter.h\u003e\n+#include \u003clinux/slab.h\u003e\n+\n+#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)\n+\n+static struct bpf_kfunc_desc *body_desc(struct bpf_verifier_env *env,\n+\t\t\t\t\tconst struct bpf_insn *insn)\n+{\n+\tstruct bpf_kfunc_desc *desc;\n+\n+\tif (!bpf_pseudo_kfunc_call(insn))\n+\t\treturn NULL;\n+\tdesc = bpf_find_kfunc_desc(env-\u003eprog, insn-\u003eimm, insn-\u003eoff);\n+\treturn desc \u0026\u0026 desc-\u003ebody ? desc : NULL;\n+}\n+\n+/*\n+ * Replace each call of a kfunc with a body by the body, so that the verifier\n+ * analyzes the operation in the caller's context. The entry and exit of the\n+ * body get the register effects of the call, see bpf_mark_kfunc_body_regs().\n+ * After verification bpf_restore_kfunc_calls() puts the call back if the JIT\n+ * has native code for it, and keeps the body otherwise.\n+ */\n+int bpf_inline_kfunc_bodies(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_kfunc_desc *desc;\n+\tstruct bpf_kfunc_inline *r;\n+\tstruct bpf_prog *prog;\n+\tu32 i, j, cnt = 0;\n+\n+\tfor (i = 0; i \u003c env-\u003eprog-\u003elen; i++)\n+\t\tcnt += !!body_desc(env, \u0026env-\u003eprog-\u003einsnsi[i]);\n+\tif (!cnt)\n+\t\treturn 0;\n+\tenv-\u003ekfunc_inlines = kvzalloc_objs(*env-\u003ekfunc_inlines, cnt, GFP_KERNEL_ACCOUNT);\n+\tif (!env-\u003ekfunc_inlines)\n+\t\treturn -ENOMEM;\n+\n+\tfor (i = 0; i \u003c env-\u003eprog-\u003elen; i++) {\n+\t\tdesc = body_desc(env, \u0026env-\u003eprog-\u003einsnsi[i]);\n+\t\tif (!desc)\n+\t\t\tcontinue;\n+\t\tr = \u0026env-\u003ekfunc_inlines[env-\u003ekfunc_inline_cnt++];\n+\t\tr-\u003ecall = env-\u003eprog-\u003einsnsi[i];\n+\t\tr-\u003ebody = desc-\u003ebody;\n+\t\tr-\u003eaddr = desc-\u003eaddr;\n+\t\tr-\u003estart = i;\n+\t\tr-\u003enargs = desc-\u003efunc_model.nr_args;\n+\t\tr-\u003eimm_mask = desc-\u003ebody_imm;\n+\t\tr-\u003eret = desc-\u003efunc_model.ret_size;\n+\t\tprog = bpf_patch_insn_data(env, i, r-\u003ebody-\u003einsns, r-\u003ebody-\u003elen);\n+\t\tif (!prog)\n+\t\t\treturn -ENOMEM;\n+\t\tenv-\u003eprog = prog;\n+\t\tfor (j = i; j \u003c i + r-\u003ebody-\u003elen; j++)\n+\t\t\tenv-\u003einsn_aux_data[j].kfunc_body = 1;\n+\t\tenv-\u003einsn_aux_data[i].kfunc_body_entry = 1;\n+\t\ti += r-\u003ebody-\u003elen - 1;\n+\t}\n+\treturn 0;\n+}\n+\n+/*\n+ * The body of a kfunc gets only the arguments of the call and leaves R1-R5\n+ * like it. The constant (__k) arguments must be known, and native code may\n+ * use their values.\n+ */\n+int bpf_mark_kfunc_body_regs(struct bpf_verifier_env *env, int prev_insn_idx,\n+\t\t\t     const struct bpf_insn_aux_data *aux)\n+{\n+\tstruct bpf_kfunc_inline *r = env-\u003ekfunc_inlines;\n+\tstruct bpf_reg_state *regs = cur_regs(env);\n+\tu32 clobber = 0;\n+\tint i, err;\n+\n+\t/* leaving the body */\n+\tif (prev_insn_idx \u003e= 0 \u0026\u0026 env-\u003einsn_aux_data[prev_insn_idx].kfunc_body \u0026\u0026\n+\t    (!aux-\u003ekfunc_body || aux-\u003ekfunc_body_entry))\n+\t\tclobber |= GENMASK(BPF_REG_5, BPF_REG_1);\n+\tif (aux-\u003ekfunc_body_entry) {\n+\t\twhile (r-\u003estart != env-\u003einsn_idx)\n+\t\t\tr++;\n+\t\tfor (i = BPF_REG_1; i \u003c= BPF_REG_5 \u0026\u0026 !env-\u003ecur_state-\u003especulative; i++) {\n+\t\t\tif (!(r-\u003eimm_mask \u0026 BIT(i)))\n+\t\t\t\tcontinue;\n+\t\t\tif (regs[i].type != SCALAR_VALUE || !tnum_is_const(regs[i].var_off)) {\n+\t\t\t\tverbose(env, \"R%d must be a known constant\\n\", i);\n+\t\t\t\treturn -EINVAL;\n+\t\t\t}\n+\t\t\terr = mark_chain_precision(env, i);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t\t/* emitted code needs the same constants on every path */\n+\t\t\tif (r-\u003eentered \u0026\u0026 r-\u003eimm[i] != (s32)regs[i].var_off.value)\n+\t\t\t\tr-\u003ecopy = true;\n+\t\t\tr-\u003eimm[i] = regs[i].var_off.value;\n+\t\t}\n+\t\tr-\u003eentered = true;\n+\t\tclobber |= BIT(BPF_REG_0) | (GENMASK(BPF_REG_5, BPF_REG_0) \u0026\n+\t\t\t\t\t     ~GENMASK(r-\u003enargs, BPF_REG_0));\n+\t}\n+\tfor (i = BPF_REG_0; i \u003c= BPF_REG_5; i++) {\n+\t\tif (!(clobber \u0026 BIT(i)))\n+\t\t\tcontinue;\n+\t\tbpf_mark_reg_not_init(env, \u0026regs[i]);\n+\t\tmark_reg_scratched(env, i);\n+\t}\n+\treturn 0;\n+}\n+\n+/*\n+ * Native code can replace the body of a kfunc call that the verifier reached\n+ * and does not rewrite later: no speculation barriers, sanitation or arena\n+ * conversion, and memory accesses only to memory that the JIT accesses as is.\n+ */\n+static bool kfunc_native_ok(struct bpf_verifier_env *env, const struct bpf_kfunc_inline *r)\n+{\n+\tu32 i;\n+\n+\tif (env-\u003eprog-\u003eblinding_requested || (r-\u003eimm_mask \u0026\u0026 !r-\u003eentered))\n+\t\treturn false;\n+\tfor (i = 0; i \u003c r-\u003ebody-\u003elen; i++) {\n+\t\tconst struct bpf_insn_aux_data *aux = \u0026env-\u003einsn_aux_data[r-\u003estart + i];\n+\t\tu8 class = BPF_CLASS(r-\u003ebody-\u003einsns[i].code);\n+\n+\t\tif (aux-\u003enospec || aux-\u003enospec_result || aux-\u003ealu_state || aux-\u003eneeds_zext ||\n+\t\t    aux-\u003earena_scalar)\n+\t\t\treturn false;\n+\t\tif (class != BPF_LDX \u0026\u0026 class != BPF_STX \u0026\u0026 class != BPF_ST)\n+\t\t\tcontinue;\n+\t\tif (type_flag(aux-\u003eptr_type) \u0026 ~MEM_RDONLY)\n+\t\t\treturn false;\n+\t\tswitch (base_type(aux-\u003eptr_type)) {\n+\t\tcase PTR_TO_STACK:\n+\t\t\tbreak;\n+\t\tcase PTR_TO_MAP_VALUE:\n+\t\tcase PTR_TO_MEM:\n+\t\tcase PTR_TO_PACKET:\n+\t\tcase PTR_TO_PACKET_META:\n+\t\t\t/* the JIT checks these accesses with KASAN, native code does not */\n+\t\t\tif (IS_ENABLED(CONFIG_BPF_JIT_KASAN))\n+\t\t\t\treturn false;\n+\t\t\tbreak;\n+\t\tdefault:\n+\t\t\treturn false;\n+\t\t}\n+\t}\n+\treturn true;\n+}\n+\n+/*\n+ * Bind the operands of a kfunc call in r-\u003ereg and return the moves that this\n+ * makes unnecessary in @drop:\n+ * - an argument copied from R6-R9 by a 64-bit move right before the call is\n+ *   used in place if that register is dead after the call;\n+ * - emitted native code has the constant arguments as immediates;\n+ * - the result goes straight to its R6-R9 destination.\n+ * No jump may land between such a move and the call. Only emitted code may\n+ * share the result register with an argument.\n+ */\n+static int kfunc_bind(struct bpf_verifier_env *env, struct bpf_kfunc_inline *r, u32 *drop)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi, *mov;\n+\tu32 end = r-\u003estart + r-\u003ebody-\u003elen, i;\n+\tbool emit = !r-\u003ecopy;\n+\tu16 used = 0, written = 0;\n+\tu8 dst, src;\n+\tint n = 0;\n+\n+\tfor (i = 0; i \u003c= MAX_BPF_FUNC_REG_ARGS; i++)\n+\t\tr-\u003ereg[i] = i;\n+\n+\t/* walk back over moves into R1-R5 that do not read R0-R5 */\n+\tfor (i = r-\u003estart; i-- \u003e 0 \u0026\u0026 !bpf_is_jump_target(env, i + 1);) {\n+\t\tmov = \u0026insns[i];\n+\t\tdst = mov-\u003edst_reg;\n+\t\tsrc = mov-\u003esrc_reg;\n+\t\tif ((BPF_CLASS(mov-\u003ecode) != BPF_ALU64 \u0026\u0026 BPF_CLASS(mov-\u003ecode) != BPF_ALU) ||\n+\t\t    BPF_OP(mov-\u003ecode) != BPF_MOV || dst \u003c BPF_REG_1 || dst \u003e BPF_REG_5 ||\n+\t\t    aux[i].kfunc_body ||\n+\t\t    (BPF_SRC(mov-\u003ecode) == BPF_X \u0026\u0026 (src \u003c BPF_REG_6 || src \u003e BPF_REG_9)))\n+\t\t\tbreak;\n+\t\tif (dst \u003c= r-\u003enargs \u0026\u0026 !(written \u0026 BIT(dst)) \u0026\u0026 !mov-\u003eoff) {\n+\t\t\tif (BPF_SRC(mov-\u003ecode) == BPF_K \u0026\u0026 (r-\u003eimm_mask \u0026 BIT(dst)) \u0026\u0026 emit) {\n+\t\t\t\tdrop[n++] = i;\n+\t\t\t} else if (mov-\u003ecode == (BPF_ALU64 | BPF_MOV | BPF_X) \u0026\u0026\n+\t\t\t\t   !(used \u0026 BIT(src)) \u0026\u0026\n+\t\t\t\t   !(aux[end].live_regs_before \u0026 BIT(src))) {\n+\t\t\t\tr-\u003ereg[dst] = src;\n+\t\t\t\tused |= BIT(src);\n+\t\t\t\tdrop[n++] = i;\n+\t\t\t}\n+\t\t}\n+\t\twritten |= BIT(dst);\n+\t}\n+\n+\tmov = \u0026insns[end];\n+\tdst = mov-\u003edst_reg;\n+\t/* the result register must be live so that the JIT saves it */\n+\tif (r-\u003eret \u0026\u0026 !bpf_is_jump_target(env, end) \u0026\u0026 end + 1 \u003c env-\u003eprog-\u003elen \u0026\u0026\n+\t    mov-\u003ecode == (BPF_ALU64 | BPF_MOV | BPF_X) \u0026\u0026 !mov-\u003eoff \u0026\u0026\n+\t    mov-\u003esrc_reg == BPF_REG_0 \u0026\u0026 dst \u003e= BPF_REG_6 \u0026\u0026 dst \u003c= BPF_REG_9 \u0026\u0026\n+\t    (emit || !(used \u0026 BIT(dst))) \u0026\u0026\n+\t    (aux[end + 1].live_regs_before \u0026 BIT(dst)) \u0026\u0026\n+\t    !(aux[end + 1].live_regs_before \u0026 BIT(BPF_REG_0))) {\n+\t\tr-\u003ereg[BPF_REG_0] = dst;\n+\t\tdrop[n++] = end;\n+\t}\n+\treturn n;\n+}\n+\n+/*\n+ * Put back the calls that the JIT has native code for: the code from the\n+ * kfunc's emit callback, or else a copy of the compiled kfunc. The rest of\n+ * the body and the moves that binding makes unnecessary become nops, which\n+ * bpf_opt_remove_nops() removes. Other calls keep their body.\n+ */\n+void bpf_restore_kfunc_calls(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n+\tu32 drop[MAX_BPF_FUNC_REG_ARGS + 1];\n+\tu8 code[BPF_KFUNC_INLINE_MAX];\n+\tint i, j, n, len;\n+\n+\tfor (i = 0; i \u003c env-\u003ekfunc_inline_cnt; i++) {\n+\t\tstruct bpf_kfunc_inline *r = \u0026env-\u003ekfunc_inlines[i];\n+\n+\t\tif (!kfunc_native_ok(env, r))\n+\t\t\tcontinue;\n+\t\tn = kfunc_bind(env, r, drop);\n+\t\tlen = bpf_jit_inline_kfunc(r, code);\n+\t\tif (len \u003c= 0 \u0026\u0026 !r-\u003ecopy) {\n+\t\t\tr-\u003ecopy = true;\n+\t\t\tn = kfunc_bind(env, r, drop);\n+\t\t\tlen = bpf_jit_inline_kfunc(r, code);\n+\t\t}\n+\t\tr-\u003eimage = len \u003e 0 ? kmemdup(code, len, GFP_KERNEL_ACCOUNT) : NULL;\n+\t\tif (!r-\u003eimage)\n+\t\t\tcontinue;\n+\t\tr-\u003eimage_len = len;\n+\t\tfor (j = 0; j \u003c n; j++)\n+\t\t\tinsns[drop[j]] = BPF_JMP_A(0);\n+\t\tinsns[r-\u003estart] = r-\u003ecall;\n+\t\tfor (j = r-\u003estart + 1; j \u003c r-\u003estart + r-\u003ebody-\u003elen; j++)\n+\t\t\tinsns[j] = BPF_JMP_A(0);\n+\t\tenv-\u003einsn_aux_data[r-\u003estart].kfunc_inline = i + 1;\n+\t}\n+}\n+\n+/* The inlined kfunc call at @idx, if the JIT puts native code there */\n+const struct bpf_kfunc_inline *bpf_kfunc_native(const struct bpf_verifier_env *env, int idx)\n+{\n+\tu32 i = env \u0026\u0026 env-\u003einsn_aux_data[idx].kfunc_body_entry ?\n+\t\tenv-\u003einsn_aux_data[idx].kfunc_inline : 0;\n+\n+\tif (!i || i \u003e env-\u003ekfunc_inline_cnt || !env-\u003ekfunc_inlines[i - 1].image)\n+\t\treturn NULL;\n+\treturn \u0026env-\u003ekfunc_inlines[i - 1];\n+}\n+\n+void bpf_free_kfunc_inlines(struct bpf_verifier_env *env)\n+{\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c env-\u003ekfunc_inline_cnt; i++)\n+\t\tkfree(env-\u003ekfunc_inlines[i].image);\n+\tkvfree(env-\u003ekfunc_inlines);\n+}\ndiff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c\nindex fd3c0206bd67d..2f58794784100 100644\n--- a/kernel/bpf/verifier.c\n+++ b/kernel/bpf/verifier.c\n@@ -2569,8 +2569,8 @@ static int kfunc_btf_cmp_by_off(const void *a, const void *b)\n \treturn d0-\u003eoffset - d1-\u003eoffset;\n }\n \n-static struct bpf_kfunc_desc *\n-find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)\n+struct bpf_kfunc_desc *\n+bpf_find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)\n {\n \tstruct bpf_kfunc_desc desc = {\n \t\t.func_id = func_id,\n@@ -2877,10 +2877,11 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n \tstruct btf_func_model func_model;\n \tstruct bpf_kfunc_desc_tab *tab;\n \tstruct bpf_prog_aux *prog_aux;\n+\tconst struct bpf_kfunc_body *body;\n \tstruct bpf_kfunc_meta kfunc;\n \tstruct bpf_kfunc_desc *desc;\n \tunsigned long addr;\n-\tint err;\n+\tint err, i;\n \n \tprog_aux = env-\u003eprog-\u003eaux;\n \ttab = prog_aux-\u003ekfunc_tab;\n@@ -2930,7 +2931,7 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n \t\tprog_aux-\u003ekfunc_btf_tab = btf_tab;\n \t}\n \n-\tif (find_kfunc_desc(env-\u003eprog, func_id, offset))\n+\tif (bpf_find_kfunc_desc(env-\u003eprog, func_id, offset))\n \t\treturn 0;\n \n \tif (tab-\u003enr_base_descs == MAX_KFUNC_DESCS) {\n@@ -2990,7 +2991,10 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n \tdesc = \u0026tab-\u003edescs[tab-\u003enr_descs];\n \tmemset(desc, 0, sizeof(*desc));\n \n-\terr = gen_kfunc_arg_proto(env, \u0026meta, \u0026func_model, \u0026desc-\u003eproto);\n+\t/* the body of a kfunc that the program may call checks its arguments */\n+\tbody = kfunc.flags \u0026\u0026 btf_kfunc_is_allowed(kfunc.btf, func_id, env-\u003eprog) ?\n+\t       btf_find_kfunc_body(kfunc.btf, func_id) : NULL;\n+\terr = body ? 0 : gen_kfunc_arg_proto(env, \u0026meta, \u0026func_model, \u0026desc-\u003eproto);\n \tif (err)\n \t\treturn err;\n \n@@ -2998,6 +3002,10 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n \tdesc-\u003eoffset = offset;\n \tdesc-\u003eaddr = addr;\n \tdesc-\u003efunc_model = func_model;\n+\tdesc-\u003ebody = body;\n+\tfor (i = 0; body \u0026\u0026 i \u003c func_model.nr_args; i++)\n+\t\tif (btf_param_match_suffix(kfunc.btf, \u0026btf_params(kfunc.proto)[i], \"__k\"))\n+\t\t\tdesc-\u003ebody_imm |= BIT(BPF_REG_1 + i);\n \ttab-\u003enr_descs++;\n \ttab-\u003enr_base_descs++;\n \tsort(tab-\u003edescs, tab-\u003enr_base_descs, sizeof(tab-\u003edescs[0]),\n@@ -14762,7 +14770,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n \tfunc_name = meta.func_name;\n \tinsn_aux = \u0026env-\u003einsn_aux_data[insn_idx];\n \n-\tdesc = find_kfunc_desc(env-\u003eprog, insn-\u003eimm, insn-\u003eoff);\n+\tdesc = bpf_find_kfunc_desc(env-\u003eprog, insn-\u003eimm, insn-\u003eoff);\n \tif (!desc) {\n \t\tverifier_bug(env, \"kfunc descriptor not found for func_id %u\", insn-\u003eimm);\n \t\treturn -EFAULT;\n@@ -19527,6 +19535,9 @@ static int do_check(struct bpf_verifier_env *env)\n \n \t\tstate-\u003elast_insn_idx = env-\u003eprev_insn_idx;\n \t\tstate-\u003einsn_idx = env-\u003einsn_idx;\n+\t\terr = bpf_mark_kfunc_body_regs(env, prev_insn_idx, insn_aux);\n+\t\tif (err)\n+\t\t\treturn err;\n \t\t/*\n \t\t * Record the incoming edge so active and queued paths use the same\n \t\t * branch-recording path. A zero-offset conditional has identical\n@@ -22180,7 +22191,7 @@ int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n \t * __bpf_call_base, unless the JIT needs to call functions that are\n \t * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).\n \t */\n-\tdesc = find_kfunc_desc(env-\u003eprog, insn-\u003eimm, insn-\u003eoff);\n+\tdesc = bpf_find_kfunc_desc(env-\u003eprog, insn-\u003eimm, insn-\u003eoff);\n \tif (!desc) {\n \t\tverifier_bug(env, \"kernel function descriptor not found for func_id %u\",\n \t\t\t     insn-\u003eimm);\n@@ -22655,15 +22666,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tenv-\u003etest_reg_invariants = attr-\u003eprog_flags \u0026 BPF_F_TEST_REG_INVARIANTS;\n \tenv-\u003earena_scalar = attr-\u003eprog_flags \u0026 BPF_F_ARENA_SCALAR;\n \n-\tenv-\u003eexplored_states = kvzalloc_objs(struct list_head,\n-\t\t\t\t\t     state_htab_size(env),\n-\t\t\t\t\t     GFP_KERNEL_ACCOUNT);\n-\tret = -ENOMEM;\n-\tif (!env-\u003eexplored_states)\n-\t\tgoto skip_full_check;\n-\n-\tfor (i = 0; i \u003c state_htab_size(env); i++)\n-\t\tINIT_LIST_HEAD(\u0026env-\u003eexplored_states[i]);\n \tINIT_LIST_HEAD(\u0026env-\u003efree_list);\n \n \t/* Prepare BTF and func_info needed to discover all subprograms. */\n@@ -22707,6 +22709,21 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tif (ret \u003c 0)\n \t\tgoto skip_full_check;\n \n+\tret = bpf_inline_kfunc_bodies(env);\n+\tif (ret \u003c 0)\n+\t\tgoto skip_full_check;\n+\n+\t/* sized by the program length, so after the lowering */\n+\tenv-\u003eexplored_states = kvzalloc_objs(struct list_head,\n+\t\t\t\t\t     state_htab_size(env),\n+\t\t\t\t\t     GFP_KERNEL_ACCOUNT);\n+\tret = -ENOMEM;\n+\tif (!env-\u003eexplored_states)\n+\t\tgoto skip_full_check;\n+\n+\tfor (i = 0; i \u003c state_htab_size(env); i++)\n+\t\tINIT_LIST_HEAD(\u0026env-\u003eexplored_states[i]);\n+\n \tif (bpf_prog_is_offloaded(env-\u003eprog-\u003eaux)) {\n \t\tret = bpf_prog_offload_verifier_prep(env-\u003eprog);\n \t\tif (ret)\n@@ -22771,6 +22788,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n skip_full_check:\n \tkvfree(env-\u003eexplored_states);\n \n+\tif (ret == 0)\n+\t\tbpf_restore_kfunc_calls(env);\n+\n \t/* might decrease stack depth, keep it before passes that\n \t * allocate additional slots.\n \t */\n@@ -22900,6 +22920,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n err_free_env:\n \tbpf_free_subprog_jts(env);\n \tvfree(env-\u003einsn_aux_data);\n+\tbpf_free_kfunc_inlines(env);\n \tkvfree(env-\u003efd_array);\n \tbpf_stack_liveness_free(env);\n \tkvfree(env-\u003ecfg.insn_postorder);\ndiff --git a/tools/testing/selftests/bpf/Makefile b/tools/testing/selftests/bpf/Makefile\nindex a22be7efd1fa2..7a5dd7fcd3d14 100644\n--- a/tools/testing/selftests/bpf/Makefile\n+++ b/tools/testing/selftests/bpf/Makefile\n@@ -48,7 +48,7 @@ TEST_PROGS_EXTENDED := \\\n \tima_setup.sh verify_sig_setup.sh\n \n TEST_KMODS := bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \\\n-\tbpf_test_modorder_y.ko bpf_test_rqspinlock.ko\n+\tbpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_kfunc_body.ko\n TEST_KMOD_TARGETS = $(addprefix $(OUTPUT)/,$(TEST_KMODS))\n \n # Compile but not part of 'make run_tests'\ndiff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config\nindex 2b883b388f90c..abc4e79d42a01 100644\n--- a/tools/testing/selftests/bpf/config\n+++ b/tools/testing/selftests/bpf/config\n@@ -3,6 +3,7 @@ CONFIG_BOOTPARAM_HARDLOCKUP_PANIC=y\n CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC=1\n CONFIG_BPF=y\n CONFIG_BPF_EVENTS=y\n+CONFIG_BPF_INSN_KFUNCS=y\n CONFIG_BPF_JIT=y\n CONFIG_BPF_KPROBE_OVERRIDE=y\n CONFIG_BPF_LIRC_MODE2=y\ndiff --git a/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c b/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c\nnew file mode 100644\nindex 0000000000000..3aa1f614b508e\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c\n@@ -0,0 +1,18 @@\n+// SPDX-License-Identifier: GPL-2.0\n+#include \u003ctest_progs.h\u003e\n+#include \u003ctesting_helpers.h\u003e\n+\n+/* bpf_test_kfunc_body.ko fails to load unless bad kfunc bodies are rejected */\n+void test_kfunc_body_registration(void)\n+{\n+\tint fd, err;\n+\n+\tfd = open(\"bpf_test_kfunc_body.ko\", O_RDONLY);\n+\tif (!ASSERT_GE(fd, 0, \"open\"))\n+\t\treturn;\n+\terr = finit_module(fd, \"\", 0);\n+\tclose(fd);\n+\tif (!ASSERT_OK(err, \"finit_module\"))\n+\t\treturn;\n+\tASSERT_OK(delete_module(\"bpf_test_kfunc_body\", 0), \"delete_module\");\n+}\ndiff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c\nindex 460ad10ddc020..ad7baf3afa248 100644\n--- a/tools/testing/selftests/bpf/prog_tests/verifier.c\n+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c\n@@ -60,6 +60,7 @@\n #include \"verifier_iterating_callbacks.skel.h\"\n #include \"verifier_jeq_infer_not_null.skel.h\"\n #include \"verifier_jit_convergence.skel.h\"\n+#include \"verifier_kfunc_inline.skel.h\"\n #include \"verifier_kfunc_packet_access.skel.h\"\n #include \"verifier_kfunc_uninit.skel.h\"\n #include \"verifier_kfunc_uninit_multi.skel.h\"\n@@ -245,6 +246,7 @@ void test_verifier_int_ptr(void)              { RUN(verifier_int_ptr); }\n void test_verifier_iterating_callbacks(void)  { RUN(verifier_iterating_callbacks); }\n void test_verifier_jeq_infer_not_null(void)   { RUN(verifier_jeq_infer_not_null); }\n void test_verifier_jit_convergence(void)      { RUN(verifier_jit_convergence); }\n+void test_verifier_kfunc_inline(void)         { RUN_TESTS(verifier_kfunc_inline); }\n void test_verifier_kfunc_packet_access(void)  { RUN_TESTS(verifier_kfunc_packet_access); }\n void test_verifier_kfunc_uninit(void)         { RUN_TESTS(verifier_kfunc_uninit); }\n void test_verifier_kfunc_uninit_multi(void)   { RUN_TESTS(verifier_kfunc_uninit_multi); }\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c b/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c\nnew file mode 100644\nindex 0000000000000..b525e7cf7a0f4\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c\n@@ -0,0 +1,543 @@\n+// SPDX-License-Identifier: GPL-2.0\n+#include \u003cvmlinux.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_misc.h\"\n+#include \"../test_kmods/bpf_testmod_kfunc.h\"\n+\n+extern u64 bpf_rol64(u64 x, u32 n) __ksym;\n+extern u64 bpf_select64(u64 cond, u64 a, u64 b) __ksym;\n+extern u64 bpf_extract64(u64 x, u32 start, u32 len) __ksym;\n+extern u64 bpf_load_be64(const void *p, s32 off) __ksym;\n+extern void bpf_prefetch(const void *p) __ksym;\n+extern void bpf_copy16(void *dst, const void *src) __ksym;\n+extern u64 bpf_lea64(u64 base, u64 index, u32 scale, s32 disp) __ksym;\n+\n+/* r6 = rol(r6, 13) is one rol, the moves around the call go away */\n+SEC(\"tc\")\n+__success __retval(8192)\n+__xlated(\"0: r6 = 1\")\n+__xlated(\"1: call\")\n+__xlated(\"2: r0 = r6\")\n+__arch_x86_64\n+__jited(\"{{.*}}movl\\t$0x1, %ebx\")\n+__jited(\"{{.*}}rolq\\t$0xd, %rbx\")\n+__jited(\"{{.*}}movq\\t%rbx, %rax\")\n+__naked void inline_rol64_in_place(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 1;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = 13;\"\n+\t\"call %[bpf_rol64];\"\n+\t\"r6 = r0;\"\n+\t\"r0 = r6;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_rol64)\n+\t: __clobber_all);\n+}\n+\n+/* r7 = rol(r6, 8) keeps r6 */\n+SEC(\"tc\")\n+__success __retval(255)\n+__arch_x86_64\n+__jited(\"{{.*}}{{rorxq\\t\\\\$0x38, %rdi, %r13|rolq\\t\\\\$0x8, %r13}}\")\n+__naked void inline_rol64_copy(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 1;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = 8;\"\n+\t\"call %[bpf_rol64];\"\n+\t\"r7 = r0;\"\n+\t\"r0 = r7;\"\n+\t\"r0 -= r6;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_rol64)\n+\t: __clobber_all);\n+}\n+\n+/* a 32-bit move of the constant goes away as well */\n+SEC(\"tc\")\n+__success __retval(16)\n+__xlated(\"1: call\")\n+__arch_x86_64\n+__jited(\"{{.*}}rolq\\t$0x4, %rbx\")\n+__naked void inline_rol_w2(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 1;\"\n+\t\"r1 = r6;\"\n+\t\"w2 = 4;\"\n+\t\"call %[bpf_rol64];\"\n+\t\"r6 = r0;\"\n+\t\"r0 = r6;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_rol64)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"tc\")\n+__success __retval(42)\n+__arch_x86_64\n+__jited(\"{{.*}}testq\\t%rbx, %rbx\")\n+__jited(\"{{.*}}movq\\t%r14, %r15\")\n+__jited(\"{{.*}}cmovneq\\t%r13, %r15\")\n+__naked void inline_select(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 1;\"\n+\t\"r7 = 42;\"\n+\t\"r8 = 7;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = r7;\"\n+\t\"r3 = r8;\"\n+\t\"call %[bpf_select64];\"\n+\t\"r9 = r0;\"\n+\t\"r0 = r9;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_select64)\n+\t: __clobber_all);\n+}\n+\n+/* r9 = r6 ? r7 : r9 is a test and a cmov */\n+SEC(\"tc\")\n+__success __retval(7)\n+__arch_x86_64\n+__jited(\"{{.*}}testq\\t%rbx, %rbx\")\n+__jited(\"{{.*}}cmovneq\\t%r13, %r15\")\n+__naked void inline_select_in_place(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0;\"\n+\t\"r7 = 42;\"\n+\t\"r9 = 7;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = r7;\"\n+\t\"r3 = r9;\"\n+\t\"call %[bpf_select64];\"\n+\t\"r9 = r0;\"\n+\t\"r0 = r9;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_select64)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"tc\")\n+__success __retval(0x56)\n+__arch_x86_64\n+__jited(\"{{.*}}{{bextrq\\t%r13, %rbx, %r13|shlq\\t%cl, %rbx}}\")\n+__naked void inline_extract(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0x12345678;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = 8;\"\n+\t\"r3 = 8;\"\n+\t\"call %[bpf_extract64];\"\n+\t\"r7 = r0;\"\n+\t\"r0 = r7;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_extract64)\n+\t: __clobber_all);\n+}\n+\n+/* the bytes 01..08 on the stack, read as big endian */\n+SEC(\"tc\")\n+__success __retval(0x05060708)\n+__arch_x86_64\n+__jited(\"{{.*}}{{movbeq\\t\\\\(%rbx\\\\), %rax|bswapq\\t%rax}}\")\n+__naked void inline_load_be64(void)\n+{\n+\tasm volatile (\n+\t\"*(u32 *)(r10 - 8) = 0x04030201;\"\n+\t\"*(u32 *)(r10 - 4) = 0x08070605;\"\n+\t\"r6 = r10;\"\n+\t\"r6 += -8;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = 0;\"\n+\t\"call %[bpf_load_be64];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_load_be64)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"tc\")\n+__success __retval(0)\n+__arch_x86_64\n+__jited(\"{{.*}}prefetcht0\\t{{.*}}%r13)\")\n+__naked void inline_prefetch(void)\n+{\n+\tasm volatile (\n+\t\"*(u64 *)(r10 - 8) = 0;\"\n+\t\"r7 = r10;\"\n+\t\"r7 += -8;\"\n+\t\"r1 = r7;\"\n+\t\"call %[bpf_prefetch];\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_prefetch)\n+\t: __clobber_all);\n+}\n+\n+/* the instructions of a prefetch load, so the address must be readable */\n+SEC(\"tc\")\n+__failure __msg(\"R1 invalid mem access 'scalar'\")\n+__naked void inline_prefetch_scalar(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 0;\"\n+\t\"call %[bpf_prefetch];\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_prefetch)\n+\t: __clobber_all);\n+}\n+\n+/* copy 16 bytes from fp-16 to fp-32: the JIT copies the compiled kfunc */\n+SEC(\"tc\")\n+__success __retval(0x22)\n+__arch_x86_64\n+__xlated(\"6: call\")\n+__jited(\"{{.*}}movq\\t(%r13), %{{.*}}\")\n+__naked void inline_copy16(void)\n+{\n+\tasm volatile (\n+\t\"*(u64 *)(r10 - 16) = 0x11;\"\n+\t\"*(u64 *)(r10 - 8) = 0x22;\"\n+\t\"r6 = r10;\"\n+\t\"r6 += -32;\"\n+\t\"r7 = r10;\"\n+\t\"r7 += -16;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = r7;\"\n+\t\"call %[bpf_copy16];\"\n+\t\"r0 = *(u64 *)(r10 - 24);\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_copy16)\n+\t: __clobber_all);\n+}\n+\n+/* the verifier checks the memory that the copy touches */\n+SEC(\"tc\")\n+__failure __msg(\"off=0 size=8\")\n+__naked void inline_copy16_out_of_bounds(void)\n+{\n+\tasm volatile (\n+\t\"*(u64 *)(r10 - 8) = 0;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -16;\"\n+\t\"r2 = r10;\"\n+\t\"r2 += -8;\"\n+\t\"call %[bpf_copy16];\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_copy16)\n+\t: __clobber_all);\n+}\n+\n+/* 100 + 3 * 4 + 16 */\n+SEC(\"tc\")\n+__success __retval(128)\n+__arch_x86_64\n+__jited(\"{{.*}}leaq\\t0x10(%rbx,%r13,4), %r14\")\n+__naked void inline_lea(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 100;\"\n+\t\"r7 = 3;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = r7;\"\n+\t\"r3 = 4;\"\n+\t\"r4 = 16;\"\n+\t\"call %[bpf_lea64];\"\n+\t\"r8 = r0;\"\n+\t\"r0 = r8;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_lea64)\n+\t: __clobber_all);\n+}\n+\n+/* the instructions bound the result, a call would not */\n+SEC(\"tc\")\n+__success __retval(0)\n+__naked void inline_precision(void)\n+{\n+\tasm volatile (\n+\t\"call %[bpf_get_prandom_u32];\"\n+\t\"r1 = r0;\"\n+\t\"r2 = 0;\"\n+\t\"r3 = 3;\"\n+\t\"call %[bpf_extract64];\"\n+\t\"r6 = r10;\"\n+\t\"r6 += -8;\"\n+\t\"r6 += r0;\"\n+\t\"r0 = 0;\"\n+\t\"*(u8 *)(r6 + 0) = r0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_get_prandom_u32), __imm(bpf_extract64)\n+\t: __clobber_all);\n+}\n+\n+/* arguments cannot be read after the instructions, as after a call */\n+SEC(\"tc\")\n+__failure __msg(\"R1 !read_ok\")\n+__naked void inline_clobber(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 1;\"\n+\t\"r2 = 42;\"\n+\t\"r3 = 7;\"\n+\t\"call %[bpf_select64];\"\n+\t\"r0 = r1;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_select64)\n+\t: __clobber_all);\n+}\n+\n+/* a kfunc that returns nothing leaves R0 unreadable after its body */\n+SEC(\"tc\")\n+__failure __msg(\"R0 !read_ok\")\n+__naked void inline_void_r0(void)\n+{\n+\tasm volatile (\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\t\"call %[bpf_prefetch];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_prefetch)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"tc\")\n+__failure __msg(\"R2 must be a known constant\")\n+__naked void inline_not_constant(void)\n+{\n+\tasm volatile (\n+\t\"call %[bpf_get_prandom_u32];\"\n+\t\"r1 = 1;\"\n+\t\"r2 = r0;\"\n+\t\"call %[bpf_rol64];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_get_prandom_u32), __imm(bpf_rol64)\n+\t: __clobber_all);\n+}\n+\n+/* r1 = r6 is skipped by a jump, so it must stay */\n+SEC(\"tc\")\n+__success __retval(42)\n+__naked void inline_bind_jump(void)\n+{\n+\tasm volatile (\n+\t\"r9 = *(u32 *)(r1 + %[len]);\"\n+\t\"r6 = 0;\"\n+\t\"r7 = 42;\"\n+\t\"r8 = 7;\"\n+\t\"r1 = 1;\"\n+\t\"if r9 != 0 goto l0_%=;\"\n+\t\"r1 = r6;\"\n+\"l0_%=:\"\n+\t\"r2 = r7;\"\n+\t\"r3 = r8;\"\n+\t\"call %[bpf_select64];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_select64),\n+\t  __imm_const(len, offsetof(struct __sk_buff, len))\n+\t: __clobber_all);\n+}\n+\n+#if __clang_major__ \u003e= 18 || defined(__BPF_FEATURE_MOVSX)\n+/* a sign-extending move is not a plain copy of R6 */\n+SEC(\"tc\")\n+__success __retval(7)\n+__naked void inline_bind_movsx(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0x100;\"\n+\t\"r7 = 42;\"\n+\t\"r8 = 7;\"\n+\t\"r1 = (s8)r6;\"\n+\t\"r2 = r7;\"\n+\t\"r3 = r8;\"\n+\t\"call %[bpf_select64];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_select64)\n+\t: __clobber_all);\n+}\n+#endif\n+\n+/* the result takes the register of the condition */\n+SEC(\"tc\")\n+__success __retval(42)\n+__naked void inline_bind_shared(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 1;\"\n+\t\"r7 = 42;\"\n+\t\"r8 = 7;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = r7;\"\n+\t\"r3 = r8;\"\n+\t\"call %[bpf_select64];\"\n+\t\"r6 = r0;\"\n+\t\"r0 = r6;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_select64)\n+\t: __clobber_all);\n+}\n+\n+/* native code from a module, with the result in the register of an argument */\n+SEC(\"tc\")\n+__success __retval(6)\n+__arch_x86_64\n+__xlated(\"2: call\")\n+__jited(\"{{.*}}xorq\\t%r13, %rbx\")\n+__naked void inline_module(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 5;\"\n+\t\"r7 = 3;\"\n+\t\"r1 = r6;\"\n+\t\"r2 = r7;\"\n+\t\"call %[bpf_testmod_inline_xor];\"\n+\t\"r6 = r0;\"\n+\t\"r0 = r6;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_testmod_inline_xor)\n+\t: __clobber_all);\n+}\n+\n+/* without emit, the JIT copies the compiled kfunc, with the registers bound */\n+SEC(\"tc\")\n+__success __retval(5)\n+__arch_x86_64\n+__xlated(\"1: call\")\n+__jited(\"{{.*}}movq\\t%rbx, %r13\")\n+__naked void inline_copy(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 5;\"\n+\t\"r1 = r6;\"\n+\t\"call %[bpf_testmod_inline_mov];\"\n+\t\"r7 = r0;\"\n+\t\"r0 = r7;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_testmod_inline_mov)\n+\t: __clobber_all);\n+}\n+\n+/* compiled code that branches or divides is not copied: the instructions stay */\n+SEC(\"tc\")\n+__success __retval(0)\n+__xlated(\"{{.*}}r0 /= r2\")\n+__naked void inline_copy_div(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 9;\"\n+\t\"r2 = 0;\"\n+\t\"call %[bpf_testmod_inline_div];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_testmod_inline_div)\n+\t: __clobber_all);\n+}\n+\n+/* a kfunc that the program may not call keeps its call, which is rejected */\n+SEC(\"xdp\")\n+__failure __msg(\"calling kernel function bpf_testmod_inline_mov is not allowed\")\n+__naked void inline_not_allowed(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 1;\"\n+\t\"call %[bpf_testmod_inline_mov];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_testmod_inline_mov)\n+\t: __clobber_all);\n+}\n+\n+#define ROL(x, n) ((x) \u003c\u003c ((n) \u0026 63) | (x) \u003e\u003e (-(n) \u0026 63))\n+\n+struct diff_state {\n+\tu64 bad;\n+\tu8 src[64], dst[64];\n+};\n+\n+static u64 rand64(void)\n+{\n+\treturn (u64)bpf_get_prandom_u32() \u003c\u003c 32 | bpf_get_prandom_u32();\n+}\n+\n+/* a global function, so that the verifier checks it once and not per call */\n+__noinline int diff_step(struct diff_state *s)\n+{\n+\tu64 x = rand64(), y = rand64(), a = rand64(), b = rand64();\n+\tint i;\n+\n+\tif (!s)\n+\t\treturn 0;\n+\ts-\u003ebad |= (bpf_rol64(x, 1) ^ ROL(x, 1)) | (bpf_rol64(x, 13) ^ ROL(x, 13)) |\n+\t\t  (bpf_rol64(x, 63) ^ ROL(x, 63)) | (bpf_rol64(x, 64) ^ x);\n+\ts-\u003ebad |= bpf_select64(x \u0026 1, a, b) ^ (x \u0026 1 ? a : b);\n+\ts-\u003ebad |= bpf_extract64(x, 0, 64) ^ x;\n+\ts-\u003ebad |= bpf_extract64(x, 13, 7) ^ (x \u003e\u003e 13 \u0026 0x7f);\n+\ts-\u003ebad |= bpf_extract64(x, 40, 24) ^ (x \u003e\u003e 40);\n+\ts-\u003ebad |= bpf_extract64(x, 63, 1) ^ (x \u003e\u003e 63);\n+\ts-\u003ebad |= bpf_lea64(x, y, 8, -12345) ^ (x + y * 8 - 12345);\n+\tfor (i = 0; i \u003c 8; i++) {\n+\t\ts-\u003esrc[i] = x \u003e\u003e (8 * i);\n+\t\ts-\u003esrc[8 + i] = y \u003e\u003e (8 * i);\n+\t}\n+\ts-\u003ebad |= bpf_load_be64(s-\u003esrc, 0) ^ __builtin_bswap64(x);\n+\ts-\u003ebad |= bpf_load_be64(s-\u003esrc + 16, -8) ^ __builtin_bswap64(y);\n+\t/* unaligned */\n+\ts-\u003ebad |= bpf_load_be64(s-\u003esrc + 8, -7) ^ __builtin_bswap64(x \u003e\u003e 8 | y \u003c\u003c 56);\n+\tbpf_copy16(s-\u003edst + 8, s-\u003esrc);\n+\tfor (i = 0; i \u003c 16; i++)\n+\t\ts-\u003ebad |= s-\u003edst[8 + i] ^ s-\u003esrc[i];\n+\treturn 0;\n+}\n+\n+/* native code and the instructions agree on random inputs */\n+SEC(\"tc\")\n+__success __retval(0)\n+int inline_differential(struct __sk_buff *skb)\n+{\n+\tstruct diff_state s = {};\n+\tint i;\n+\n+\tfor (i = 0; i \u003c 256; i++)\n+\t\tdiff_step(\u0026s);\n+\treturn s.bad != 0;\n+}\n+\n+/* emits BTF for the kfuncs that only inline assembly calls */\n+void __kfunc_btf_root(void)\n+{\n+\tbpf_prefetch(0);\n+\tbpf_testmod_inline_mov(0);\n+\tbpf_testmod_inline_xor(0, 0);\n+\tbpf_testmod_inline_div(0, 0);\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/test_kmods/Makefile b/tools/testing/selftests/bpf/test_kmods/Makefile\nindex 031c7454ce65f..1800a0cd7a771 100644\n--- a/tools/testing/selftests/bpf/test_kmods/Makefile\n+++ b/tools/testing/selftests/bpf/test_kmods/Makefile\n@@ -19,7 +19,7 @@ Q = @\n endif\n \n MODULES = bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \\\n-\tbpf_test_modorder_y.ko bpf_test_rqspinlock.ko\n+\tbpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_kfunc_body.ko\n \n $(foreach m,$(MODULES),$(eval obj-m += $(m:.ko=.o)))\n \ndiff --git a/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c b/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c\nnew file mode 100644\nindex 0000000000000..2149bbd683381\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c\n@@ -0,0 +1,121 @@\n+// SPDX-License-Identifier: GPL-2.0\n+#include \u003clinux/bpf.h\u003e\n+#include \u003clinux/btf.h\u003e\n+#include \u003clinux/btf_ids.h\u003e\n+#include \u003clinux/filter.h\u003e\n+#include \u003clinux/init.h\u003e\n+#include \u003clinux/module.h\u003e\n+\n+struct bpf_test_kfunc_body_pair {\n+\tu64 a, b;\n+};\n+\n+__bpf_kfunc_start_defs();\n+\n+__bpf_kfunc u64 bpf_test_kfunc_body(u64 x)\n+{\n+\treturn x;\n+}\n+\n+__bpf_kfunc u64 bpf_test_kfunc_body_unset(u64 x)\n+{\n+\treturn x;\n+}\n+\n+__bpf_kfunc u64 bpf_test_kfunc_body_pair(struct bpf_test_kfunc_body_pair p)\n+{\n+\treturn p.a;\n+}\n+\n+__bpf_kfunc u64 bpf_test_kfunc_body_sleepable(u64 x)\n+{\n+\treturn x;\n+}\n+\n+__bpf_kfunc_end_defs();\n+\n+BTF_KFUNCS_START(test_body_kfunc_ids)\n+BTF_ID_FLAGS(func, bpf_test_kfunc_body)\n+BTF_KFUNCS_END(test_body_kfunc_ids)\n+\n+/* never registered */\n+BTF_KFUNCS_START(test_body_bad_kfunc_ids)\n+BTF_ID_FLAGS(func, bpf_test_kfunc_body_pair)\n+BTF_ID_FLAGS(func, bpf_test_kfunc_body_sleepable, KF_SLEEPABLE)\n+BTF_KFUNCS_END(test_body_bad_kfunc_ids)\n+\n+BTF_ID_LIST(test_body_ids)\n+BTF_ID(func, bpf_test_kfunc_body)\n+BTF_ID(func, bpf_test_kfunc_body_unset)\n+BTF_ID(func, bpf_test_kfunc_body_pair)\n+BTF_ID(func, bpf_test_kfunc_body_sleepable)\n+\n+static const struct bpf_insn test_body_insns[] = {\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+};\n+\n+/* writes R6 */\n+static const struct bpf_insn test_body_bad_insns[] = {\n+\tBPF_MOV64_REG(BPF_REG_6, BPF_REG_1),\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+};\n+\n+/* jumps past the last instruction */\n+static const struct bpf_insn test_body_jump_insns[] = {\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+\tBPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0, 1),\n+\tBPF_MOV64_IMM(BPF_REG_0, 0),\n+};\n+\n+static struct bpf_kfunc_body test_body = { .id = \u0026test_body_ids[0] };\n+\n+static struct btf_kfunc_id_set test_body_set = {\n+\t.owner = THIS_MODULE,\n+\t.set = \u0026test_body_kfunc_ids,\n+\t.bodies = \u0026test_body,\n+\t.body_cnt = 1,\n+};\n+\n+static int test_body_rejected(struct btf_id_set8 *set, const u32 *id,\n+\t\t\t      const struct bpf_insn *insns, u32 len)\n+{\n+\ttest_body_set.set = set;\n+\ttest_body.id = id;\n+\ttest_body.insns = insns;\n+\ttest_body.len = len;\n+\treturn register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, \u0026test_body_set) == -EINVAL;\n+}\n+\n+/*\n+ * The module loads only if registration rejects a body without instructions,\n+ * one with an instruction that writes R6, one with a jump past its last\n+ * instruction, one for a kfunc outside the set, one with an argument of two\n+ * registers and one for a kfunc with flags.\n+ */\n+static int bpf_test_kfunc_body_init(void)\n+{\n+\tstruct btf_id_set8 *good = \u0026test_body_kfunc_ids, *bad = \u0026test_body_bad_kfunc_ids;\n+\n+\tif (!test_body_rejected(good, \u0026test_body_ids[0], NULL, 0) ||\n+\t    !test_body_rejected(good, \u0026test_body_ids[0], test_body_bad_insns,\n+\t\t\t\tARRAY_SIZE(test_body_bad_insns)) ||\n+\t    !test_body_rejected(good, \u0026test_body_ids[0], test_body_jump_insns,\n+\t\t\t\tARRAY_SIZE(test_body_jump_insns)) ||\n+\t    !test_body_rejected(good, \u0026test_body_ids[1], test_body_insns, 1) ||\n+\t    !test_body_rejected(bad, \u0026test_body_ids[2], test_body_insns, 1) ||\n+\t    !test_body_rejected(bad, \u0026test_body_ids[3], test_body_insns, 1))\n+\t\treturn -EINVAL;\n+\ttest_body_set.set = good;\n+\ttest_body.id = \u0026test_body_ids[0];\n+\treturn register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, \u0026test_body_set);\n+}\n+\n+static void bpf_test_kfunc_body_exit(void)\n+{\n+}\n+\n+module_init(bpf_test_kfunc_body_init);\n+module_exit(bpf_test_kfunc_body_exit);\n+\n+MODULE_DESCRIPTION(\"BPF kfunc body registration test module\");\n+MODULE_LICENSE(\"GPL\");\ndiff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c\nindex 93847ca6293b4..13d5abe249d25 100644\n--- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c\n+++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c\n@@ -931,6 +931,78 @@ BTF_ID_LIST(bpf_testmod_dtor_ids)\n BTF_ID(struct, bpf_testmod_ctx)\n BTF_ID(func, bpf_testmod_ctx_release_dtor)\n \n+/*\n+ * Kfuncs with a body, in a set that XDP programs may not use: the JIT copies\n+ * the first, the second has native code from this module, and the third,\n+ * which divides, keeps its body.\n+ */\n+__bpf_kfunc u64 bpf_testmod_inline_mov(u64 x)\n+{\n+\treturn x;\n+}\n+\n+__bpf_kfunc u64 bpf_testmod_inline_xor(u64 a, u64 b)\n+{\n+\treturn a ^ b;\n+}\n+\n+__bpf_kfunc u64 bpf_testmod_inline_div(u64 a, u64 b)\n+{\n+\treturn b ? a / b : 0;\n+}\n+\n+BTF_ID_LIST(bpf_testmod_body_ids)\n+BTF_ID(func, bpf_testmod_inline_mov)\n+BTF_ID(func, bpf_testmod_inline_xor)\n+BTF_ID(func, bpf_testmod_inline_div)\n+\n+static const struct bpf_insn mov_body[] = {\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+};\n+\n+static const struct bpf_insn xor_body[] = {\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+\tBPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_2),\n+};\n+\n+static const struct bpf_insn div_body[] = {\n+\tBPF_MOV64_REG(BPF_REG_0, BPF_REG_1),\n+\tBPF_ALU64_REG(BPF_DIV, BPF_REG_0, BPF_REG_2),\n+};\n+\n+#ifdef CONFIG_X86_64\n+/* op %src, %dst on 64-bit registers */\n+static u8 *x86_op(u8 *p, u8 op, u8 src, u8 dst)\n+{\n+\t*p++ = 0x48 | (src \u0026 8 ? 4 : 0) | (dst \u0026 8 ? 1 : 0);\n+\t*p++ = op;\n+\t*p++ = 0xc0 | (src \u0026 7) \u003c\u003c 3 | (dst \u0026 7);\n+\treturn p;\n+}\n+\n+/* the result can take the register of an argument, which a copy cannot */\n+static int xor_emit(const u8 *reg, const s32 *imm, u8 *buf)\n+{\n+\tu8 dst = reg[0], a = reg[1], b = reg[2], *p = buf;\n+\n+\tif (dst == b)\n+\t\tswap(a, b);\n+\tif (dst != a)\n+\t\tp = x86_op(p, 0x89, a, dst);\t/* mov %a, %dst */\n+\treturn x86_op(p, 0x31, b, dst) - buf;\t/* xor %b, %dst */\n+}\n+#else\n+#define xor_emit\tNULL\n+#endif\n+\n+#define BODY(i, op, emit)\t{ \u0026bpf_testmod_body_ids[i], op##_body, ARRAY_SIZE(op##_body), emit }\n+\n+static const struct bpf_kfunc_body bpf_testmod_bodies[] = {\n+\tBODY(0, mov, NULL),\n+\tBODY(1, xor, xor_emit),\n+\tBODY(2, div, NULL),\n+};\n+\n static const struct btf_kfunc_id_set bpf_testmod_common_kfunc_set = {\n \t.owner = THIS_MODULE,\n \t.set   = \u0026bpf_testmod_common_kfunc_ids,\n@@ -1827,6 +1899,9 @@ BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg, KF_IMPLICIT_ARGS)\n BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy, KF_IMPLICIT_ARGS)\n BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy_impl)\n BTF_ID_FLAGS(func, bpf_kfunc_trigger_ctx_check)\n+BTF_ID_FLAGS(func, bpf_testmod_inline_mov)\n+BTF_ID_FLAGS(func, bpf_testmod_inline_xor)\n+BTF_ID_FLAGS(func, bpf_testmod_inline_div)\n BTF_KFUNCS_END(bpf_testmod_check_kfunc_ids)\n \n static int bpf_testmod_ops_init(struct btf *btf)\n@@ -1861,6 +1936,8 @@ static int bpf_testmod_ops_init_member(const struct btf_type *t,\n static const struct btf_kfunc_id_set bpf_testmod_kfunc_set = {\n \t.owner = THIS_MODULE,\n \t.set   = \u0026bpf_testmod_check_kfunc_ids,\n+\t.bodies = bpf_testmod_bodies,\n+\t.body_cnt = ARRAY_SIZE(bpf_testmod_bodies),\n };\n \n static const struct bpf_verifier_ops bpf_testmod_verifier_ops = {\ndiff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h b/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h\nindex 67c02a421d133..2a55f1b145b42 100644\n--- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h\n+++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h\n@@ -357,4 +357,8 @@ void bpf_testmod_test_hardirq_fn(void);\n void bpf_testmod_test_softirq_fn(void);\n void bpf_kfunc_trigger_ctx_check(void) __ksym;\n \n+u64 bpf_testmod_inline_mov(u64 x) __ksym;\n+u64 bpf_testmod_inline_xor(u64 a, u64 b) __ksym;\n+u64 bpf_testmod_inline_div(u64 a, u64 b) __ksym;\n+\n #endif /* _BPF_TESTMOD_KFUNC_H */\n"
}

2/1 2026/10/05 14:28 agent patch-evaluator
0m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BPF_INSN_KFUNCS"
  ],
  "FocusSymbols": [
    "bpf_inline_kfunc_bodies",
    "bpf_restore_kfunc_calls",
    "bpf_mark_kfunc_body_regs",
    "bpf_jit_inline_kfunc",
    "kfunc_copy",
    "kfunc_copy_insn",
    "kfunc_bind",
    "btf_check_kfunc_body",
    "bpf_rol64",
    "bpf_select64",
    "bpf_extract64",
    "bpf_load_be64",
    "bpf_lea64"
  ],
  "Reasoning": "The patch series introduces inline kfuncs in the BPF subsystem and the x86-64 BPF JIT compiler. The verifier inlines kfunc bodies during verification and restores calls or emits/copies native machine code during JIT compilation. This modifies core BPF verifier behavior, register state/liveness tracking, and x86 machine code generation/copying, which is directly reachable from unprivileged or privileged userspace via the bpf() syscall. Fuzzing is essential to test for verifier inconsistencies, register binding issues, and JIT instruction generation bugs.",
  "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 b05094a96f90fd89caede9601c328198860eabdc
Author: syz-cluster <triage@syzkaller.com>
Date:   Mon Oct 5 14:28:34 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/bpf/kfuncs.rst b/Documentation/bpf/kfuncs.rst
index 73578a4c3b1fb..432e61a82aa9d 100644
--- a/Documentation/bpf/kfuncs.rst
+++ b/Documentation/bpf/kfuncs.rst
@@ -695,6 +695,59 @@ verified inline, so an unassigned R2 is simply passed back to the caller as
 uninitialized and only a caller that reads it fails. A stack pointer left in
 R2 is still rejected there, just as one in R0 is.
 
+2.10 Inline kfuncs
+------------------
+
+A kfunc can come with a body: a few BPF instructions that compute it from its
+arguments in R1-R5 into R0. The verifier then checks each call of the kfunc as
+its body, so it knows as much about the result as if the program had computed
+it in BPF, and the JIT puts native code in place of the call. Where the JIT has
+no native code, the body runs in place of the call. BPF programs call such
+kfuncs like any other, and arguments whose names end in ``__k`` must be known
+constants (see section 2.3.2). ``CONFIG_BPF_INSN_KFUNCS`` provides
+``bpf_rol64()``, ``bpf_select64()``, ``bpf_extract64()``, ``bpf_load_be64()``,
+``bpf_prefetch()``, ``bpf_copy16()`` and ``bpf_lea64()``.
+
+The verifier replaces each call with the body before it analyzes the program.
+Only the arguments are readable at the entry of the body, and R1-R5 are not
+readable after it, as after a call. After the analysis, a call goes back into
+the program if the JIT has native code for it, with its operands bound to the
+registers that the moves around the call copied them from or to. The body stays
+when the verifier rewrites it later, for example with speculation barriers,
+when it accesses memory other than the stack, map values, memory and packets,
+and when constant blinding is on.
+
+The native code comes from the kfunc set: an ``emit`` callback writes it for
+the architecture, such as ``rol $13`` or ``movbe 8(%rdi)`` on x86-64. Without
+``emit``, or when it has no code for the CPU, the x86-64 JIT copies the
+compiled kfunc with its registers renamed. It copies only straight-line moves,
+ALU instructions and address computations on the registers of a call, without
+division or rip-relative addressing. Native code is trusted like the rest of
+the JIT: it has to compute what the body computes, with the same memory
+accesses.
+
+A kfunc set gives bodies to some of its kfuncs::
+
+        static const struct bpf_insn rol64_body[] = { ... };
+
+        static const struct bpf_kfunc_body bodies[] = {
+                { &body_ids[0], rol64_body, ARRAY_SIZE(rol64_body), rol64_emit },
+        };
+
+        static const struct btf_kfunc_id_set kfunc_set = {
+                .set      = &kfunc_ids,
+                .bodies   = bodies,
+                .body_cnt = ARRAY_SIZE(bodies),
+        };
+
+Registration checks each body: it may use R0-R5, ALU instructions, loads and
+stores, and forward jumps that land within it, so that it ends by falling
+through its last instruction, but not the sign extension, signed division and
+byte swap of cpu v4, which not every JIT has. Each argument and the result must
+fit in one register, and the kfunc may have no kfunc flags. ``emit`` writes at
+most ``BPF_KFUNC_INLINE_MAX`` bytes. Modules give their kfuncs bodies and
+native code in the same way.
+
 .. _BPF_kfunc_lifecycle_expectations:
 
 3. kfunc lifecycle expectations
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 083fcd6cf15b7..6a57109caa97a 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -15,8 +15,12 @@
 #include <linux/memory.h>
 #include <linux/sort.h>
 #include <linux/execmem.h>
+#include <linux/kallsyms.h>
+#include <linux/uaccess.h>
 #include <asm/extable.h>
 #include <asm/ftrace.h>
+#include <asm/insn.h>
+#include <asm/insn-eval.h>
 #include <asm/set_memory.h>
 #include <asm/nospec-branch.h>
 #include <asm/text-patching.h>
@@ -2000,6 +2004,174 @@ static int emit_kfunc_arena_args(struct bpf_prog *bpf_prog,
 	return prog - start;
 }
 
+/*
+ * Registers that copied kfunc code may use: those of R0-R5, which hold the
+ * arguments and the result as for a call, and the scratch registers r10 and
+ * r11. r9 can hold the private frame pointer.
+ */
+#define KFUNC_COPY_REGS	(BIT(0) | BIT(1) | BIT(2) | BIT(6) | BIT(7) | BIT(8) | \
+			 BIT(10) | BIT(11))
+
+/*
+ * Write an instruction of a compiled kfunc with the registers of R0-R5
+ * renamed by @map to those that the verifier bound them to. It must be a
+ * move, ALU or address computation without control flow, prefixes other than
+ * operand size, rip-relative addressing or registers other than
+ * KFUNC_COPY_REGS, and no division, which can trap.
+ */
+static u8 *kfunc_copy_insn(u8 *p, const struct insn *insn, const u8 *c, const u8 *map)
+{
+	u8 op = insn->opcode.bytes[insn->opcode.nbytes - 1], rex = insn->rex_prefix.bytes[0];
+	u8 modrm = insn->modrm.value, sib = insn->sib.value, ext = X86_MODRM_REG(modrm);
+	u8 mod = X86_MODRM_MOD(modrm), reg = ext, rm = 0, idx = 4;
+	bool two = insn->opcode.nbytes == 2, group, opreg, disp8, implicit;
+	u16 regs = 0;
+	int head;
+
+	if (insn->vex_prefix.nbytes || insn->opcode.nbytes > 2 || insn->prefixes.nbytes > 1 ||
+	    (insn->prefixes.nbytes && insn->prefixes.bytes[0] != 0x66))
+		return NULL;
+	if (two) {
+		/* cmovcc, imul, movzx/movsx of words, bswap, prefetch */
+		group = op == 0x18;
+		if ((op & 0xf0) != 0x40 && op != 0xaf && op != 0xb7 && op != 0xbf &&
+		    (op & 0xf8) != 0xc8 && !(group && ext < 4))
+			return NULL;
+	} else {
+		/* add, or, and, sub, xor, cmp, mov, lea, test, imul, shifts, not, neg, mul */
+		group = op == 0x81 || op == 0x83 || op == 0xc1 || op == 0xc7 ||
+			op == 0xd1 || op == 0xd3 || op == 0xf7;
+		if (!(op < 0x40 && (op & 0xf0) != 0x10 && (op & 7) % 2 && (op & 7) < 6) &&
+		    op != 0x63 && op != 0x69 && op != 0x6b && op != 0x85 && op != 0x89 &&
+		    op != 0x8b && op != 0x8d && op != 0x98 && op != 0x99 && op != 0xa9 &&
+		    (op & 0xf8) != 0xb8 &&
+		    !(group && op != 0xc7 && op != 0xf7 && ext != 2 && ext != 3) &&
+		    !(op == 0xc7 && !ext) && !(op == 0xf7 && ext != 1 && ext < 6))
+			return NULL;
+	}
+
+	/* uses %rax, %rcx or %rdx without naming it, as in "and $imm, %eax" */
+	implicit = !two && ((op < 0x40 && (op & 7) == 5) || op == 0x98 || op == 0x99 ||
+			    op == 0xa9 || op == 0xd3 || (op == 0xf7 && (ext == 4 || ext == 5)));
+
+	opreg = (op & 0xf8) == (two ? 0xc8 : 0xb8);
+	if (opreg)
+		rm = (op & 7) + (X86_REX_B(rex) ? 8 : 0);
+	if (insn->modrm.nbytes) {
+		reg = group ? ext : ext + (X86_REX_R(rex) ? 8 : 0);
+		rm = (insn->sib.nbytes ? X86_SIB_BASE(sib) : X86_MODRM_RM(modrm)) +
+		     (X86_REX_B(rex) ? 8 : 0);
+		if (insn->sib.nbytes)
+			idx = X86_SIB_INDEX(sib) + (X86_REX_X(rex) ? 8 : 0);
+		/* rip-relative or absolute */
+		if (!mod && (rm & 7) == 5)
+			return NULL;
+		regs = (group ? 0 : BIT(reg)) | (idx != 4 ? BIT(idx) : 0);
+	}
+	if ((regs | (opreg || insn->modrm.nbytes ? BIT(rm) : 0)) & ~KFUNC_COPY_REGS)
+		return NULL;
+	/* which cannot be renamed, so they must hold their operands as for a call */
+	if (implicit && (map[0] != 0 || map[1] != 1 || map[2] != 2))
+		return NULL;
+
+	/* the instruction again, with the registers renamed */
+	if (!group)
+		reg = map[reg];
+	rm = map[rm];
+	idx = idx != 4 ? map[idx] : 4;
+	if (insn->prefixes.nbytes)
+		*p++ = 0x66;
+	rex = 0x40 | X86_REX_W(rex) | (reg & 8 ? 4 : 0) | (idx & 8 ? 2 : 0) | (rm & 8 ? 1 : 0);
+	if (rex != 0x40)
+		*p++ = rex;
+	if (two)
+		*p++ = 0x0f;
+	*p++ = opreg ? (op & 0xf8) | (rm & 7) : op;
+	if (insn->modrm.nbytes) {
+		/* a base of r13 needs a displacement */
+		disp8 = !mod && (rm & 7) == 5;
+		*p++ = (disp8 ? 1 : mod) << 6 | (reg & 7) << 3 | (insn->sib.nbytes ? 4 : rm & 7);
+		if (insn->sib.nbytes)
+			*p++ = (sib & 0xc0) | (idx & 7) << 3 | (rm & 7);
+		if (disp8)
+			*p++ = 0;
+	}
+	head = insn->prefixes.nbytes + insn->rex_prefix.nbytes + insn->opcode.nbytes +
+	       insn->modrm.nbytes + insn->sib.nbytes;
+	memcpy(p, c + head, insn->length - head);
+	return p + insn->length - head;
+}
+
+/*
+ * Copy the compiled kfunc of an inlined call up to its return, without the
+ * ENDBR and NOPs at its entry, with the operands renamed by @map.
+ */
+static int kfunc_copy(const struct bpf_kfunc_inline *in, const u8 *map, u8 *buf)
+{
+	u8 code[BPF_KFUNC_INLINE_MAX + MAX_INSN_SIZE], *c, *p = buf;
+	unsigned long size, off, ret;
+	struct insn insn;
+	int pos;
+
+	if (!kallsyms_lookup_size_offset(in->addr, &size, &off) || off)
+		return -EINVAL;
+	size = min(size, sizeof(code));
+	if (copy_from_kernel_nofault(code, (void *)in->addr, size))
+		return -EFAULT;
+	for (pos = 0; pos < size; pos += insn.length) {
+		if (insn_decode(&insn, code + pos, size - pos, INSN_MODE_64))
+			return -EINVAL;
+		c = code + pos;
+		/* ret, or a jump to the return thunk */
+		ret = in->addr + pos + insn.length + insn.immediate.value;
+		if ((insn.length == 1 && c[0] == 0xc3) ||
+		    (c[0] == 0xe9 && (ret == (unsigned long)x86_return_thunk ||
+				      ret == (unsigned long)__x86_return_thunk)))
+			return p > buf ? p - buf : -EINVAL;
+		if ((insn.length == 4 && is_endbr((u32 *)c)) || insn_is_nop(&insn))
+			continue;
+		if (insn_is_rex2(&insn))
+			return -EINVAL;
+		/* renaming adds at most a REX prefix and a displacement */
+		if (p - buf + insn.length + 2 > BPF_KFUNC_INLINE_MAX)
+			return -E2BIG;
+		p = kfunc_copy_insn(p, &insn, c, map);
+		if (!p)
+			return -EINVAL;
+	}
+	return -EINVAL;
+}
+
+static u8 x86_reg(u32 reg)
+{
+	return reg2hex[reg] + (is_ereg(reg) ? 8 : 0);
+}
+
+/*
+ * Get native code for an inlined kfunc call, with the operands in the x86
+ * registers that the verifier bound them to: the code from the emit callback
+ * of the kfunc's body, or else a copy of the compiled kfunc.
+ */
+int bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf)
+{
+	u8 reg[MAX_BPF_FUNC_REG_ARGS + 1], map[16];
+	int i, len;
+
+	for (i = 0; i < ARRAY_SIZE(map); i++)
+		map[i] = i;
+	for (i = BPF_REG_0; i <= BPF_REG_5; i++) {
+		reg[i] = x86_reg(in->reg[i]);
+		map[x86_reg(i)] = reg[i];
+	}
+	/* copying needs the instruction decoder */
+	if (in->copy && IS_ENABLED(CONFIG_INSTRUCTION_DECODER))
+		return kfunc_copy(in, map, buf);
+	if (in->copy || !in->body->emit)
+		return -EOPNOTSUPP;
+	len = in->body->emit(reg, in->imm, buf);
+	return len > 0 && len <= BPF_KFUNC_INLINE_MAX ? len : -EINVAL;
+}
+
 static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *addrs, u8 *image,
 		  u8 *rw_image, int oldproglen, struct jit_context *ctx, bool jmp_padding)
 {
@@ -2952,6 +3124,15 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			if (!imm32)
 				return -EINVAL;
 			if (src_reg == BPF_PSEUDO_KFUNC_CALL) {
+				const struct bpf_kfunc_inline *in;
+
+				/* an inlined kfunc call gets its native code */
+				in = bpf_kfunc_native(env, insn_idx);
+				if (in) {
+					memcpy(prog, in->image, in->image_len);
+					prog += in->image_len;
+					break;
+				}
 				fm = bpf_jit_find_kfunc_model(bpf_prog, insn);
 				if (!fm)
 					return -EINVAL;
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index c51083c761cf2..571c8d4da3271 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -634,6 +634,7 @@ struct bpf_insn_aux_data {
 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
 		struct bpf_map_ptr_state map_ptr_state;
 		s32 call_imm;			/* saved imm field of call insn */
+		u32 kfunc_inline;		/* 1 + index into env->kfunc_inlines, at a call */
 		u32 alu_limit;			/* limit for add/sub register with pointer */
 		struct {
 			u32 map_index;		/* index into used_maps[] */
@@ -683,6 +684,9 @@ struct bpf_insn_aux_data {
 	 */
 	u8 fastcall_spills_num:3;
 	u8 arg_prog:4;
+	/* insn belongs to the body of a kfunc call, see bpf_inline_kfunc_bodies() */
+	u8 kfunc_body:1;
+	u8 kfunc_body_entry:1;
 
 	/* below fields are initialized once */
 	unsigned int orig_idx; /* original instruction index */
@@ -1083,6 +1087,8 @@ struct bpf_verifier_env {
 	u32 scc_cnt;
 	struct bpf_iarray *succ;
 	struct bpf_iarray *gotox_tmp_buf;
+	struct bpf_kfunc_inline *kfunc_inlines;
+	u32 kfunc_inline_cnt;
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1794,14 +1800,42 @@ enum bpf_reg_arg_type {
 #define MAX_KFUNC_CALL_DESCS (MAX_KFUNC_DESCS * 2)
 static_assert(MAX_KFUNC_CALL_DESCS <= S16_MAX + 1);
 
+/* A call of a kfunc with a body, which the verifier replaced by the body */
+struct bpf_kfunc_inline {
+	struct bpf_insn call;
+	const struct bpf_kfunc_body *body;
+	unsigned long addr;		/* of the compiled kfunc */
+	u8 *image;			/* native code for the JIT */
+	u32 start;
+	/* the BPF registers that R0-R5 are bound to, and the constant arguments */
+	u8 reg[MAX_BPF_FUNC_REG_ARGS + 1];
+	s32 imm[MAX_BPF_FUNC_REG_ARGS + 1];
+	u8 image_len;
+	u8 nargs;
+	u8 imm_mask;	/* R1-R5 that hold constant (__k) arguments */
+	bool entered;	/* the verifier reached the body */
+	bool ret;	/* the kfunc returns a value */
+	bool copy;	/* the native code is a copy of the compiled kfunc */
+};
+
 struct bpf_kfunc_desc {
 	struct btf_func_model func_model;
 	struct bpf_func_proto proto;
+	const struct bpf_kfunc_body *body;
 	u32 func_id;
 	u16 offset;
+	u8 body_imm;	/* R1-R5 that are constant (__k) arguments of the body */
 	unsigned long addr;
 };
 
+struct bpf_kfunc_desc *bpf_find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset);
+int bpf_inline_kfunc_bodies(struct bpf_verifier_env *env);
+int bpf_mark_kfunc_body_regs(struct bpf_verifier_env *env, int prev_insn_idx,
+			     const struct bpf_insn_aux_data *aux);
+void bpf_restore_kfunc_calls(struct bpf_verifier_env *env);
+void bpf_free_kfunc_inlines(struct bpf_verifier_env *env);
+const struct bpf_kfunc_inline *bpf_kfunc_native(const struct bpf_verifier_env *env, int idx);
+
 struct bpf_kfunc_desc_tab {
 	u32 nr_descs;
 	u32 nr_base_descs;
diff --git a/include/linux/btf.h b/include/linux/btf.h
index 4b63bb91550a1..1e7e52e778d82 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -120,10 +120,36 @@ struct bpf_prog;
 
 typedef int (*btf_kfunc_filter_t)(const struct bpf_prog *prog, u32 kfunc_id);
 
+#define BPF_KFUNC_BODY_MAX_INSNS	32
+#define BPF_KFUNC_INLINE_MAX		128
+
+/*
+ * The body of a kfunc: len BPF instructions that compute the kfunc from its
+ * arguments in R1-R5 into R0. The verifier analyzes each call of the kfunc as
+ * the body, and the body runs in place of the call unless the JIT has native
+ * code for it, see kernel/bpf/kfunc_inline.c.
+ *
+ * emit, if set, writes native code for a call to buf, at most
+ * BPF_KFUNC_INLINE_MAX bytes, and returns its length, or an error if it has
+ * no code, for example because the CPU lacks a feature; the JIT then copies
+ * the compiled kfunc. reg[i] is the native register that the verifier bound
+ * Ri to, for R0-R5, and those of R1-R5 that are not arguments are free to
+ * use. imm[i] is the value of Ri if it is a constant (__k) argument. Like the
+ * rest of the JIT, native code is trusted to compute what the body computes.
+ */
+struct bpf_kfunc_body {
+	const u32 *id;
+	const struct bpf_insn *insns;
+	u32 len;
+	int (*emit)(const u8 *reg, const s32 *imm, u8 *buf);
+};
+
 struct btf_kfunc_id_set {
 	struct module *owner;
 	struct btf_id_set8 *set;
 	btf_kfunc_filter_t filter;
+	const struct bpf_kfunc_body *bodies;
+	u32 body_cnt;
 };
 
 struct btf_id_dtor_kfunc {
@@ -604,6 +630,7 @@ const char *btf_str_by_offset(const struct btf *btf, u32 offset);
 struct btf *btf_parse_vmlinux(void);
 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);
+const struct bpf_kfunc_body *btf_find_kfunc_body(const struct btf *btf, u32 kfunc_btf_id);
 int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag);
 bool btf_kfunc_is_allowed(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog);
 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 9339c6131f8ff..d93629eb40cd3 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -1239,6 +1239,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 void bpf_jit_compile(struct bpf_prog *prog);
 bool bpf_jit_needs_zext(void);
 bool bpf_jit_inlines_helper_call(s32 imm);
+struct bpf_kfunc_inline;
+int bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf);
 bool bpf_jit_supports_subprog_tailcalls(void);
 bool bpf_jit_supports_percpu_insn(void);
 bool bpf_jit_supports_kfunc_call(void);
diff --git a/kernel/bpf/Kconfig b/kernel/bpf/Kconfig
index 98493e32db2ad..ca0dbfa1f81c5 100644
--- a/kernel/bpf/Kconfig
+++ b/kernel/bpf/Kconfig
@@ -101,6 +101,7 @@ config BPF_CRYPTO
 	  data. The supported algorithms are AES-CBC and AES-ECB.
 
 source "kernel/bpf/preload/Kconfig"
+source "kernel/bpf/insn_kfuncs/Kconfig"
 
 config BPF_LSM
 	bool "Enable BPF LSM Instrumentation"
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index c1f9b0d3468d3..94c81491a8e65 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_
 obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
 obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o
+obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o kfunc_inline.o
 obj-${CONFIG_BPF_LSM}	  += bpf_inode_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
 obj-$(CONFIG_BPF_JIT) += trampoline.o
@@ -60,6 +60,7 @@ obj-${CONFIG_BPF_LSM} += bpf_lsm_proto.o bpf_lsm.o
 endif
 obj-$(CONFIG_BPF_CRYPTO) += crypto.o
 obj-$(CONFIG_BPF_PRELOAD) += preload/
+obj-$(CONFIG_BPF_INSN_KFUNCS) += insn_kfuncs/
 
 obj-$(CONFIG_BPF_SYSCALL) += relo_core.o
 obj-$(CONFIG_BPF_SYSCALL) += btf_iter.o
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 0630675377aaa..4b729d0367bb2 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -246,6 +246,14 @@ struct btf_id_dtor_kfunc_tab {
 	struct btf_id_dtor_kfunc dtors[];
 };
 
+struct btf_kfunc_body_tab {
+	u32 cnt;
+	struct {
+		u32 id;
+		const struct bpf_kfunc_body *body;
+	} bodies[];
+};
+
 struct btf_struct_ops_tab {
 	u32 cnt;
 	u32 capacity;
@@ -269,6 +277,7 @@ struct btf {
 	struct rcu_head rcu;
 	struct btf_kfunc_set_tab *kfunc_set_tab;
 	struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
+	struct btf_kfunc_body_tab *kfunc_body_tab;
 	struct btf_struct_metas *struct_meta_tab;
 	struct btf_struct_ops_tab *struct_ops_tab;
 	struct btf_layout *layout;
@@ -1883,6 +1892,7 @@ static void btf_free(struct btf *btf)
 	btf_free_struct_meta_tab(btf);
 	btf_free_dtor_kfunc_tab(btf);
 	btf_free_kfunc_set_tab(btf);
+	kfree(btf->kfunc_body_tab);
 	btf_free_struct_ops_tab(btf);
 	kvfree(btf->types);
 	kvfree(btf->resolved_sizes);
@@ -9695,6 +9705,118 @@ 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);
 }
 
+const struct bpf_kfunc_body *btf_find_kfunc_body(const struct btf *btf, u32 kfunc_btf_id)
+{
+	const struct btf_kfunc_body_tab *tab = btf->kfunc_body_tab;
+	u32 i;
+
+	for (i = 0; tab && i < tab->cnt; i++)
+		if (tab->bodies[i].id == kfunc_btf_id)
+			return tab->bodies[i].body;
+	return NULL;
+}
+
+/* a scalar or a pointer of one register */
+static bool btf_kfunc_reg_type(const struct btf *btf, u32 id)
+{
+	const struct btf_type *t = btf_type_skip_modifiers(btf, id, NULL);
+
+	return btf_type_is_ptr(t) ||
+	       ((btf_type_is_int(t) || btf_is_any_enum(t)) && t->size <= sizeof(u64));
+}
+
+/*
+ * A kfunc with a body takes each argument in one of R1-R5, constant (__k)
+ * ones in 32 bits for native code, and returns in R0. Its body uses R0-R5,
+ * no instruction of cpu v4, which not every JIT has, and jumps only forward
+ * within it, so that it ends by falling through the last instruction. The
+ * verifier checks the rest.
+ */
+static bool btf_check_kfunc_body(const struct btf *btf, const struct btf_type *func,
+				 const struct bpf_kfunc_body *b)
+{
+	const struct btf_type *proto = btf_type_by_id(btf, func->type);
+	const struct btf_param *args = btf_params(proto);
+	int i, n = btf_type_vlen(proto), len = b->len;
+	const struct bpf_insn *insn;
+	u8 op;
+
+	if (n > MAX_BPF_FUNC_REG_ARGS || !b->insns || !len || len > BPF_KFUNC_BODY_MAX_INSNS ||
+	    (proto->type && !btf_kfunc_reg_type(btf, proto->type)))
+		return false;
+	for (i = 0; i < n; i++)
+		if (!btf_kfunc_reg_type(btf, args[i].type) ||
+		    (btf_param_match_suffix(btf, &args[i], "__k") &&
+		     btf_type_skip_modifiers(btf, args[i].type, NULL)->size > sizeof(s32)))
+			return false;
+	for (i = 0; i < len; i++) {
+		insn = &b->insns[i];
+		op = BPF_OP(insn->code);
+		if (insn->dst_reg > BPF_REG_5 || insn->src_reg > BPF_REG_5)
+			return false;
+		switch (BPF_CLASS(insn->code)) {
+		case BPF_ALU:
+		case BPF_ALU64:		/* not movsx, sdiv, smod or bswap */
+			if (insn->off || (BPF_CLASS(insn->code) == BPF_ALU64 && op == BPF_END))
+				return false;
+			break;
+		case BPF_LDX:
+		case BPF_ST:
+		case BPF_STX:		/* not ldsx or atomics */
+			if (BPF_MODE(insn->code) != BPF_MEM)
+				return false;
+			break;
+		case BPF_JMP:
+		case BPF_JMP32:		/* forward jumps within the body, not gotol */
+			if (op == BPF_CALL || op == BPF_EXIT || op == BPF_JCOND ||
+			    (op == BPF_JA && insn->code != (BPF_JMP | BPF_JA)) ||
+			    insn->off < 0 || insn->off >= len - i - 1)
+				return false;
+			break;
+		default:		/* not ld_imm64 */
+			return false;
+		}
+	}
+	return true;
+}
+
+static int btf_add_kfunc_bodies(struct btf *btf, const struct btf_kfunc_id_set *kset)
+{
+	u32 i, id, cnt = btf->kfunc_body_tab ? btf->kfunc_body_tab->cnt : 0;
+	struct btf_kfunc_body_tab *tab;
+	const struct bpf_kfunc_body *b;
+	const struct btf_type *t;
+	u32 *pair;
+
+	if (!kset->body_cnt)
+		return 0;
+	tab = krealloc(btf->kfunc_body_tab, struct_size(tab, bodies, cnt + kset->body_cnt),
+		       GFP_KERNEL | __GFP_NOWARN);
+	if (!tab)
+		return -ENOMEM;
+	tab->cnt = cnt;
+	btf->kfunc_body_tab = tab;
+	for (i = 0; i < kset->body_cnt; i++) {
+		b = &kset->bodies[i];
+		id = btf_relocate_id(btf, *b->id);
+		t = btf_type_by_id(btf, id);
+		pair = btf_id_set8_contains(kset->set, *b->id);
+		/* the body stands for the call, so no kfunc flags apply */
+		if (!pair || pair[1] || !t || !btf_type_is_func(t) ||
+		    !btf_check_kfunc_body(btf, t, b)) {
+			/* a set that fails to register leaves no bodies */
+			tab->cnt = cnt;
+			return -EINVAL;
+		}
+		/* a set registered for several hooks adds its bodies once */
+		if (!btf_find_kfunc_body(btf, id)) {
+			tab->bodies[tab->cnt].id = id;
+			tab->bodies[tab->cnt++].body = b;
+		}
+	}
+	return 0;
+}
+
 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
 				       const struct btf_kfunc_id_set *kset)
 {
@@ -9714,6 +9836,10 @@ static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
 			goto err_out;
 	}
 
+	ret = btf_add_kfunc_bodies(btf, kset);
+	if (ret)
+		goto err_out;
+
 	ret = btf_populate_kfunc_set(btf, hook, kset);
 
 err_out:
diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c
index b1528adbeb79d..8fa745e62e7ee 100644
--- a/kernel/bpf/const_fold.c
+++ b/kernel/bpf/const_fold.c
@@ -268,6 +268,10 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 		memcpy(ci_out, ci, sizeof(ci_out));
 
 		const_reg_xfer(env, ci_out, insn, insns, idx);
+		/* the body of a kfunc call leaves R0-R5 unknown, like the call */
+		if (insn_aux[idx].kfunc_body)
+			for (r = BPF_REG_0; r <= BPF_REG_5; r++)
+				ci_out[r] = unknown;
 
 		succ = bpf_insn_successors(env, idx);
 		for (int s = 0; s < succ->cnt; s++)
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 05c89396119ad..68665ea2499e9 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -3299,6 +3299,15 @@ bool __weak bpf_jit_inlines_helper_call(s32 imm)
 	return false;
 }
 
+/* Write native code for an inlined kfunc call, see struct bpf_kfunc_inline,
+ * to @buf for the JIT to copy. Return its length, or an error to keep the
+ * body of the kfunc.
+ */
+int __weak bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf)
+{
+	return -EOPNOTSUPP;
+}
+
 /* Return TRUE if the JIT backend supports mixing bpf2bpf and tailcalls. */
 bool __weak bpf_jit_supports_subprog_tailcalls(void)
 {
diff --git a/kernel/bpf/insn_kfuncs/Kconfig b/kernel/bpf/insn_kfuncs/Kconfig
new file mode 100644
index 0000000000000..179236855d652
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/Kconfig
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: GPL-2.0-only
+config BPF_INSN_KFUNCS
+	tristate "Kfuncs for CPU instructions that BPF lacks"
+	depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+	help
+	  Provide kfuncs for rotate, conditional select, bit field extract,
+	  big-endian load, prefetch, 16-byte copy and address computation.
+	  The verifier checks each call as the kfunc's BPF body, and the JIT
+	  puts native code in its place where it can.
+
+	  If unsure, say N.
+
+config BPF_INSN_KFUNCS_ARCH
+	bool
+	depends on BPF_INSN_KFUNCS
+	default y if X86_64
diff --git a/kernel/bpf/insn_kfuncs/Makefile b/kernel/bpf/insn_kfuncs/Makefile
new file mode 100644
index 0000000000000..31e7ef567c90f
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_BPF_INSN_KFUNCS) += bpf_insn_kfuncs.o
+ifeq ($(CONFIG_BPF_INSN_KFUNCS_ARCH),y)
+CFLAGS_bpf_insn_kfuncs.o += -I$(src)/$(SRCARCH)
+endif
diff --git a/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c b/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c
new file mode 100644
index 0000000000000..1fcd0d7d0690c
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Kfuncs for CPU instructions that BPF lacks, with BPF bodies, see struct
+ * bpf_kfunc_body. Arguments named __k must be known constants.
+ */
+#include <linux/bitops.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
+#include <linux/filter.h>
+#include <linux/module.h>
+#include <linux/unaligned.h>
+
+__bpf_kfunc_start_defs();
+
+__bpf_kfunc u64 bpf_rol64(u64 x, u32 n__k)
+{
+	return rol64(x, n__k);
+}
+
+__bpf_kfunc u64 bpf_select64(u64 cond, u64 a, u64 b)
+{
+	return cond ? a : b;
+}
+
+__bpf_kfunc u64 bpf_extract64(u64 x, u32 start__k, u32 len__k)
+{
+	return x << (64 - start__k - len__k) >> (64 - len__k);
+}
+
+__bpf_kfunc u64 bpf_load_be64(const void *p, s32 off__k)
+{
+	return get_unaligned_be64(p + off__k);
+}
+
+__bpf_kfunc void bpf_prefetch(const void *p)
+{
+	/* not prefetch(), which boot-time alternatives may rewrite */
+	__builtin_prefetch(p);
+}
+
+__bpf_kfunc void bpf_copy16(void *dst, const void *src)
+{
+	/* both loads first, as in the body, in case the buffers overlap */
+	u64 lo = get_unaligned((const u64 *)src);
+	u64 hi = get_unaligned((const u64 *)(src + 8));
+
+	put_unaligned(lo, (u64 *)dst);
+	put_unaligned(hi, (u64 *)(dst + 8));
+}
+
+__bpf_kfunc u64 bpf_lea64(u64 base, u64 index, u32 scale__k, s32 disp__k)
+{
+	return base + index * scale__k + disp__k;
+}
+
+__bpf_kfunc_end_defs();
+
+/* x << n | x >> (-n & 63) */
+static const struct bpf_insn rol64_body[] = {
+	BPF_ALU64_IMM(BPF_AND, BPF_REG_2, 63),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_LSH, BPF_REG_0, BPF_REG_2),
+	BPF_ALU64_IMM(BPF_NEG, BPF_REG_2, 0),
+	BPF_ALU64_IMM(BPF_AND, BPF_REG_2, 63),
+	BPF_ALU64_REG(BPF_RSH, BPF_REG_1, BPF_REG_2),
+	BPF_ALU64_REG(BPF_OR, BPF_REG_0, BPF_REG_1),
+};
+
+/* the jump lands within the body, here on its last instruction */
+static const struct bpf_insn select64_body[] = {
+	BPF_JMP_IMM(BPF_JNE, BPF_REG_1, 0, 1),
+	BPF_MOV64_REG(BPF_REG_2, BPF_REG_3),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
+};
+
+/* x << (64 - start - len) >> (64 - len) */
+static const struct bpf_insn extract64_body[] = {
+	BPF_MOV32_IMM(BPF_REG_4, 64),
+	BPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_2),
+	BPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_3),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_LSH, BPF_REG_0, BPF_REG_4),
+	BPF_MOV32_IMM(BPF_REG_4, 64),
+	BPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_3),
+	BPF_ALU64_REG(BPF_RSH, BPF_REG_0, BPF_REG_4),
+};
+
+/* the offset is an s32 */
+static const struct bpf_insn load_be64_body[] = {
+	BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 32),
+	BPF_ALU64_IMM(BPF_ARSH, BPF_REG_2, 32),
+	BPF_ALU64_REG(BPF_ADD, BPF_REG_1, BPF_REG_2),
+	BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, 0),
+	BPF_ENDIAN(BPF_TO_BE, BPF_REG_0, 64),
+};
+
+/* a load whose value is not used, of memory that the program may read */
+static const struct bpf_insn prefetch_body[] = {
+	BPF_LDX_MEM(BPF_B, BPF_REG_1, BPF_REG_1, 0),
+};
+
+/* two loads, then two stores */
+static const struct bpf_insn copy16_body[] = {
+	BPF_LDX_MEM(BPF_DW, BPF_REG_4, BPF_REG_2, 0),
+	BPF_LDX_MEM(BPF_DW, BPF_REG_5, BPF_REG_2, 8),
+	BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_4, 0),
+	BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_5, 8),
+};
+
+/* base + index * scale + disp, scale a u32 and disp an s32 */
+static const struct bpf_insn lea64_body[] = {
+	BPF_MOV32_REG(BPF_REG_3, BPF_REG_3),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
+	BPF_ALU64_REG(BPF_MUL, BPF_REG_0, BPF_REG_3),
+	BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_IMM(BPF_LSH, BPF_REG_4, 32),
+	BPF_ALU64_IMM(BPF_ARSH, BPF_REG_4, 32),
+	BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_4),
+};
+
+#ifdef CONFIG_BPF_INSN_KFUNCS_ARCH
+#include "insn_kfuncs.h" /* $(SRCARCH)/insn_kfuncs.h */
+#else
+#define rol64_emit	NULL
+#define select64_emit	NULL
+#define extract64_emit	NULL
+#define load_be64_emit	NULL
+#define lea64_emit	NULL
+#endif
+
+BTF_KFUNCS_START(insn_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_rol64)
+BTF_ID_FLAGS(func, bpf_select64)
+BTF_ID_FLAGS(func, bpf_extract64)
+BTF_ID_FLAGS(func, bpf_load_be64)
+BTF_ID_FLAGS(func, bpf_prefetch)
+BTF_ID_FLAGS(func, bpf_copy16)
+BTF_ID_FLAGS(func, bpf_lea64)
+BTF_KFUNCS_END(insn_kfunc_ids)
+
+BTF_ID_LIST(body_ids)
+BTF_ID(func, bpf_rol64)
+BTF_ID(func, bpf_select64)
+BTF_ID(func, bpf_extract64)
+BTF_ID(func, bpf_load_be64)
+BTF_ID(func, bpf_prefetch)
+BTF_ID(func, bpf_copy16)
+BTF_ID(func, bpf_lea64)
+
+#define BODY(i, op, emit)	{ &body_ids[i], op##_body, ARRAY_SIZE(op##_body), emit }
+
+/* without emit, the JIT copies the kfunc, whose code is the instruction itself */
+static const struct bpf_kfunc_body bodies[] = {
+	BODY(0, rol64, rol64_emit),
+	BODY(1, select64, select64_emit),
+	BODY(2, extract64, extract64_emit),
+	BODY(3, load_be64, load_be64_emit),
+	BODY(4, prefetch, NULL),
+	BODY(5, copy16, NULL),
+	BODY(6, lea64, lea64_emit),
+};
+
+static const struct btf_kfunc_id_set insn_kfunc_set = {
+	.owner    = THIS_MODULE,
+	.set      = &insn_kfunc_ids,
+	.bodies   = bodies,
+	.body_cnt = ARRAY_SIZE(bodies),
+};
+
+static int __init insn_kfuncs_init(void)
+{
+	return register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &insn_kfunc_set);
+}
+
+/* the kfunc set goes away with the module's BTF */
+static void __exit insn_kfuncs_exit(void)
+{
+}
+
+module_init(insn_kfuncs_init);
+module_exit(insn_kfuncs_exit);
+
+MODULE_DESCRIPTION("Kfuncs for CPU instructions that BPF lacks");
+MODULE_LICENSE("GPL");
diff --git a/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h b/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h
new file mode 100644
index 0000000000000..5809bb69b4cd6
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h
@@ -0,0 +1,155 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* x86-64 code for the kfuncs in bpf_insn_kfuncs.c, see struct bpf_kfunc_body */
+#include <linux/cpufeature.h>
+#include <linux/log2.h>
+#include <linux/unaligned.h>
+
+static u8 *x86_rex(u8 *p, bool w, u8 reg, u8 rm)
+{
+	u8 b = 0x40 | (w ? 8 : 0) | (reg & 8 ? 4 : 0) | (rm & 8 ? 1 : 0);
+
+	if (b != 0x40)
+		*p++ = b;
+	return p;
+}
+
+/* 64-bit op %reg, %rm */
+static u8 *x86_op_rr(u8 *p, u8 op, u8 reg, u8 rm)
+{
+	p = x86_rex(p, true, reg, rm);
+	*p++ = op;
+	*p++ = 0xc0 | (reg & 7) << 3 | (rm & 7);
+	return p;
+}
+
+/*
+ * ModRM, SIB and displacement of disp(%base, %index, 1 << scale), with @reg in
+ * the reg field. An @index of 4 (%rsp) is none.
+ */
+static u8 *x86_mem(u8 *p, u8 reg, u8 base, u8 index, u8 scale, s32 disp)
+{
+	u8 mod = !disp && (base & 7) != 5 ? 0 : disp == (s8)disp ? 1 : 2;
+	bool sib = index != 4 || (base & 7) == 4;
+
+	*p++ = mod << 6 | (reg & 7) << 3 | (sib ? 4 : base & 7);
+	if (sib)
+		*p++ = scale << 6 | (index & 7) << 3 | (base & 7);
+	if (mod == 1)
+		*p++ = disp;
+	if (mod == 2) {
+		put_unaligned_le32(disp, p);
+		p += 4;
+	}
+	return p;
+}
+
+static int rol64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], src = reg[1], n = imm[BPF_REG_2] & 63, *p = buf;
+
+	if (n && dst != src && cpu_feature_enabled(X86_FEATURE_BMI2)) {
+		/* rorx $(64 - n), %src, %dst */
+		*p++ = 0xc4;
+		*p++ = (dst & 8 ? 0 : 0x80) | 0x40 | (src & 8 ? 0 : 0x20) | 0x03;
+		*p++ = 0xfb;
+		*p++ = 0xf0;
+		*p++ = 0xc0 | (dst & 7) << 3 | (src & 7);
+		*p++ = 64 - n;
+		return p - buf;
+	}
+	if (dst != src || !n)
+		p = x86_op_rr(p, 0x89, src, dst);	/* mov %src, %dst */
+	if (n) {
+		/* rol $n, %dst */
+		p = x86_rex(p, true, 0, dst);
+		*p++ = 0xc1;
+		*p++ = 0xc0 | (dst & 7);
+		*p++ = n;
+	}
+	return p - buf;
+}
+
+/* cmovcc %src, %dst */
+static u8 *x86_cmov(u8 *p, u8 cc, u8 dst, u8 src)
+{
+	p = x86_rex(p, true, dst, src);
+	*p++ = 0x0f;
+	*p++ = 0x40 | cc;
+	*p++ = 0xc0 | (dst & 7) << 3 | (src & 7);
+	return p;
+}
+
+/*
+ * dst = cc ? a : b, after the test or compare at @p. The flags come first, so
+ * the result may take the register of an operand they read. A result in the
+ * register of a takes b with the inverse condition, which a copy of the
+ * compiled kfunc cannot do.
+ */
+static int x86_select(u8 *buf, u8 *p, u8 cc, u8 dst, u8 a, u8 b)
+{
+	if (dst == a)
+		return x86_cmov(p, cc ^ 1, dst, b) - buf;
+	if (dst != b)
+		p = x86_op_rr(p, 0x89, b, dst);	/* mov %b, %dst */
+	return x86_cmov(p, cc, dst, a) - buf;
+}
+
+static int select64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 cond = reg[1];
+
+	/* test %cond, %cond; cmovne */
+	return x86_select(buf, x86_op_rr(buf, 0x85, cond, cond), 0x5, reg[0],
+			   reg[2], reg[3]);
+}
+
+/* R4 is free for the control word, as there are three arguments */
+static int extract64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], src = reg[1], ctl = dst != src ? dst : reg[4];
+	u32 start = imm[BPF_REG_2], len = imm[BPF_REG_3];
+	u8 *p = buf;
+
+	if (!cpu_feature_enabled(X86_FEATURE_BMI1) || start > 63 || !len || len > 64 - start)
+		return -EOPNOTSUPP;
+	/* mov $(start | len << 8), %ctl */
+	p = x86_rex(p, false, 0, ctl);
+	*p++ = 0xb8 | (ctl & 7);
+	put_unaligned_le32(start | len << 8, p);
+	p += 4;
+	/* bextr %ctl, %src, %dst */
+	*p++ = 0xc4;
+	*p++ = (dst & 8 ? 0 : 0x80) | 0x40 | (src & 8 ? 0 : 0x20) | 0x02;
+	*p++ = 0x80 | (~ctl & 0xf) << 3;
+	*p++ = 0xf7;
+	*p++ = 0xc0 | (dst & 7) << 3 | (src & 7);
+	return p - buf;
+}
+
+static int load_be64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], base = reg[1], *p = buf;
+
+	if (!cpu_feature_enabled(X86_FEATURE_MOVBE))
+		return -EOPNOTSUPP;
+	/* movbe off(%base), %dst */
+	p = x86_rex(p, true, dst, base);
+	*p++ = 0x0f;
+	*p++ = 0x38;
+	*p++ = 0xf0;
+	return x86_mem(p, dst, base, 4, 0, imm[BPF_REG_2]) - buf;
+}
+
+static int lea64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], base = reg[1], index = reg[2], *p = buf;
+	u32 scale = imm[BPF_REG_3];
+
+	/* %rsp cannot be an index, and the scale is 1, 2, 4 or 8 */
+	if (index == 4 || !is_power_of_2(scale) || scale > 8)
+		return -EOPNOTSUPP;
+	/* lea disp(%base, %index, scale), %dst */
+	*p++ = 0x48 | (dst & 8 ? 4 : 0) | (index & 8 ? 2 : 0) | (base & 8 ? 1 : 0);
+	*p++ = 0x8d;
+	return x86_mem(p, dst, base, index, ilog2(scale), imm[BPF_REG_4]) - buf;
+}
diff --git a/kernel/bpf/kfunc_inline.c b/kernel/bpf/kfunc_inline.c
new file mode 100644
index 0000000000000..daf92c3ad512c
--- /dev/null
+++ b/kernel/bpf/kfunc_inline.c
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Calls of kfuncs that have a BPF body, see struct bpf_kfunc_body */
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/filter.h>
+#include <linux/slab.h>
+
+#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
+
+static struct bpf_kfunc_desc *body_desc(struct bpf_verifier_env *env,
+					const struct bpf_insn *insn)
+{
+	struct bpf_kfunc_desc *desc;
+
+	if (!bpf_pseudo_kfunc_call(insn))
+		return NULL;
+	desc = bpf_find_kfunc_desc(env->prog, insn->imm, insn->off);
+	return desc && desc->body ? desc : NULL;
+}
+
+/*
+ * Replace each call of a kfunc with a body by the body, so that the verifier
+ * analyzes the operation in the caller's context. The entry and exit of the
+ * body get the register effects of the call, see bpf_mark_kfunc_body_regs().
+ * After verification bpf_restore_kfunc_calls() puts the call back if the JIT
+ * has native code for it, and keeps the body otherwise.
+ */
+int bpf_inline_kfunc_bodies(struct bpf_verifier_env *env)
+{
+	struct bpf_kfunc_desc *desc;
+	struct bpf_kfunc_inline *r;
+	struct bpf_prog *prog;
+	u32 i, j, cnt = 0;
+
+	for (i = 0; i < env->prog->len; i++)
+		cnt += !!body_desc(env, &env->prog->insnsi[i]);
+	if (!cnt)
+		return 0;
+	env->kfunc_inlines = kvzalloc_objs(*env->kfunc_inlines, cnt, GFP_KERNEL_ACCOUNT);
+	if (!env->kfunc_inlines)
+		return -ENOMEM;
+
+	for (i = 0; i < env->prog->len; i++) {
+		desc = body_desc(env, &env->prog->insnsi[i]);
+		if (!desc)
+			continue;
+		r = &env->kfunc_inlines[env->kfunc_inline_cnt++];
+		r->call = env->prog->insnsi[i];
+		r->body = desc->body;
+		r->addr = desc->addr;
+		r->start = i;
+		r->nargs = desc->func_model.nr_args;
+		r->imm_mask = desc->body_imm;
+		r->ret = desc->func_model.ret_size;
+		prog = bpf_patch_insn_data(env, i, r->body->insns, r->body->len);
+		if (!prog)
+			return -ENOMEM;
+		env->prog = prog;
+		for (j = i; j < i + r->body->len; j++)
+			env->insn_aux_data[j].kfunc_body = 1;
+		env->insn_aux_data[i].kfunc_body_entry = 1;
+		i += r->body->len - 1;
+	}
+	return 0;
+}
+
+/*
+ * The body of a kfunc gets only the arguments of the call and leaves R1-R5
+ * like it. The constant (__k) arguments must be known, and native code may
+ * use their values.
+ */
+int bpf_mark_kfunc_body_regs(struct bpf_verifier_env *env, int prev_insn_idx,
+			     const struct bpf_insn_aux_data *aux)
+{
+	struct bpf_kfunc_inline *r = env->kfunc_inlines;
+	struct bpf_reg_state *regs = cur_regs(env);
+	u32 clobber = 0;
+	int i, err;
+
+	/* leaving the body */
+	if (prev_insn_idx >= 0 && env->insn_aux_data[prev_insn_idx].kfunc_body &&
+	    (!aux->kfunc_body || aux->kfunc_body_entry))
+		clobber |= GENMASK(BPF_REG_5, BPF_REG_1);
+	if (aux->kfunc_body_entry) {
+		while (r->start != env->insn_idx)
+			r++;
+		for (i = BPF_REG_1; i <= BPF_REG_5 && !env->cur_state->speculative; i++) {
+			if (!(r->imm_mask & BIT(i)))
+				continue;
+			if (regs[i].type != SCALAR_VALUE || !tnum_is_const(regs[i].var_off)) {
+				verbose(env, "R%d must be a known constant\n", i);
+				return -EINVAL;
+			}
+			err = mark_chain_precision(env, i);
+			if (err)
+				return err;
+			/* emitted code needs the same constants on every path */
+			if (r->entered && r->imm[i] != (s32)regs[i].var_off.value)
+				r->copy = true;
+			r->imm[i] = regs[i].var_off.value;
+		}
+		r->entered = true;
+		clobber |= BIT(BPF_REG_0) | (GENMASK(BPF_REG_5, BPF_REG_0) &
+					     ~GENMASK(r->nargs, BPF_REG_0));
+	}
+	for (i = BPF_REG_0; i <= BPF_REG_5; i++) {
+		if (!(clobber & BIT(i)))
+			continue;
+		bpf_mark_reg_not_init(env, &regs[i]);
+		mark_reg_scratched(env, i);
+	}
+	return 0;
+}
+
+/*
+ * Native code can replace the body of a kfunc call that the verifier reached
+ * and does not rewrite later: no speculation barriers, sanitation or arena
+ * conversion, and memory accesses only to memory that the JIT accesses as is.
+ */
+static bool kfunc_native_ok(struct bpf_verifier_env *env, const struct bpf_kfunc_inline *r)
+{
+	u32 i;
+
+	if (env->prog->blinding_requested || (r->imm_mask && !r->entered))
+		return false;
+	for (i = 0; i < r->body->len; i++) {
+		const struct bpf_insn_aux_data *aux = &env->insn_aux_data[r->start + i];
+		u8 class = BPF_CLASS(r->body->insns[i].code);
+
+		if (aux->nospec || aux->nospec_result || aux->alu_state || aux->needs_zext ||
+		    aux->arena_scalar)
+			return false;
+		if (class != BPF_LDX && class != BPF_STX && class != BPF_ST)
+			continue;
+		if (type_flag(aux->ptr_type) & ~MEM_RDONLY)
+			return false;
+		switch (base_type(aux->ptr_type)) {
+		case PTR_TO_STACK:
+			break;
+		case PTR_TO_MAP_VALUE:
+		case PTR_TO_MEM:
+		case PTR_TO_PACKET:
+		case PTR_TO_PACKET_META:
+			/* the JIT checks these accesses with KASAN, native code does not */
+			if (IS_ENABLED(CONFIG_BPF_JIT_KASAN))
+				return false;
+			break;
+		default:
+			return false;
+		}
+	}
+	return true;
+}
+
+/*
+ * Bind the operands of a kfunc call in r->reg and return the moves that this
+ * makes unnecessary in @drop:
+ * - an argument copied from R6-R9 by a 64-bit move right before the call is
+ *   used in place if that register is dead after the call;
+ * - emitted native code has the constant arguments as immediates;
+ * - the result goes straight to its R6-R9 destination.
+ * No jump may land between such a move and the call. Only emitted code may
+ * share the result register with an argument.
+ */
+static int kfunc_bind(struct bpf_verifier_env *env, struct bpf_kfunc_inline *r, u32 *drop)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_insn *insns = env->prog->insnsi, *mov;
+	u32 end = r->start + r->body->len, i;
+	bool emit = !r->copy;
+	u16 used = 0, written = 0;
+	u8 dst, src;
+	int n = 0;
+
+	for (i = 0; i <= MAX_BPF_FUNC_REG_ARGS; i++)
+		r->reg[i] = i;
+
+	/* walk back over moves into R1-R5 that do not read R0-R5 */
+	for (i = r->start; i-- > 0 && !bpf_is_jump_target(env, i + 1);) {
+		mov = &insns[i];
+		dst = mov->dst_reg;
+		src = mov->src_reg;
+		if ((BPF_CLASS(mov->code) != BPF_ALU64 && BPF_CLASS(mov->code) != BPF_ALU) ||
+		    BPF_OP(mov->code) != BPF_MOV || dst < BPF_REG_1 || dst > BPF_REG_5 ||
+		    aux[i].kfunc_body ||
+		    (BPF_SRC(mov->code) == BPF_X && (src < BPF_REG_6 || src > BPF_REG_9)))
+			break;
+		if (dst <= r->nargs && !(written & BIT(dst)) && !mov->off) {
+			if (BPF_SRC(mov->code) == BPF_K && (r->imm_mask & BIT(dst)) && emit) {
+				drop[n++] = i;
+			} else if (mov->code == (BPF_ALU64 | BPF_MOV | BPF_X) &&
+				   !(used & BIT(src)) &&
+				   !(aux[end].live_regs_before & BIT(src))) {
+				r->reg[dst] = src;
+				used |= BIT(src);
+				drop[n++] = i;
+			}
+		}
+		written |= BIT(dst);
+	}
+
+	mov = &insns[end];
+	dst = mov->dst_reg;
+	/* the result register must be live so that the JIT saves it */
+	if (r->ret && !bpf_is_jump_target(env, end) && end + 1 < env->prog->len &&
+	    mov->code == (BPF_ALU64 | BPF_MOV | BPF_X) && !mov->off &&
+	    mov->src_reg == BPF_REG_0 && dst >= BPF_REG_6 && dst <= BPF_REG_9 &&
+	    (emit || !(used & BIT(dst))) &&
+	    (aux[end + 1].live_regs_before & BIT(dst)) &&
+	    !(aux[end + 1].live_regs_before & BIT(BPF_REG_0))) {
+		r->reg[BPF_REG_0] = dst;
+		drop[n++] = end;
+	}
+	return n;
+}
+
+/*
+ * Put back the calls that the JIT has native code for: the code from the
+ * kfunc's emit callback, or else a copy of the compiled kfunc. The rest of
+ * the body and the moves that binding makes unnecessary become nops, which
+ * bpf_opt_remove_nops() removes. Other calls keep their body.
+ */
+void bpf_restore_kfunc_calls(struct bpf_verifier_env *env)
+{
+	struct bpf_insn *insns = env->prog->insnsi;
+	u32 drop[MAX_BPF_FUNC_REG_ARGS + 1];
+	u8 code[BPF_KFUNC_INLINE_MAX];
+	int i, j, n, len;
+
+	for (i = 0; i < env->kfunc_inline_cnt; i++) {
+		struct bpf_kfunc_inline *r = &env->kfunc_inlines[i];
+
+		if (!kfunc_native_ok(env, r))
+			continue;
+		n = kfunc_bind(env, r, drop);
+		len = bpf_jit_inline_kfunc(r, code);
+		if (len <= 0 && !r->copy) {
+			r->copy = true;
+			n = kfunc_bind(env, r, drop);
+			len = bpf_jit_inline_kfunc(r, code);
+		}
+		r->image = len > 0 ? kmemdup(code, len, GFP_KERNEL_ACCOUNT) : NULL;
+		if (!r->image)
+			continue;
+		r->image_len = len;
+		for (j = 0; j < n; j++)
+			insns[drop[j]] = BPF_JMP_A(0);
+		insns[r->start] = r->call;
+		for (j = r->start + 1; j < r->start + r->body->len; j++)
+			insns[j] = BPF_JMP_A(0);
+		env->insn_aux_data[r->start].kfunc_inline = i + 1;
+	}
+}
+
+/* The inlined kfunc call at @idx, if the JIT puts native code there */
+const struct bpf_kfunc_inline *bpf_kfunc_native(const struct bpf_verifier_env *env, int idx)
+{
+	u32 i = env && env->insn_aux_data[idx].kfunc_body_entry ?
+		env->insn_aux_data[idx].kfunc_inline : 0;
+
+	if (!i || i > env->kfunc_inline_cnt || !env->kfunc_inlines[i - 1].image)
+		return NULL;
+	return &env->kfunc_inlines[i - 1];
+}
+
+void bpf_free_kfunc_inlines(struct bpf_verifier_env *env)
+{
+	u32 i;
+
+	for (i = 0; i < env->kfunc_inline_cnt; i++)
+		kfree(env->kfunc_inlines[i].image);
+	kvfree(env->kfunc_inlines);
+}
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index fd3c0206bd67d..2f58794784100 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -2569,8 +2569,8 @@ static int kfunc_btf_cmp_by_off(const void *a, const void *b)
 	return d0->offset - d1->offset;
 }
 
-static struct bpf_kfunc_desc *
-find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
+struct bpf_kfunc_desc *
+bpf_find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
 {
 	struct bpf_kfunc_desc desc = {
 		.func_id = func_id,
@@ -2877,10 +2877,11 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 	struct btf_func_model func_model;
 	struct bpf_kfunc_desc_tab *tab;
 	struct bpf_prog_aux *prog_aux;
+	const struct bpf_kfunc_body *body;
 	struct bpf_kfunc_meta kfunc;
 	struct bpf_kfunc_desc *desc;
 	unsigned long addr;
-	int err;
+	int err, i;
 
 	prog_aux = env->prog->aux;
 	tab = prog_aux->kfunc_tab;
@@ -2930,7 +2931,7 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 		prog_aux->kfunc_btf_tab = btf_tab;
 	}
 
-	if (find_kfunc_desc(env->prog, func_id, offset))
+	if (bpf_find_kfunc_desc(env->prog, func_id, offset))
 		return 0;
 
 	if (tab->nr_base_descs == MAX_KFUNC_DESCS) {
@@ -2990,7 +2991,10 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 	desc = &tab->descs[tab->nr_descs];
 	memset(desc, 0, sizeof(*desc));
 
-	err = gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
+	/* the body of a kfunc that the program may call checks its arguments */
+	body = kfunc.flags && btf_kfunc_is_allowed(kfunc.btf, func_id, env->prog) ?
+	       btf_find_kfunc_body(kfunc.btf, func_id) : NULL;
+	err = body ? 0 : gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
 	if (err)
 		return err;
 
@@ -2998,6 +3002,10 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 	desc->offset = offset;
 	desc->addr = addr;
 	desc->func_model = func_model;
+	desc->body = body;
+	for (i = 0; body && i < func_model.nr_args; i++)
+		if (btf_param_match_suffix(kfunc.btf, &btf_params(kfunc.proto)[i], "__k"))
+			desc->body_imm |= BIT(BPF_REG_1 + i);
 	tab->nr_descs++;
 	tab->nr_base_descs++;
 	sort(tab->descs, tab->nr_base_descs, sizeof(tab->descs[0]),
@@ -14762,7 +14770,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	func_name = meta.func_name;
 	insn_aux = &env->insn_aux_data[insn_idx];
 
-	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
+	desc = bpf_find_kfunc_desc(env->prog, insn->imm, insn->off);
 	if (!desc) {
 		verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm);
 		return -EFAULT;
@@ -19527,6 +19535,9 @@ static int do_check(struct bpf_verifier_env *env)
 
 		state->last_insn_idx = env->prev_insn_idx;
 		state->insn_idx = env->insn_idx;
+		err = bpf_mark_kfunc_body_regs(env, prev_insn_idx, insn_aux);
+		if (err)
+			return err;
 		/*
 		 * Record the incoming edge so active and queued paths use the same
 		 * branch-recording path. A zero-offset conditional has identical
@@ -22180,7 +22191,7 @@ int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	 * __bpf_call_base, unless the JIT needs to call functions that are
 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
 	 */
-	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
+	desc = bpf_find_kfunc_desc(env->prog, insn->imm, insn->off);
 	if (!desc) {
 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
 			     insn->imm);
@@ -22655,15 +22666,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
 	env->arena_scalar = attr->prog_flags & BPF_F_ARENA_SCALAR;
 
-	env->explored_states = kvzalloc_objs(struct list_head,
-					     state_htab_size(env),
-					     GFP_KERNEL_ACCOUNT);
-	ret = -ENOMEM;
-	if (!env->explored_states)
-		goto skip_full_check;
-
-	for (i = 0; i < state_htab_size(env); i++)
-		INIT_LIST_HEAD(&env->explored_states[i]);
 	INIT_LIST_HEAD(&env->free_list);
 
 	/* Prepare BTF and func_info needed to discover all subprograms. */
@@ -22707,6 +22709,21 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	ret = bpf_inline_kfunc_bodies(env);
+	if (ret < 0)
+		goto skip_full_check;
+
+	/* sized by the program length, so after the lowering */
+	env->explored_states = kvzalloc_objs(struct list_head,
+					     state_htab_size(env),
+					     GFP_KERNEL_ACCOUNT);
+	ret = -ENOMEM;
+	if (!env->explored_states)
+		goto skip_full_check;
+
+	for (i = 0; i < state_htab_size(env); i++)
+		INIT_LIST_HEAD(&env->explored_states[i]);
+
 	if (bpf_prog_is_offloaded(env->prog->aux)) {
 		ret = bpf_prog_offload_verifier_prep(env->prog);
 		if (ret)
@@ -22771,6 +22788,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 skip_full_check:
 	kvfree(env->explored_states);
 
+	if (ret == 0)
+		bpf_restore_kfunc_calls(env);
+
 	/* might decrease stack depth, keep it before passes that
 	 * allocate additional slots.
 	 */
@@ -22900,6 +22920,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 err_free_env:
 	bpf_free_subprog_jts(env);
 	vfree(env->insn_aux_data);
+	bpf_free_kfunc_inlines(env);
 	kvfree(env->fd_array);
 	bpf_stack_liveness_free(env);
 	kvfree(env->cfg.insn_postorder);
diff --git a/tools/testing/selftests/bpf/Makefile b/tools/testing/selftests/bpf/Makefile
index a22be7efd1fa2..7a5dd7fcd3d14 100644
--- a/tools/testing/selftests/bpf/Makefile
+++ b/tools/testing/selftests/bpf/Makefile
@@ -48,7 +48,7 @@ TEST_PROGS_EXTENDED := \
 	ima_setup.sh verify_sig_setup.sh
 
 TEST_KMODS := bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \
-	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko
+	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_kfunc_body.ko
 TEST_KMOD_TARGETS = $(addprefix $(OUTPUT)/,$(TEST_KMODS))
 
 # Compile but not part of 'make run_tests'
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2b883b388f90c..abc4e79d42a01 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -3,6 +3,7 @@ CONFIG_BOOTPARAM_HARDLOCKUP_PANIC=y
 CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC=1
 CONFIG_BPF=y
 CONFIG_BPF_EVENTS=y
+CONFIG_BPF_INSN_KFUNCS=y
 CONFIG_BPF_JIT=y
 CONFIG_BPF_KPROBE_OVERRIDE=y
 CONFIG_BPF_LIRC_MODE2=y
diff --git a/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c b/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c
new file mode 100644
index 0000000000000..3aa1f614b508e
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <testing_helpers.h>
+
+/* bpf_test_kfunc_body.ko fails to load unless bad kfunc bodies are rejected */
+void test_kfunc_body_registration(void)
+{
+	int fd, err;
+
+	fd = open("bpf_test_kfunc_body.ko", O_RDONLY);
+	if (!ASSERT_GE(fd, 0, "open"))
+		return;
+	err = finit_module(fd, "", 0);
+	close(fd);
+	if (!ASSERT_OK(err, "finit_module"))
+		return;
+	ASSERT_OK(delete_module("bpf_test_kfunc_body", 0), "delete_module");
+}
diff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c
index 460ad10ddc020..ad7baf3afa248 100644
--- a/tools/testing/selftests/bpf/prog_tests/verifier.c
+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c
@@ -60,6 +60,7 @@
 #include "verifier_iterating_callbacks.skel.h"
 #include "verifier_jeq_infer_not_null.skel.h"
 #include "verifier_jit_convergence.skel.h"
+#include "verifier_kfunc_inline.skel.h"
 #include "verifier_kfunc_packet_access.skel.h"
 #include "verifier_kfunc_uninit.skel.h"
 #include "verifier_kfunc_uninit_multi.skel.h"
@@ -245,6 +246,7 @@ void test_verifier_int_ptr(void)              { RUN(verifier_int_ptr); }
 void test_verifier_iterating_callbacks(void)  { RUN(verifier_iterating_callbacks); }
 void test_verifier_jeq_infer_not_null(void)   { RUN(verifier_jeq_infer_not_null); }
 void test_verifier_jit_convergence(void)      { RUN(verifier_jit_convergence); }
+void test_verifier_kfunc_inline(void)         { RUN_TESTS(verifier_kfunc_inline); }
 void test_verifier_kfunc_packet_access(void)  { RUN_TESTS(verifier_kfunc_packet_access); }
 void test_verifier_kfunc_uninit(void)         { RUN_TESTS(verifier_kfunc_uninit); }
 void test_verifier_kfunc_uninit_multi(void)   { RUN_TESTS(verifier_kfunc_uninit_multi); }
diff --git a/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c b/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c
new file mode 100644
index 0000000000000..b525e7cf7a0f4
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c
@@ -0,0 +1,543 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "../test_kmods/bpf_testmod_kfunc.h"
+
+extern u64 bpf_rol64(u64 x, u32 n) __ksym;
+extern u64 bpf_select64(u64 cond, u64 a, u64 b) __ksym;
+extern u64 bpf_extract64(u64 x, u32 start, u32 len) __ksym;
+extern u64 bpf_load_be64(const void *p, s32 off) __ksym;
+extern void bpf_prefetch(const void *p) __ksym;
+extern void bpf_copy16(void *dst, const void *src) __ksym;
+extern u64 bpf_lea64(u64 base, u64 index, u32 scale, s32 disp) __ksym;
+
+/* r6 = rol(r6, 13) is one rol, the moves around the call go away */
+SEC("tc")
+__success __retval(8192)
+__xlated("0: r6 = 1")
+__xlated("1: call")
+__xlated("2: r0 = r6")
+__arch_x86_64
+__jited("{{.*}}movl\t$0x1, %ebx")
+__jited("{{.*}}rolq\t$0xd, %rbx")
+__jited("{{.*}}movq\t%rbx, %rax")
+__naked void inline_rol64_in_place(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r1 = r6;"
+	"r2 = 13;"
+	"call %[bpf_rol64];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+/* r7 = rol(r6, 8) keeps r6 */
+SEC("tc")
+__success __retval(255)
+__arch_x86_64
+__jited("{{.*}}{{rorxq\t\\$0x38, %rdi, %r13|rolq\t\\$0x8, %r13}}")
+__naked void inline_rol64_copy(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r1 = r6;"
+	"r2 = 8;"
+	"call %[bpf_rol64];"
+	"r7 = r0;"
+	"r0 = r7;"
+	"r0 -= r6;"
+	"exit;"
+	:
+	: __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+/* a 32-bit move of the constant goes away as well */
+SEC("tc")
+__success __retval(16)
+__xlated("1: call")
+__arch_x86_64
+__jited("{{.*}}rolq\t$0x4, %rbx")
+__naked void inline_rol_w2(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r1 = r6;"
+	"w2 = 4;"
+	"call %[bpf_rol64];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+SEC("tc")
+__success __retval(42)
+__arch_x86_64
+__jited("{{.*}}testq\t%rbx, %rbx")
+__jited("{{.*}}movq\t%r14, %r15")
+__jited("{{.*}}cmovneq\t%r13, %r15")
+__naked void inline_select(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"r9 = r0;"
+	"r0 = r9;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+/* r9 = r6 ? r7 : r9 is a test and a cmov */
+SEC("tc")
+__success __retval(7)
+__arch_x86_64
+__jited("{{.*}}testq\t%rbx, %rbx")
+__jited("{{.*}}cmovneq\t%r13, %r15")
+__naked void inline_select_in_place(void)
+{
+	asm volatile (
+	"r6 = 0;"
+	"r7 = 42;"
+	"r9 = 7;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = r9;"
+	"call %[bpf_select64];"
+	"r9 = r0;"
+	"r0 = r9;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+SEC("tc")
+__success __retval(0x56)
+__arch_x86_64
+__jited("{{.*}}{{bextrq\t%r13, %rbx, %r13|shlq\t%cl, %rbx}}")
+__naked void inline_extract(void)
+{
+	asm volatile (
+	"r6 = 0x12345678;"
+	"r1 = r6;"
+	"r2 = 8;"
+	"r3 = 8;"
+	"call %[bpf_extract64];"
+	"r7 = r0;"
+	"r0 = r7;"
+	"exit;"
+	:
+	: __imm(bpf_extract64)
+	: __clobber_all);
+}
+
+/* the bytes 01..08 on the stack, read as big endian */
+SEC("tc")
+__success __retval(0x05060708)
+__arch_x86_64
+__jited("{{.*}}{{movbeq\t\\(%rbx\\), %rax|bswapq\t%rax}}")
+__naked void inline_load_be64(void)
+{
+	asm volatile (
+	"*(u32 *)(r10 - 8) = 0x04030201;"
+	"*(u32 *)(r10 - 4) = 0x08070605;"
+	"r6 = r10;"
+	"r6 += -8;"
+	"r1 = r6;"
+	"r2 = 0;"
+	"call %[bpf_load_be64];"
+	"exit;"
+	:
+	: __imm(bpf_load_be64)
+	: __clobber_all);
+}
+
+SEC("tc")
+__success __retval(0)
+__arch_x86_64
+__jited("{{.*}}prefetcht0\t{{.*}}%r13)")
+__naked void inline_prefetch(void)
+{
+	asm volatile (
+	"*(u64 *)(r10 - 8) = 0;"
+	"r7 = r10;"
+	"r7 += -8;"
+	"r1 = r7;"
+	"call %[bpf_prefetch];"
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm(bpf_prefetch)
+	: __clobber_all);
+}
+
+/* the instructions of a prefetch load, so the address must be readable */
+SEC("tc")
+__failure __msg("R1 invalid mem access 'scalar'")
+__naked void inline_prefetch_scalar(void)
+{
+	asm volatile (
+	"r1 = 0;"
+	"call %[bpf_prefetch];"
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm(bpf_prefetch)
+	: __clobber_all);
+}
+
+/* copy 16 bytes from fp-16 to fp-32: the JIT copies the compiled kfunc */
+SEC("tc")
+__success __retval(0x22)
+__arch_x86_64
+__xlated("6: call")
+__jited("{{.*}}movq\t(%r13), %{{.*}}")
+__naked void inline_copy16(void)
+{
+	asm volatile (
+	"*(u64 *)(r10 - 16) = 0x11;"
+	"*(u64 *)(r10 - 8) = 0x22;"
+	"r6 = r10;"
+	"r6 += -32;"
+	"r7 = r10;"
+	"r7 += -16;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"call %[bpf_copy16];"
+	"r0 = *(u64 *)(r10 - 24);"
+	"exit;"
+	:
+	: __imm(bpf_copy16)
+	: __clobber_all);
+}
+
+/* the verifier checks the memory that the copy touches */
+SEC("tc")
+__failure __msg("off=0 size=8")
+__naked void inline_copy16_out_of_bounds(void)
+{
+	asm volatile (
+	"*(u64 *)(r10 - 8) = 0;"
+	"r1 = r10;"
+	"r1 += -16;"
+	"r2 = r10;"
+	"r2 += -8;"
+	"call %[bpf_copy16];"
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm(bpf_copy16)
+	: __clobber_all);
+}
+
+/* 100 + 3 * 4 + 16 */
+SEC("tc")
+__success __retval(128)
+__arch_x86_64
+__jited("{{.*}}leaq\t0x10(%rbx,%r13,4), %r14")
+__naked void inline_lea(void)
+{
+	asm volatile (
+	"r6 = 100;"
+	"r7 = 3;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = 4;"
+	"r4 = 16;"
+	"call %[bpf_lea64];"
+	"r8 = r0;"
+	"r0 = r8;"
+	"exit;"
+	:
+	: __imm(bpf_lea64)
+	: __clobber_all);
+}
+
+/* the instructions bound the result, a call would not */
+SEC("tc")
+__success __retval(0)
+__naked void inline_precision(void)
+{
+	asm volatile (
+	"call %[bpf_get_prandom_u32];"
+	"r1 = r0;"
+	"r2 = 0;"
+	"r3 = 3;"
+	"call %[bpf_extract64];"
+	"r6 = r10;"
+	"r6 += -8;"
+	"r6 += r0;"
+	"r0 = 0;"
+	"*(u8 *)(r6 + 0) = r0;"
+	"exit;"
+	:
+	: __imm(bpf_get_prandom_u32), __imm(bpf_extract64)
+	: __clobber_all);
+}
+
+/* arguments cannot be read after the instructions, as after a call */
+SEC("tc")
+__failure __msg("R1 !read_ok")
+__naked void inline_clobber(void)
+{
+	asm volatile (
+	"r1 = 1;"
+	"r2 = 42;"
+	"r3 = 7;"
+	"call %[bpf_select64];"
+	"r0 = r1;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+/* a kfunc that returns nothing leaves R0 unreadable after its body */
+SEC("tc")
+__failure __msg("R0 !read_ok")
+__naked void inline_void_r0(void)
+{
+	asm volatile (
+	"r1 = r10;"
+	"r1 += -8;"
+	"call %[bpf_prefetch];"
+	"exit;"
+	:
+	: __imm(bpf_prefetch)
+	: __clobber_all);
+}
+
+SEC("tc")
+__failure __msg("R2 must be a known constant")
+__naked void inline_not_constant(void)
+{
+	asm volatile (
+	"call %[bpf_get_prandom_u32];"
+	"r1 = 1;"
+	"r2 = r0;"
+	"call %[bpf_rol64];"
+	"exit;"
+	:
+	: __imm(bpf_get_prandom_u32), __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+/* r1 = r6 is skipped by a jump, so it must stay */
+SEC("tc")
+__success __retval(42)
+__naked void inline_bind_jump(void)
+{
+	asm volatile (
+	"r9 = *(u32 *)(r1 + %[len]);"
+	"r6 = 0;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = 1;"
+	"if r9 != 0 goto l0_%=;"
+	"r1 = r6;"
+"l0_%=:"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"exit;"
+	:
+	: __imm(bpf_select64),
+	  __imm_const(len, offsetof(struct __sk_buff, len))
+	: __clobber_all);
+}
+
+#if __clang_major__ >= 18 || defined(__BPF_FEATURE_MOVSX)
+/* a sign-extending move is not a plain copy of R6 */
+SEC("tc")
+__success __retval(7)
+__naked void inline_bind_movsx(void)
+{
+	asm volatile (
+	"r6 = 0x100;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = (s8)r6;"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+#endif
+
+/* the result takes the register of the condition */
+SEC("tc")
+__success __retval(42)
+__naked void inline_bind_shared(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+/* native code from a module, with the result in the register of an argument */
+SEC("tc")
+__success __retval(6)
+__arch_x86_64
+__xlated("2: call")
+__jited("{{.*}}xorq\t%r13, %rbx")
+__naked void inline_module(void)
+{
+	asm volatile (
+	"r6 = 5;"
+	"r7 = 3;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"call %[bpf_testmod_inline_xor];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_xor)
+	: __clobber_all);
+}
+
+/* without emit, the JIT copies the compiled kfunc, with the registers bound */
+SEC("tc")
+__success __retval(5)
+__arch_x86_64
+__xlated("1: call")
+__jited("{{.*}}movq\t%rbx, %r13")
+__naked void inline_copy(void)
+{
+	asm volatile (
+	"r6 = 5;"
+	"r1 = r6;"
+	"call %[bpf_testmod_inline_mov];"
+	"r7 = r0;"
+	"r0 = r7;"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_mov)
+	: __clobber_all);
+}
+
+/* compiled code that branches or divides is not copied: the instructions stay */
+SEC("tc")
+__success __retval(0)
+__xlated("{{.*}}r0 /= r2")
+__naked void inline_copy_div(void)
+{
+	asm volatile (
+	"r1 = 9;"
+	"r2 = 0;"
+	"call %[bpf_testmod_inline_div];"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_div)
+	: __clobber_all);
+}
+
+/* a kfunc that the program may not call keeps its call, which is rejected */
+SEC("xdp")
+__failure __msg("calling kernel function bpf_testmod_inline_mov is not allowed")
+__naked void inline_not_allowed(void)
+{
+	asm volatile (
+	"r1 = 1;"
+	"call %[bpf_testmod_inline_mov];"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_mov)
+	: __clobber_all);
+}
+
+#define ROL(x, n) ((x) << ((n) & 63) | (x) >> (-(n) & 63))
+
+struct diff_state {
+	u64 bad;
+	u8 src[64], dst[64];
+};
+
+static u64 rand64(void)
+{
+	return (u64)bpf_get_prandom_u32() << 32 | bpf_get_prandom_u32();
+}
+
+/* a global function, so that the verifier checks it once and not per call */
+__noinline int diff_step(struct diff_state *s)
+{
+	u64 x = rand64(), y = rand64(), a = rand64(), b = rand64();
+	int i;
+
+	if (!s)
+		return 0;
+	s->bad |= (bpf_rol64(x, 1) ^ ROL(x, 1)) | (bpf_rol64(x, 13) ^ ROL(x, 13)) |
+		  (bpf_rol64(x, 63) ^ ROL(x, 63)) | (bpf_rol64(x, 64) ^ x);
+	s->bad |= bpf_select64(x & 1, a, b) ^ (x & 1 ? a : b);
+	s->bad |= bpf_extract64(x, 0, 64) ^ x;
+	s->bad |= bpf_extract64(x, 13, 7) ^ (x >> 13 & 0x7f);
+	s->bad |= bpf_extract64(x, 40, 24) ^ (x >> 40);
+	s->bad |= bpf_extract64(x, 63, 1) ^ (x >> 63);
+	s->bad |= bpf_lea64(x, y, 8, -12345) ^ (x + y * 8 - 12345);
+	for (i = 0; i < 8; i++) {
+		s->src[i] = x >> (8 * i);
+		s->src[8 + i] = y >> (8 * i);
+	}
+	s->bad |= bpf_load_be64(s->src, 0) ^ __builtin_bswap64(x);
+	s->bad |= bpf_load_be64(s->src + 16, -8) ^ __builtin_bswap64(y);
+	/* unaligned */
+	s->bad |= bpf_load_be64(s->src + 8, -7) ^ __builtin_bswap64(x >> 8 | y << 56);
+	bpf_copy16(s->dst + 8, s->src);
+	for (i = 0; i < 16; i++)
+		s->bad |= s->dst[8 + i] ^ s->src[i];
+	return 0;
+}
+
+/* native code and the instructions agree on random inputs */
+SEC("tc")
+__success __retval(0)
+int inline_differential(struct __sk_buff *skb)
+{
+	struct diff_state s = {};
+	int i;
+
+	for (i = 0; i < 256; i++)
+		diff_step(&s);
+	return s.bad != 0;
+}
+
+/* emits BTF for the kfuncs that only inline assembly calls */
+void __kfunc_btf_root(void)
+{
+	bpf_prefetch(0);
+	bpf_testmod_inline_mov(0);
+	bpf_testmod_inline_xor(0, 0);
+	bpf_testmod_inline_div(0, 0);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/test_kmods/Makefile b/tools/testing/selftests/bpf/test_kmods/Makefile
index 031c7454ce65f..1800a0cd7a771 100644
--- a/tools/testing/selftests/bpf/test_kmods/Makefile
+++ b/tools/testing/selftests/bpf/test_kmods/Makefile
@@ -19,7 +19,7 @@ Q = @
 endif
 
 MODULES = bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \
-	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko
+	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_kfunc_body.ko
 
 $(foreach m,$(MODULES),$(eval obj-m += $(m:.ko=.o)))
 
diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c b/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c
new file mode 100644
index 0000000000000..2149bbd683381
--- /dev/null
+++ b/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/bpf.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
+#include <linux/filter.h>
+#include <linux/init.h>
+#include <linux/module.h>
+
+struct bpf_test_kfunc_body_pair {
+	u64 a, b;
+};
+
+__bpf_kfunc_start_defs();
+
+__bpf_kfunc u64 bpf_test_kfunc_body(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc u64 bpf_test_kfunc_body_unset(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc u64 bpf_test_kfunc_body_pair(struct bpf_test_kfunc_body_pair p)
+{
+	return p.a;
+}
+
+__bpf_kfunc u64 bpf_test_kfunc_body_sleepable(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc_end_defs();
+
+BTF_KFUNCS_START(test_body_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_test_kfunc_body)
+BTF_KFUNCS_END(test_body_kfunc_ids)
+
+/* never registered */
+BTF_KFUNCS_START(test_body_bad_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_test_kfunc_body_pair)
+BTF_ID_FLAGS(func, bpf_test_kfunc_body_sleepable, KF_SLEEPABLE)
+BTF_KFUNCS_END(test_body_bad_kfunc_ids)
+
+BTF_ID_LIST(test_body_ids)
+BTF_ID(func, bpf_test_kfunc_body)
+BTF_ID(func, bpf_test_kfunc_body_unset)
+BTF_ID(func, bpf_test_kfunc_body_pair)
+BTF_ID(func, bpf_test_kfunc_body_sleepable)
+
+static const struct bpf_insn test_body_insns[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+};
+
+/* writes R6 */
+static const struct bpf_insn test_body_bad_insns[] = {
+	BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+};
+
+/* jumps past the last instruction */
+static const struct bpf_insn test_body_jump_insns[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0, 1),
+	BPF_MOV64_IMM(BPF_REG_0, 0),
+};
+
+static struct bpf_kfunc_body test_body = { .id = &test_body_ids[0] };
+
+static struct btf_kfunc_id_set test_body_set = {
+	.owner = THIS_MODULE,
+	.set = &test_body_kfunc_ids,
+	.bodies = &test_body,
+	.body_cnt = 1,
+};
+
+static int test_body_rejected(struct btf_id_set8 *set, const u32 *id,
+			      const struct bpf_insn *insns, u32 len)
+{
+	test_body_set.set = set;
+	test_body.id = id;
+	test_body.insns = insns;
+	test_body.len = len;
+	return register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &test_body_set) == -EINVAL;
+}
+
+/*
+ * The module loads only if registration rejects a body without instructions,
+ * one with an instruction that writes R6, one with a jump past its last
+ * instruction, one for a kfunc outside the set, one with an argument of two
+ * registers and one for a kfunc with flags.
+ */
+static int bpf_test_kfunc_body_init(void)
+{
+	struct btf_id_set8 *good = &test_body_kfunc_ids, *bad = &test_body_bad_kfunc_ids;
+
+	if (!test_body_rejected(good, &test_body_ids[0], NULL, 0) ||
+	    !test_body_rejected(good, &test_body_ids[0], test_body_bad_insns,
+				ARRAY_SIZE(test_body_bad_insns)) ||
+	    !test_body_rejected(good, &test_body_ids[0], test_body_jump_insns,
+				ARRAY_SIZE(test_body_jump_insns)) ||
+	    !test_body_rejected(good, &test_body_ids[1], test_body_insns, 1) ||
+	    !test_body_rejected(bad, &test_body_ids[2], test_body_insns, 1) ||
+	    !test_body_rejected(bad, &test_body_ids[3], test_body_insns, 1))
+		return -EINVAL;
+	test_body_set.set = good;
+	test_body.id = &test_body_ids[0];
+	return register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &test_body_set);
+}
+
+static void bpf_test_kfunc_body_exit(void)
+{
+}
+
+module_init(bpf_test_kfunc_body_init);
+module_exit(bpf_test_kfunc_body_exit);
+
+MODULE_DESCRIPTION("BPF kfunc body registration test module");
+MODULE_LICENSE("GPL");
diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c
index 93847ca6293b4..13d5abe249d25 100644
--- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c
+++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c
@@ -931,6 +931,78 @@ BTF_ID_LIST(bpf_testmod_dtor_ids)
 BTF_ID(struct, bpf_testmod_ctx)
 BTF_ID(func, bpf_testmod_ctx_release_dtor)
 
+/*
+ * Kfuncs with a body, in a set that XDP programs may not use: the JIT copies
+ * the first, the second has native code from this module, and the third,
+ * which divides, keeps its body.
+ */
+__bpf_kfunc u64 bpf_testmod_inline_mov(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc u64 bpf_testmod_inline_xor(u64 a, u64 b)
+{
+	return a ^ b;
+}
+
+__bpf_kfunc u64 bpf_testmod_inline_div(u64 a, u64 b)
+{
+	return b ? a / b : 0;
+}
+
+BTF_ID_LIST(bpf_testmod_body_ids)
+BTF_ID(func, bpf_testmod_inline_mov)
+BTF_ID(func, bpf_testmod_inline_xor)
+BTF_ID(func, bpf_testmod_inline_div)
+
+static const struct bpf_insn mov_body[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+};
+
+static const struct bpf_insn xor_body[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_2),
+};
+
+static const struct bpf_insn div_body[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_DIV, BPF_REG_0, BPF_REG_2),
+};
+
+#ifdef CONFIG_X86_64
+/* op %src, %dst on 64-bit registers */
+static u8 *x86_op(u8 *p, u8 op, u8 src, u8 dst)
+{
+	*p++ = 0x48 | (src & 8 ? 4 : 0) | (dst & 8 ? 1 : 0);
+	*p++ = op;
+	*p++ = 0xc0 | (src & 7) << 3 | (dst & 7);
+	return p;
+}
+
+/* the result can take the register of an argument, which a copy cannot */
+static int xor_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], a = reg[1], b = reg[2], *p = buf;
+
+	if (dst == b)
+		swap(a, b);
+	if (dst != a)
+		p = x86_op(p, 0x89, a, dst);	/* mov %a, %dst */
+	return x86_op(p, 0x31, b, dst) - buf;	/* xor %b, %dst */
+}
+#else
+#define xor_emit	NULL
+#endif
+
+#define BODY(i, op, emit)	{ &bpf_testmod_body_ids[i], op##_body, ARRAY_SIZE(op##_body), emit }
+
+static const struct bpf_kfunc_body bpf_testmod_bodies[] = {
+	BODY(0, mov, NULL),
+	BODY(1, xor, xor_emit),
+	BODY(2, div, NULL),
+};
+
 static const struct btf_kfunc_id_set bpf_testmod_common_kfunc_set = {
 	.owner = THIS_MODULE,
 	.set   = &bpf_testmod_common_kfunc_ids,
@@ -1827,6 +1899,9 @@ BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy_impl)
 BTF_ID_FLAGS(func, bpf_kfunc_trigger_ctx_check)
+BTF_ID_FLAGS(func, bpf_testmod_inline_mov)
+BTF_ID_FLAGS(func, bpf_testmod_inline_xor)
+BTF_ID_FLAGS(func, bpf_testmod_inline_div)
 BTF_KFUNCS_END(bpf_testmod_check_kfunc_ids)
 
 static int bpf_testmod_ops_init(struct btf *btf)
@@ -1861,6 +1936,8 @@ static int bpf_testmod_ops_init_member(const struct btf_type *t,
 static const struct btf_kfunc_id_set bpf_testmod_kfunc_set = {
 	.owner = THIS_MODULE,
 	.set   = &bpf_testmod_check_kfunc_ids,
+	.bodies = bpf_testmod_bodies,
+	.body_cnt = ARRAY_SIZE(bpf_testmod_bodies),
 };
 
 static const struct bpf_verifier_ops bpf_testmod_verifier_ops = {
diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h b/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h
index 67c02a421d133..2a55f1b145b42 100644
--- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h
+++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h
@@ -357,4 +357,8 @@ void bpf_testmod_test_hardirq_fn(void);
 void bpf_testmod_test_softirq_fn(void);
 void bpf_kfunc_trigger_ctx_check(void) __ksym;
 
+u64 bpf_testmod_inline_mov(u64 x) __ksym;
+u64 bpf_testmod_inline_xor(u64 a, u64 b) __ksym;
+u64 bpf_testmod_inline_div(u64 a, u64 b) __ksym;
+
 #endif /* _BPF_TESTMOD_KFUNC_H */

3/2 2026/10/05 14:28 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36798
							output: 21
							thoughts: 1130
						

Thoughts:
**BPF Patch Analysis: Worthy of Syzkaller Fuzzing?**

Alright, let's break this down. My initial assessment is that this patch *absolutely* warrants fuzzing with syzkaller. The patch introduces "Inline kfuncs" support, and, frankly, that sounds like a significant architectural change within the BPF subsystem, especially considering it touches the x86 JIT compiler.

First, I reviewed the patch contents. It's not just a minor tweak; it's a deep dive into how BPF kfuncs are handled: documentation, x86 JIT compiler modifications (introducing new functions like `kfunc_copy_insn`, `bpf_jit_inline_kfunc`, JIT hooks), verifier updates, new Kconfig options (`CONFIG_BPF_INSN_KFUNCS`), and additions of several new files.  I see modifications to BTF parsing, constant folding, and the core JIT. The addition of x86 instruction decoding/copying and register rewriting is a red flag on its own. It's a fundamental shift in how BPF kfuncs are integrated and executed, and the depth of the change screams for thorough testing.

Now, the crucial question: is this reachable in standard environments? This is amd64.  BPF is reached through the `bpf(2)` syscall, specifically `BPF_PROG_LOAD` etc. And syzkaller is specifically targeting this, using `syz_bpf_prog_load` and the `bpf$PROG_LOAD` syscall.  Crucially, these new kfuncs and inlining mechanism *can* be triggered during BPF verification and JIT compilation, which is exactly what syzkaller excels at. We're talking about direct access to the BPF verifier and JIT compiler on x86_64 from userspace, which is syzkaller's bread and butter.  Given that we are modifying the BPF verifier and x86 JIT, and it's all reachable via the `bpf` syscall, I'd say this is definitely a "WorthFuzzing = true" situation.

Let's double check the rules: We always verify the reachability and that the core subsystems are being targeted. BPF is definitely reachable. And yes, this touches the BPF core. Bingo.

Let's quickly check the EnableConfigs.  We need: `BPF_SYSCALL`, `BPF_JIT`, and `BPF_INSN_KFUNCS`, which itself depends on `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. We also have `DEBUG_INFO_BTF`.  Alright, checking the `kfunc_copy()` in the `arch/x86/net/bpf_jit_comp.c` file, we see this line: `if (in->copy && IS_ENABLED(CONFIG_INSTRUCTION_DECODER))`.

Let me quickly double-check the Kconfig using a grepper. Now let's see what `INSTRUCTION_DECODER` depends on.  I have my answer. Ok, so no dependencies there.

Okay, all the checks are complete and the configurations look good. Time to unleash the fuzzers!



4/2 2026/10/05 14:28 tool grepper
0m Args:
{
  "Expression": "config INSTRUCTION_DECODER"
}

Results:
{
  "Output": "arch/x86/Kconfig=58=config X86\n--\narch/x86/Kconfig-344-\narch/x86/Kconfig:345:config INSTRUCTION_DECODER\narch/x86/Kconfig-346-\tdef_bool y\n"
}

5/2 2026/10/05 14:28 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38739
							output: 39
							thoughts: 19
						

Thoughts:
Here's my thought process, as requested:

**Navigating the BPF Landscape**

Alright, let's dive into this. The task at hand involves something related to BPF, and I'm thinking the logical starting point is the `kernel/bpf/insn_kfuncs/Kconfig` file. That's usually where the configuration options for BPF instruction and kernel function support are declared. It's a key spot to understand what features are available, how they're enabled, and any dependencies they might have. Going there first will give me a good lay of the land, letting me see the available options and narrow down potential areas of focus based on the specific problem. It's a sensible starting point for any BPF-related investigation, especially if I'm not entirely familiar with the specific subsystem involved.



6/2 2026/10/05 14:28 tool read-file
0m Args:
{
  "File": "kernel/bpf/insn_kfuncs/Kconfig",
  "FirstLine": 1,
  "LineCount": 20
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\tconfig BPF_INSN_KFUNCS\n   3:\t\ttristate \"Kfuncs for CPU instructions that BPF lacks\"\n   4:\t\tdepends on BPF_SYSCALL \u0026\u0026 BPF_JIT \u0026\u0026 DEBUG_INFO_BTF\n   5:\t\thelp\n   6:\t\t  Provide kfuncs for rotate, conditional select, bit field extract,\n   7:\t\t  big-endian load, prefetch, 16-byte copy and address computation.\n   8:\t\t  The verifier checks each call as the kfunc's BPF body, and the JIT\n   9:\t\t  puts native code in its place where it can.\n  10:\t\n  11:\t\t  If unsure, say N.\n  12:\t\n  13:\tconfig BPF_INSN_KFUNCS_ARCH\n  14:\t\tbool\n  15:\t\tdepends on BPF_INSN_KFUNCS\n  16:\t\tdefault y if X86_64\n"
}

7/2 2026/10/05 14:28 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39237
							output: 319
							thoughts: 1753
						

Thoughts:
**Analysis of BPF Kfunc Inlining for Fuzzing Focus**

Alright, let's break this down for fuzzing purposes. First, I need to identify the key configurations and dependencies involved. From the `Makefile` and source code, it's clear we're dealing with `BPF_SYSCALL`, `BPF_JIT`, `DEBUG_INFO_BTF`, and `BPF_INSN_KFUNCS`. No other conditional dependencies seem to exist.

Now, the crucial step: pinpointing the "FocusSymbols." We want to target kernel functions directly implementing the new BPF inline kfunc logic, or acting as entry points to the subsystem. We have a set of functions introduced or modified by the patch:

*   **x86 JIT:** `bpf_jit_inline_kfunc`, `kfunc_copy`, `kfunc_copy_insn`.
*   **kfunc Inline:** `bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `bpf_restore_kfunc_calls`, `bpf_kfunc_native`, `kfunc_bind`, `kfunc_native_ok`.
*   **BTF:** `btf_add_kfunc_bodies`, `btf_check_kfunc_body`, `btf_find_kfunc_body`.
*   **Instruction kfuncs:** `bpf_rol64`, `bpf_select64`, `bpf_extract64`, `bpf_load_be64`, `bpf_prefetch`, `bpf_copy16`, `bpf_lea64`.
*   **Verifier:** `bpf_add_kfunc_call`, `bpf_find_kfunc_desc`.

We need to select which ones are linkable or focusable (non-static) symbols. Checking the headers and source, we can see that:

*   `bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `bpf_restore_kfunc_calls`, `bpf_jit_inline_kfunc` are exported and linkable.
*   `kfunc_copy`, `kfunc_copy_insn` are static (but relevant due to their central logic.)
*   `kfunc_bind` is also static, in `kfunc_inline.c`.
*   `btf_check_kfunc_body` is also static.
*   The kfuncs themselves, `bpf_rol64` etc, are static, but core.

None of these functions are ubiquitous; they are all specific to this kfunc inlining feature. This makes them ideal for targeted fuzzing.

My analysis dictates the following:

*   `WorthFuzzing`: True.
*   `EnableConfigs`: `BPF_SYSCALL`, `BPF_JIT`, `DEBUG_INFO_BTF`, `BPF_INSN_KFUNCS`.
*   `FocusSymbols`: `bpf_inline_kfunc_bodies`, `bpf_restore_kfunc_calls`, `bpf_mark_kfunc_body_regs`, `bpf_jit_inline_kfunc`, `kfunc_copy`, `kfunc_copy_insn`, `kfunc_bind`, `btf_check_kfunc_body`, `bpf_rol64`, `bpf_select64`, `bpf_extract64`, `bpf_load_be64`, `bpf_lea64`.
*   `Reasoning`: This patch series introduces BPF inline kfunc support, which allows kfunc calls to be inlined as BPF bytecode. This touches BPF verification, register binding and x86 JIT binary rewriting. Fuzzing is essential to catch verifier soundness bugs, JIT buffer overflows, and invalid instruction emission.



8/2 2026/10/05 14:29 tool set-results
0m Args:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BPF_INSN_KFUNCS"
  ],
  "FocusSymbols": [
    "bpf_inline_kfunc_bodies",
    "bpf_restore_kfunc_calls",
    "bpf_mark_kfunc_body_regs",
    "bpf_jit_inline_kfunc",
    "kfunc_copy",
    "kfunc_copy_insn",
    "kfunc_bind",
    "btf_check_kfunc_body",
    "bpf_rol64",
    "bpf_select64",
    "bpf_extract64",
    "bpf_load_be64",
    "bpf_lea64"
  ],
  "Reasoning": "The patch series introduces inline kfuncs in the BPF subsystem and the x86-64 BPF JIT compiler. The verifier inlines kfunc bodies during verification and restores calls or emits/copies native machine code during JIT compilation. This modifies core BPF verifier behavior, register state/liveness tracking, and x86 machine code generation/copying, which is directly reachable from unprivileged or privileged userspace via the bpf() syscall. Fuzzing is essential to test for verifier inconsistencies, register binding issues, and JIT instruction generation bugs.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BPF_INSN_KFUNCS"
  ],
  "FocusSymbols": [
    "bpf_inline_kfunc_bodies",
    "bpf_restore_kfunc_calls",
    "bpf_mark_kfunc_body_regs",
    "bpf_jit_inline_kfunc",
    "kfunc_copy",
    "kfunc_copy_insn",
    "kfunc_bind",
    "btf_check_kfunc_body",
    "bpf_rol64",
    "bpf_select64",
    "bpf_extract64",
    "bpf_load_be64",
    "bpf_lea64"
  ],
  "Reasoning": "The patch series introduces inline kfuncs in the BPF subsystem and the x86-64 BPF JIT compiler. The verifier inlines kfunc bodies during verification and restores calls or emits/copies native machine code during JIT compilation. This modifies core BPF verifier behavior, register state/liveness tracking, and x86 machine code generation/copying, which is directly reachable from unprivileged or privileged userspace via the bpf() syscall. Fuzzing is essential to test for verifier inconsistencies, register binding issues, and JIT instruction generation bugs.",
  "WorthFuzzing": true
}

9/1 2026/10/05 14:29 action If
48m Args:
{
  "WorthFuzzing": true
}

Results:
null

10/2 2026/10/05 14:29 agent kmsan-evaluator
48m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series introduces BPF inline kfuncs, allowing kfuncs to provide BPF instruction bodies and native x86-64 inline/copied implementations.\n\n1. Analysis of Memory Allocation and Initialization:\n- In `bpf_inline_kfunc_bodies()`, `env-\u003ekfunc_inlines` is allocated using `kvzalloc_objs`, ensuring all inline descriptors are zero-initialized.\n- In `bpf_add_kfunc_call()`, descriptor allocations are zeroed with `memset(desc, 0, sizeof(*desc))`.\n- When expanding `insn_aux_data` in `bpf_patch_insn_data()`, memory is allocated with `__GFP_ZERO`.\n- Stack buffers such as `code` in `bpf_restore_kfunc_calls()` and `kfunc_copy()` are written sequentially and completely up to the returned `len` bytes prior to `kmemdup()` and copying into the JIT image.\n\n2. Absence of Kernel-to-User Info-Leaks or Uninitialized Reads:\n- No new or modified kernel data structures are exposed to userspace via `copy_to_user`, netlink, socket options, or syscalls without full initialization.\n- Control flow and branching logic throughout the new verifier passes (`bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `kfunc_bind`, `bpf_restore_kfunc_calls`) depend only on initialized state fields, instruction opcodes, and BTF metadata.\n\n3. KASAN vs KMSAN Applicability:\n- Potential failure modes in this patch involve bounds checking during x86 instruction decoding/copying (`kfunc_copy`, `kfunc_copy_insn`), out-of-bounds indexing in `kfunc_bind()`, or invalid JIT native code generation. These are out-of-bounds access or control-flow bugs that fall within the scope of KASAN and standard kernel debuggers.\n- Furthermore, BPF JIT generated instructions are not instrumented by KMSAN.\n- As there are no uninitialized memory risks or kernel-to-user info-leak vectors unique to KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "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 b05094a96f90fd89caede9601c328198860eabdc
Author: syz-cluster <triage@syzkaller.com>
Date:   Mon Oct 5 14:28:34 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/bpf/kfuncs.rst b/Documentation/bpf/kfuncs.rst
index 73578a4c3b1fb..432e61a82aa9d 100644
--- a/Documentation/bpf/kfuncs.rst
+++ b/Documentation/bpf/kfuncs.rst
@@ -695,6 +695,59 @@ verified inline, so an unassigned R2 is simply passed back to the caller as
 uninitialized and only a caller that reads it fails. A stack pointer left in
 R2 is still rejected there, just as one in R0 is.
 
+2.10 Inline kfuncs
+------------------
+
+A kfunc can come with a body: a few BPF instructions that compute it from its
+arguments in R1-R5 into R0. The verifier then checks each call of the kfunc as
+its body, so it knows as much about the result as if the program had computed
+it in BPF, and the JIT puts native code in place of the call. Where the JIT has
+no native code, the body runs in place of the call. BPF programs call such
+kfuncs like any other, and arguments whose names end in ``__k`` must be known
+constants (see section 2.3.2). ``CONFIG_BPF_INSN_KFUNCS`` provides
+``bpf_rol64()``, ``bpf_select64()``, ``bpf_extract64()``, ``bpf_load_be64()``,
+``bpf_prefetch()``, ``bpf_copy16()`` and ``bpf_lea64()``.
+
+The verifier replaces each call with the body before it analyzes the program.
+Only the arguments are readable at the entry of the body, and R1-R5 are not
+readable after it, as after a call. After the analysis, a call goes back into
+the program if the JIT has native code for it, with its operands bound to the
+registers that the moves around the call copied them from or to. The body stays
+when the verifier rewrites it later, for example with speculation barriers,
+when it accesses memory other than the stack, map values, memory and packets,
+and when constant blinding is on.
+
+The native code comes from the kfunc set: an ``emit`` callback writes it for
+the architecture, such as ``rol $13`` or ``movbe 8(%rdi)`` on x86-64. Without
+``emit``, or when it has no code for the CPU, the x86-64 JIT copies the
+compiled kfunc with its registers renamed. It copies only straight-line moves,
+ALU instructions and address computations on the registers of a call, without
+division or rip-relative addressing. Native code is trusted like the rest of
+the JIT: it has to compute what the body computes, with the same memory
+accesses.
+
+A kfunc set gives bodies to some of its kfuncs::
+
+        static const struct bpf_insn rol64_body[] = { ... };
+
+        static const struct bpf_kfunc_body bodies[] = {
+                { &body_ids[0], rol64_body, ARRAY_SIZE(rol64_body), rol64_emit },
+        };
+
+        static const struct btf_kfunc_id_set kfunc_set = {
+                .set      = &kfunc_ids,
+                .bodies   = bodies,
+                .body_cnt = ARRAY_SIZE(bodies),
+        };
+
+Registration checks each body: it may use R0-R5, ALU instructions, loads and
+stores, and forward jumps that land within it, so that it ends by falling
+through its last instruction, but not the sign extension, signed division and
+byte swap of cpu v4, which not every JIT has. Each argument and the result must
+fit in one register, and the kfunc may have no kfunc flags. ``emit`` writes at
+most ``BPF_KFUNC_INLINE_MAX`` bytes. Modules give their kfuncs bodies and
+native code in the same way.
+
 .. _BPF_kfunc_lifecycle_expectations:
 
 3. kfunc lifecycle expectations
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 083fcd6cf15b7..6a57109caa97a 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -15,8 +15,12 @@
 #include <linux/memory.h>
 #include <linux/sort.h>
 #include <linux/execmem.h>
+#include <linux/kallsyms.h>
+#include <linux/uaccess.h>
 #include <asm/extable.h>
 #include <asm/ftrace.h>
+#include <asm/insn.h>
+#include <asm/insn-eval.h>
 #include <asm/set_memory.h>
 #include <asm/nospec-branch.h>
 #include <asm/text-patching.h>
@@ -2000,6 +2004,174 @@ static int emit_kfunc_arena_args(struct bpf_prog *bpf_prog,
 	return prog - start;
 }
 
+/*
+ * Registers that copied kfunc code may use: those of R0-R5, which hold the
+ * arguments and the result as for a call, and the scratch registers r10 and
+ * r11. r9 can hold the private frame pointer.
+ */
+#define KFUNC_COPY_REGS	(BIT(0) | BIT(1) | BIT(2) | BIT(6) | BIT(7) | BIT(8) | \
+			 BIT(10) | BIT(11))
+
+/*
+ * Write an instruction of a compiled kfunc with the registers of R0-R5
+ * renamed by @map to those that the verifier bound them to. It must be a
+ * move, ALU or address computation without control flow, prefixes other than
+ * operand size, rip-relative addressing or registers other than
+ * KFUNC_COPY_REGS, and no division, which can trap.
+ */
+static u8 *kfunc_copy_insn(u8 *p, const struct insn *insn, const u8 *c, const u8 *map)
+{
+	u8 op = insn->opcode.bytes[insn->opcode.nbytes - 1], rex = insn->rex_prefix.bytes[0];
+	u8 modrm = insn->modrm.value, sib = insn->sib.value, ext = X86_MODRM_REG(modrm);
+	u8 mod = X86_MODRM_MOD(modrm), reg = ext, rm = 0, idx = 4;
+	bool two = insn->opcode.nbytes == 2, group, opreg, disp8, implicit;
+	u16 regs = 0;
+	int head;
+
+	if (insn->vex_prefix.nbytes || insn->opcode.nbytes > 2 || insn->prefixes.nbytes > 1 ||
+	    (insn->prefixes.nbytes && insn->prefixes.bytes[0] != 0x66))
+		return NULL;
+	if (two) {
+		/* cmovcc, imul, movzx/movsx of words, bswap, prefetch */
+		group = op == 0x18;
+		if ((op & 0xf0) != 0x40 && op != 0xaf && op != 0xb7 && op != 0xbf &&
+		    (op & 0xf8) != 0xc8 && !(group && ext < 4))
+			return NULL;
+	} else {
+		/* add, or, and, sub, xor, cmp, mov, lea, test, imul, shifts, not, neg, mul */
+		group = op == 0x81 || op == 0x83 || op == 0xc1 || op == 0xc7 ||
+			op == 0xd1 || op == 0xd3 || op == 0xf7;
+		if (!(op < 0x40 && (op & 0xf0) != 0x10 && (op & 7) % 2 && (op & 7) < 6) &&
+		    op != 0x63 && op != 0x69 && op != 0x6b && op != 0x85 && op != 0x89 &&
+		    op != 0x8b && op != 0x8d && op != 0x98 && op != 0x99 && op != 0xa9 &&
+		    (op & 0xf8) != 0xb8 &&
+		    !(group && op != 0xc7 && op != 0xf7 && ext != 2 && ext != 3) &&
+		    !(op == 0xc7 && !ext) && !(op == 0xf7 && ext != 1 && ext < 6))
+			return NULL;
+	}
+
+	/* uses %rax, %rcx or %rdx without naming it, as in "and $imm, %eax" */
+	implicit = !two && ((op < 0x40 && (op & 7) == 5) || op == 0x98 || op == 0x99 ||
+			    op == 0xa9 || op == 0xd3 || (op == 0xf7 && (ext == 4 || ext == 5)));
+
+	opreg = (op & 0xf8) == (two ? 0xc8 : 0xb8);
+	if (opreg)
+		rm = (op & 7) + (X86_REX_B(rex) ? 8 : 0);
+	if (insn->modrm.nbytes) {
+		reg = group ? ext : ext + (X86_REX_R(rex) ? 8 : 0);
+		rm = (insn->sib.nbytes ? X86_SIB_BASE(sib) : X86_MODRM_RM(modrm)) +
+		     (X86_REX_B(rex) ? 8 : 0);
+		if (insn->sib.nbytes)
+			idx = X86_SIB_INDEX(sib) + (X86_REX_X(rex) ? 8 : 0);
+		/* rip-relative or absolute */
+		if (!mod && (rm & 7) == 5)
+			return NULL;
+		regs = (group ? 0 : BIT(reg)) | (idx != 4 ? BIT(idx) : 0);
+	}
+	if ((regs | (opreg || insn->modrm.nbytes ? BIT(rm) : 0)) & ~KFUNC_COPY_REGS)
+		return NULL;
+	/* which cannot be renamed, so they must hold their operands as for a call */
+	if (implicit && (map[0] != 0 || map[1] != 1 || map[2] != 2))
+		return NULL;
+
+	/* the instruction again, with the registers renamed */
+	if (!group)
+		reg = map[reg];
+	rm = map[rm];
+	idx = idx != 4 ? map[idx] : 4;
+	if (insn->prefixes.nbytes)
+		*p++ = 0x66;
+	rex = 0x40 | X86_REX_W(rex) | (reg & 8 ? 4 : 0) | (idx & 8 ? 2 : 0) | (rm & 8 ? 1 : 0);
+	if (rex != 0x40)
+		*p++ = rex;
+	if (two)
+		*p++ = 0x0f;
+	*p++ = opreg ? (op & 0xf8) | (rm & 7) : op;
+	if (insn->modrm.nbytes) {
+		/* a base of r13 needs a displacement */
+		disp8 = !mod && (rm & 7) == 5;
+		*p++ = (disp8 ? 1 : mod) << 6 | (reg & 7) << 3 | (insn->sib.nbytes ? 4 : rm & 7);
+		if (insn->sib.nbytes)
+			*p++ = (sib & 0xc0) | (idx & 7) << 3 | (rm & 7);
+		if (disp8)
+			*p++ = 0;
+	}
+	head = insn->prefixes.nbytes + insn->rex_prefix.nbytes + insn->opcode.nbytes +
+	       insn->modrm.nbytes + insn->sib.nbytes;
+	memcpy(p, c + head, insn->length - head);
+	return p + insn->length - head;
+}
+
+/*
+ * Copy the compiled kfunc of an inlined call up to its return, without the
+ * ENDBR and NOPs at its entry, with the operands renamed by @map.
+ */
+static int kfunc_copy(const struct bpf_kfunc_inline *in, const u8 *map, u8 *buf)
+{
+	u8 code[BPF_KFUNC_INLINE_MAX + MAX_INSN_SIZE], *c, *p = buf;
+	unsigned long size, off, ret;
+	struct insn insn;
+	int pos;
+
+	if (!kallsyms_lookup_size_offset(in->addr, &size, &off) || off)
+		return -EINVAL;
+	size = min(size, sizeof(code));
+	if (copy_from_kernel_nofault(code, (void *)in->addr, size))
+		return -EFAULT;
+	for (pos = 0; pos < size; pos += insn.length) {
+		if (insn_decode(&insn, code + pos, size - pos, INSN_MODE_64))
+			return -EINVAL;
+		c = code + pos;
+		/* ret, or a jump to the return thunk */
+		ret = in->addr + pos + insn.length + insn.immediate.value;
+		if ((insn.length == 1 && c[0] == 0xc3) ||
+		    (c[0] == 0xe9 && (ret == (unsigned long)x86_return_thunk ||
+				      ret == (unsigned long)__x86_return_thunk)))
+			return p > buf ? p - buf : -EINVAL;
+		if ((insn.length == 4 && is_endbr((u32 *)c)) || insn_is_nop(&insn))
+			continue;
+		if (insn_is_rex2(&insn))
+			return -EINVAL;
+		/* renaming adds at most a REX prefix and a displacement */
+		if (p - buf + insn.length + 2 > BPF_KFUNC_INLINE_MAX)
+			return -E2BIG;
+		p = kfunc_copy_insn(p, &insn, c, map);
+		if (!p)
+			return -EINVAL;
+	}
+	return -EINVAL;
+}
+
+static u8 x86_reg(u32 reg)
+{
+	return reg2hex[reg] + (is_ereg(reg) ? 8 : 0);
+}
+
+/*
+ * Get native code for an inlined kfunc call, with the operands in the x86
+ * registers that the verifier bound them to: the code from the emit callback
+ * of the kfunc's body, or else a copy of the compiled kfunc.
+ */
+int bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf)
+{
+	u8 reg[MAX_BPF_FUNC_REG_ARGS + 1], map[16];
+	int i, len;
+
+	for (i = 0; i < ARRAY_SIZE(map); i++)
+		map[i] = i;
+	for (i = BPF_REG_0; i <= BPF_REG_5; i++) {
+		reg[i] = x86_reg(in->reg[i]);
+		map[x86_reg(i)] = reg[i];
+	}
+	/* copying needs the instruction decoder */
+	if (in->copy && IS_ENABLED(CONFIG_INSTRUCTION_DECODER))
+		return kfunc_copy(in, map, buf);
+	if (in->copy || !in->body->emit)
+		return -EOPNOTSUPP;
+	len = in->body->emit(reg, in->imm, buf);
+	return len > 0 && len <= BPF_KFUNC_INLINE_MAX ? len : -EINVAL;
+}
+
 static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *addrs, u8 *image,
 		  u8 *rw_image, int oldproglen, struct jit_context *ctx, bool jmp_padding)
 {
@@ -2952,6 +3124,15 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			if (!imm32)
 				return -EINVAL;
 			if (src_reg == BPF_PSEUDO_KFUNC_CALL) {
+				const struct bpf_kfunc_inline *in;
+
+				/* an inlined kfunc call gets its native code */
+				in = bpf_kfunc_native(env, insn_idx);
+				if (in) {
+					memcpy(prog, in->image, in->image_len);
+					prog += in->image_len;
+					break;
+				}
 				fm = bpf_jit_find_kfunc_model(bpf_prog, insn);
 				if (!fm)
 					return -EINVAL;
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index c51083c761cf2..571c8d4da3271 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -634,6 +634,7 @@ struct bpf_insn_aux_data {
 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
 		struct bpf_map_ptr_state map_ptr_state;
 		s32 call_imm;			/* saved imm field of call insn */
+		u32 kfunc_inline;		/* 1 + index into env->kfunc_inlines, at a call */
 		u32 alu_limit;			/* limit for add/sub register with pointer */
 		struct {
 			u32 map_index;		/* index into used_maps[] */
@@ -683,6 +684,9 @@ struct bpf_insn_aux_data {
 	 */
 	u8 fastcall_spills_num:3;
 	u8 arg_prog:4;
+	/* insn belongs to the body of a kfunc call, see bpf_inline_kfunc_bodies() */
+	u8 kfunc_body:1;
+	u8 kfunc_body_entry:1;
 
 	/* below fields are initialized once */
 	unsigned int orig_idx; /* original instruction index */
@@ -1083,6 +1087,8 @@ struct bpf_verifier_env {
 	u32 scc_cnt;
 	struct bpf_iarray *succ;
 	struct bpf_iarray *gotox_tmp_buf;
+	struct bpf_kfunc_inline *kfunc_inlines;
+	u32 kfunc_inline_cnt;
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1794,14 +1800,42 @@ enum bpf_reg_arg_type {
 #define MAX_KFUNC_CALL_DESCS (MAX_KFUNC_DESCS * 2)
 static_assert(MAX_KFUNC_CALL_DESCS <= S16_MAX + 1);
 
+/* A call of a kfunc with a body, which the verifier replaced by the body */
+struct bpf_kfunc_inline {
+	struct bpf_insn call;
+	const struct bpf_kfunc_body *body;
+	unsigned long addr;		/* of the compiled kfunc */
+	u8 *image;			/* native code for the JIT */
+	u32 start;
+	/* the BPF registers that R0-R5 are bound to, and the constant arguments */
+	u8 reg[MAX_BPF_FUNC_REG_ARGS + 1];
+	s32 imm[MAX_BPF_FUNC_REG_ARGS + 1];
+	u8 image_len;
+	u8 nargs;
+	u8 imm_mask;	/* R1-R5 that hold constant (__k) arguments */
+	bool entered;	/* the verifier reached the body */
+	bool ret;	/* the kfunc returns a value */
+	bool copy;	/* the native code is a copy of the compiled kfunc */
+};
+
 struct bpf_kfunc_desc {
 	struct btf_func_model func_model;
 	struct bpf_func_proto proto;
+	const struct bpf_kfunc_body *body;
 	u32 func_id;
 	u16 offset;
+	u8 body_imm;	/* R1-R5 that are constant (__k) arguments of the body */
 	unsigned long addr;
 };
 
+struct bpf_kfunc_desc *bpf_find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset);
+int bpf_inline_kfunc_bodies(struct bpf_verifier_env *env);
+int bpf_mark_kfunc_body_regs(struct bpf_verifier_env *env, int prev_insn_idx,
+			     const struct bpf_insn_aux_data *aux);
+void bpf_restore_kfunc_calls(struct bpf_verifier_env *env);
+void bpf_free_kfunc_inlines(struct bpf_verifier_env *env);
+const struct bpf_kfunc_inline *bpf_kfunc_native(const struct bpf_verifier_env *env, int idx);
+
 struct bpf_kfunc_desc_tab {
 	u32 nr_descs;
 	u32 nr_base_descs;
diff --git a/include/linux/btf.h b/include/linux/btf.h
index 4b63bb91550a1..1e7e52e778d82 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -120,10 +120,36 @@ struct bpf_prog;
 
 typedef int (*btf_kfunc_filter_t)(const struct bpf_prog *prog, u32 kfunc_id);
 
+#define BPF_KFUNC_BODY_MAX_INSNS	32
+#define BPF_KFUNC_INLINE_MAX		128
+
+/*
+ * The body of a kfunc: len BPF instructions that compute the kfunc from its
+ * arguments in R1-R5 into R0. The verifier analyzes each call of the kfunc as
+ * the body, and the body runs in place of the call unless the JIT has native
+ * code for it, see kernel/bpf/kfunc_inline.c.
+ *
+ * emit, if set, writes native code for a call to buf, at most
+ * BPF_KFUNC_INLINE_MAX bytes, and returns its length, or an error if it has
+ * no code, for example because the CPU lacks a feature; the JIT then copies
+ * the compiled kfunc. reg[i] is the native register that the verifier bound
+ * Ri to, for R0-R5, and those of R1-R5 that are not arguments are free to
+ * use. imm[i] is the value of Ri if it is a constant (__k) argument. Like the
+ * rest of the JIT, native code is trusted to compute what the body computes.
+ */
+struct bpf_kfunc_body {
+	const u32 *id;
+	const struct bpf_insn *insns;
+	u32 len;
+	int (*emit)(const u8 *reg, const s32 *imm, u8 *buf);
+};
+
 struct btf_kfunc_id_set {
 	struct module *owner;
 	struct btf_id_set8 *set;
 	btf_kfunc_filter_t filter;
+	const struct bpf_kfunc_body *bodies;
+	u32 body_cnt;
 };
 
 struct btf_id_dtor_kfunc {
@@ -604,6 +630,7 @@ const char *btf_str_by_offset(const struct btf *btf, u32 offset);
 struct btf *btf_parse_vmlinux(void);
 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);
+const struct bpf_kfunc_body *btf_find_kfunc_body(const struct btf *btf, u32 kfunc_btf_id);
 int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag);
 bool btf_kfunc_is_allowed(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog);
 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 9339c6131f8ff..d93629eb40cd3 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -1239,6 +1239,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 void bpf_jit_compile(struct bpf_prog *prog);
 bool bpf_jit_needs_zext(void);
 bool bpf_jit_inlines_helper_call(s32 imm);
+struct bpf_kfunc_inline;
+int bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf);
 bool bpf_jit_supports_subprog_tailcalls(void);
 bool bpf_jit_supports_percpu_insn(void);
 bool bpf_jit_supports_kfunc_call(void);
diff --git a/kernel/bpf/Kconfig b/kernel/bpf/Kconfig
index 98493e32db2ad..ca0dbfa1f81c5 100644
--- a/kernel/bpf/Kconfig
+++ b/kernel/bpf/Kconfig
@@ -101,6 +101,7 @@ config BPF_CRYPTO
 	  data. The supported algorithms are AES-CBC and AES-ECB.
 
 source "kernel/bpf/preload/Kconfig"
+source "kernel/bpf/insn_kfuncs/Kconfig"
 
 config BPF_LSM
 	bool "Enable BPF LSM Instrumentation"
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index c1f9b0d3468d3..94c81491a8e65 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_
 obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
 obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o
+obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o kfunc_inline.o
 obj-${CONFIG_BPF_LSM}	  += bpf_inode_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
 obj-$(CONFIG_BPF_JIT) += trampoline.o
@@ -60,6 +60,7 @@ obj-${CONFIG_BPF_LSM} += bpf_lsm_proto.o bpf_lsm.o
 endif
 obj-$(CONFIG_BPF_CRYPTO) += crypto.o
 obj-$(CONFIG_BPF_PRELOAD) += preload/
+obj-$(CONFIG_BPF_INSN_KFUNCS) += insn_kfuncs/
 
 obj-$(CONFIG_BPF_SYSCALL) += relo_core.o
 obj-$(CONFIG_BPF_SYSCALL) += btf_iter.o
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 0630675377aaa..4b729d0367bb2 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -246,6 +246,14 @@ struct btf_id_dtor_kfunc_tab {
 	struct btf_id_dtor_kfunc dtors[];
 };
 
+struct btf_kfunc_body_tab {
+	u32 cnt;
+	struct {
+		u32 id;
+		const struct bpf_kfunc_body *body;
+	} bodies[];
+};
+
 struct btf_struct_ops_tab {
 	u32 cnt;
 	u32 capacity;
@@ -269,6 +277,7 @@ struct btf {
 	struct rcu_head rcu;
 	struct btf_kfunc_set_tab *kfunc_set_tab;
 	struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
+	struct btf_kfunc_body_tab *kfunc_body_tab;
 	struct btf_struct_metas *struct_meta_tab;
 	struct btf_struct_ops_tab *struct_ops_tab;
 	struct btf_layout *layout;
@@ -1883,6 +1892,7 @@ static void btf_free(struct btf *btf)
 	btf_free_struct_meta_tab(btf);
 	btf_free_dtor_kfunc_tab(btf);
 	btf_free_kfunc_set_tab(btf);
+	kfree(btf->kfunc_body_tab);
 	btf_free_struct_ops_tab(btf);
 	kvfree(btf->types);
 	kvfree(btf->resolved_sizes);
@@ -9695,6 +9705,118 @@ 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);
 }
 
+const struct bpf_kfunc_body *btf_find_kfunc_body(const struct btf *btf, u32 kfunc_btf_id)
+{
+	const struct btf_kfunc_body_tab *tab = btf->kfunc_body_tab;
+	u32 i;
+
+	for (i = 0; tab && i < tab->cnt; i++)
+		if (tab->bodies[i].id == kfunc_btf_id)
+			return tab->bodies[i].body;
+	return NULL;
+}
+
+/* a scalar or a pointer of one register */
+static bool btf_kfunc_reg_type(const struct btf *btf, u32 id)
+{
+	const struct btf_type *t = btf_type_skip_modifiers(btf, id, NULL);
+
+	return btf_type_is_ptr(t) ||
+	       ((btf_type_is_int(t) || btf_is_any_enum(t)) && t->size <= sizeof(u64));
+}
+
+/*
+ * A kfunc with a body takes each argument in one of R1-R5, constant (__k)
+ * ones in 32 bits for native code, and returns in R0. Its body uses R0-R5,
+ * no instruction of cpu v4, which not every JIT has, and jumps only forward
+ * within it, so that it ends by falling through the last instruction. The
+ * verifier checks the rest.
+ */
+static bool btf_check_kfunc_body(const struct btf *btf, const struct btf_type *func,
+				 const struct bpf_kfunc_body *b)
+{
+	const struct btf_type *proto = btf_type_by_id(btf, func->type);
+	const struct btf_param *args = btf_params(proto);
+	int i, n = btf_type_vlen(proto), len = b->len;
+	const struct bpf_insn *insn;
+	u8 op;
+
+	if (n > MAX_BPF_FUNC_REG_ARGS || !b->insns || !len || len > BPF_KFUNC_BODY_MAX_INSNS ||
+	    (proto->type && !btf_kfunc_reg_type(btf, proto->type)))
+		return false;
+	for (i = 0; i < n; i++)
+		if (!btf_kfunc_reg_type(btf, args[i].type) ||
+		    (btf_param_match_suffix(btf, &args[i], "__k") &&
+		     btf_type_skip_modifiers(btf, args[i].type, NULL)->size > sizeof(s32)))
+			return false;
+	for (i = 0; i < len; i++) {
+		insn = &b->insns[i];
+		op = BPF_OP(insn->code);
+		if (insn->dst_reg > BPF_REG_5 || insn->src_reg > BPF_REG_5)
+			return false;
+		switch (BPF_CLASS(insn->code)) {
+		case BPF_ALU:
+		case BPF_ALU64:		/* not movsx, sdiv, smod or bswap */
+			if (insn->off || (BPF_CLASS(insn->code) == BPF_ALU64 && op == BPF_END))
+				return false;
+			break;
+		case BPF_LDX:
+		case BPF_ST:
+		case BPF_STX:		/* not ldsx or atomics */
+			if (BPF_MODE(insn->code) != BPF_MEM)
+				return false;
+			break;
+		case BPF_JMP:
+		case BPF_JMP32:		/* forward jumps within the body, not gotol */
+			if (op == BPF_CALL || op == BPF_EXIT || op == BPF_JCOND ||
+			    (op == BPF_JA && insn->code != (BPF_JMP | BPF_JA)) ||
+			    insn->off < 0 || insn->off >= len - i - 1)
+				return false;
+			break;
+		default:		/* not ld_imm64 */
+			return false;
+		}
+	}
+	return true;
+}
+
+static int btf_add_kfunc_bodies(struct btf *btf, const struct btf_kfunc_id_set *kset)
+{
+	u32 i, id, cnt = btf->kfunc_body_tab ? btf->kfunc_body_tab->cnt : 0;
+	struct btf_kfunc_body_tab *tab;
+	const struct bpf_kfunc_body *b;
+	const struct btf_type *t;
+	u32 *pair;
+
+	if (!kset->body_cnt)
+		return 0;
+	tab = krealloc(btf->kfunc_body_tab, struct_size(tab, bodies, cnt + kset->body_cnt),
+		       GFP_KERNEL | __GFP_NOWARN);
+	if (!tab)
+		return -ENOMEM;
+	tab->cnt = cnt;
+	btf->kfunc_body_tab = tab;
+	for (i = 0; i < kset->body_cnt; i++) {
+		b = &kset->bodies[i];
+		id = btf_relocate_id(btf, *b->id);
+		t = btf_type_by_id(btf, id);
+		pair = btf_id_set8_contains(kset->set, *b->id);
+		/* the body stands for the call, so no kfunc flags apply */
+		if (!pair || pair[1] || !t || !btf_type_is_func(t) ||
+		    !btf_check_kfunc_body(btf, t, b)) {
+			/* a set that fails to register leaves no bodies */
+			tab->cnt = cnt;
+			return -EINVAL;
+		}
+		/* a set registered for several hooks adds its bodies once */
+		if (!btf_find_kfunc_body(btf, id)) {
+			tab->bodies[tab->cnt].id = id;
+			tab->bodies[tab->cnt++].body = b;
+		}
+	}
+	return 0;
+}
+
 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
 				       const struct btf_kfunc_id_set *kset)
 {
@@ -9714,6 +9836,10 @@ static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
 			goto err_out;
 	}
 
+	ret = btf_add_kfunc_bodies(btf, kset);
+	if (ret)
+		goto err_out;
+
 	ret = btf_populate_kfunc_set(btf, hook, kset);
 
 err_out:
diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c
index b1528adbeb79d..8fa745e62e7ee 100644
--- a/kernel/bpf/const_fold.c
+++ b/kernel/bpf/const_fold.c
@@ -268,6 +268,10 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 		memcpy(ci_out, ci, sizeof(ci_out));
 
 		const_reg_xfer(env, ci_out, insn, insns, idx);
+		/* the body of a kfunc call leaves R0-R5 unknown, like the call */
+		if (insn_aux[idx].kfunc_body)
+			for (r = BPF_REG_0; r <= BPF_REG_5; r++)
+				ci_out[r] = unknown;
 
 		succ = bpf_insn_successors(env, idx);
 		for (int s = 0; s < succ->cnt; s++)
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 05c89396119ad..68665ea2499e9 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -3299,6 +3299,15 @@ bool __weak bpf_jit_inlines_helper_call(s32 imm)
 	return false;
 }
 
+/* Write native code for an inlined kfunc call, see struct bpf_kfunc_inline,
+ * to @buf for the JIT to copy. Return its length, or an error to keep the
+ * body of the kfunc.
+ */
+int __weak bpf_jit_inline_kfunc(const struct bpf_kfunc_inline *in, u8 *buf)
+{
+	return -EOPNOTSUPP;
+}
+
 /* Return TRUE if the JIT backend supports mixing bpf2bpf and tailcalls. */
 bool __weak bpf_jit_supports_subprog_tailcalls(void)
 {
diff --git a/kernel/bpf/insn_kfuncs/Kconfig b/kernel/bpf/insn_kfuncs/Kconfig
new file mode 100644
index 0000000000000..179236855d652
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/Kconfig
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: GPL-2.0-only
+config BPF_INSN_KFUNCS
+	tristate "Kfuncs for CPU instructions that BPF lacks"
+	depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+	help
+	  Provide kfuncs for rotate, conditional select, bit field extract,
+	  big-endian load, prefetch, 16-byte copy and address computation.
+	  The verifier checks each call as the kfunc's BPF body, and the JIT
+	  puts native code in its place where it can.
+
+	  If unsure, say N.
+
+config BPF_INSN_KFUNCS_ARCH
+	bool
+	depends on BPF_INSN_KFUNCS
+	default y if X86_64
diff --git a/kernel/bpf/insn_kfuncs/Makefile b/kernel/bpf/insn_kfuncs/Makefile
new file mode 100644
index 0000000000000..31e7ef567c90f
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_BPF_INSN_KFUNCS) += bpf_insn_kfuncs.o
+ifeq ($(CONFIG_BPF_INSN_KFUNCS_ARCH),y)
+CFLAGS_bpf_insn_kfuncs.o += -I$(src)/$(SRCARCH)
+endif
diff --git a/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c b/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c
new file mode 100644
index 0000000000000..1fcd0d7d0690c
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/bpf_insn_kfuncs.c
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Kfuncs for CPU instructions that BPF lacks, with BPF bodies, see struct
+ * bpf_kfunc_body. Arguments named __k must be known constants.
+ */
+#include <linux/bitops.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
+#include <linux/filter.h>
+#include <linux/module.h>
+#include <linux/unaligned.h>
+
+__bpf_kfunc_start_defs();
+
+__bpf_kfunc u64 bpf_rol64(u64 x, u32 n__k)
+{
+	return rol64(x, n__k);
+}
+
+__bpf_kfunc u64 bpf_select64(u64 cond, u64 a, u64 b)
+{
+	return cond ? a : b;
+}
+
+__bpf_kfunc u64 bpf_extract64(u64 x, u32 start__k, u32 len__k)
+{
+	return x << (64 - start__k - len__k) >> (64 - len__k);
+}
+
+__bpf_kfunc u64 bpf_load_be64(const void *p, s32 off__k)
+{
+	return get_unaligned_be64(p + off__k);
+}
+
+__bpf_kfunc void bpf_prefetch(const void *p)
+{
+	/* not prefetch(), which boot-time alternatives may rewrite */
+	__builtin_prefetch(p);
+}
+
+__bpf_kfunc void bpf_copy16(void *dst, const void *src)
+{
+	/* both loads first, as in the body, in case the buffers overlap */
+	u64 lo = get_unaligned((const u64 *)src);
+	u64 hi = get_unaligned((const u64 *)(src + 8));
+
+	put_unaligned(lo, (u64 *)dst);
+	put_unaligned(hi, (u64 *)(dst + 8));
+}
+
+__bpf_kfunc u64 bpf_lea64(u64 base, u64 index, u32 scale__k, s32 disp__k)
+{
+	return base + index * scale__k + disp__k;
+}
+
+__bpf_kfunc_end_defs();
+
+/* x << n | x >> (-n & 63) */
+static const struct bpf_insn rol64_body[] = {
+	BPF_ALU64_IMM(BPF_AND, BPF_REG_2, 63),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_LSH, BPF_REG_0, BPF_REG_2),
+	BPF_ALU64_IMM(BPF_NEG, BPF_REG_2, 0),
+	BPF_ALU64_IMM(BPF_AND, BPF_REG_2, 63),
+	BPF_ALU64_REG(BPF_RSH, BPF_REG_1, BPF_REG_2),
+	BPF_ALU64_REG(BPF_OR, BPF_REG_0, BPF_REG_1),
+};
+
+/* the jump lands within the body, here on its last instruction */
+static const struct bpf_insn select64_body[] = {
+	BPF_JMP_IMM(BPF_JNE, BPF_REG_1, 0, 1),
+	BPF_MOV64_REG(BPF_REG_2, BPF_REG_3),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
+};
+
+/* x << (64 - start - len) >> (64 - len) */
+static const struct bpf_insn extract64_body[] = {
+	BPF_MOV32_IMM(BPF_REG_4, 64),
+	BPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_2),
+	BPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_3),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_LSH, BPF_REG_0, BPF_REG_4),
+	BPF_MOV32_IMM(BPF_REG_4, 64),
+	BPF_ALU32_REG(BPF_SUB, BPF_REG_4, BPF_REG_3),
+	BPF_ALU64_REG(BPF_RSH, BPF_REG_0, BPF_REG_4),
+};
+
+/* the offset is an s32 */
+static const struct bpf_insn load_be64_body[] = {
+	BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 32),
+	BPF_ALU64_IMM(BPF_ARSH, BPF_REG_2, 32),
+	BPF_ALU64_REG(BPF_ADD, BPF_REG_1, BPF_REG_2),
+	BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, 0),
+	BPF_ENDIAN(BPF_TO_BE, BPF_REG_0, 64),
+};
+
+/* a load whose value is not used, of memory that the program may read */
+static const struct bpf_insn prefetch_body[] = {
+	BPF_LDX_MEM(BPF_B, BPF_REG_1, BPF_REG_1, 0),
+};
+
+/* two loads, then two stores */
+static const struct bpf_insn copy16_body[] = {
+	BPF_LDX_MEM(BPF_DW, BPF_REG_4, BPF_REG_2, 0),
+	BPF_LDX_MEM(BPF_DW, BPF_REG_5, BPF_REG_2, 8),
+	BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_4, 0),
+	BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_5, 8),
+};
+
+/* base + index * scale + disp, scale a u32 and disp an s32 */
+static const struct bpf_insn lea64_body[] = {
+	BPF_MOV32_REG(BPF_REG_3, BPF_REG_3),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
+	BPF_ALU64_REG(BPF_MUL, BPF_REG_0, BPF_REG_3),
+	BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_IMM(BPF_LSH, BPF_REG_4, 32),
+	BPF_ALU64_IMM(BPF_ARSH, BPF_REG_4, 32),
+	BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_4),
+};
+
+#ifdef CONFIG_BPF_INSN_KFUNCS_ARCH
+#include "insn_kfuncs.h" /* $(SRCARCH)/insn_kfuncs.h */
+#else
+#define rol64_emit	NULL
+#define select64_emit	NULL
+#define extract64_emit	NULL
+#define load_be64_emit	NULL
+#define lea64_emit	NULL
+#endif
+
+BTF_KFUNCS_START(insn_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_rol64)
+BTF_ID_FLAGS(func, bpf_select64)
+BTF_ID_FLAGS(func, bpf_extract64)
+BTF_ID_FLAGS(func, bpf_load_be64)
+BTF_ID_FLAGS(func, bpf_prefetch)
+BTF_ID_FLAGS(func, bpf_copy16)
+BTF_ID_FLAGS(func, bpf_lea64)
+BTF_KFUNCS_END(insn_kfunc_ids)
+
+BTF_ID_LIST(body_ids)
+BTF_ID(func, bpf_rol64)
+BTF_ID(func, bpf_select64)
+BTF_ID(func, bpf_extract64)
+BTF_ID(func, bpf_load_be64)
+BTF_ID(func, bpf_prefetch)
+BTF_ID(func, bpf_copy16)
+BTF_ID(func, bpf_lea64)
+
+#define BODY(i, op, emit)	{ &body_ids[i], op##_body, ARRAY_SIZE(op##_body), emit }
+
+/* without emit, the JIT copies the kfunc, whose code is the instruction itself */
+static const struct bpf_kfunc_body bodies[] = {
+	BODY(0, rol64, rol64_emit),
+	BODY(1, select64, select64_emit),
+	BODY(2, extract64, extract64_emit),
+	BODY(3, load_be64, load_be64_emit),
+	BODY(4, prefetch, NULL),
+	BODY(5, copy16, NULL),
+	BODY(6, lea64, lea64_emit),
+};
+
+static const struct btf_kfunc_id_set insn_kfunc_set = {
+	.owner    = THIS_MODULE,
+	.set      = &insn_kfunc_ids,
+	.bodies   = bodies,
+	.body_cnt = ARRAY_SIZE(bodies),
+};
+
+static int __init insn_kfuncs_init(void)
+{
+	return register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &insn_kfunc_set);
+}
+
+/* the kfunc set goes away with the module's BTF */
+static void __exit insn_kfuncs_exit(void)
+{
+}
+
+module_init(insn_kfuncs_init);
+module_exit(insn_kfuncs_exit);
+
+MODULE_DESCRIPTION("Kfuncs for CPU instructions that BPF lacks");
+MODULE_LICENSE("GPL");
diff --git a/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h b/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h
new file mode 100644
index 0000000000000..5809bb69b4cd6
--- /dev/null
+++ b/kernel/bpf/insn_kfuncs/x86/insn_kfuncs.h
@@ -0,0 +1,155 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* x86-64 code for the kfuncs in bpf_insn_kfuncs.c, see struct bpf_kfunc_body */
+#include <linux/cpufeature.h>
+#include <linux/log2.h>
+#include <linux/unaligned.h>
+
+static u8 *x86_rex(u8 *p, bool w, u8 reg, u8 rm)
+{
+	u8 b = 0x40 | (w ? 8 : 0) | (reg & 8 ? 4 : 0) | (rm & 8 ? 1 : 0);
+
+	if (b != 0x40)
+		*p++ = b;
+	return p;
+}
+
+/* 64-bit op %reg, %rm */
+static u8 *x86_op_rr(u8 *p, u8 op, u8 reg, u8 rm)
+{
+	p = x86_rex(p, true, reg, rm);
+	*p++ = op;
+	*p++ = 0xc0 | (reg & 7) << 3 | (rm & 7);
+	return p;
+}
+
+/*
+ * ModRM, SIB and displacement of disp(%base, %index, 1 << scale), with @reg in
+ * the reg field. An @index of 4 (%rsp) is none.
+ */
+static u8 *x86_mem(u8 *p, u8 reg, u8 base, u8 index, u8 scale, s32 disp)
+{
+	u8 mod = !disp && (base & 7) != 5 ? 0 : disp == (s8)disp ? 1 : 2;
+	bool sib = index != 4 || (base & 7) == 4;
+
+	*p++ = mod << 6 | (reg & 7) << 3 | (sib ? 4 : base & 7);
+	if (sib)
+		*p++ = scale << 6 | (index & 7) << 3 | (base & 7);
+	if (mod == 1)
+		*p++ = disp;
+	if (mod == 2) {
+		put_unaligned_le32(disp, p);
+		p += 4;
+	}
+	return p;
+}
+
+static int rol64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], src = reg[1], n = imm[BPF_REG_2] & 63, *p = buf;
+
+	if (n && dst != src && cpu_feature_enabled(X86_FEATURE_BMI2)) {
+		/* rorx $(64 - n), %src, %dst */
+		*p++ = 0xc4;
+		*p++ = (dst & 8 ? 0 : 0x80) | 0x40 | (src & 8 ? 0 : 0x20) | 0x03;
+		*p++ = 0xfb;
+		*p++ = 0xf0;
+		*p++ = 0xc0 | (dst & 7) << 3 | (src & 7);
+		*p++ = 64 - n;
+		return p - buf;
+	}
+	if (dst != src || !n)
+		p = x86_op_rr(p, 0x89, src, dst);	/* mov %src, %dst */
+	if (n) {
+		/* rol $n, %dst */
+		p = x86_rex(p, true, 0, dst);
+		*p++ = 0xc1;
+		*p++ = 0xc0 | (dst & 7);
+		*p++ = n;
+	}
+	return p - buf;
+}
+
+/* cmovcc %src, %dst */
+static u8 *x86_cmov(u8 *p, u8 cc, u8 dst, u8 src)
+{
+	p = x86_rex(p, true, dst, src);
+	*p++ = 0x0f;
+	*p++ = 0x40 | cc;
+	*p++ = 0xc0 | (dst & 7) << 3 | (src & 7);
+	return p;
+}
+
+/*
+ * dst = cc ? a : b, after the test or compare at @p. The flags come first, so
+ * the result may take the register of an operand they read. A result in the
+ * register of a takes b with the inverse condition, which a copy of the
+ * compiled kfunc cannot do.
+ */
+static int x86_select(u8 *buf, u8 *p, u8 cc, u8 dst, u8 a, u8 b)
+{
+	if (dst == a)
+		return x86_cmov(p, cc ^ 1, dst, b) - buf;
+	if (dst != b)
+		p = x86_op_rr(p, 0x89, b, dst);	/* mov %b, %dst */
+	return x86_cmov(p, cc, dst, a) - buf;
+}
+
+static int select64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 cond = reg[1];
+
+	/* test %cond, %cond; cmovne */
+	return x86_select(buf, x86_op_rr(buf, 0x85, cond, cond), 0x5, reg[0],
+			   reg[2], reg[3]);
+}
+
+/* R4 is free for the control word, as there are three arguments */
+static int extract64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], src = reg[1], ctl = dst != src ? dst : reg[4];
+	u32 start = imm[BPF_REG_2], len = imm[BPF_REG_3];
+	u8 *p = buf;
+
+	if (!cpu_feature_enabled(X86_FEATURE_BMI1) || start > 63 || !len || len > 64 - start)
+		return -EOPNOTSUPP;
+	/* mov $(start | len << 8), %ctl */
+	p = x86_rex(p, false, 0, ctl);
+	*p++ = 0xb8 | (ctl & 7);
+	put_unaligned_le32(start | len << 8, p);
+	p += 4;
+	/* bextr %ctl, %src, %dst */
+	*p++ = 0xc4;
+	*p++ = (dst & 8 ? 0 : 0x80) | 0x40 | (src & 8 ? 0 : 0x20) | 0x02;
+	*p++ = 0x80 | (~ctl & 0xf) << 3;
+	*p++ = 0xf7;
+	*p++ = 0xc0 | (dst & 7) << 3 | (src & 7);
+	return p - buf;
+}
+
+static int load_be64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], base = reg[1], *p = buf;
+
+	if (!cpu_feature_enabled(X86_FEATURE_MOVBE))
+		return -EOPNOTSUPP;
+	/* movbe off(%base), %dst */
+	p = x86_rex(p, true, dst, base);
+	*p++ = 0x0f;
+	*p++ = 0x38;
+	*p++ = 0xf0;
+	return x86_mem(p, dst, base, 4, 0, imm[BPF_REG_2]) - buf;
+}
+
+static int lea64_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], base = reg[1], index = reg[2], *p = buf;
+	u32 scale = imm[BPF_REG_3];
+
+	/* %rsp cannot be an index, and the scale is 1, 2, 4 or 8 */
+	if (index == 4 || !is_power_of_2(scale) || scale > 8)
+		return -EOPNOTSUPP;
+	/* lea disp(%base, %index, scale), %dst */
+	*p++ = 0x48 | (dst & 8 ? 4 : 0) | (index & 8 ? 2 : 0) | (base & 8 ? 1 : 0);
+	*p++ = 0x8d;
+	return x86_mem(p, dst, base, index, ilog2(scale), imm[BPF_REG_4]) - buf;
+}
diff --git a/kernel/bpf/kfunc_inline.c b/kernel/bpf/kfunc_inline.c
new file mode 100644
index 0000000000000..daf92c3ad512c
--- /dev/null
+++ b/kernel/bpf/kfunc_inline.c
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Calls of kfuncs that have a BPF body, see struct bpf_kfunc_body */
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/filter.h>
+#include <linux/slab.h>
+
+#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
+
+static struct bpf_kfunc_desc *body_desc(struct bpf_verifier_env *env,
+					const struct bpf_insn *insn)
+{
+	struct bpf_kfunc_desc *desc;
+
+	if (!bpf_pseudo_kfunc_call(insn))
+		return NULL;
+	desc = bpf_find_kfunc_desc(env->prog, insn->imm, insn->off);
+	return desc && desc->body ? desc : NULL;
+}
+
+/*
+ * Replace each call of a kfunc with a body by the body, so that the verifier
+ * analyzes the operation in the caller's context. The entry and exit of the
+ * body get the register effects of the call, see bpf_mark_kfunc_body_regs().
+ * After verification bpf_restore_kfunc_calls() puts the call back if the JIT
+ * has native code for it, and keeps the body otherwise.
+ */
+int bpf_inline_kfunc_bodies(struct bpf_verifier_env *env)
+{
+	struct bpf_kfunc_desc *desc;
+	struct bpf_kfunc_inline *r;
+	struct bpf_prog *prog;
+	u32 i, j, cnt = 0;
+
+	for (i = 0; i < env->prog->len; i++)
+		cnt += !!body_desc(env, &env->prog->insnsi[i]);
+	if (!cnt)
+		return 0;
+	env->kfunc_inlines = kvzalloc_objs(*env->kfunc_inlines, cnt, GFP_KERNEL_ACCOUNT);
+	if (!env->kfunc_inlines)
+		return -ENOMEM;
+
+	for (i = 0; i < env->prog->len; i++) {
+		desc = body_desc(env, &env->prog->insnsi[i]);
+		if (!desc)
+			continue;
+		r = &env->kfunc_inlines[env->kfunc_inline_cnt++];
+		r->call = env->prog->insnsi[i];
+		r->body = desc->body;
+		r->addr = desc->addr;
+		r->start = i;
+		r->nargs = desc->func_model.nr_args;
+		r->imm_mask = desc->body_imm;
+		r->ret = desc->func_model.ret_size;
+		prog = bpf_patch_insn_data(env, i, r->body->insns, r->body->len);
+		if (!prog)
+			return -ENOMEM;
+		env->prog = prog;
+		for (j = i; j < i + r->body->len; j++)
+			env->insn_aux_data[j].kfunc_body = 1;
+		env->insn_aux_data[i].kfunc_body_entry = 1;
+		i += r->body->len - 1;
+	}
+	return 0;
+}
+
+/*
+ * The body of a kfunc gets only the arguments of the call and leaves R1-R5
+ * like it. The constant (__k) arguments must be known, and native code may
+ * use their values.
+ */
+int bpf_mark_kfunc_body_regs(struct bpf_verifier_env *env, int prev_insn_idx,
+			     const struct bpf_insn_aux_data *aux)
+{
+	struct bpf_kfunc_inline *r = env->kfunc_inlines;
+	struct bpf_reg_state *regs = cur_regs(env);
+	u32 clobber = 0;
+	int i, err;
+
+	/* leaving the body */
+	if (prev_insn_idx >= 0 && env->insn_aux_data[prev_insn_idx].kfunc_body &&
+	    (!aux->kfunc_body || aux->kfunc_body_entry))
+		clobber |= GENMASK(BPF_REG_5, BPF_REG_1);
+	if (aux->kfunc_body_entry) {
+		while (r->start != env->insn_idx)
+			r++;
+		for (i = BPF_REG_1; i <= BPF_REG_5 && !env->cur_state->speculative; i++) {
+			if (!(r->imm_mask & BIT(i)))
+				continue;
+			if (regs[i].type != SCALAR_VALUE || !tnum_is_const(regs[i].var_off)) {
+				verbose(env, "R%d must be a known constant\n", i);
+				return -EINVAL;
+			}
+			err = mark_chain_precision(env, i);
+			if (err)
+				return err;
+			/* emitted code needs the same constants on every path */
+			if (r->entered && r->imm[i] != (s32)regs[i].var_off.value)
+				r->copy = true;
+			r->imm[i] = regs[i].var_off.value;
+		}
+		r->entered = true;
+		clobber |= BIT(BPF_REG_0) | (GENMASK(BPF_REG_5, BPF_REG_0) &
+					     ~GENMASK(r->nargs, BPF_REG_0));
+	}
+	for (i = BPF_REG_0; i <= BPF_REG_5; i++) {
+		if (!(clobber & BIT(i)))
+			continue;
+		bpf_mark_reg_not_init(env, &regs[i]);
+		mark_reg_scratched(env, i);
+	}
+	return 0;
+}
+
+/*
+ * Native code can replace the body of a kfunc call that the verifier reached
+ * and does not rewrite later: no speculation barriers, sanitation or arena
+ * conversion, and memory accesses only to memory that the JIT accesses as is.
+ */
+static bool kfunc_native_ok(struct bpf_verifier_env *env, const struct bpf_kfunc_inline *r)
+{
+	u32 i;
+
+	if (env->prog->blinding_requested || (r->imm_mask && !r->entered))
+		return false;
+	for (i = 0; i < r->body->len; i++) {
+		const struct bpf_insn_aux_data *aux = &env->insn_aux_data[r->start + i];
+		u8 class = BPF_CLASS(r->body->insns[i].code);
+
+		if (aux->nospec || aux->nospec_result || aux->alu_state || aux->needs_zext ||
+		    aux->arena_scalar)
+			return false;
+		if (class != BPF_LDX && class != BPF_STX && class != BPF_ST)
+			continue;
+		if (type_flag(aux->ptr_type) & ~MEM_RDONLY)
+			return false;
+		switch (base_type(aux->ptr_type)) {
+		case PTR_TO_STACK:
+			break;
+		case PTR_TO_MAP_VALUE:
+		case PTR_TO_MEM:
+		case PTR_TO_PACKET:
+		case PTR_TO_PACKET_META:
+			/* the JIT checks these accesses with KASAN, native code does not */
+			if (IS_ENABLED(CONFIG_BPF_JIT_KASAN))
+				return false;
+			break;
+		default:
+			return false;
+		}
+	}
+	return true;
+}
+
+/*
+ * Bind the operands of a kfunc call in r->reg and return the moves that this
+ * makes unnecessary in @drop:
+ * - an argument copied from R6-R9 by a 64-bit move right before the call is
+ *   used in place if that register is dead after the call;
+ * - emitted native code has the constant arguments as immediates;
+ * - the result goes straight to its R6-R9 destination.
+ * No jump may land between such a move and the call. Only emitted code may
+ * share the result register with an argument.
+ */
+static int kfunc_bind(struct bpf_verifier_env *env, struct bpf_kfunc_inline *r, u32 *drop)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_insn *insns = env->prog->insnsi, *mov;
+	u32 end = r->start + r->body->len, i;
+	bool emit = !r->copy;
+	u16 used = 0, written = 0;
+	u8 dst, src;
+	int n = 0;
+
+	for (i = 0; i <= MAX_BPF_FUNC_REG_ARGS; i++)
+		r->reg[i] = i;
+
+	/* walk back over moves into R1-R5 that do not read R0-R5 */
+	for (i = r->start; i-- > 0 && !bpf_is_jump_target(env, i + 1);) {
+		mov = &insns[i];
+		dst = mov->dst_reg;
+		src = mov->src_reg;
+		if ((BPF_CLASS(mov->code) != BPF_ALU64 && BPF_CLASS(mov->code) != BPF_ALU) ||
+		    BPF_OP(mov->code) != BPF_MOV || dst < BPF_REG_1 || dst > BPF_REG_5 ||
+		    aux[i].kfunc_body ||
+		    (BPF_SRC(mov->code) == BPF_X && (src < BPF_REG_6 || src > BPF_REG_9)))
+			break;
+		if (dst <= r->nargs && !(written & BIT(dst)) && !mov->off) {
+			if (BPF_SRC(mov->code) == BPF_K && (r->imm_mask & BIT(dst)) && emit) {
+				drop[n++] = i;
+			} else if (mov->code == (BPF_ALU64 | BPF_MOV | BPF_X) &&
+				   !(used & BIT(src)) &&
+				   !(aux[end].live_regs_before & BIT(src))) {
+				r->reg[dst] = src;
+				used |= BIT(src);
+				drop[n++] = i;
+			}
+		}
+		written |= BIT(dst);
+	}
+
+	mov = &insns[end];
+	dst = mov->dst_reg;
+	/* the result register must be live so that the JIT saves it */
+	if (r->ret && !bpf_is_jump_target(env, end) && end + 1 < env->prog->len &&
+	    mov->code == (BPF_ALU64 | BPF_MOV | BPF_X) && !mov->off &&
+	    mov->src_reg == BPF_REG_0 && dst >= BPF_REG_6 && dst <= BPF_REG_9 &&
+	    (emit || !(used & BIT(dst))) &&
+	    (aux[end + 1].live_regs_before & BIT(dst)) &&
+	    !(aux[end + 1].live_regs_before & BIT(BPF_REG_0))) {
+		r->reg[BPF_REG_0] = dst;
+		drop[n++] = end;
+	}
+	return n;
+}
+
+/*
+ * Put back the calls that the JIT has native code for: the code from the
+ * kfunc's emit callback, or else a copy of the compiled kfunc. The rest of
+ * the body and the moves that binding makes unnecessary become nops, which
+ * bpf_opt_remove_nops() removes. Other calls keep their body.
+ */
+void bpf_restore_kfunc_calls(struct bpf_verifier_env *env)
+{
+	struct bpf_insn *insns = env->prog->insnsi;
+	u32 drop[MAX_BPF_FUNC_REG_ARGS + 1];
+	u8 code[BPF_KFUNC_INLINE_MAX];
+	int i, j, n, len;
+
+	for (i = 0; i < env->kfunc_inline_cnt; i++) {
+		struct bpf_kfunc_inline *r = &env->kfunc_inlines[i];
+
+		if (!kfunc_native_ok(env, r))
+			continue;
+		n = kfunc_bind(env, r, drop);
+		len = bpf_jit_inline_kfunc(r, code);
+		if (len <= 0 && !r->copy) {
+			r->copy = true;
+			n = kfunc_bind(env, r, drop);
+			len = bpf_jit_inline_kfunc(r, code);
+		}
+		r->image = len > 0 ? kmemdup(code, len, GFP_KERNEL_ACCOUNT) : NULL;
+		if (!r->image)
+			continue;
+		r->image_len = len;
+		for (j = 0; j < n; j++)
+			insns[drop[j]] = BPF_JMP_A(0);
+		insns[r->start] = r->call;
+		for (j = r->start + 1; j < r->start + r->body->len; j++)
+			insns[j] = BPF_JMP_A(0);
+		env->insn_aux_data[r->start].kfunc_inline = i + 1;
+	}
+}
+
+/* The inlined kfunc call at @idx, if the JIT puts native code there */
+const struct bpf_kfunc_inline *bpf_kfunc_native(const struct bpf_verifier_env *env, int idx)
+{
+	u32 i = env && env->insn_aux_data[idx].kfunc_body_entry ?
+		env->insn_aux_data[idx].kfunc_inline : 0;
+
+	if (!i || i > env->kfunc_inline_cnt || !env->kfunc_inlines[i - 1].image)
+		return NULL;
+	return &env->kfunc_inlines[i - 1];
+}
+
+void bpf_free_kfunc_inlines(struct bpf_verifier_env *env)
+{
+	u32 i;
+
+	for (i = 0; i < env->kfunc_inline_cnt; i++)
+		kfree(env->kfunc_inlines[i].image);
+	kvfree(env->kfunc_inlines);
+}
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index fd3c0206bd67d..2f58794784100 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -2569,8 +2569,8 @@ static int kfunc_btf_cmp_by_off(const void *a, const void *b)
 	return d0->offset - d1->offset;
 }
 
-static struct bpf_kfunc_desc *
-find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
+struct bpf_kfunc_desc *
+bpf_find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
 {
 	struct bpf_kfunc_desc desc = {
 		.func_id = func_id,
@@ -2877,10 +2877,11 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 	struct btf_func_model func_model;
 	struct bpf_kfunc_desc_tab *tab;
 	struct bpf_prog_aux *prog_aux;
+	const struct bpf_kfunc_body *body;
 	struct bpf_kfunc_meta kfunc;
 	struct bpf_kfunc_desc *desc;
 	unsigned long addr;
-	int err;
+	int err, i;
 
 	prog_aux = env->prog->aux;
 	tab = prog_aux->kfunc_tab;
@@ -2930,7 +2931,7 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 		prog_aux->kfunc_btf_tab = btf_tab;
 	}
 
-	if (find_kfunc_desc(env->prog, func_id, offset))
+	if (bpf_find_kfunc_desc(env->prog, func_id, offset))
 		return 0;
 
 	if (tab->nr_base_descs == MAX_KFUNC_DESCS) {
@@ -2990,7 +2991,10 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 	desc = &tab->descs[tab->nr_descs];
 	memset(desc, 0, sizeof(*desc));
 
-	err = gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
+	/* the body of a kfunc that the program may call checks its arguments */
+	body = kfunc.flags && btf_kfunc_is_allowed(kfunc.btf, func_id, env->prog) ?
+	       btf_find_kfunc_body(kfunc.btf, func_id) : NULL;
+	err = body ? 0 : gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
 	if (err)
 		return err;
 
@@ -2998,6 +3002,10 @@ int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
 	desc->offset = offset;
 	desc->addr = addr;
 	desc->func_model = func_model;
+	desc->body = body;
+	for (i = 0; body && i < func_model.nr_args; i++)
+		if (btf_param_match_suffix(kfunc.btf, &btf_params(kfunc.proto)[i], "__k"))
+			desc->body_imm |= BIT(BPF_REG_1 + i);
 	tab->nr_descs++;
 	tab->nr_base_descs++;
 	sort(tab->descs, tab->nr_base_descs, sizeof(tab->descs[0]),
@@ -14762,7 +14770,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	func_name = meta.func_name;
 	insn_aux = &env->insn_aux_data[insn_idx];
 
-	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
+	desc = bpf_find_kfunc_desc(env->prog, insn->imm, insn->off);
 	if (!desc) {
 		verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm);
 		return -EFAULT;
@@ -19527,6 +19535,9 @@ static int do_check(struct bpf_verifier_env *env)
 
 		state->last_insn_idx = env->prev_insn_idx;
 		state->insn_idx = env->insn_idx;
+		err = bpf_mark_kfunc_body_regs(env, prev_insn_idx, insn_aux);
+		if (err)
+			return err;
 		/*
 		 * Record the incoming edge so active and queued paths use the same
 		 * branch-recording path. A zero-offset conditional has identical
@@ -22180,7 +22191,7 @@ int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	 * __bpf_call_base, unless the JIT needs to call functions that are
 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
 	 */
-	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
+	desc = bpf_find_kfunc_desc(env->prog, insn->imm, insn->off);
 	if (!desc) {
 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
 			     insn->imm);
@@ -22655,15 +22666,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
 	env->arena_scalar = attr->prog_flags & BPF_F_ARENA_SCALAR;
 
-	env->explored_states = kvzalloc_objs(struct list_head,
-					     state_htab_size(env),
-					     GFP_KERNEL_ACCOUNT);
-	ret = -ENOMEM;
-	if (!env->explored_states)
-		goto skip_full_check;
-
-	for (i = 0; i < state_htab_size(env); i++)
-		INIT_LIST_HEAD(&env->explored_states[i]);
 	INIT_LIST_HEAD(&env->free_list);
 
 	/* Prepare BTF and func_info needed to discover all subprograms. */
@@ -22707,6 +22709,21 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	ret = bpf_inline_kfunc_bodies(env);
+	if (ret < 0)
+		goto skip_full_check;
+
+	/* sized by the program length, so after the lowering */
+	env->explored_states = kvzalloc_objs(struct list_head,
+					     state_htab_size(env),
+					     GFP_KERNEL_ACCOUNT);
+	ret = -ENOMEM;
+	if (!env->explored_states)
+		goto skip_full_check;
+
+	for (i = 0; i < state_htab_size(env); i++)
+		INIT_LIST_HEAD(&env->explored_states[i]);
+
 	if (bpf_prog_is_offloaded(env->prog->aux)) {
 		ret = bpf_prog_offload_verifier_prep(env->prog);
 		if (ret)
@@ -22771,6 +22788,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 skip_full_check:
 	kvfree(env->explored_states);
 
+	if (ret == 0)
+		bpf_restore_kfunc_calls(env);
+
 	/* might decrease stack depth, keep it before passes that
 	 * allocate additional slots.
 	 */
@@ -22900,6 +22920,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 err_free_env:
 	bpf_free_subprog_jts(env);
 	vfree(env->insn_aux_data);
+	bpf_free_kfunc_inlines(env);
 	kvfree(env->fd_array);
 	bpf_stack_liveness_free(env);
 	kvfree(env->cfg.insn_postorder);
diff --git a/tools/testing/selftests/bpf/Makefile b/tools/testing/selftests/bpf/Makefile
index a22be7efd1fa2..7a5dd7fcd3d14 100644
--- a/tools/testing/selftests/bpf/Makefile
+++ b/tools/testing/selftests/bpf/Makefile
@@ -48,7 +48,7 @@ TEST_PROGS_EXTENDED := \
 	ima_setup.sh verify_sig_setup.sh
 
 TEST_KMODS := bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \
-	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko
+	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_kfunc_body.ko
 TEST_KMOD_TARGETS = $(addprefix $(OUTPUT)/,$(TEST_KMODS))
 
 # Compile but not part of 'make run_tests'
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2b883b388f90c..abc4e79d42a01 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -3,6 +3,7 @@ CONFIG_BOOTPARAM_HARDLOCKUP_PANIC=y
 CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC=1
 CONFIG_BPF=y
 CONFIG_BPF_EVENTS=y
+CONFIG_BPF_INSN_KFUNCS=y
 CONFIG_BPF_JIT=y
 CONFIG_BPF_KPROBE_OVERRIDE=y
 CONFIG_BPF_LIRC_MODE2=y
diff --git a/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c b/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c
new file mode 100644
index 0000000000000..3aa1f614b508e
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/kfunc_body_registration.c
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <testing_helpers.h>
+
+/* bpf_test_kfunc_body.ko fails to load unless bad kfunc bodies are rejected */
+void test_kfunc_body_registration(void)
+{
+	int fd, err;
+
+	fd = open("bpf_test_kfunc_body.ko", O_RDONLY);
+	if (!ASSERT_GE(fd, 0, "open"))
+		return;
+	err = finit_module(fd, "", 0);
+	close(fd);
+	if (!ASSERT_OK(err, "finit_module"))
+		return;
+	ASSERT_OK(delete_module("bpf_test_kfunc_body", 0), "delete_module");
+}
diff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c
index 460ad10ddc020..ad7baf3afa248 100644
--- a/tools/testing/selftests/bpf/prog_tests/verifier.c
+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c
@@ -60,6 +60,7 @@
 #include "verifier_iterating_callbacks.skel.h"
 #include "verifier_jeq_infer_not_null.skel.h"
 #include "verifier_jit_convergence.skel.h"
+#include "verifier_kfunc_inline.skel.h"
 #include "verifier_kfunc_packet_access.skel.h"
 #include "verifier_kfunc_uninit.skel.h"
 #include "verifier_kfunc_uninit_multi.skel.h"
@@ -245,6 +246,7 @@ void test_verifier_int_ptr(void)              { RUN(verifier_int_ptr); }
 void test_verifier_iterating_callbacks(void)  { RUN(verifier_iterating_callbacks); }
 void test_verifier_jeq_infer_not_null(void)   { RUN(verifier_jeq_infer_not_null); }
 void test_verifier_jit_convergence(void)      { RUN(verifier_jit_convergence); }
+void test_verifier_kfunc_inline(void)         { RUN_TESTS(verifier_kfunc_inline); }
 void test_verifier_kfunc_packet_access(void)  { RUN_TESTS(verifier_kfunc_packet_access); }
 void test_verifier_kfunc_uninit(void)         { RUN_TESTS(verifier_kfunc_uninit); }
 void test_verifier_kfunc_uninit_multi(void)   { RUN_TESTS(verifier_kfunc_uninit_multi); }
diff --git a/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c b/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c
new file mode 100644
index 0000000000000..b525e7cf7a0f4
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_kfunc_inline.c
@@ -0,0 +1,543 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "../test_kmods/bpf_testmod_kfunc.h"
+
+extern u64 bpf_rol64(u64 x, u32 n) __ksym;
+extern u64 bpf_select64(u64 cond, u64 a, u64 b) __ksym;
+extern u64 bpf_extract64(u64 x, u32 start, u32 len) __ksym;
+extern u64 bpf_load_be64(const void *p, s32 off) __ksym;
+extern void bpf_prefetch(const void *p) __ksym;
+extern void bpf_copy16(void *dst, const void *src) __ksym;
+extern u64 bpf_lea64(u64 base, u64 index, u32 scale, s32 disp) __ksym;
+
+/* r6 = rol(r6, 13) is one rol, the moves around the call go away */
+SEC("tc")
+__success __retval(8192)
+__xlated("0: r6 = 1")
+__xlated("1: call")
+__xlated("2: r0 = r6")
+__arch_x86_64
+__jited("{{.*}}movl\t$0x1, %ebx")
+__jited("{{.*}}rolq\t$0xd, %rbx")
+__jited("{{.*}}movq\t%rbx, %rax")
+__naked void inline_rol64_in_place(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r1 = r6;"
+	"r2 = 13;"
+	"call %[bpf_rol64];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+/* r7 = rol(r6, 8) keeps r6 */
+SEC("tc")
+__success __retval(255)
+__arch_x86_64
+__jited("{{.*}}{{rorxq\t\\$0x38, %rdi, %r13|rolq\t\\$0x8, %r13}}")
+__naked void inline_rol64_copy(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r1 = r6;"
+	"r2 = 8;"
+	"call %[bpf_rol64];"
+	"r7 = r0;"
+	"r0 = r7;"
+	"r0 -= r6;"
+	"exit;"
+	:
+	: __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+/* a 32-bit move of the constant goes away as well */
+SEC("tc")
+__success __retval(16)
+__xlated("1: call")
+__arch_x86_64
+__jited("{{.*}}rolq\t$0x4, %rbx")
+__naked void inline_rol_w2(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r1 = r6;"
+	"w2 = 4;"
+	"call %[bpf_rol64];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+SEC("tc")
+__success __retval(42)
+__arch_x86_64
+__jited("{{.*}}testq\t%rbx, %rbx")
+__jited("{{.*}}movq\t%r14, %r15")
+__jited("{{.*}}cmovneq\t%r13, %r15")
+__naked void inline_select(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"r9 = r0;"
+	"r0 = r9;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+/* r9 = r6 ? r7 : r9 is a test and a cmov */
+SEC("tc")
+__success __retval(7)
+__arch_x86_64
+__jited("{{.*}}testq\t%rbx, %rbx")
+__jited("{{.*}}cmovneq\t%r13, %r15")
+__naked void inline_select_in_place(void)
+{
+	asm volatile (
+	"r6 = 0;"
+	"r7 = 42;"
+	"r9 = 7;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = r9;"
+	"call %[bpf_select64];"
+	"r9 = r0;"
+	"r0 = r9;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+SEC("tc")
+__success __retval(0x56)
+__arch_x86_64
+__jited("{{.*}}{{bextrq\t%r13, %rbx, %r13|shlq\t%cl, %rbx}}")
+__naked void inline_extract(void)
+{
+	asm volatile (
+	"r6 = 0x12345678;"
+	"r1 = r6;"
+	"r2 = 8;"
+	"r3 = 8;"
+	"call %[bpf_extract64];"
+	"r7 = r0;"
+	"r0 = r7;"
+	"exit;"
+	:
+	: __imm(bpf_extract64)
+	: __clobber_all);
+}
+
+/* the bytes 01..08 on the stack, read as big endian */
+SEC("tc")
+__success __retval(0x05060708)
+__arch_x86_64
+__jited("{{.*}}{{movbeq\t\\(%rbx\\), %rax|bswapq\t%rax}}")
+__naked void inline_load_be64(void)
+{
+	asm volatile (
+	"*(u32 *)(r10 - 8) = 0x04030201;"
+	"*(u32 *)(r10 - 4) = 0x08070605;"
+	"r6 = r10;"
+	"r6 += -8;"
+	"r1 = r6;"
+	"r2 = 0;"
+	"call %[bpf_load_be64];"
+	"exit;"
+	:
+	: __imm(bpf_load_be64)
+	: __clobber_all);
+}
+
+SEC("tc")
+__success __retval(0)
+__arch_x86_64
+__jited("{{.*}}prefetcht0\t{{.*}}%r13)")
+__naked void inline_prefetch(void)
+{
+	asm volatile (
+	"*(u64 *)(r10 - 8) = 0;"
+	"r7 = r10;"
+	"r7 += -8;"
+	"r1 = r7;"
+	"call %[bpf_prefetch];"
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm(bpf_prefetch)
+	: __clobber_all);
+}
+
+/* the instructions of a prefetch load, so the address must be readable */
+SEC("tc")
+__failure __msg("R1 invalid mem access 'scalar'")
+__naked void inline_prefetch_scalar(void)
+{
+	asm volatile (
+	"r1 = 0;"
+	"call %[bpf_prefetch];"
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm(bpf_prefetch)
+	: __clobber_all);
+}
+
+/* copy 16 bytes from fp-16 to fp-32: the JIT copies the compiled kfunc */
+SEC("tc")
+__success __retval(0x22)
+__arch_x86_64
+__xlated("6: call")
+__jited("{{.*}}movq\t(%r13), %{{.*}}")
+__naked void inline_copy16(void)
+{
+	asm volatile (
+	"*(u64 *)(r10 - 16) = 0x11;"
+	"*(u64 *)(r10 - 8) = 0x22;"
+	"r6 = r10;"
+	"r6 += -32;"
+	"r7 = r10;"
+	"r7 += -16;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"call %[bpf_copy16];"
+	"r0 = *(u64 *)(r10 - 24);"
+	"exit;"
+	:
+	: __imm(bpf_copy16)
+	: __clobber_all);
+}
+
+/* the verifier checks the memory that the copy touches */
+SEC("tc")
+__failure __msg("off=0 size=8")
+__naked void inline_copy16_out_of_bounds(void)
+{
+	asm volatile (
+	"*(u64 *)(r10 - 8) = 0;"
+	"r1 = r10;"
+	"r1 += -16;"
+	"r2 = r10;"
+	"r2 += -8;"
+	"call %[bpf_copy16];"
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm(bpf_copy16)
+	: __clobber_all);
+}
+
+/* 100 + 3 * 4 + 16 */
+SEC("tc")
+__success __retval(128)
+__arch_x86_64
+__jited("{{.*}}leaq\t0x10(%rbx,%r13,4), %r14")
+__naked void inline_lea(void)
+{
+	asm volatile (
+	"r6 = 100;"
+	"r7 = 3;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = 4;"
+	"r4 = 16;"
+	"call %[bpf_lea64];"
+	"r8 = r0;"
+	"r0 = r8;"
+	"exit;"
+	:
+	: __imm(bpf_lea64)
+	: __clobber_all);
+}
+
+/* the instructions bound the result, a call would not */
+SEC("tc")
+__success __retval(0)
+__naked void inline_precision(void)
+{
+	asm volatile (
+	"call %[bpf_get_prandom_u32];"
+	"r1 = r0;"
+	"r2 = 0;"
+	"r3 = 3;"
+	"call %[bpf_extract64];"
+	"r6 = r10;"
+	"r6 += -8;"
+	"r6 += r0;"
+	"r0 = 0;"
+	"*(u8 *)(r6 + 0) = r0;"
+	"exit;"
+	:
+	: __imm(bpf_get_prandom_u32), __imm(bpf_extract64)
+	: __clobber_all);
+}
+
+/* arguments cannot be read after the instructions, as after a call */
+SEC("tc")
+__failure __msg("R1 !read_ok")
+__naked void inline_clobber(void)
+{
+	asm volatile (
+	"r1 = 1;"
+	"r2 = 42;"
+	"r3 = 7;"
+	"call %[bpf_select64];"
+	"r0 = r1;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+/* a kfunc that returns nothing leaves R0 unreadable after its body */
+SEC("tc")
+__failure __msg("R0 !read_ok")
+__naked void inline_void_r0(void)
+{
+	asm volatile (
+	"r1 = r10;"
+	"r1 += -8;"
+	"call %[bpf_prefetch];"
+	"exit;"
+	:
+	: __imm(bpf_prefetch)
+	: __clobber_all);
+}
+
+SEC("tc")
+__failure __msg("R2 must be a known constant")
+__naked void inline_not_constant(void)
+{
+	asm volatile (
+	"call %[bpf_get_prandom_u32];"
+	"r1 = 1;"
+	"r2 = r0;"
+	"call %[bpf_rol64];"
+	"exit;"
+	:
+	: __imm(bpf_get_prandom_u32), __imm(bpf_rol64)
+	: __clobber_all);
+}
+
+/* r1 = r6 is skipped by a jump, so it must stay */
+SEC("tc")
+__success __retval(42)
+__naked void inline_bind_jump(void)
+{
+	asm volatile (
+	"r9 = *(u32 *)(r1 + %[len]);"
+	"r6 = 0;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = 1;"
+	"if r9 != 0 goto l0_%=;"
+	"r1 = r6;"
+"l0_%=:"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"exit;"
+	:
+	: __imm(bpf_select64),
+	  __imm_const(len, offsetof(struct __sk_buff, len))
+	: __clobber_all);
+}
+
+#if __clang_major__ >= 18 || defined(__BPF_FEATURE_MOVSX)
+/* a sign-extending move is not a plain copy of R6 */
+SEC("tc")
+__success __retval(7)
+__naked void inline_bind_movsx(void)
+{
+	asm volatile (
+	"r6 = 0x100;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = (s8)r6;"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+#endif
+
+/* the result takes the register of the condition */
+SEC("tc")
+__success __retval(42)
+__naked void inline_bind_shared(void)
+{
+	asm volatile (
+	"r6 = 1;"
+	"r7 = 42;"
+	"r8 = 7;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"r3 = r8;"
+	"call %[bpf_select64];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_select64)
+	: __clobber_all);
+}
+
+/* native code from a module, with the result in the register of an argument */
+SEC("tc")
+__success __retval(6)
+__arch_x86_64
+__xlated("2: call")
+__jited("{{.*}}xorq\t%r13, %rbx")
+__naked void inline_module(void)
+{
+	asm volatile (
+	"r6 = 5;"
+	"r7 = 3;"
+	"r1 = r6;"
+	"r2 = r7;"
+	"call %[bpf_testmod_inline_xor];"
+	"r6 = r0;"
+	"r0 = r6;"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_xor)
+	: __clobber_all);
+}
+
+/* without emit, the JIT copies the compiled kfunc, with the registers bound */
+SEC("tc")
+__success __retval(5)
+__arch_x86_64
+__xlated("1: call")
+__jited("{{.*}}movq\t%rbx, %r13")
+__naked void inline_copy(void)
+{
+	asm volatile (
+	"r6 = 5;"
+	"r1 = r6;"
+	"call %[bpf_testmod_inline_mov];"
+	"r7 = r0;"
+	"r0 = r7;"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_mov)
+	: __clobber_all);
+}
+
+/* compiled code that branches or divides is not copied: the instructions stay */
+SEC("tc")
+__success __retval(0)
+__xlated("{{.*}}r0 /= r2")
+__naked void inline_copy_div(void)
+{
+	asm volatile (
+	"r1 = 9;"
+	"r2 = 0;"
+	"call %[bpf_testmod_inline_div];"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_div)
+	: __clobber_all);
+}
+
+/* a kfunc that the program may not call keeps its call, which is rejected */
+SEC("xdp")
+__failure __msg("calling kernel function bpf_testmod_inline_mov is not allowed")
+__naked void inline_not_allowed(void)
+{
+	asm volatile (
+	"r1 = 1;"
+	"call %[bpf_testmod_inline_mov];"
+	"exit;"
+	:
+	: __imm(bpf_testmod_inline_mov)
+	: __clobber_all);
+}
+
+#define ROL(x, n) ((x) << ((n) & 63) | (x) >> (-(n) & 63))
+
+struct diff_state {
+	u64 bad;
+	u8 src[64], dst[64];
+};
+
+static u64 rand64(void)
+{
+	return (u64)bpf_get_prandom_u32() << 32 | bpf_get_prandom_u32();
+}
+
+/* a global function, so that the verifier checks it once and not per call */
+__noinline int diff_step(struct diff_state *s)
+{
+	u64 x = rand64(), y = rand64(), a = rand64(), b = rand64();
+	int i;
+
+	if (!s)
+		return 0;
+	s->bad |= (bpf_rol64(x, 1) ^ ROL(x, 1)) | (bpf_rol64(x, 13) ^ ROL(x, 13)) |
+		  (bpf_rol64(x, 63) ^ ROL(x, 63)) | (bpf_rol64(x, 64) ^ x);
+	s->bad |= bpf_select64(x & 1, a, b) ^ (x & 1 ? a : b);
+	s->bad |= bpf_extract64(x, 0, 64) ^ x;
+	s->bad |= bpf_extract64(x, 13, 7) ^ (x >> 13 & 0x7f);
+	s->bad |= bpf_extract64(x, 40, 24) ^ (x >> 40);
+	s->bad |= bpf_extract64(x, 63, 1) ^ (x >> 63);
+	s->bad |= bpf_lea64(x, y, 8, -12345) ^ (x + y * 8 - 12345);
+	for (i = 0; i < 8; i++) {
+		s->src[i] = x >> (8 * i);
+		s->src[8 + i] = y >> (8 * i);
+	}
+	s->bad |= bpf_load_be64(s->src, 0) ^ __builtin_bswap64(x);
+	s->bad |= bpf_load_be64(s->src + 16, -8) ^ __builtin_bswap64(y);
+	/* unaligned */
+	s->bad |= bpf_load_be64(s->src + 8, -7) ^ __builtin_bswap64(x >> 8 | y << 56);
+	bpf_copy16(s->dst + 8, s->src);
+	for (i = 0; i < 16; i++)
+		s->bad |= s->dst[8 + i] ^ s->src[i];
+	return 0;
+}
+
+/* native code and the instructions agree on random inputs */
+SEC("tc")
+__success __retval(0)
+int inline_differential(struct __sk_buff *skb)
+{
+	struct diff_state s = {};
+	int i;
+
+	for (i = 0; i < 256; i++)
+		diff_step(&s);
+	return s.bad != 0;
+}
+
+/* emits BTF for the kfuncs that only inline assembly calls */
+void __kfunc_btf_root(void)
+{
+	bpf_prefetch(0);
+	bpf_testmod_inline_mov(0);
+	bpf_testmod_inline_xor(0, 0);
+	bpf_testmod_inline_div(0, 0);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/test_kmods/Makefile b/tools/testing/selftests/bpf/test_kmods/Makefile
index 031c7454ce65f..1800a0cd7a771 100644
--- a/tools/testing/selftests/bpf/test_kmods/Makefile
+++ b/tools/testing/selftests/bpf/test_kmods/Makefile
@@ -19,7 +19,7 @@ Q = @
 endif
 
 MODULES = bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \
-	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko
+	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_kfunc_body.ko
 
 $(foreach m,$(MODULES),$(eval obj-m += $(m:.ko=.o)))
 
diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c b/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c
new file mode 100644
index 0000000000000..2149bbd683381
--- /dev/null
+++ b/tools/testing/selftests/bpf/test_kmods/bpf_test_kfunc_body.c
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/bpf.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
+#include <linux/filter.h>
+#include <linux/init.h>
+#include <linux/module.h>
+
+struct bpf_test_kfunc_body_pair {
+	u64 a, b;
+};
+
+__bpf_kfunc_start_defs();
+
+__bpf_kfunc u64 bpf_test_kfunc_body(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc u64 bpf_test_kfunc_body_unset(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc u64 bpf_test_kfunc_body_pair(struct bpf_test_kfunc_body_pair p)
+{
+	return p.a;
+}
+
+__bpf_kfunc u64 bpf_test_kfunc_body_sleepable(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc_end_defs();
+
+BTF_KFUNCS_START(test_body_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_test_kfunc_body)
+BTF_KFUNCS_END(test_body_kfunc_ids)
+
+/* never registered */
+BTF_KFUNCS_START(test_body_bad_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_test_kfunc_body_pair)
+BTF_ID_FLAGS(func, bpf_test_kfunc_body_sleepable, KF_SLEEPABLE)
+BTF_KFUNCS_END(test_body_bad_kfunc_ids)
+
+BTF_ID_LIST(test_body_ids)
+BTF_ID(func, bpf_test_kfunc_body)
+BTF_ID(func, bpf_test_kfunc_body_unset)
+BTF_ID(func, bpf_test_kfunc_body_pair)
+BTF_ID(func, bpf_test_kfunc_body_sleepable)
+
+static const struct bpf_insn test_body_insns[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+};
+
+/* writes R6 */
+static const struct bpf_insn test_body_bad_insns[] = {
+	BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+};
+
+/* jumps past the last instruction */
+static const struct bpf_insn test_body_jump_insns[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0, 1),
+	BPF_MOV64_IMM(BPF_REG_0, 0),
+};
+
+static struct bpf_kfunc_body test_body = { .id = &test_body_ids[0] };
+
+static struct btf_kfunc_id_set test_body_set = {
+	.owner = THIS_MODULE,
+	.set = &test_body_kfunc_ids,
+	.bodies = &test_body,
+	.body_cnt = 1,
+};
+
+static int test_body_rejected(struct btf_id_set8 *set, const u32 *id,
+			      const struct bpf_insn *insns, u32 len)
+{
+	test_body_set.set = set;
+	test_body.id = id;
+	test_body.insns = insns;
+	test_body.len = len;
+	return register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &test_body_set) == -EINVAL;
+}
+
+/*
+ * The module loads only if registration rejects a body without instructions,
+ * one with an instruction that writes R6, one with a jump past its last
+ * instruction, one for a kfunc outside the set, one with an argument of two
+ * registers and one for a kfunc with flags.
+ */
+static int bpf_test_kfunc_body_init(void)
+{
+	struct btf_id_set8 *good = &test_body_kfunc_ids, *bad = &test_body_bad_kfunc_ids;
+
+	if (!test_body_rejected(good, &test_body_ids[0], NULL, 0) ||
+	    !test_body_rejected(good, &test_body_ids[0], test_body_bad_insns,
+				ARRAY_SIZE(test_body_bad_insns)) ||
+	    !test_body_rejected(good, &test_body_ids[0], test_body_jump_insns,
+				ARRAY_SIZE(test_body_jump_insns)) ||
+	    !test_body_rejected(good, &test_body_ids[1], test_body_insns, 1) ||
+	    !test_body_rejected(bad, &test_body_ids[2], test_body_insns, 1) ||
+	    !test_body_rejected(bad, &test_body_ids[3], test_body_insns, 1))
+		return -EINVAL;
+	test_body_set.set = good;
+	test_body.id = &test_body_ids[0];
+	return register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &test_body_set);
+}
+
+static void bpf_test_kfunc_body_exit(void)
+{
+}
+
+module_init(bpf_test_kfunc_body_init);
+module_exit(bpf_test_kfunc_body_exit);
+
+MODULE_DESCRIPTION("BPF kfunc body registration test module");
+MODULE_LICENSE("GPL");
diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c
index 93847ca6293b4..13d5abe249d25 100644
--- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c
+++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c
@@ -931,6 +931,78 @@ BTF_ID_LIST(bpf_testmod_dtor_ids)
 BTF_ID(struct, bpf_testmod_ctx)
 BTF_ID(func, bpf_testmod_ctx_release_dtor)
 
+/*
+ * Kfuncs with a body, in a set that XDP programs may not use: the JIT copies
+ * the first, the second has native code from this module, and the third,
+ * which divides, keeps its body.
+ */
+__bpf_kfunc u64 bpf_testmod_inline_mov(u64 x)
+{
+	return x;
+}
+
+__bpf_kfunc u64 bpf_testmod_inline_xor(u64 a, u64 b)
+{
+	return a ^ b;
+}
+
+__bpf_kfunc u64 bpf_testmod_inline_div(u64 a, u64 b)
+{
+	return b ? a / b : 0;
+}
+
+BTF_ID_LIST(bpf_testmod_body_ids)
+BTF_ID(func, bpf_testmod_inline_mov)
+BTF_ID(func, bpf_testmod_inline_xor)
+BTF_ID(func, bpf_testmod_inline_div)
+
+static const struct bpf_insn mov_body[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+};
+
+static const struct bpf_insn xor_body[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_2),
+};
+
+static const struct bpf_insn div_body[] = {
+	BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
+	BPF_ALU64_REG(BPF_DIV, BPF_REG_0, BPF_REG_2),
+};
+
+#ifdef CONFIG_X86_64
+/* op %src, %dst on 64-bit registers */
+static u8 *x86_op(u8 *p, u8 op, u8 src, u8 dst)
+{
+	*p++ = 0x48 | (src & 8 ? 4 : 0) | (dst & 8 ? 1 : 0);
+	*p++ = op;
+	*p++ = 0xc0 | (src & 7) << 3 | (dst & 7);
+	return p;
+}
+
+/* the result can take the register of an argument, which a copy cannot */
+static int xor_emit(const u8 *reg, const s32 *imm, u8 *buf)
+{
+	u8 dst = reg[0], a = reg[1], b = reg[2], *p = buf;
+
+	if (dst == b)
+		swap(a, b);
+	if (dst != a)
+		p = x86_op(p, 0x89, a, dst);	/* mov %a, %dst */
+	return x86_op(p, 0x31, b, dst) - buf;	/* xor %b, %dst */
+}
+#else
+#define xor_emit	NULL
+#endif
+
+#define BODY(i, op, emit)	{ &bpf_testmod_body_ids[i], op##_body, ARRAY_SIZE(op##_body), emit }
+
+static const struct bpf_kfunc_body bpf_testmod_bodies[] = {
+	BODY(0, mov, NULL),
+	BODY(1, xor, xor_emit),
+	BODY(2, div, NULL),
+};
+
 static const struct btf_kfunc_id_set bpf_testmod_common_kfunc_set = {
 	.owner = THIS_MODULE,
 	.set   = &bpf_testmod_common_kfunc_ids,
@@ -1827,6 +1899,9 @@ BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, bpf_kfunc_implicit_arg_legacy_impl)
 BTF_ID_FLAGS(func, bpf_kfunc_trigger_ctx_check)
+BTF_ID_FLAGS(func, bpf_testmod_inline_mov)
+BTF_ID_FLAGS(func, bpf_testmod_inline_xor)
+BTF_ID_FLAGS(func, bpf_testmod_inline_div)
 BTF_KFUNCS_END(bpf_testmod_check_kfunc_ids)
 
 static int bpf_testmod_ops_init(struct btf *btf)
@@ -1861,6 +1936,8 @@ static int bpf_testmod_ops_init_member(const struct btf_type *t,
 static const struct btf_kfunc_id_set bpf_testmod_kfunc_set = {
 	.owner = THIS_MODULE,
 	.set   = &bpf_testmod_check_kfunc_ids,
+	.bodies = bpf_testmod_bodies,
+	.body_cnt = ARRAY_SIZE(bpf_testmod_bodies),
 };
 
 static const struct bpf_verifier_ops bpf_testmod_verifier_ops = {
diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h b/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h
index 67c02a421d133..2a55f1b145b42 100644
--- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h
+++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h
@@ -357,4 +357,8 @@ void bpf_testmod_test_hardirq_fn(void);
 void bpf_testmod_test_softirq_fn(void);
 void bpf_kfunc_trigger_ctx_check(void) __ksym;
 
+u64 bpf_testmod_inline_mov(u64 x) __ksym;
+u64 bpf_testmod_inline_xor(u64 a, u64 b) __ksym;
+u64 bpf_testmod_inline_div(u64 a, u64 b) __ksym;
+
 #endif /* _BPF_TESTMOD_KFUNC_H */

11/3 2026/10/05 14:29 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36010
							output: 23
							thoughts: 3882
						

Thoughts:
**KMSAN Fuzzing Analysis for BPF Inline Kfuncs**

Okay, I need to determine if this patch series, introducing inline kfuncs for BPF, warrants a dedicated KMSAN fuzzing session. The rule is clear: KMSAN is only for uninitialized memory risks *not* caught by KASAN, LOCKDEP, or standard detectors. So, I need to focus on where the patch modifies data flows, memory allocation, and interaction with user space.

First, I see the core concept is adding kfuncs with either BPF instruction bodies or native x86 instruction generation or copying. I am looking for situations where uninitialized data could be read or leaked. I'm especially concerned about kernel structures passed to user space, conditional logic based on potentially uninitialized variables, and data structure initialization.

The patch updates several files, including the verifier, BTF, and JIT compiler. I see new structures like `bpf_kfunc_inline` within `bpf_verifier_env`, along with `kfunc_inline_cnt`. The `kvzalloc_objs` function is used for allocations. Zeroing is good, but I need to examine the data flow more precisely.

I scrutinize `bpf_mark_kfunc_body_regs()` and immediately notice a potential out-of-bounds read if `r` walks past the allocated array `env->kfunc_inlines`.  However, this should be caught by KASAN.

Then I move to `bpf_restore_kfunc_calls()`. This is where inline code bodies are generated into `code` and copied to `r->image`. Critically, `bpf_jit_inline_kfunc()` is responsible for filling the buffer `code`. I need to ensure this buffer is *fully* initialized before being copied.

I drill into `bpf_jit_inline_kfunc()` and discover `kfunc_copy()`. This function copies compiled kfunc code. `kfunc_copy` calculates a length `len` and then uses `kmemdup(code, len, ...)` to copy the data. The important question is whether *all* bytes up to `len` in the `code` array are written to.

Further inspection of `kfunc_copy()` reveals that `kfunc_copy_insn()` advances a pointer `p`, writing to memory. The returned value `p - buf` is used to determine the `len` passed to `kmemdup`. The bytes `0..p` are definitely initialized and copied. However, I need to verify that `bpf_jit_inline_kfunc` does *not* expose uninitialized bytes.

Next, I need to consider what happens if user space queries BPF program information. Does user space receive the BPF instructions (`xlated`) or the JITed code? I need to analyze `BPF_PROG_GET_INFO_BY_FD` to see if the user-accessible code can contain uninitialized data.

Looking at `bpf_restore_kfunc_calls()`, I observe that parts of the original instruction stream are overwritten with `BPF_JMP_A(0)` and the call instruction `r->call`. This *should* be safe.

However, I need to check the entire data path, especially when `xlated` insns are copied to user space to ensure no BPF code is returned with parts uninitialized. The `bpf_opt_remove_nops` function potentially removes nops that are set in the body. I will look for references to this function.

Based on this analysis, I need to check if there is some way to leak the `code` buffer if it is not totally populated. It's likely that I need to dive deeper into the `bpf_jit_inline_kfunc` function to determine if there is an information leak. For now, I'm leaning toward *not* needing KMSAN, but I want to be 100% sure.



12/3 2026/10/05 14:29 tool grepper
0m Args:
{
  "Expression": "bpf_opt_remove_nops"
}

Results:
{
  "Output": "include/linux/bpf_verifier.h=1870=int bpf_opt_remove_dead_code(struct bpf_verifier_env *env);\ninclude/linux/bpf_verifier.h:1871:int bpf_opt_remove_nops(struct bpf_verifier_env *env);\ninclude/linux/bpf_verifier.h-1872-int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union bpf_attr *attr);\n--\nkernel/bpf/fixups.c=699=int bpf_opt_remove_dead_code(struct bpf_verifier_env *env)\n--\nkernel/bpf/fixups.c-724-\nkernel/bpf/fixups.c:725:int bpf_opt_remove_nops(struct bpf_verifier_env *env)\nkernel/bpf/fixups.c-726-{\n--\nkernel/bpf/kfunc_inline.c=165=static int kfunc_bind(struct bpf_verifier_env *env, struct bpf_kfunc_inline *r, u32 *drop)\n--\nkernel/bpf/kfunc_inline.c-220- * the body and the moves that binding makes unnecessary become nops, which\nkernel/bpf/kfunc_inline.c:221: * bpf_opt_remove_nops() removes. Other calls keep their body.\nkernel/bpf/kfunc_inline.c-222- */\n--\nkernel/bpf/verifier.c=22560=int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n--\nkernel/bpf/verifier.c-22812-\t\tif (ret == 0)\nkernel/bpf/verifier.c:22813:\t\t\tret = bpf_opt_remove_nops(env);\nkernel/bpf/verifier.c-22814-\t} else {\n"
}

13/3 2026/10/05 14:30 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41283
							output: 38
							thoughts: 61
						

Thoughts:
Okay, let's dive into this.

**Examining BPF Verifier Interaction**

Alright, I need to jog my memory on how `bpf_restore_kfunc_calls` handles things, and how it relates to this specific section in the kernel BPF verifier. My target is line 22813 within `kernel/bpf/verifier.c`. I should probably back up a bit, let's start reading around line 22780 in `kernel/bpf/verifier.c` to get the necessary context.



14/3 2026/10/05 14:30 tool read-file
0m Args:
{
  "File": "kernel/bpf/verifier.c",
  "FirstLine": 22765,
  "LineCount": 60
}

Results:
{
  "Contents": "22765:\t\t/* must precede the first bpf_ret_reg_pair() user below */\n22766:\t\tret = bpf_compute_subprog_ret_regs(env);\n22767:\t\tif (ret \u003c 0)\n22768:\t\t\tgoto skip_full_check;\n22769:\t\n22770:\t\tret = bpf_compute_live_registers(env);\n22771:\t\tif (ret \u003c 0)\n22772:\t\t\tgoto skip_full_check;\n22773:\t\n22774:\t\tret = mark_fastcall_patterns(env);\n22775:\t\tif (ret \u003c 0)\n22776:\t\t\tgoto skip_full_check;\n22777:\t\n22778:\t\tret = do_check_main(env);\n22779:\t\tret = ret ?: do_check_subprogs(env);\n22780:\t\n22781:\t\t/* reject recursion through the callx edges found by the main pass */\n22782:\t\tif (ret == 0 \u0026\u0026 env-\u003ecallx_edges)\n22783:\t\t\tret = sort_subprogs_topo(env);\n22784:\t\n22785:\t\tif (ret == 0 \u0026\u0026 bpf_prog_is_offloaded(env-\u003eprog-\u003eaux))\n22786:\t\t\tret = bpf_prog_offload_finalize(env);\n22787:\t\n22788:\tskip_full_check:\n22789:\t\tkvfree(env-\u003eexplored_states);\n22790:\t\n22791:\t\tif (ret == 0)\n22792:\t\t\tbpf_restore_kfunc_calls(env);\n22793:\t\n22794:\t\t/* might decrease stack depth, keep it before passes that\n22795:\t\t * allocate additional slots.\n22796:\t\t */\n22797:\t\tif (ret == 0)\n22798:\t\t\tret = bpf_remove_fastcall_spills_fills(env);\n22799:\t\n22800:\t\tif (ret == 0)\n22801:\t\t\tret = check_max_stack_depth(env);\n22802:\t\n22803:\t\t/* instruction rewrites happen after this point */\n22804:\t\tif (ret == 0)\n22805:\t\t\tret = bpf_optimize_bpf_loop(env);\n22806:\t\n22807:\t\tif (is_priv) {\n22808:\t\t\tif (ret == 0)\n22809:\t\t\t\tbpf_opt_hard_wire_dead_code_branches(env);\n22810:\t\t\tif (ret == 0)\n22811:\t\t\t\tret = bpf_opt_remove_dead_code(env);\n22812:\t\t\tif (ret == 0)\n22813:\t\t\t\tret = bpf_opt_remove_nops(env);\n22814:\t\t} else {\n22815:\t\t\tif (ret == 0)\n22816:\t\t\t\tsanitize_dead_code(env);\n22817:\t\t}\n22818:\t\n22819:\t\tif (ret == 0)\n22820:\t\t\t/* program is valid, convert *(u32*)(ctx + off) accesses */\n22821:\t\t\tret = bpf_convert_ctx_accesses(env);\n22822:\t\n22823:\t\tif (ret == 0)\n22824:\t\t\tret = bpf_do_misc_fixups(env);\n"
}

15/3 2026/10/05 14:30 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42472
							output: 23
							thoughts: 907
						

Thoughts:
**Analyzing BPF Kfunc Inlining and Instruction Handling**

Okay, let's break this down. My initial thought is to examine what happens when the `!is_priv` condition is met. Specifically, the call to `sanitize_dead_code(env)` versus `bpf_opt_remove_nops(env)`. Then, I need to focus on `bpf_restore_kfunc_calls`. I'm seeing that `BPF_JMP_A(0)`, which is essentially a jump to the next instruction, is used. The key difference I know is that in unprivileged BPF, dead code is replaced with `ja -1` (or something similar), but `BPF_JMP_A(0)` is perfectly valid. That's a good starting point.

Now, let's shift gears and double-check `kfunc_native_ok()` and related instruction indexes. I'm focusing on the instruction patching within `kfunc_restore_calls` or `bpf_restore_kfunc_calls`, but now in the context of the inlining, specifically within `bpf_inline_kfunc_bodies`. It looks like the core of the problem lies here: `bpf_patch_insn_data(env, i, r->body->insns, r->body->len)`. This function is replacing a single instruction at index `i` with a sequence of `r->body->len` instructions.

Okay, this is where it's critical. What happens to the `insn_aux_data` when `bpf_patch_insn_data` is called? Does it get resized or moved, potentially leading to inconsistencies? This feels like the critical area. I need to trace how `insn_aux_data` is handled through this process and, specifically, how `bpf_patch_insn_data` affects it. I'm going to search for instances of `bpf_patch_insn_data`.



16/3 2026/10/05 14:31 tool grepper
0m Args:
{
  "Expression": "bpf_patch_insn_data"
}

Results:
{
  "Output": "include/linux/filter.h=1307=struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,\n--\ninclude/linux/filter.h-1310-#ifdef CONFIG_BPF_SYSCALL\ninclude/linux/filter.h:1311:struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,\ninclude/linux/filter.h-1312-\t\t\t\t     const struct bpf_insn *patch, u32 len);\ninclude/linux/filter.h-1313-#else\ninclude/linux/filter.h:1314:static inline struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,\ninclude/linux/filter.h-1315-\t\t\t\t\t\t   const struct bpf_insn *patch, u32 len)\n--\nkernel/bpf/core.c=1571=struct bpf_prog *bpf_jit_blind_constants(struct bpf_verifier_env *env, struct bpf_prog *prog)\n--\nkernel/bpf/core.c-1585-\nkernel/bpf/core.c:1586:\t/* make sure bpf_patch_insn_data() patches the correct prog */\nkernel/bpf/core.c-1587-\tif (env)\n--\nkernel/bpf/core.c-1619-\t\telse if (env)\nkernel/bpf/core.c:1620:\t\t\ttmp = bpf_patch_insn_data(env, i, insn_buff, rewritten);\nkernel/bpf/core.c-1621-\t\telse\n--\nkernel/bpf/fixups.c=328=static bool bpf_rewrite_must_abort(void)\n--\nkernel/bpf/fixups.c-335-\nkernel/bpf/fixups.c:336:static struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,\nkernel/bpf/fixups.c-337-\t\t\t\t\t      const struct bpf_insn *patch, u32 len,\n--\nkernel/bpf/fixups.c-376-\nkernel/bpf/fixups.c:377:struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,\nkernel/bpf/fixups.c-378-\t\t\t\t     const struct bpf_insn *patch, u32 len)\nkernel/bpf/fixups.c-379-{\nkernel/bpf/fixups.c:380:\treturn __bpf_patch_insn_data(env, off, patch, len, BPF_PATCH_KEEP_TARGET);\nkernel/bpf/fixups.c-381-}\n--\nkernel/bpf/fixups.c=753=int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,\n--\nkernel/bpf/fixups.c-837-apply_patch_buffer:\nkernel/bpf/fixups.c:838:\t\tnew_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);\nkernel/bpf/fixups.c-839-\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c=855=int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)\n--\nkernel/bpf/fixups.c-882-\t\t\tinsn_buf[cnt++] = env-\u003eprog-\u003einsnsi[0];\nkernel/bpf/fixups.c:883:\t\t\tnew_prog = __bpf_patch_insn_data(env, 0, insn_buf, cnt,\nkernel/bpf/fixups.c-884-\t\t\t\t\t\t\t BPF_PATCH_MOVE_TARGET);\n--\nkernel/bpf/fixups.c-906-\t\t} else if (cnt) {\nkernel/bpf/fixups.c:907:\t\t\tnew_prog = __bpf_patch_insn_data(env, 0, insn_buf, cnt,\nkernel/bpf/fixups.c-908-\t\t\t\t\t\t\t BPF_PATCH_MOVE_TARGET);\n--\nkernel/bpf/fixups.c-946-\t\t\tcnt = patch - insn_buf;\nkernel/bpf/fixups.c:947:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-948-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-1019-\t\t\tcnt = patch - insn_buf;\nkernel/bpf/fixups.c:1020:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1021-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-1153-patch_insn_buf:\nkernel/bpf/fixups.c:1154:\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1155-\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c=1660=static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)\n--\nkernel/bpf/fixups.c-1672-\t * ones for the hidden subprog. Hence all of the adjustment operations\nkernel/bpf/fixups.c:1673:\t * in bpf_patch_insn_data are no-ops.\nkernel/bpf/fixups.c-1674-\t */\nkernel/bpf/fixups.c:1675:\tprog = bpf_patch_insn_data(env, env-\u003eprog-\u003elen - 1, patch, len);\nkernel/bpf/fixups.c-1676-\tif (!prog)\n--\nkernel/bpf/fixups.c=1715=int bpf_do_misc_fixups(struct bpf_verifier_env *env)\n--\nkernel/bpf/fixups.c-1766-\nkernel/bpf/fixups.c:1767:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1768-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-1796-\nkernel/bpf/fixups.c:1797:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1798-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-1887-\nkernel/bpf/fixups.c:1888:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1889-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-1917-\t\t\tcnt = patch - insn_buf;\nkernel/bpf/fixups.c:1918:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1919-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-1937-\nkernel/bpf/fixups.c:1938:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1939-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-1990-\nkernel/bpf/fixups.c:1991:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-1992-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2033-\nkernel/bpf/fixups.c:2034:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2035-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2052-\nkernel/bpf/fixups.c:2053:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2054-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2079-\t\t\t * with that same half + mov64_percpu_reg insn.\nkernel/bpf/fixups.c:2080:\t\t\t * All because bpf_patch_insn_data() can only\nkernel/bpf/fixups.c-2081-\t\t\t * replace one 8-byte insn, which does not work\n--\nkernel/bpf/fixups.c-2089-\t\t\ti++;\nkernel/bpf/fixups.c:2090:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2091-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2110-\nkernel/bpf/fixups.c:2111:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2112-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2197-\t\t\tcnt = 3;\nkernel/bpf/fixups.c:2198:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2199-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2231-\nkernel/bpf/fixups.c:2232:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2233-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2250-\nkernel/bpf/fixups.c:2251:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2252-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2293-\nkernel/bpf/fixups.c:2294:\t\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta,\nkernel/bpf/fixups.c-2295-\t\t\t\t\t\t\t       insn_buf, cnt);\n--\nkernel/bpf/fixups.c-2376-\nkernel/bpf/fixups.c:2377:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf,\nkernel/bpf/fixups.c-2378-\t\t\t\t\t\t       cnt);\n--\nkernel/bpf/fixups.c-2406-#endif\nkernel/bpf/fixups.c:2407:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2408-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2425-\nkernel/bpf/fixups.c:2426:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2427-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2459-\nkernel/bpf/fixups.c:2460:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2461-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2491-\nkernel/bpf/fixups.c:2492:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2493-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2517-\nkernel/bpf/fixups.c:2518:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2519-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2533-\nkernel/bpf/fixups.c:2534:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);\nkernel/bpf/fixups.c-2535-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2588-\nkernel/bpf/fixups.c:2589:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2590-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2606-\nkernel/bpf/fixups.c:2607:\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\nkernel/bpf/fixups.c-2608-\t\t\tif (!new_prog)\n--\nkernel/bpf/fixups.c-2681-\nkernel/bpf/fixups.c:2682:\t\tnew_prog = __bpf_patch_insn_data(env, subprog_start, insn_buf, cnt,\nkernel/bpf/fixups.c-2683-\t\t\t\t\t\t BPF_PATCH_MOVE_TARGET);\n--\nkernel/bpf/fixups.c-2690-\t\t * to insn after BPF_ST that inits may_goto count.\nkernel/bpf/fixups.c:2691:\t\t * Adjustment will succeed because bpf_patch_insn_data() didn't fail.\nkernel/bpf/fixups.c-2692-\t\t */\n--\nkernel/bpf/fixups.c=2716=static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,\n--\nkernel/bpf/fixups.c-2777-\t*total_cnt = cnt;\nkernel/bpf/fixups.c:2778:\tnew_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);\nkernel/bpf/fixups.c-2779-\tif (!new_prog)\n--\nkernel/bpf/kfunc_inline.c=28=int bpf_inline_kfunc_bodies(struct bpf_verifier_env *env)\n--\nkernel/bpf/kfunc_inline.c-54-\t\tr-\u003eret = desc-\u003efunc_model.ret_size;\nkernel/bpf/kfunc_inline.c:55:\t\tprog = bpf_patch_insn_data(env, i, r-\u003ebody-\u003einsns, r-\u003ebody-\u003elen);\nkernel/bpf/kfunc_inline.c-56-\t\tif (!prog)\n"
}

17/3 2026/10/05 14:31 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 47980
							output: 37
							thoughts: 30
						

Thoughts:
Okay, here's my take on summarizing those thoughts, presented as a first-person monologue aimed at a fellow expert:

**Diving into `__bpf_patch_insn_data`**

Alright, let's get down to brass tacks. I need to understand this `__bpf_patch_insn_data` function, so I'm headed straight to `kernel/bpf/fixups.c`. That's where the magic probably happens. My focus is going to be dissecting what this utility's purpose is and how it functions. Understanding the BPF internals is crucial when you want to write performant code. I wonder if it's related to some kind of relocation, data modification, or maybe just some kind of optimization. This fixup likely touches instruction metadata or the data they operate on, so I'll see where its used and what arguments it accepts. I expect some interesting low-level details in there. Let's see what gems are hidden in this function.



18/3 2026/10/05 14:31 tool read-file
0m Args:
{
  "File": "kernel/bpf/fixups.c",
  "FirstLine": 336,
  "LineCount": 45
}

Results:
{
  "Contents": " 336:\tstatic struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,\n 337:\t\t\t\t\t\t      const struct bpf_insn *patch, u32 len,\n 338:\t\t\t\t\t\t      enum bpf_patch_mode mode)\n 339:\t{\n 340:\t\tstruct bpf_prog *new_prog;\n 341:\t\tstruct bpf_insn_aux_data *new_data = NULL;\n 342:\t\t/* The first slot whose targets move. */\n 343:\t\tu32 first = mode == BPF_PATCH_MOVE_TARGET ? off : off + 1;\n 344:\t\tstruct bpf_insn original_insn;\n 345:\t\n 346:\t\tif (bpf_rewrite_must_abort())\n 347:\t\t\treturn NULL;\n 348:\t\n 349:\t\tif (len \u003e 1) {\n 350:\t\t\tnew_data = vrealloc(env-\u003einsn_aux_data,\n 351:\t\t\t\t\t    array_size(env-\u003eprog-\u003elen + len - 1,\n 352:\t\t\t\t\t\t       sizeof(struct bpf_insn_aux_data)),\n 353:\t\t\t\t\t    GFP_KERNEL_ACCOUNT | __GFP_ZERO);\n 354:\t\t\tif (!new_data)\n 355:\t\t\t\treturn NULL;\n 356:\t\n 357:\t\t\tenv-\u003einsn_aux_data = new_data;\n 358:\t\t}\n 359:\t\n 360:\t\tmemcpy(\u0026original_insn, env-\u003eprog-\u003einsnsi + off, sizeof(struct bpf_insn));\n 361:\t\tnew_prog = bpf_patch_insn_single(env-\u003eprog, off, patch, len);\n 362:\t\tif (IS_ERR(new_prog)) {\n 363:\t\t\tif (PTR_ERR(new_prog) == -ERANGE)\n 364:\t\t\t\tverbose(env,\n 365:\t\t\t\t\t\"insn %d cannot be patched due to 16-bit range\\n\",\n 366:\t\t\t\t\tenv-\u003einsn_aux_data[off].orig_idx);\n 367:\t\t\treturn NULL;\n 368:\t\t}\n 369:\t\tadjust_insn_aux_data(env, new_prog, off, len, \u0026original_insn, mode);\n 370:\t\tadjust_subprog_starts(env, off, len);\n 371:\t\tadjust_insn_arrays(env, first, len);\n 372:\t\tbpf_adjust_func_ptrs(env, off, len);\n 373:\t\tadjust_poke_descs(new_prog, first, len);\n 374:\t\treturn new_prog;\n 375:\t}\n 376:\t\n 377:\tstruct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,\n 378:\t\t\t\t\t     const struct bpf_insn *patch, u32 len)\n 379:\t{\n 380:\t\treturn __bpf_patch_insn_data(env, off, patch, len, BPF_PATCH_KEEP_TARGET);\n"
}

19/3 2026/10/05 14:31 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49107
							output: 29
							thoughts: 2506
						

Thoughts:
**Analyzing BPF Verifier and Kfunc Inlining**

Okay, let's break this down systematically. I'm focusing on the `kfunc` mechanisms within the BPF verifier and how they interact, particularly concerning potential out-of-bounds access.

My initial observation is about `vrealloc` and zeroed `insn_aux_data`. This sets the stage for the analysis of subsequent structures and data.

Now, my attention is drawn to `kfunc_bind`. The logic there seems to be handling argument passing to inlined kfunctions, which can be optimized (dropped) by moving args into registers before the call. The loop back-walking and the use of the `drop` array are the core points of interest here.

I immediately spot a potential vulnerability: the check `end + 1 < env->prog->len` occurring *after* `mov = &insns[end]`. If `end` equals `env->prog->len`, `mov` becomes a pointer to one byte past the end of the `insns` array! This is an out-of-bounds access. It appears that KASAN should be able to catch this.

Next, I look at `drop`. Specifically, I want to verify that `n`, the number of elements in `drop` doesn't exceed the bounds of `MAX_BPF_FUNC_REG_ARGS + 1`. Since the program can have at most 5 args (R1-R5) plus a possible return, which limits the number of `drop` entries to 6, this should be fine.

Moving on to `kfunc_copy`, I examine the copy of the kfunc body into a local `code` buffer. Specifically, the size of the copy from kernel space into `code` is determined by the size of the kfunc body, and the size of the code buffer is determined by `sizeof(code)`. I notice `size = min(size, sizeof(code))` is used. So, `size` may be smaller than `sizeof(code)`. The potential problem here is that `kfunc_copy` copies `size` bytes, and subsequent instructions will process this data. However, the rest of `code` is never initialized. `insn_decode` can initialize `insn`, which is fine. The code uses `memcpy` to copy from this buffer to other locations. `memcpy` copies from the *initialized* part.

Finally, `bpf_copy16`. This reveals an important interaction between the verifier and kfunc arguments. Specifically, I'm checking if the verifier examines arguments for inlined kfuncs. In `bpf_add_kfunc_call`, `body` is checked for validity based on the `kfunc.flags` and whether the inline kfunc is allowed. The key is to look at the condition `kfunc.flags`. Based on the code, `kfunc.flags` is initialized in `btf_add_kfunc_bodies`. The crucial part of the logic is `pair[1]`, which stands for `kfunc.flags`. The code checks if it is a valid inline kfunc. It is `0`! So, in the previous code, the body of the `copy16_body` inline kfunc is used to check the arguments.



20/3 2026/10/05 14:32 tool grepper
0m Args:
{
  "Expression": "kfunc\\.flags",
  "PathPrefix": "kernel/bpf/"
}

Results:
{
  "Output": "kernel/bpf/verifier.c=2873=int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n--\nkernel/bpf/verifier.c-2966-\tif (func_model.ret_size \u003e 8) {\nkernel/bpf/verifier.c:2967:\t\tif (kfunc.flags \u0026\u0026 (*kfunc.flags \u0026 KF_FASTCALL)) {\nkernel/bpf/verifier.c-2968-\t\t\tverbose(env, \"kfunc %s with \u003e8-byte return is not supported with KF_FASTCALL\\n\",\n--\nkernel/bpf/verifier.c-2983-\tmeta.func_name = kfunc.name;\nkernel/bpf/verifier.c:2984:\tmeta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0;\nkernel/bpf/verifier.c-2985-\n--\nkernel/bpf/verifier.c-2994-\t/* the body of a kfunc that the program may call checks its arguments */\nkernel/bpf/verifier.c:2995:\tbody = kfunc.flags \u0026\u0026 btf_kfunc_is_allowed(kfunc.btf, func_id, env-\u003eprog) ?\nkernel/bpf/verifier.c-2996-\t       btf_find_kfunc_body(kfunc.btf, func_id) : NULL;\n--\nkernel/bpf/verifier.c=14048=static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 offset)\n--\nkernel/bpf/verifier.c-14053-\terr = fetch_kfunc_meta(env, func_id, offset, \u0026kfunc);\nkernel/bpf/verifier.c:14054:\tif (err || !kfunc.flags)\nkernel/bpf/verifier.c-14055-\t\treturn false;\nkernel/bpf/verifier.c-14056-\nkernel/bpf/verifier.c:14057:\treturn *kfunc.flags \u0026 KF_SPINLOCK_SAFE;\nkernel/bpf/verifier.c-14058-}\n--\nkernel/bpf/verifier.c=14323=int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-14341-\nkernel/bpf/verifier.c:14342:\tif (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env-\u003eprog))\nkernel/bpf/verifier.c-14343-\t\treturn -EACCES;\nkernel/bpf/verifier.c-14344-\nkernel/bpf/verifier.c:14345:\tmeta-\u003ekfunc_flags = *kfunc.flags;\nkernel/bpf/verifier.c-14346-\n"
}

21/3 2026/10/05 14:32 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 53111
							output: 23
							thoughts: 318
						

Thoughts:
**My Analysis of Kfunc Flag Pointers and Verification Order**

Okay, let's break this down. My understanding is that `kfunc.flags` is a pointer, specifically a `u32 *flags`, which points to the flags entry within a kfunc set. Crucially, if that `flags` pointer is `NULL`, it means the kfunc wasn't registered within a kfunc set. This seems straightforward enough. When I dereference `*kfunc.flags`, I'm getting the actual flags value. So, non-null means registered.

Now, I need to understand the role of `bpf_inline_kfunc_bodies`. The code shows that `bpf_inline_kfunc_bodies` is called within `bpf_check`, specifically *before* the full verification, `do_check_main`. Hang on, let me look at the `bpf_check()` function to confirm the order... Here it is: `bpf_check` calls `bpf_check_subprogs`, then `bpf_inline_kfunc_bodies`. After these, only then the environment states are being explored.

Hold on a minute, before `bpf_check_subprogs` is called, has `bpf_add_kfunc_call` already run? That's the crucial question. I need to trace where `bpf_add_kfunc_call` is actually being invoked. This determines the overall flow.



22/3 2026/10/05 14:32 tool grepper
0m Args:
{
  "Expression": "bpf_add_kfunc_call"
}

Results:
{
  "Output": "include/linux/bpf_verifier.h=1839=struct bpf_kfunc_desc_tab {\n--\ninclude/linux/bpf_verifier.h-1847-\t *\ninclude/linux/bpf_verifier.h:1848:\t * Grown one entry at a time by bpf_add_kfunc_call() and during\ninclude/linux/bpf_verifier.h-1849-\t * call specialization.\n--\ninclude/linux/bpf_verifier.h=1857=bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm);\ninclude/linux/bpf_verifier.h:1858:int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset);\ninclude/linux/bpf_verifier.h-1859-int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/fixups.c=165=static int add_kfunc_in_insns(struct bpf_verifier_env *env,\n--\nkernel/bpf/fixups.c-171-\t\tif (bpf_pseudo_kfunc_call(insn)) {\nkernel/bpf/fixups.c:172:\t\t\tret = bpf_add_kfunc_call(env, insn-\u003eimm, insn-\u003eoff);\nkernel/bpf/fixups.c-173-\t\t\tif (ret \u003c 0)\n--\nkernel/bpf/verifier.c=2870=static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-2872-\nkernel/bpf/verifier.c:2873:int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\nkernel/bpf/verifier.c-2874-{\n--\nkernel/bpf/verifier.c=3102=static int add_kfuncs(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-3119-\nkernel/bpf/verifier.c:3120:\t\tret = bpf_add_kfunc_call(env, insn-\u003eimm, insn-\u003eoff);\nkernel/bpf/verifier.c-3121-\t\tif (ret \u003c 0)\n"
}

23/3 2026/10/05 14:33 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 54413
							output: 38
							thoughts: 62
						

Thoughts:
Here's my understanding of the situation:

**Investigating the BPF Verifier's Function Addition and Subprogram Checks**

Okay, so I'm trying to trace the logic of the BPF verifier, and I've hit a specific point where function calls are being set up. I need to understand the order of operations, specifically around function addition and subprogram verification. It seems that `add_kfuncs(env)` is called *before* `bpf_check_subprogs` during the verification process. This sequence is important, so I want to confirm the details. My next step is to examine the code directly. I'll focus on lines 22690 through 22720 within the `kernel/bpf/verifier.c` file. This area should detail how these two operations interact, and hopefully clarify the dependency I'm observing.



24/3 2026/10/05 14:33 tool read-file
0m Args:
{
  "File": "kernel/bpf/verifier.c",
  "FirstLine": 22690,
  "LineCount": 35
}

Results:
{
  "Contents": "22690:\t\tif (ret \u003c 0)\n22691:\t\t\tgoto skip_full_check;\n22692:\t\n22693:\t\tret = check_subprogs(env);\n22694:\t\tif (ret \u003c 0)\n22695:\t\t\tgoto skip_full_check;\n22696:\t\n22697:\t\t/* Validate instructions and resolve the program's referenced resources. */\n22698:\t\tret = check_and_resolve_insns(env);\n22699:\t\tif (ret \u003c 0)\n22700:\t\t\tgoto skip_full_check;\n22701:\t\n22702:\t\t/* Find pointers to functions in the read-only maps of the program. */\n22703:\t\tret = resolve_func_ptrs(env);\n22704:\t\tif (ret \u003c 0)\n22705:\t\t\tgoto skip_full_check;\n22706:\t\n22707:\t\t/* Build kfunc prototypes after resolving program resources. */\n22708:\t\tret = add_kfuncs(env);\n22709:\t\tif (ret \u003c 0)\n22710:\t\t\tgoto skip_full_check;\n22711:\t\n22712:\t\tret = bpf_inline_kfunc_bodies(env);\n22713:\t\tif (ret \u003c 0)\n22714:\t\t\tgoto skip_full_check;\n22715:\t\n22716:\t\t/* sized by the program length, so after the lowering */\n22717:\t\tenv-\u003eexplored_states = kvzalloc_objs(struct list_head,\n22718:\t\t\t\t\t\t     state_htab_size(env),\n22719:\t\t\t\t\t\t     GFP_KERNEL_ACCOUNT);\n22720:\t\tret = -ENOMEM;\n22721:\t\tif (!env-\u003eexplored_states)\n22722:\t\t\tgoto skip_full_check;\n22723:\t\n22724:\t\tfor (i = 0; i \u003c state_htab_size(env); i++)\n"
}

25/3 2026/10/05 14:33 llm kmsan-evaluator
12m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 55263
							output: 31
							thoughts: 4705
						

Thoughts:
**KMSAN Analysis of BPF KFunc Code**

Okay, let's dissect this code with a KMSAN-focused mindset. My primary concern here is uninitialized memory and potential information leaks.  I need to meticulously examine how data flows, especially kernel structures shared with userspace, conditional logic, and the allocation/initialization of data structures. I need to be *sure* this code handles memory properly.

First, I need to focus on any data structures passed to userspace via mechanisms like `copy_to_user`, `ioctl`, and BPF buffers. In this patch set, the primary area of interest appears to be related to `BPF_PROG_LOAD` and `BPF_PROG_GET_INFO_BY_FD`, and the use of `xlated_prog_insns` and `jited_prog_insns`. Can userspace potentially request some of this information? Is any of that data uninitialized?

My attention is drawn to `bpf_restore_kfunc_calls()` and the stack buffer `u8 code[BPF_KFUNC_INLINE_MAX]`. This is a stack buffer that's *not* initialized before use. The `bpf_jit_inline_kfunc()` function might write to this buffer. My hypothesis is that if `bpf_jit_inline_kfunc()` does not write all the allocated bytes, an information leak could occur. I must scrutinize every possible code path within `bpf_jit_inline_kfunc()` to determine if this is true!

I have to carefully analyze each `bpf_jit_inline_kfunc()` case, each `emit` function, and `kfunc_copy_insn()` and make sure all allocated bytes are written. I need to check all the possible instructions used in this path and *prove* that they fill the buffer. So, I will be analyzing:
*   `kfunc_copy`:
    *   `kfunc_copy_insn()`
*   `rol64_emit()`
*   `select64_emit()`
*   `extract64_emit()`
*   `load_be64_emit()`
*   `lea64_emit()`
*   `xor_emit()`

I will also evaluate the `btf_add_kfunc_bodies` path because `krealloc()` is used, and those calls don't zero the allocated memory. However, the code does seem to only loop over initialized entries with `btf_find_kfunc_body()`.

Finally, the `struct bpf_kfunc_desc` is initialized with `memset(desc, 0, sizeof(*desc))`. I need to review what calls `bpf_add_kfunc_call()` and if any uninitialized variables exist. If `body != NULL`, `func_model` is not initialized. I must understand how this influences the overall state.

The key to a successful KMSAN test is to understand all data flows and *prove* that memory is correctly initialized before any potential access from user space.



26/3 2026/10/05 14:45 tool grepper
0m Args:
{
  "Expression": "func_model",
  "PathPrefix": "kernel/bpf/verifier.c"
}

Results:
{
  "Output": "kernel/bpf/verifier.c=2870=static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\nkernel/bpf/verifier.c:2871:\t\t\t       const struct btf_func_model *fm, struct bpf_func_proto *proto);\nkernel/bpf/verifier.c-2872-\nkernel/bpf/verifier.c=2873=int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\n--\nkernel/bpf/verifier.c-2876-\tstruct bpf_kfunc_btf_tab *btf_tab;\nkernel/bpf/verifier.c:2877:\tstruct btf_func_model func_model;\nkernel/bpf/verifier.c-2878-\tstruct bpf_kfunc_desc_tab *tab;\n--\nkernel/bpf/verifier.c-2962-\nkernel/bpf/verifier.c:2963:\terr = btf_distill_func_proto(\u0026env-\u003elog, kfunc.btf, kfunc.proto, kfunc.name, \u0026func_model);\nkernel/bpf/verifier.c-2964-\tif (err)\nkernel/bpf/verifier.c-2965-\t\treturn err;\nkernel/bpf/verifier.c:2966:\tif (func_model.ret_size \u003e 8) {\nkernel/bpf/verifier.c-2967-\t\tif (kfunc.flags \u0026\u0026 (*kfunc.flags \u0026 KF_FASTCALL)) {\n--\nkernel/bpf/verifier.c-2996-\t       btf_find_kfunc_body(kfunc.btf, func_id) : NULL;\nkernel/bpf/verifier.c:2997:\terr = body ? 0 : gen_kfunc_arg_proto(env, \u0026meta, \u0026func_model, \u0026desc-\u003eproto);\nkernel/bpf/verifier.c-2998-\tif (err)\n--\nkernel/bpf/verifier.c-3003-\tdesc-\u003eaddr = addr;\nkernel/bpf/verifier.c:3004:\tdesc-\u003efunc_model = func_model;\nkernel/bpf/verifier.c-3005-\tdesc-\u003ebody = body;\nkernel/bpf/verifier.c:3006:\tfor (i = 0; body \u0026\u0026 i \u003c func_model.nr_args; i++)\nkernel/bpf/verifier.c-3007-\t\tif (btf_param_match_suffix(kfunc.btf, \u0026btf_params(kfunc.proto)[i], \"__k\"))\n--\nkernel/bpf/verifier.c=9435=static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,\n--\nkernel/bpf/verifier.c-10014- * The slots a parameter takes, from its BTF type. This has to agree with\nkernel/bpf/verifier.c:10015: * btf_func_model_arg_slots(), which answers the same from the size the\nkernel/bpf/verifier.c-10016- * func model recorded, or the verifier would check an argument at a slot\n--\nkernel/bpf/verifier.c=13393=bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta)\n--\nkernel/bpf/verifier.c-13397-\nkernel/bpf/verifier.c:13398:static u32 kfunc_abi_slots(const struct btf_func_model *fm)\nkernel/bpf/verifier.c-13399-{\n--\nkernel/bpf/verifier.c-13404-\tfor (i = 0; i \u003c fm-\u003enr_args; i++)\nkernel/bpf/verifier.c:13405:\t\tslots += btf_func_model_arg_slots(fm, i);\nkernel/bpf/verifier.c-13406-\n--\nkernel/bpf/verifier.c=13680=static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\nkernel/bpf/verifier.c:13681:\t\t\t       const struct btf_func_model *fm, struct bpf_func_proto *proto)\nkernel/bpf/verifier.c-13682-{\n--\nkernel/bpf/verifier.c-13698-\tfor (i = 0, slots_used = 0; i \u003c nargs; i++) {\nkernel/bpf/verifier.c:13699:\t\tu32 nslots = btf_func_model_arg_slots(fm, i);\nkernel/bpf/verifier.c-13700-\n--\nkernel/bpf/verifier.c-13723-\tfor (i = 0, slots_used = 0; i \u003c nargs; i++) {\nkernel/bpf/verifier.c:13724:\t\tu32 nslots = btf_func_model_arg_slots(fm, i);\nkernel/bpf/verifier.c-13725-\n--\nkernel/bpf/verifier.c=14738=static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-15198-\nkernel/bpf/verifier.c:15199:\tproto_slots = kfunc_abi_slots(\u0026desc-\u003efunc_model);\nkernel/bpf/verifier.c-15200-\tif (proto_slots \u003e MAX_BPF_FUNC_REG_ARGS) {\n"
}

27/3 2026/10/05 14:45 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62137
							output: 35
							thoughts: 496
						

Thoughts:
**Analyzing the Kernel Function Inline Process**

Okay, let's break this down. Line 2963 tells me that `func_model` is initialized using `btf_distill_func_proto` before line 2997. But what's the deal with `desc->proto`? If `body` isn't null, then `gen_kfunc_arg_proto` *isn't* called, meaning `desc->proto` is just zeroed out initially via `memset`. The real question is, does the code ever read `desc->proto` when `desc->body` is not NULL?

Hold on... does `check_kfunc_call` even get run on inlined kfuncs? This is important.

Wait a second. When a kfunc is inlined, `bpf_inline_kfunc_bodies` replaces the call instruction with the function body *before* `do_check_main` is even called! Let me confirm... yes, the call instruction in `env->prog->insnsi` gets replaced by `r->body->insns`. So, during verification, `check_kfunc_call` is *bypassed* entirely for inlined kfuncs!

But what if the call instruction is restored *after* verification? `bpf_restore_kfunc_calls()` is called in `bpf_check`, specifically at line 22792. It only gets called if verification passes, after `do_check_main`. Then, the program proceeds to `bpf_opt_remove_nops`, `bpf_convert_ctx_accesses`, and then `bpf_do_misc_fixups`. My immediate thought is, does `bpf_do_misc_fixups` call `bpf_fixup_kfunc_call`? I need to check the code. Let's look at `bpf_do_misc_fixups` in `kernel/bpf/fixups.c`.



28/3 2026/10/05 14:46 tool grepper
0m Args:
{
  "Expression": "bpf_fixup_kfunc_call",
  "PathPrefix": "kernel/bpf/"
}

Results:
{
  "Output": "kernel/bpf/fixups.c=1715=int bpf_do_misc_fixups(struct bpf_verifier_env *env)\n--\nkernel/bpf/fixups.c-2104-\t\tif (insn-\u003esrc_reg == BPF_PSEUDO_KFUNC_CALL) {\nkernel/bpf/fixups.c:2105:\t\t\tret = bpf_fixup_kfunc_call(env, insn, insn_buf, i + delta, \u0026cnt);\nkernel/bpf/fixups.c-2106-\t\t\tif (ret)\n--\nkernel/bpf/verifier.c=22156=static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,\n--\nkernel/bpf/verifier.c-22172-\nkernel/bpf/verifier.c:22173:int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\nkernel/bpf/verifier.c-22174-\t\t     struct bpf_insn *insn_buf, int insn_idx, int *cnt)\n"
}

29/3 2026/10/05 14:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 63410
							output: 38
							thoughts: 27
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Diving into `bpf_fixup_kfunc_call`**

Alright, let's get into the weeds of the verifier. My initial thought is to grab `bpf_fixup_kfunc_call` in `kernel/bpf/verifier.c`. I know this function is crucial for handling calls to kernel functions (`kfuncs`) from within BPF programs. I'm probably going to be looking for how it resolves the function pointers, validates the call arguments, and handles any potential side effects. I'll likely be interested in how it interacts with the type system and whether there are any potential vulnerabilities, such as unchecked pointers or argument coercion issues. I'll also want to see how it handles different BPF program types. Essentially, I want to understand exactly how the verifier ensures that these kfunc calls are safe and efficient. I'll be keeping an eye out for interesting implementation details and any subtle optimizations or potential areas for improvement. Let's see what's what.



30/3 2026/10/05 14:46 tool read-file
0m Args:
{
  "File": "kernel/bpf/verifier.c",
  "FirstLine": 22170,
  "LineCount": 45
}

Results:
{
  "Contents": "22170:\t\t*cnt = 4;\n22171:\t}\n22172:\t\n22173:\tint bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n22174:\t\t\t     struct bpf_insn *insn_buf, int insn_idx, int *cnt)\n22175:\t{\n22176:\t\tstruct bpf_kfunc_desc desc_copy;\n22177:\t\tstruct bpf_kfunc_desc *desc;\n22178:\t\tunsigned long call_imm;\n22179:\t\tu16 base_desc_idx, desc_idx;\n22180:\t\tbool near_call;\n22181:\t\tint err;\n22182:\t\n22183:\t\tif (!insn-\u003eimm) {\n22184:\t\t\tverbose(env, \"invalid kernel function call not eliminated in verifier pass\\n\");\n22185:\t\t\treturn -EINVAL;\n22186:\t\t}\n22187:\t\n22188:\t\t*cnt = 0;\n22189:\t\n22190:\t\t/* insn-\u003eimm has the btf func_id. Replace it with an offset relative to\n22191:\t\t * __bpf_call_base, unless the JIT needs to call functions that are\n22192:\t\t * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).\n22193:\t\t */\n22194:\t\tdesc = bpf_find_kfunc_desc(env-\u003eprog, insn-\u003eimm, insn-\u003eoff);\n22195:\t\tif (!desc) {\n22196:\t\t\tverifier_bug(env, \"kernel function descriptor not found for func_id %u\",\n22197:\t\t\t\t     insn-\u003eimm);\n22198:\t\t\treturn -EFAULT;\n22199:\t\t}\n22200:\t\tbase_desc_idx = desc - env-\u003eprog-\u003eaux-\u003ekfunc_tab-\u003edescs;\n22201:\t\n22202:\t\tnear_call = !bpf_jit_supports_far_kfunc_call();\n22203:\t\tdesc_copy = *desc;\n22204:\t\tdesc = \u0026desc_copy;\n22205:\t\n22206:\t\terr = specialize_kfunc(env, desc, insn_idx);\n22207:\t\tif (err)\n22208:\t\t\treturn err;\n22209:\t\n22210:\t\tif (near_call) {\n22211:\t\t\tcall_imm = BPF_CALL_IMM(desc-\u003eaddr);\n22212:\t\t\tif ((unsigned long)(s32)call_imm != call_imm) {\n22213:\t\t\t\tverbose(env, \"address of kernel func_id %u is out of range\\n\",\n22214:\t\t\t\t\tdesc-\u003efunc_id);\n"
}

31/3 2026/10/05 14:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 64498
							output: 38
							thoughts: 20
						

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

**Diving into `bpf_fixup_kfunc_call`**

Alright, let's get down to brass tacks and see what's going on *now* in the `bpf_fixup_kfunc_call` function. I need to understand what the next logical step is within this particular function. Thinking through the control flow is essential for diagnosing potential issues here. Is there a call stack involved, perhaps I'm looking for a particular function call, or maybe I am trying to determine an execution path within `bpf_fixup_kfunc_call` that's not clearly defined? I am probably working on a specific problem relating to kfunc calls; let me zoom in on the specific details in the code...



32/3 2026/10/05 14:46 tool read-file
0m Args:
{
  "File": "kernel/bpf/verifier.c",
  "FirstLine": 22215,
  "LineCount": 45
}

Results:
{
  "Contents": "22215:\t\t\t\treturn -EINVAL;\n22216:\t\t\t}\n22217:\t\t\tinsn-\u003eimm = call_imm;\n22218:\t\t}\n22219:\t\n22220:\t\terr = add_kfunc_desc_target(env, desc, base_desc_idx, \u0026desc_idx);\n22221:\t\tif (err)\n22222:\t\t\treturn err;\n22223:\t\tinsn-\u003eoff = desc_idx;\n22224:\t\n22225:\t\tif (is_bpf_obj_new_kfunc(desc-\u003efunc_id) || is_bpf_percpu_obj_new_kfunc(desc-\u003efunc_id)) {\n22226:\t\t\tstruct btf_struct_meta *kptr_struct_meta = env-\u003einsn_aux_data[insn_idx].kptr_struct_meta;\n22227:\t\t\tstruct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };\n22228:\t\t\tu64 obj_new_size = env-\u003einsn_aux_data[insn_idx].obj_new_size;\n22229:\t\n22230:\t\t\tif (is_bpf_percpu_obj_new_kfunc(desc-\u003efunc_id) \u0026\u0026 kptr_struct_meta) {\n22231:\t\t\t\tverifier_bug(env, \"NULL kptr_struct_meta expected at insn_idx %d\",\n22232:\t\t\t\t\t     insn_idx);\n22233:\t\t\t\treturn -EFAULT;\n22234:\t\t\t}\n22235:\t\n22236:\t\t\tinsn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);\n22237:\t\t\tinsn_buf[1] = addr[0];\n22238:\t\t\tinsn_buf[2] = addr[1];\n22239:\t\t\tinsn_buf[3] = *insn;\n22240:\t\t\t*cnt = 4;\n22241:\t\t} else if (is_bpf_obj_drop_kfunc(desc-\u003efunc_id) ||\n22242:\t\t\t   is_bpf_percpu_obj_drop_kfunc(desc-\u003efunc_id) ||\n22243:\t\t\t   is_bpf_refcount_acquire_kfunc(desc-\u003efunc_id)) {\n22244:\t\t\tstruct btf_struct_meta *kptr_struct_meta = env-\u003einsn_aux_data[insn_idx].kptr_struct_meta;\n22245:\t\t\tstruct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };\n22246:\t\n22247:\t\t\tif (is_bpf_percpu_obj_drop_kfunc(desc-\u003efunc_id) \u0026\u0026 kptr_struct_meta) {\n22248:\t\t\t\tverifier_bug(env, \"NULL kptr_struct_meta expected at insn_idx %d\",\n22249:\t\t\t\t\t     insn_idx);\n22250:\t\t\t\treturn -EFAULT;\n22251:\t\t\t}\n22252:\t\n22253:\t\t\tif (is_bpf_refcount_acquire_kfunc(desc-\u003efunc_id) \u0026\u0026 !kptr_struct_meta) {\n22254:\t\t\t\tverifier_bug(env, \"kptr_struct_meta expected at insn_idx %d\",\n22255:\t\t\t\t\t     insn_idx);\n22256:\t\t\t\treturn -EFAULT;\n22257:\t\t\t}\n22258:\t\n22259:\t\t\tinsn_buf[0] = addr[0];\n"
}

33/3 2026/10/05 14:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65744
							output: 30
							thoughts: 44
						

Thoughts:
Here's my take on the situation:

**Investigating Potential Uninitialized Reads in KFunc Handling**

Okay, so I'm digging into this `bpf_fixup_kfunc_call` function, and it seems like it's another one that's *not* touching the `desc->proto` field. Hmm, that's interesting. I need to make a mental note of that. Now, I'm shifting my focus to `specialize_kfunc`. Let's see if there's any chance this function is attempting to read uninitialized memory during its execution. That's always a fun one to hunt down. Let me start tracing the execution flow...



34/3 2026/10/05 14:46 tool grepper
0m Args:
{
  "Expression": "specialize_kfunc",
  "PathPrefix": "kernel/bpf/"
}

Results:
{
  "Output": "kernel/bpf/verifier.c=22021=static int process_fd_array(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-22046-/* replace a generic kfunc with a specialized version if necessary */\nkernel/bpf/verifier.c:22047:static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)\nkernel/bpf/verifier.c-22048-{\n--\nkernel/bpf/verifier.c=22173=int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-22205-\nkernel/bpf/verifier.c:22206:\terr = specialize_kfunc(env, desc, insn_idx);\nkernel/bpf/verifier.c-22207-\tif (err)\n"
}

35/3 2026/10/05 14:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 66229
							output: 38
							thoughts: 11
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:

**Diving into `specialize_kfunc`**

Alright, let's see what's happening with this `specialize_kfunc` function. My initial thought is to quickly assess its role in the overall system. I'm assuming it's involved in some kind of kernel function specialization, likely for performance optimization or code generation. I need to understand its inputs, outputs, and any potential side effects. Is it working on a high level, for example generating a specialized kernel that is compiled on the fly, or a low level, for example applying optimization passes to the IR of an existing kernel?

I’m particularly interested in how it handles different data types, control flow, and hardware targets. Are there any assumptions or limitations baked into its logic? Does it employ any heuristics or analysis techniques to decide when specialization is beneficial, or is it triggered by some other event? And importantly, are there any potential edge cases or scenarios where this specialization could lead to unexpected behavior or performance regressions? The devil is often in the details, so I need to go beyond the surface and look for any clues.



36/3 2026/10/05 14:46 tool read-file
0m Args:
{
  "File": "kernel/bpf/verifier.c",
  "FirstLine": 22047,
  "LineCount": 35
}

Results:
{
  "Contents": "22047:\tstatic int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)\n22048:\t{\n22049:\t\tstruct bpf_prog *prog = env-\u003eprog;\n22050:\t\tbool seen_direct_write;\n22051:\t\tvoid *xdp_kfunc;\n22052:\t\tbool is_rdonly;\n22053:\t\tu32 func_id = desc-\u003efunc_id;\n22054:\t\tu16 offset = desc-\u003eoffset;\n22055:\t\tunsigned long addr = desc-\u003eaddr;\n22056:\t\n22057:\t\tif (offset) /* return if module BTF is used */\n22058:\t\t\treturn 0;\n22059:\t\n22060:\t\tif (bpf_dev_bound_kfunc_id(func_id)) {\n22061:\t\t\txdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);\n22062:\t\t\tif (xdp_kfunc)\n22063:\t\t\t\taddr = (unsigned long)xdp_kfunc;\n22064:\t\t\t/* fallback to default kfunc when not supported by netdev */\n22065:\t\t} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {\n22066:\t\t\tseen_direct_write = env-\u003eseen_direct_write;\n22067:\t\t\tis_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);\n22068:\t\n22069:\t\t\tif (is_rdonly)\n22070:\t\t\t\taddr = (unsigned long)bpf_dynptr_from_skb_rdonly;\n22071:\t\n22072:\t\t\t/* restore env-\u003eseen_direct_write to its original value, since\n22073:\t\t\t * may_access_direct_pkt_data mutates it\n22074:\t\t\t */\n22075:\t\t\tenv-\u003eseen_direct_write = seen_direct_write;\n22076:\t\t} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {\n22077:\t\t\tif (bpf_lsm_has_d_inode_locked(prog))\n22078:\t\t\t\taddr = (unsigned long)bpf_set_dentry_xattr_locked;\n22079:\t\t} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {\n22080:\t\t\tif (bpf_lsm_has_d_inode_locked(prog))\n22081:\t\t\t\taddr = (unsigned long)bpf_remove_dentry_xattr_locked;\n"
}

37/3 2026/10/05 14:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 67284
							output: 30
							thoughts: 2027
						

Thoughts:
**Unraveling Potential Uninitialized Memory Reads in BPF Kfuncs**

Okay, so I'm looking into potential issues with uninitialized memory reads within these new BPF kfuncs. The code's using `bpf_kfunc_native` and JIT compilation, and I need to be *thorough*.

First, nothing jumps out initially. But I'm going through the `bpf_kfunc_native` function to understand how the native code for inlined kfunc calls is handled. I see the native code (`in->image`) is copied into the JIT image buffer. The critical part is that `in->image` is allocated using `kmemdup`, and the length is determined by `in->image_len`. This looks okay at first glance.

Now, the question is: can these new kfuncs *actually* introduce a read of uninitialized memory during BPF program execution? Time to dive into the kfuncs themselves: `bpf_rol64`, `bpf_select64`, and others. My primary concern right now is the verifier. It checks each kfunc call as its body, and the JIT puts native code in place of the call. So the verifier should be able to track stack slot initialization with `BPF_LDX_MEM`.

Let's check the verifier's checks of the body's memory accesses. For example, for `load_be64_body`, the body includes `BPF_LDX_MEM`. My initial concern is addressed, as the verifier *does* check if the stack memory is initialized. It rejects the reading of `STACK_INVALID` (uninitialized memory). And I think the same thing should be true for the body of `copy16_body` as well.

But what about the cases where native code is used instead of the body? I have to consider `kfunc_native_ok()`! Okay, there's a key comment here: "*the JIT checks these accesses with KASAN, native code does not*". Essentially, native code *is* disabled for map value, mem, packet, and packet meta accesses when `CONFIG_BPF_JIT_KASAN` is enabled! Only stack accesses are allowed with native code. It seems like the standard JIT memory accesses use KASAN, but the copied kfunc instructions *don't* emit KASAN callbacks.

Now, the real kicker: Does KMSAN instrument BPF JIT code? Nope! I need to double-check that BPF JIT doesn't support KMSAN at all. Time to search for `CONFIG_KMSAN` or `kmsan` within the JIT compilation code... and the answer should be clear.



38/3 2026/10/05 14:46 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "kmsan",
  "PathPrefix": "arch/x86/net/"
}

Results:
{
  "error": "no matches"
}

39/3 2026/10/05 14:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 69937
							output: 27
							thoughts: 20
						

Thoughts:
Here's my thought process, as requested:

**Checking for KMSAN Mentions in BPF Code**

Alright, let's dive into this. The task at hand is to see if KMSAN (Kernel Memory Sanitizer) is referenced within the `kernel/bpf/` directory of the kernel source. My immediate mental process is: I need to determine if KMSAN has any specific integration or interaction with the BPF subsystem. This could involve checks for enabling or disabling KMSAN features based on BPF usage, special considerations for BPF-related memory operations when KMSAN is active, or perhaps even KMSAN instrumentation applied directly to BPF code for debugging purposes. Knowing the intricacies of both BPF and KMSAN, I would expect the references to be related to memory safety, security, or potential conflict resolution. Time to start digging!



40/3 2026/10/05 14:47 tool grepper
0m Args:
{
  "Expression": "kmsan",
  "PathPrefix": "kernel/bpf/"
}

Results:
{
  "Output": "kernel/bpf/core.c=2423=static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \\\n--\nkernel/bpf/core.c-2427-\\\nkernel/bpf/core.c:2428:\tkmsan_unpoison_memory(stack, sizeof(stack)); \\\nkernel/bpf/core.c-2429-\tFP = (u64) (unsigned long) \u0026stack[ARRAY_SIZE(stack)]; \\\n--\nkernel/bpf/core.c=2436=static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \\\n--\nkernel/bpf/core.c-2441-\\\nkernel/bpf/core.c:2442:\tkmsan_unpoison_memory(stack, sizeof(stack)); \\\nkernel/bpf/core.c-2443-\tFP = (u64) (unsigned long) \u0026stack[ARRAY_SIZE(stack)]; \\\n"
}

41/3 2026/10/05 14:47 llm kmsan-evaluator
30m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 70448
							output: 26
							thoughts: 396
						

Thoughts:
**KMSAN Risk Assessment for BPF Patch**

Okay, so the interpreter is the only one that potentially needs KMSAN protection for the BPF stack, the JIT doesn't. Right, let's look at the actual kernel code in this patch now, focusing on the areas that could be problematic: syscalls, the verifier, kfunc registration, and module loading.

The key question is whether this code introduces uninitialized memory vulnerabilities directly. Let's apply the criteria for when `NeedsKMSAN` *should* be set: if the patch modifies or introduces code related to:

1.  Kernel structures passed to user space. This is done via `copy_to_user`, `put_user`, netlink skb attributes, ioctl, socket options, or BPF buffers.
2.  Conditional logic where decisions are based on uninitialized variables or struct fields.
3.  Allocation or initialization of complex data structures where uninitialized fields could be read later.
4.  Bounds checks or length logic that might allow access to uninitialized bytes in existing buffers.

Let's dissect this patch against those conditions. First, anything going to user space. It doesn't look like we're using any of the standard `copy_to_user` calls, `put_user`, or the other obvious things. The patch doesn't explicitly add any new netlink attributes, ioctls, or socket options. But wait, what about BPF program info? Specifically, is `bpf_prog_get_info_by_fd` affected? Does it send `insn_aux_data` or `kfunc_inlines` to userspace? That's what I need to verify.



42/3 2026/10/05 15:17 tool grepper
0m Args:
{
  "Expression": "bpf_prog_get_info_by_fd"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 530 lines.\nUse more precise expression if possible.\n\nkernel/bpf/syscall.c=5113=static int set_info_rec_size(struct bpf_prog_info *info)\n--\nkernel/bpf/syscall.c-5143-\nkernel/bpf/syscall.c:5144:static int bpf_prog_get_info_by_fd(struct file *file,\nkernel/bpf/syscall.c-5145-\t\t\t\t   struct bpf_prog *prog,\n--\nkernel/bpf/syscall.c=5580=static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,\n--\nkernel/bpf/syscall.c-5590-\tif (fd_file(f)-\u003ef_op == \u0026bpf_prog_fops)\nkernel/bpf/syscall.c:5591:\t\treturn bpf_prog_get_info_by_fd(fd_file(f), fd_file(f)-\u003eprivate_data, attr,\nkernel/bpf/syscall.c-5592-\t\t\t\t\t      uattr);\n--\nsamples/bpf/xdp_adjust_tail_user.c=82=int main(int argc, char **argv)\n--\nsamples/bpf/xdp_adjust_tail_user.c-186-\nsamples/bpf/xdp_adjust_tail_user.c:187:\terr = bpf_prog_get_info_by_fd(prog_fd, \u0026info, \u0026info_len);\nsamples/bpf/xdp_adjust_tail_user.c-188-\tif (err) {\n--\nsamples/bpf/xdp_fwd_user.c=50=static int do_detach(int ifindex, const char *ifname, const char *app_name)\n--\nsamples/bpf/xdp_fwd_user.c-78-\nsamples/bpf/xdp_fwd_user.c:79:\terr = bpf_prog_get_info_by_fd(prog_fd, \u0026prog_info, \u0026info_len);\nsamples/bpf/xdp_fwd_user.c-80-\tif (err) {\nsamples/bpf/xdp_fwd_user.c:81:\t\tprintf(\"ERROR: bpf_prog_get_info_by_fd failed (%s)\\n\",\nsamples/bpf/xdp_fwd_user.c-82-\t\t       strerror(errno));\n--\nsamples/bpf/xdp_tx_iptunnel_user.c=152=int main(int argc, char **argv)\n--\nsamples/bpf/xdp_tx_iptunnel_user.c-297-\nsamples/bpf/xdp_tx_iptunnel_user.c:298:\terr = bpf_prog_get_info_by_fd(prog_fd, \u0026info, \u0026info_len);\nsamples/bpf/xdp_tx_iptunnel_user.c-299-\tif (err) {\n--\ntools/bpf/bpftool/btf.c=1248=static int do_dump(int argc, char **argv)\n--\ntools/bpf/bpftool/btf.c-1309-\ntools/bpf/bpftool/btf.c:1310:\t\terr = bpf_prog_get_info_by_fd(fd, \u0026info, \u0026len);\ntools/bpf/bpftool/btf.c-1311-\t\tif (err) {\n--\ntools/bpf/bpftool/btf.c=1537=build_btf_type_table(struct hashmap *tab, enum bpf_obj_type type,\n--\ntools/bpf/bpftool/btf.c-1598-\t\tif (type == BPF_OBJ_PROG)\ntools/bpf/bpftool/btf.c:1599:\t\t\terr = bpf_prog_get_info_by_fd(fd, info, len);\ntools/bpf/bpftool/btf.c-1600-\t\telse\n--\ntools/bpf/bpftool/btf_dumper.c=31=static int dump_prog_id_as_func_ptr(const struct btf_dumper *d,\n--\ntools/bpf/bpftool/btf_dumper.c-59-\ntools/bpf/bpftool/btf_dumper.c:60:\terr = bpf_prog_get_info_by_fd(prog_fd, \u0026info, \u0026info_len);\ntools/bpf/bpftool/btf_dumper.c-61-\tif (err)\n--\ntools/bpf/bpftool/btf_dumper.c-72-\ntools/bpf/bpftool/btf_dumper.c:73:\terr = bpf_prog_get_info_by_fd(prog_fd, \u0026info, \u0026info_len);\ntools/bpf/bpftool/btf_dumper.c-74-\tif (err)\n--\ntools/bpf/bpftool/cgroup.c=199=static int show_bpf_prog(int id, enum bpf_attach_type attach_type,\n--\ntools/bpf/bpftool/cgroup.c-213-\ntools/bpf/bpftool/cgroup.c:214:\tif (bpf_prog_get_info_by_fd(prog_fd, \u0026info, \u0026info_len)) {\ntools/bpf/bpftool/cgroup.c-215-\t\tclose(prog_fd);\n--\ntools/bpf/bpftool/common.c=414=void get_prog_full_name(const struct bpf_prog_info *prog_info, int prog_fd,\n--\ntools/bpf/bpftool/common.c-436-\ntools/bpf/bpftool/common.c:437:\tif (bpf_prog_get_info_by_fd(prog_fd, \u0026info, \u0026info_len))\ntools/bpf/bpftool/common.c-438-\t\tgoto copy_name;\n--\ntools/bpf/bpftool/common.c=552=static int do_build_table_cb(const char *fpath, const struct stat *sb,\n--\ntools/bpf/bpftool/common.c-572-\tmemset(\u0026pinned_info, 0, sizeof(pinned_info));\ntools/bpf/bpftool/common.c:573:\tif (bpf_prog_get_info_by_fd(fd, \u0026pinned_info, \u0026len))\ntools/bpf/bpftool/common.c-574-\t\tgoto out_close;\n--\ntools/bpf/bpftool/common.c=852=static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)\n--\ntools/bpf/bpftool/common.c-881-\ntools/bpf/bpftool/common.c:882:\t\terr = bpf_prog_get_info_by_fd(fd, \u0026info, \u0026len);\ntools/bpf/bpftool/common.c-883-\t\tif (err) {\n--\ntools/bpf/bpftool/link.c=235=static int get_prog_info(int prog_id, struct bpf_prog_info *info)\n--\ntools/bpf/bpftool/link.c-244-\tmemset(info, 0, sizeof(*info));\ntools/bpf/bpftool/link.c:245:\terr = bpf_prog_get_info_by_fd(prog_fd, info, \u0026len);\ntools/bpf/bpftool/link.c-246-\tif (err)\n--\ntools/bpf/bpftool/prog.c=191=static void show_prog_maps(int fd, __u32 num_maps)\n--\ntools/bpf/bpftool/prog.c-201-\ntools/bpf/bpftool/prog.c:202:\terr = bpf_prog_get_info_by_fd(fd, \u0026info, \u0026len);\ntools/bpf/bpftool/prog.c-203-\tif (err || !info.nr_map_ids)\n--\ntools/bpf/bpftool/prog.c=220=static void *find_metadata(int prog_fd, struct bpf_map_info *map_info)\n--\ntools/bpf/bpftool/prog.c-234-\tprog_info_len = sizeof(prog_info);\ntools/bpf/bpftool/prog.c:235:\tret = bpf_prog_get_info_by_fd(prog_fd, \u0026prog_info, \u0026prog_info_len);\ntools/bpf/bpftool/prog.c-236-\tif (ret)\n--\ntools/bpf/bpftool/prog.c-251-\ntools/bpf/bpftool/prog.c:252:\tret = bpf_prog_get_info_by_fd(prog_fd, \u0026prog_info, \u0026prog_info_len);\ntools/bpf/bpftool/prog.c-253-\tif (ret)\n--\ntools/bpf/bpftool/prog.c=582=static int show_prog(int fd)\n--\ntools/bpf/bpftool/prog.c-587-\ntools/bpf/bpftool/prog.c:588:\terr = bpf_prog_get_info_by_fd(fd, \u0026info, \u0026len);\ntools/bpf/bpftool/prog.c-589-\tif (err \u0026\u0026 err != -ENODEV) {\n--\ntools/bpf/bpftool/prog.c=881=static int do_dump(int argc, char **argv)\n--\ntools/bpf/bpftool/prog.c-967-\ntools/bpf/bpftool/prog.c:968:\t\terr = bpf_prog_get_info_by_fd(fds[i], \u0026info, \u0026info_len);\ntools/bpf/bpftool/prog.c-969-\t\tif (err) {\n--\ntools/bpf/bpftool/prog.c-979-\ntools/bpf/bpftool/prog.c:980:\t\terr = bpf_prog_get_info_by_fd(fds[i], \u0026info, \u0026info_len);\ntools/bpf/bpftool/prog.c-981-\t\tif (err) {\n--\ntools/bpf/bpftool/prog.c=2374=static char *profile_target_name(int tgt_fd)\n--\ntools/bpf/bpftool/prog.c-2384-\ntools/bpf/bpftool/prog.c:2385:\terr = bpf_prog_get_info_by_fd(tgt_fd, \u0026info, \u0026info_len);\ntools/bpf/bpftool/prog.c-2386-\tif (err) {\n--\ntools/bpf/bpftool/prog.c-2406-\ntools/bpf/bpftool/prog.c:2407:\terr = bpf_prog_get_info_by_fd(tgt_fd, \u0026info, \u0026info_len);\ntools/bpf/bpftool/prog.c-2408-\tif (err) {\n--\ntools/lib/bpf/bpf.c=1258=int bpf_obj_get_info_by_fd(int bpf_fd, void *info, __u32 *info_len)\n--\ntools/lib/bpf/bpf.c-1274-\ntools/lib/bpf/bpf.c:1275:int bpf_prog_get_info_by_fd(int prog_fd, struct bpf_prog_info *info, __u32 *info_len)\ntools/lib/bpf/bpf.c-1276-{\n--\ntools/lib/bpf/bpf.h=544=LIBBPF_API int bpf_obj_get_info_by_fd(int bpf_fd, void *info, __u32 *info_len);\n--\ntools/lib/bpf/bpf.h-546-/**\ntools/lib/bpf/bpf.h:547: * @brief **bpf_prog_get_info_by_fd()** obtains information about the BPF\ntools/lib/bpf/bpf.h-548- * program corresponding to *prog_fd*.\n--\ntools/lib/bpf/bpf.h-563- */\ntools/lib/bpf/bpf.h:564:LIBBPF_API int bpf_prog_get_info_by_fd(int prog_fd, struct bpf_prog_info *info, __u32 *info_len);\ntools/lib/bpf/bpf.h-565-\n--\ntools/lib/bpf/libbpf.c=11607=static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)\n--\ntools/lib/bpf/libbpf.c-11614-\tmemset(\u0026info, 0, info_len);\ntools/lib/bpf/libbpf.c:11615:\terr = bpf_prog_get_info_by_fd(attach_prog_fd, \u0026info, \u0026info_len);\ntools/lib/bpf/libbpf.c-11616-\tif (err) {\ntools/lib/bpf/libbpf.c:11617:\t\tpr_warn(\"failed bpf_prog_get_info_by_fd for FD %u: %s\\n\",\ntools/lib/bpf/libbpf.c-11618-\t\t\tattach_prog_fd, errstr(err));\n--\ntools/lib/bpf/libbpf.map=384=LIBBPF_1.2.0 {\n--\ntools/lib/bpf/libbpf.map-389-\t\tbpf_map_get_info_by_fd;\ntools/lib/bpf/libbpf.map:390:\t\tbpf_prog_get_info_by_fd;\ntools/lib/bpf/libbpf.map-391-} LIBBPF_1.1.0;\n--\ntools/lib/bpf/netlink.c=711=static int tc_add_fd_and_name(struct libbpf_nla_req *req, int fd)\n--\ntools/lib/bpf/netlink.c-718-\tmemset(\u0026info, 0, info_len);\ntools/lib/bpf/netlink.c:719:\tret = bpf_prog_get_info_by_fd(fd, \u0026info, \u0026info_len);\ntools/lib/bpf/netlink.c-720-\tif (ret \u003c 0)\n--\ntools/testing/selftests/bpf/jit_disasm_helpers.c=177=int get_jited_program_text(int fd, char *text, size_t text_sz)\n--\ntools/testing/selftests/bpf/jit_disasm_helpers.c-200-\t/* first call is to find out jited program len */\ntools/testing/selftests/bpf/jit_disasm_helpers.c:201:\terr = bpf_prog_get_info_by_fd(fd, \u0026info, \u0026info_len);\ntools/testing/selftests/bpf/jit_disasm_helpers.c:202:\tif (!ASSERT_OK(err, \"bpf_prog_get_info_by_fd #1\"))\ntools/testing/selftests/bpf/jit_disasm_helpers.c-203-\t\tgoto out;\n--\ntools/testing/selftests/bpf/jit_disasm_helpers.c-223-\tinfo.nr_jited_func_lens = jited_funcs;\ntools/testing/selftests/bpf/jit_disasm_helpers.c:224:\terr = bpf_prog_get_info_by_fd(fd, \u0026info, \u0026info_len);\ntools/testing/selftests/bpf/jit_disasm_helpers.c:225:\tif (!ASSERT_OK(err, \"bpf_prog_get_info_by_fd #2\"))\ntools/testing/selftests/bpf/jit_disasm_helpers.c-226-\t\tgoto out;\n--\ntools/testing/selftests/bpf/prog_tests/bpf_insn_array.c=654=static void check_gotox_jt_dead_subprogs(void)\n--\ntools/testing/selftests/bpf/prog_tests/bpf_insn_array.c-694-\t/* Both dead subprograms and the calls to them must be gone. */\ntools/testing/selftests/bpf/prog_tests/bpf_insn_array.c:695:\tif (ASSERT_OK(bpf_prog_get_info_by_fd(prog_fd, \u0026info, \u0026len),\ntools/testing/selftests/bpf/prog_tests/bpf_insn_array.c:696:\t\t      \"bpf_prog_get_info_by_fd\"))\ntools/testing/selftests/bpf/prog_tests/bpf_insn_array.c-697-\t\tASSERT_EQ(info.xlated_prog_len / sizeof(struct bpf_insn),\n--\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c=6=void serial_test_bpf_obj_id(void)\n--\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-114-\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c:115:\t\terr = bpf_prog_get_info_by_fd(prog_fds[i], \u0026prog_infos[i],\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-116-\t\t\t\t\t      \u0026info_len);\n--\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-119-\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c:120:\t\tif (!ASSERT_OK(err, \"bpf_prog_get_info_by_fd\") ||\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-121-\t\t\t\t!ASSERT_EQ(prog_infos[i].type, BPF_PROG_TYPE_RAW_TRACEPOINT, \"prog_type\") ||\n--\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-181-\t\tprog_info.nr_map_ids = 1;\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c:182:\t\terr = bpf_prog_get_info_by_fd(prog_fd, \u0026prog_info, \u0026info_len);\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c:183:\t\tif (!ASSERT_ERR(err, \"bpf_prog_get_info_by_fd\") ||\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c:184:\t\t\t\t!ASSERT_EQ(errno, EFAULT, \"bpf_prog_get_info_by_fd\"))\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-185-\t\t\tbreak;\n--\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-191-\t\tprog_info.nr_map_ids = 2;\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c:192:\t\terr = bpf_prog_get_info_by_fd(prog_fd, \u0026prog_info, \u0026info_len);\ntools/testing/selftests/bpf/prog_tests/bpf_obj_id.c-193-\t\tprog_infos[i].jited_prog_insns = 0;\n\n"
}

43/3 2026/10/05 15:17 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 76411
							output: 510
							thoughts: 2234
						

Thoughts:
**KMSAN Needs Analysis for BPF Kfunc Inlining**

Okay, let's break this down systematically. My primary concern here is ensuring this patch series doesn't introduce any new risks related to uninitialized memory. I'm focusing on the interaction between user and kernel space, and how data flows through this new BPF kfunc inlining functionality.

First, I need to understand how the BPF instructions are handled. I see that `bpf_prog_get_info_by_fd` copies instructions to user space. It seems that the kernel instructions are fully initialized. Further, I know that `do_jit` is the function that generates `prog->bpf_func`. Therefore, there should be no memory uninitialized to copy.

I've got to carefully assess where the potential risks lie: the instruction decoder and JIT emitter code (in `kfunc_copy_insn`, `kfunc_copy`), the verifier (`bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `kfunc_bind`, `bpf_restore_kfunc_calls`, `bpf_free_kfunc_inlines`), and the BTF-related functions (`btf_add_kfunc_bodies`, `btf_check_kfunc_body`). I need to make sure there are no new vulnerabilities related to invalid opcodes, out-of-bounds reads/writes, and JIT code generation and their potential invalid CPU instruction execution or crash. However, these risks can be detected by KASAN.

I need to confirm there's no data being passed uninitialized to user space, or that there is no conditional logic that depends on uninitialized kernel variables. All the variables used in the newly added and modified code are initialized before read. This includes variables in the `kfunc_copy_insn`, `kfunc_copy`, `bpf_jit_inline_kfunc`, `btf_check_kfunc_body`, `bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `kfunc_native_ok`, and `kfunc_bind` functions. I need to make sure that the memory that is copied into the user space is fully written.

The kfuncs themselves, like `bpf_load_be64` which might seem risky for uninitialized memory exposure, are safe because the verifier ensures memory validity before allowing loads. Other kfuncs are pure math or use the verifier for bounds and permissions.

Now, let's apply the KMSAN guidelines. Considering the KMSAN guidelines, this patch series doesn't appear to introduce any uninitialized memory risks that would be uniquely detected by KMSAN. No kernel structures are sent to user space with uninitialized data, there's no conditional logic based on uninitialized variables, all complex data structures are initialized, and there are no new bounds checks that could lead to uninitialized byte access. All stack and heap structures are zeroed or initialized before use. The potential bugs found are memory corruption or bounds bugs, directly caught by KASAN. I've confirmed that the BPF JIT code is not instrumented by KMSAN. Therefore, `NeedsKMSAN` should be set to `false`. I feel confident this is the right call. It's time to set the results and move on.



44/3 2026/10/05 15:17 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series introduces BPF inline kfuncs, allowing kfuncs to provide BPF instruction bodies and native x86-64 inline/copied implementations.\n\n1. Analysis of Memory Allocation and Initialization:\n- In `bpf_inline_kfunc_bodies()`, `env-\u003ekfunc_inlines` is allocated using `kvzalloc_objs`, ensuring all inline descriptors are zero-initialized.\n- In `bpf_add_kfunc_call()`, descriptor allocations are zeroed with `memset(desc, 0, sizeof(*desc))`.\n- When expanding `insn_aux_data` in `bpf_patch_insn_data()`, memory is allocated with `__GFP_ZERO`.\n- Stack buffers such as `code` in `bpf_restore_kfunc_calls()` and `kfunc_copy()` are written sequentially and completely up to the returned `len` bytes prior to `kmemdup()` and copying into the JIT image.\n\n2. Absence of Kernel-to-User Info-Leaks or Uninitialized Reads:\n- No new or modified kernel data structures are exposed to userspace via `copy_to_user`, netlink, socket options, or syscalls without full initialization.\n- Control flow and branching logic throughout the new verifier passes (`bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `kfunc_bind`, `bpf_restore_kfunc_calls`) depend only on initialized state fields, instruction opcodes, and BTF metadata.\n\n3. KASAN vs KMSAN Applicability:\n- Potential failure modes in this patch involve bounds checking during x86 instruction decoding/copying (`kfunc_copy`, `kfunc_copy_insn`), out-of-bounds indexing in `kfunc_bind()`, or invalid JIT native code generation. These are out-of-bounds access or control-flow bugs that fall within the scope of KASAN and standard kernel debuggers.\n- Furthermore, BPF JIT generated instructions are not instrumented by KMSAN.\n- As there are no uninitialized memory risks or kernel-to-user info-leak vectors unique to KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series introduces BPF inline kfuncs, allowing kfuncs to provide BPF instruction bodies and native x86-64 inline/copied implementations.\n\n1. Analysis of Memory Allocation and Initialization:\n- In `bpf_inline_kfunc_bodies()`, `env-\u003ekfunc_inlines` is allocated using `kvzalloc_objs`, ensuring all inline descriptors are zero-initialized.\n- In `bpf_add_kfunc_call()`, descriptor allocations are zeroed with `memset(desc, 0, sizeof(*desc))`.\n- When expanding `insn_aux_data` in `bpf_patch_insn_data()`, memory is allocated with `__GFP_ZERO`.\n- Stack buffers such as `code` in `bpf_restore_kfunc_calls()` and `kfunc_copy()` are written sequentially and completely up to the returned `len` bytes prior to `kmemdup()` and copying into the JIT image.\n\n2. Absence of Kernel-to-User Info-Leaks or Uninitialized Reads:\n- No new or modified kernel data structures are exposed to userspace via `copy_to_user`, netlink, socket options, or syscalls without full initialization.\n- Control flow and branching logic throughout the new verifier passes (`bpf_inline_kfunc_bodies`, `bpf_mark_kfunc_body_regs`, `kfunc_bind`, `bpf_restore_kfunc_calls`) depend only on initialized state fields, instruction opcodes, and BTF metadata.\n\n3. KASAN vs KMSAN Applicability:\n- Potential failure modes in this patch involve bounds checking during x86 instruction decoding/copying (`kfunc_copy`, `kfunc_copy_insn`), out-of-bounds indexing in `kfunc_bind()`, or invalid JIT native code generation. These are out-of-bounds access or control-flow bugs that fall within the scope of KASAN and standard kernel debuggers.\n- Furthermore, BPF JIT generated instructions are not instrumented by KMSAN.\n- As there are no uninitialized memory risks or kernel-to-user info-leak vectors unique to KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "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)