Skip to contentSkip to conversation

arm64: ftrace: support CALL_OPS on kernels built with kCFI

PATCH Superseded Jose Fernandez (Anthropic) 4 participants 14 messages Sep 24 – Sep 27

Subsystems (9)
Kbuild BPF arm64 Tracing +5 more subsystems

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover arm64: ftrace: support CALL_OPS on kernels built with kCFI

CALL_OPS and kCFI have been mutually exclusive on arm64 since commit baaf553d3bc3 ("arm64: Implement HAVE_DYNAMIC_FTRACE_WITH_CALL_OPS"). kCFI checks the type hash at a fixed offset before the entry point, so every function needs the same number of prefix NOPs. Before clang 21 the compiler could not emit prefix NOPs without also adding the function to ftrace's table. Since commit 9315e22b0c0a ("arm64: ftrace: allow DIRECT_CALLS without CALL_OPS") a kCFI kernel can attach BPF trampolines. A trampoline out of BL range is reached through ftrace_caller. That path costs ~10 ns more per call than on a CALL_OPS kernel, plus ~4 ns for every extra ftrace_ops registered. Clang 21 takes a section name as a third argument of -fpatchable-function-entry [1]. This series uses it to give every function three prefix NOPs while keeping untraced functions out of ftrace's table, and enables CALL_OPS under kCFI. The per-call cost drops by ~10 ns and stops growing with the number of ftrace_ops registered.

Patch 1 frees the page group of a module whose patch sites are all skipped, which patch 2 can cause. Patch 2 lets core ftrace skip a patch site the architecture rejects, which patch 5 relies on. Patch 3 takes the sorttable entry offset from Kconfig. Patch 4 lets notrace keep the prefix NOPs. Patch 5 makes the arm64 prefix layout configurable and refuses patch sites that do not fit. Patch 6 applies the prefix count where the type hash is emitted or read by hand. Patch 7 adds the compiler probe and enables CALL_OPS under CFI. Patch 8 uses five NOPs on ThinLTO kernels with BTI. Patch 9 gives Rust functions the same prefix NOPs.

The cost is text size, 4.8% of .text on a defconfig-based build with CFI and 7.4% with ThinLTO and BTI. CALL_OPS under CFI needs clang 21 or later, and Rust 1.98 or later with RUST=y. Commit d3359af21fc9e ("arm64:
bti: Disable in-kernel BTI with recent versions of Clang") turns BTI off on clang 21 or later, so a mainline build has one or the other today. A module must be built with the same prefix count as its kernel, since vermagic does not carry the count.

Numbers below are from a KVM guest on a Graviton4 host, v7.3-rc1 with and without this series, clang 21.1.4. Cost of a fentry program on a syscall, per call, the call with the program attached minus the call without it:

  Kernel            | Trampoline   | Extra      || Per-call cost (ns)
                    | vs. BL range | ftrace_ops || Median | Min  | Max
  ==================+==============+============++========+======+======
  kCFI, base        | out of range |          0 ||   32.9 | 32.6 | 33.4
  kCFI, base        | out of range |         16 ||   92.6 | 92.4 | 96.3
  kCFI, base        | in range     |          0 ||   21.3 | 21.0 | 21.8
  ------------------+--------------+------------++--------+------+------
  kCFI, this series | out of range |          0 ||   22.7 | 22.0 | 22.9
  kCFI, this series | out of range |         16 ||   22.1 | 21.9 | 22.4
  kCFI, this series | in range     |          0 ||   22.4 | 22.1 | 22.6

------------------+--------------+------------++--------+------+------

Mark Rutland discussed the uniform prefix with a section for untraced entries in 2022 [2]. His review of the DIRECT_CALLS series raised the cost of the ftrace_caller path [3]. Josh Poimboeuf's objtool support for arm64 livepatch [4] detects the prefix by the CALL_OPS layout and treats kCFI and CALL_OPS as never meeting, which this series changes.

[1] https://github.com/llvm/llvm-project/pull/131230
[2] https://lore.kernel.org/all/Y1LBGZPMfCZ8A1bl@FVFF77S0Q05N/
[3] https://lore.kernel.org/all/amjnf5gz0xP5PTSB@J2N7QTR9R3/
[4] https://lore.kernel.org/all/[email protected]/

---
Changes in v2:
- Drop the RFC tag.
- New patch 1: free the page group of a module whose patch sites are all skipped (sashiko on v1 patch 1). Tested on arm64 under KVM with

  KASAN: a module built without the prefix NOPs, loaded 20 times,
  leaks one page group per load without it and none with it.

- Patch 2: comment the new check in ftrace_process_locs() (Steven
Rostedt).
- Patch 3: comment the 0 case of the sorttable Makefile guard (bpf-ci).
- Patches 4 and 9: reword the bindgen comments, the flag can go because
removing it does not change the ABI (Miguel Ojeda).
- Patch 9: filter -fpatchable-function-entry out of bindgen's flags on
the bindgen_c_flags_final line, so GCC builds are covered too
(Miguel Ojeda).
- Link to v1: https://patch.msgid.link/[email protected]

---
Jose Fernandez (Anthropic) (9):
ftrace: Do not leak a module's empty page group
ftrace: Let ftrace_call_adjust() reject a patch site scripts/sorttable: Make the arm64 before_func offset configurable
compiler_types: Let notrace keep the function prefix NOPs
arm64: ftrace: Make the CALL_OPS prefix layout configurable
arm64: cfi: Use CONFIG_ARM64_FUNCTION_PREFIX_NOPS for the type hash offset
arm64: ftrace: Support CALL_OPS on kernels built with kCFI
arm64: ftrace: Use five prefix NOPs on ThinLTO kernels with BTI
arm64: ftrace: Allow CALL_OPS on kCFI kernels built with Rust

 arch/arm64/Kconfig                    |  27 +++++++-
 arch/arm64/Makefile                   |  15 ++++-
 arch/arm64/include/asm/cfi.h          |   8 +++
 arch/arm64/include/asm/ftrace.h       |  16 +++++
 arch/arm64/include/asm/linkage.h      |  11 ++++
 arch/arm64/kernel/entry-ftrace.S      |  16 ++---
 arch/arm64/kernel/ftrace.c            | 120 +++++++++++++++++++---------------
 arch/arm64/kernel/pi/Makefile         |   2 +
 arch/arm64/kernel/vdso/Makefile       |   2 +-
 arch/arm64/net/bpf_jit_comp.c         |   8 ++-
 drivers/firmware/efi/libstub/Makefile |   2 +-
 include/linux/compiler_types.h        |   9 +++
 kernel/trace/ftrace.c                 |  19 ++++++
 rust/Makefile                         |   7 +-
 scripts/Makefile                      |   4 ++
 scripts/sorttable.c                   |   7 +-
 16 files changed, 206 insertions(+), 67 deletions(-)

---
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
change-id: 20260904-b4-arm64-callops-kcfi-40016eed4fb0

Best regards,

Signature · 1 line
Jose Fernandez (Anthropic) <[email protected]>
#1 lore raw

PATCH v2 1/9 ftrace: Do not leak a module's empty page group

When every mcount_loc entry of a module is skipped, ftrace_process_locs() leaves the module's first page group linked with no records. ftrace_release_mod() matches a module's groups by records[0].ip, which is 0 here, so the group is never freed. While it stays linked, ftrace_free_mem() reads pg->records[pg->index - 1] with pg->index == 0 on every later module load, as lookup_rec() did before commit ee92fa443358f ("ftrace: Fix invalid address access in lookup_rec() when index is 0").

Unlink and free the new page groups when none of them got a record.

---
 kernel/trace/ftrace.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
kernel/trace/ftrace.c +14 -0
index f9d80c7bd9f16..2cc2d41353c10 100644
@@ -7689,6 +7689,20 @@ static int ftrace_process_locs(struct module *mod,
 		rec->ip = addr;
 	}
 
+	/*
+	 * ftrace_release_mod() finds a module's page groups by their first
+	 * record. If every entry was skipped there is none, so unlink the
+	 * new page groups and free them now.
+	 */
+	if (mod && !start_pg->index) {
+		ftrace_pages->next = NULL;
+		mutex_unlock(&ftrace_lock);
+		/* Need to synchronize with ftrace_location_range() */
+		synchronize_rcu();
+		ftrace_free_pages(start_pg);
+		return 0;
+	}
+
 	if (pg->next) {
 		pg_unuse = pg->next;
 		pg->next = NULL;
Signature · 1 line
2.52.0
#2 lore raw

PATCH v2 2/9 ftrace: Let ftrace_call_adjust() reject a patch site

In reply to Jose Fernandez (Anthropic)

When ftrace_call_adjust() returns 0 for a patch site, ftrace_process_locs() does not skip the site. The NULL test runs before the adjustment since commit 6eeca746fa5f ("ftrace: Test mcount_loc addr before calling ftrace_call_addr()"), so the 0 is stored as the record's ip and ftrace_init_nop() later hits the BUG_ON() in arm64's patch_map(). Test the adjusted address too and count the site as skipped.

---
 kernel/trace/ftrace.c | 5 +++++
 1 file changed, 5 insertions(+)
kernel/trace/ftrace.c +5 -0
index 2cc2d41353c10..fa541d3e8784a 100644
@@ -7676,6 +7676,11 @@ static int ftrace_process_locs(struct module *mod,
 		}
 
 		addr = ftrace_call_adjust(addr);
+		/* The architecture may return 0 to reject a patch site */
+		if (!addr) {
+			skipped++;
+			continue;
+		}
 
 		end_offset = (pg->index+1) * sizeof(pg->records[0]);
 		if (end_offset > PAGE_SIZE << pg->order) {
Signature · 1 line
2.52.0
#3 lore raw

PATCH v2 3/9 scripts/sorttable: Make the arm64 before_func offset configurable

In reply to Jose Fernandez (Anthropic)

sorttable hardcodes before_func to 8 bytes on arm64 (two prefix NOPs). Make it configurable from CONFIG_ARM64_FUNCTION_PREFIX_NOPS instead. kCFI kernels with CALL_OPS need three NOPs. The symbol does not exist yet, so no functional change.

---
 scripts/Makefile    | 4 ++++
 scripts/sorttable.c | 7 ++++++-
 2 files changed, 10 insertions(+), 1 deletion(-)
scripts/Makefile +4 -0
index 3434a82a119f0..daad9b9540b8d 100644
@@ -51,6 +51,10 @@ endif
 
 ifdef CONFIG_BUILDTIME_MCOUNT_SORT
 HOSTCFLAGS_sorttable.o += -DMCOUNT_SORT_ENABLED
+# 0 or unset (no prefix NOPs) leaves sorttable's built-in default in place.
+ifneq ($(filter-out 0,$(CONFIG_ARM64_FUNCTION_PREFIX_NOPS)),)
+HOSTCFLAGS_sorttable.o += -DFUNCTION_PREFIX_BYTES=$(shell expr 4 \* $(CONFIG_ARM64_FUNCTION_PREFIX_NOPS))
+endif
 endif
 
 # The following programs are only built on demand
scripts/sorttable.c +6 -1
index d8dc2a1b7c312..925382bb23dcc 100644
@@ -281,6 +281,11 @@ static int add_field(uint64_t addr, uint64_t size)
 /* Used for when mcount/fentry is before the function entry */
 static int before_func;
 
+/* How far before the function entry a patchable entry may be recorded */
+#ifndef FUNCTION_PREFIX_BYTES
+#define FUNCTION_PREFIX_BYTES	8
+#endif
+
 /* Only return match if the address lies inside the function size */
 static int cmp_func_addr(const void *K, const void *A)
 {
@@ -899,7 +904,7 @@ static int do_file(char const *const fname, void *addr)
 		/* fallthrough */
 	case EM_RISCV:
 		/* arm64 and RISC-V place patchable entries before the function. */
-		before_func = 8;
+		before_func = FUNCTION_PREFIX_BYTES;
 #else
 	case EM_AARCH64:
 	case EM_RISCV:
Signature · 1 line
2.52.0
#4 lore raw

PATCH v2 4/9 compiler_types: Let notrace keep the function prefix NOPs

In reply to Jose Fernandez (Anthropic)

Let notrace keep the prefix NOPs when the architecture defines CC_USING_PATCHABLE_FUNCTION_PREFIX. kCFI callers check the type hash at a fixed offset before the entry point, so a notrace function needs the same prefix NOPs as any other. Record the entry in a section the linker drops, so ftrace never sees it. Clang 21 takes a section name as a third argument of the attribute. Nothing defines the macro yet, so no functional change.

---
 include/linux/compiler_types.h | 9 +++++++++
 1 file changed, 9 insertions(+)
include/linux/compiler_types.h +9 -0
index c5921f1390079..43dafaa061942 100644
@@ -211,6 +211,15 @@ struct ftrace_likely_data {
 
 #if defined(CC_USING_HOTPATCH)
 #define notrace			__attribute__((hotpatch(0, 0)))
+#elif defined(CC_USING_PATCHABLE_FUNCTION_PREFIX) && !defined(__BINDGEN__)
+/*
+ * Not for bindgen: its libclang may not support the section argument
+ * (Clang >= 21), and leaving the attribute out does not change the ABI.
+ */
+#define notrace								\
+	__attribute__((patchable_function_entry(CC_USING_PATCHABLE_FUNCTION_PREFIX, \
+						 CC_USING_PATCHABLE_FUNCTION_PREFIX, \
+						 ".discard.patchable_function_entries")))
 #elif defined(CC_USING_PATCHABLE_FUNCTION_ENTRY)
 #define notrace			__attribute__((patchable_function_entry(0, 0)))
 #else
Signature · 1 line
2.52.0
#5 lore raw

PATCH v2 5/9 arm64: ftrace: Make the CALL_OPS prefix layout configurable

In reply to Jose Fernandez (Anthropic)

The arm64 ftrace code assumes two NOPs before every function in several places. Replace the hardcoded count with a Kconfig value named CONFIG_ARM64_FUNCTION_PREFIX_NOPS that defaults to 2. Compute the ops literal address with one formula in both the assembly that reads it and the C code that writes it. kCFI kernels with CALL_OPS need three NOPs, or five with ThinLTO and BTI, and the reader and the writer stay in sync either way.

Also make ftrace_call_adjust() look at each site's bytes and refuse the ones that do not match the expected layout instead of patching them. The two instructions to patch must be NOPs and the literal must fall within the prefix NOPs. Log a refused site and leave it untraced.

No functional change for the layouts compilers generate today.

---
 arch/arm64/Kconfig               |   5 ++
 arch/arm64/include/asm/ftrace.h  |  16 ++++++
 arch/arm64/kernel/entry-ftrace.S |  16 +++---
 arch/arm64/kernel/ftrace.c       | 120 ++++++++++++++++++++++-----------------
 4 files changed, 98 insertions(+), 59 deletions(-)
arch/arm64/Kconfig +5 -0
index b5a51b0ef9440..9fbcf12a3808b 100644
@@ -276,6 +276,11 @@ config GCC_SUPPORTS_DYNAMIC_FTRACE_WITH_ARGS
 	def_bool CC_IS_GCC
 	depends on $(cc-option,-fpatchable-function-entry=2)
 
+config ARM64_FUNCTION_PREFIX_NOPS
+	int
+	default 2 if DYNAMIC_FTRACE_WITH_CALL_OPS
+	default 0
+
 config 64BIT
 	def_bool y
 
arch/arm64/include/asm/ftrace.h +16 -0
index 1621c84f44b32..5a7a515bf7cdc 100644
@@ -24,6 +24,22 @@
 #define FTRACE_PLT_IDX		0
 #define NR_FTRACE_PLTS		1
 
+#ifdef CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS
+/*
+ * ftrace_caller reads the callsite's ftrace_ops literal at
+ * ALIGN_DOWN(LR, 8) - FTRACE_CALL_OPS_BIAS. See ftrace_call_ops_adjust()
+ * for the layouts this serves.
+ */
+#define FTRACE_PREFIX_NOPS	CONFIG_ARM64_FUNCTION_PREFIX_NOPS
+#if FTRACE_PREFIX_NOPS == 2 || FTRACE_PREFIX_NOPS == 3
+#define FTRACE_CALL_OPS_BIAS	16
+#elif FTRACE_PREFIX_NOPS == 5
+#define FTRACE_CALL_OPS_BIAS	24
+#else
+#error "Unsupported number of function prefix NOPs"
+#endif
+#endif /* CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS */
+
 /*
  * Currently, gcc tends to save the link register after the local variables
  * on the stack. This causes the max stack tracer to report the function
arch/arm64/kernel/entry-ftrace.S +8 -8
index 025140caafe74..95727fee3cc55 100644
@@ -39,17 +39,17 @@ SYM_CODE_START(ftrace_caller)
 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS
 	/*
 	 * The literal pointer to the ops is at an 8-byte aligned boundary
-	 * which is either 12 or 16 bytes before the BL instruction in the call
-	 * site. See ftrace_call_adjust() for details.
+	 * before the BL instruction in the call site. See ftrace_call_adjust()
+	 * and <asm/ftrace.h> for details.
 	 *
-	 * Therefore here the LR points at `literal + 16` or `literal + 20`,
-	 * and we can find the address of the literal in either case by
-	 * aligning to an 8-byte boundary and subtracting 16. We do the
-	 * alignment first as this allows us to fold the subtraction into the
-	 * LDR.
+	 * Therefore here the LR points at `literal + FTRACE_CALL_OPS_BIAS` or
+	 * `literal + FTRACE_CALL_OPS_BIAS + 4`, and we can find the address of
+	 * the literal in either case by aligning to an 8-byte boundary and
+	 * subtracting FTRACE_CALL_OPS_BIAS. We do the alignment first as this
+	 * allows us to fold the subtraction into the LDR.
 	 */
 	bic	x11, x30, 0x7
-	ldr	x11, [x11, #-(4 * AARCH64_INSN_SIZE)]		// op
+	ldr	x11, [x11, #-FTRACE_CALL_OPS_BIAS]		// op
 
 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
 	/*
arch/arm64/kernel/ftrace.c +69 -51

138 lines not on this page · raw message

Signature · 1 line
2.52.0
#6 lore raw

PATCH v2 6/9 arm64: cfi: Use CONFIG_ARM64_FUNCTION_PREFIX_NOPS for the type hash offset

In reply to Jose Fernandez (Anthropic)

Make cfi_get_offset(), SYM_TYPED_FUNC_START and the BPF JIT use CONFIG_ARM64_FUNCTION_PREFIX_NOPS instead of hardcoding four bytes. kCFI kernels with CALL_OPS need three NOPs, or five with ThinLTO and BTI.

CONFIG_ARM64_FUNCTION_PREFIX_NOPS is 0 on every CFI kernel today, so no functional change.

---
 arch/arm64/include/asm/cfi.h     |  8 ++++++++
 arch/arm64/include/asm/linkage.h | 11 +++++++++++
 arch/arm64/net/bpf_jit_comp.c    |  8 ++++++--
 3 files changed, 25 insertions(+), 2 deletions(-)
arch/arm64/include/asm/cfi.h +8 -0
index ab90f0351b7ae..03f02d4614c23 100644
@@ -4,4 +4,12 @@
 
 #define __bpfcall
 
+#ifdef CONFIG_CFI
+static inline int cfi_get_offset(void)
+{
+	return 4 + 4 * CONFIG_ARM64_FUNCTION_PREFIX_NOPS;
+}
+#define cfi_get_offset cfi_get_offset
+#endif /* CONFIG_CFI */
+
 #endif /* _ASM_ARM64_CFI_H */
arch/arm64/include/asm/linkage.h +11 -0
index d1f7a16729d25..14bc3c67c38b3 100644
@@ -39,6 +39,17 @@
 	SYM_START(name, SYM_L_WEAK, SYM_A_NONE)		\
 	bti c ;
 
+/*
+ * The compiler emits CONFIG_ARM64_FUNCTION_PREFIX_NOPS NOPs between a C
+ * function's kCFI type hash and its entry point. Callers check the hash
+ * at that offset.
+ */
+#define __CFI_TYPE(name)				\
+	.4byte __kcfi_typeid_##name ASM_NL		\
+	.rept CONFIG_ARM64_FUNCTION_PREFIX_NOPS ASM_NL	\
+	nop ASM_NL					\
+	.endr
+
 #define SYM_TYPED_FUNC_START(name)				\
 	SYM_TYPED_START(name, SYM_L_GLOBAL, SYM_A_ALIGN)	\
 	bti c ;
arch/arm64/net/bpf_jit_comp.c +6 -2
index c18e005a41dbe..7ad14d9847138 100644
@@ -185,8 +185,12 @@ static inline void emit_bti(u32 insn, struct jit_ctx *ctx)
 
 static inline void emit_kcfi(u32 hash, struct jit_ctx *ctx)
 {
-	if (IS_ENABLED(CONFIG_CFI))
-		emit_u32_data(hash, ctx);
+	if (!IS_ENABLED(CONFIG_CFI))
+		return;
+
+	emit_u32_data(hash, ctx);
+	for (int i = 0; i < CONFIG_ARM64_FUNCTION_PREFIX_NOPS; i++)
+		emit(A64_NOP, ctx);
 }
 
 /*
Signature · 1 line
2.52.0
Acked-by on v2 6/9
#7 lore raw

Re: [PATCH v2 6/9] arm64: cfi: Use CONFIG_ARM64_FUNCTION_PREFIX_NOPS for the type hash offset

arch/arm64/net/bpf_jit_comp.c static inline void emit_bti(u32 insn, struct jit_ctx *ctx) · line 194

Quoted 11 lines · Jose Fernandez (Anthropic)

static inline void emit_kcfi(u32 hash, struct jit_ctx *ctx) {

arch/arm64/net/bpf_jit_comp.c +6 -2
-	if (IS_ENABLED(CONFIG_CFI))
-		emit_u32_data(hash, ctx);
+	if (!IS_ENABLED(CONFIG_CFI))
+		return;
+
+	emit_u32_data(hash, ctx);
+	for (int i = 0; i < CONFIG_ARM64_FUNCTION_PREFIX_NOPS; i++)
+		emit(A64_NOP, ctx);
 }

For the series:

unrelated minor issue:
ctx.offset[] is counted from ro_image, but bpf_prog_fill_jited_linfo() adds it to prog->bpf_func which is ro_image + cfi_get_offset(). So with CFI jited_line_info is already off by one insn. After this patch it will be off by 4 or 6.
s390 does

	jit.addrs[i] -= cfi_get_offset();

before the call.
Would be great to send a follow up eventually.

#8 lore raw

Re: [PATCH v2 6/9] arm64: cfi: Use CONFIG_ARM64_FUNCTION_PREFIX_NOPS for the type hash offset

In reply to Jose Fernandez (Anthropic)
Quoted 23 lines · Jose Fernandez (Anthropic)

Make cfi_get_offset(), SYM_TYPED_FUNC_START and the BPF JIT use CONFIG_ARM64_FUNCTION_PREFIX_NOPS instead of hardcoding four bytes. kCFI kernels with CALL_OPS need three NOPs, or five with ThinLTO and BTI.

CONFIG_ARM64_FUNCTION_PREFIX_NOPS is 0 on every CFI kernel today, so no functional change.

---
 arch/arm64/include/asm/cfi.h     |  8 ++++++++
 arch/arm64/include/asm/linkage.h | 11 +++++++++++
 arch/arm64/net/bpf_jit_comp.c    |  8 ++++++--
 3 files changed, 25 insertions(+), 2 deletions(-)
arch/arm64/include/asm/cfi.h +0 -0
index ab90f0351b7ae..03f02d4614c23 100644

arch/arm64/include/asm/cfi.h line 10

Quoted 7 lines
arch/arm64/include/asm/cfi.h +4 -0
@@ -4,4 +4,12 @@
 
 #define __bpfcall
 
+#ifdef CONFIG_CFI
+static inline int cfi_get_offset(void)
+{
+       return 4 + 4 * CONFIG_ARM64_FUNCTION_PREFIX_NOPS;

*drive by review* Could you explain the two fours in this equation with a comment? (Feel free to ignore this if it's obvious to developers.)

-bw

Quoted 50 lines
arch/arm64/include/asm/cfi.h +4 -0
+}
+#define cfi_get_offset cfi_get_offset
+#endif /* CONFIG_CFI */
+
 #endif /* _ASM_ARM64_CFI_H */
arch/arm64/include/asm/linkage.h +11 -0
index d1f7a16729d25..14bc3c67c38b3 100644
@@ -39,6 +39,17 @@
        SYM_START(name, SYM_L_WEAK, SYM_A_NONE)         \
        bti c ;
 
+/*
+ * The compiler emits CONFIG_ARM64_FUNCTION_PREFIX_NOPS NOPs between a C
+ * function's kCFI type hash and its entry point. Callers check the hash
+ * at that offset.
+ */
+#define __CFI_TYPE(name)                               \
+       .4byte __kcfi_typeid_##name ASM_NL              \
+       .rept CONFIG_ARM64_FUNCTION_PREFIX_NOPS ASM_NL  \
+       nop ASM_NL                                      \
+       .endr
+
 #define SYM_TYPED_FUNC_START(name)                             \
        SYM_TYPED_START(name, SYM_L_GLOBAL, SYM_A_ALIGN)        \
        bti c ;
arch/arm64/net/bpf_jit_comp.c +6 -3
index c18e005a41dbe..7ad14d9847138 100644
@@ -185,8 +185,12 @@ static inline void emit_bti(u32 insn, struct jit_ctx *ctx)
 
 static inline void emit_kcfi(u32 hash, struct jit_ctx *ctx)
 {
-       if (IS_ENABLED(CONFIG_CFI))
-               emit_u32_data(hash, ctx);
+       if (!IS_ENABLED(CONFIG_CFI))
+               return;
+
+       emit_u32_data(hash, ctx);
+       for (int i = 0; i < CONFIG_ARM64_FUNCTION_PREFIX_NOPS; i++)
+               emit(A64_NOP, ctx);
 }
 
 /*
 
--

2.52.0

#9 lore raw

Re: [PATCH v2 6/9] arm64: cfi: Use CONFIG_ARM64_FUNCTION_PREFIX_NOPS for the type hash offset

Quoted 5 lines · Bill Wendling
Quoted 1 line

+ return 4 + 4 * CONFIG_ARM64_FUNCTION_PREFIX_NOPS;

*drive by review* Could you explain the two fours in this equation with a comment? (Feel free to ignore this if it's obvious to developers.)

The first is the type hash and the second is the size of a NOP. For v3 I'll spell the second one out and add a comment for the first.

	/* The 4-byte type hash sits before the prefix NOPs. */
	return 4 + CONFIG_ARM64_FUNCTION_PREFIX_NOPS * AARCH64_INSN_SIZE;

- Jose

#10 lore raw

PATCH v2 7/9 arm64: ftrace: Support CALL_OPS on kernels built with kCFI

In reply to Jose Fernandez (Anthropic)

CALL_OPS and kCFI have been mutually exclusive on arm64 since commit baaf553d3bc3 ("arm64: Implement HAVE_DYNAMIC_FTRACE_WITH_CALL_OPS"). kCFI checks the type hash at a fixed offset before the entry point, so every function needs the same number of prefix NOPs. Before clang 21, prefix NOPs came only with an entry in ftrace's table, and untraced functions had none. Since commit 9315e22b0c0a ("arm64: ftrace: allow DIRECT_CALLS without CALL_OPS") a kCFI kernel can attach BPF trampolines. But without CALL_OPS, a trampoline out of BL range is reached through ftrace_caller, ~10 ns more per call than on a CALL_OPS kernel, plus ~4 ns for every extra ftrace_ops registered.

Clang 21 added a third argument to -fpatchable-function-entry that names the section the entries go to [1]. Point it at a section the linker scripts already drop and a function gets prefix NOPs with no entry in ftrace's table. When CFI and CALL_OPS are both enabled, compile every object with -fpatchable-function-entry=M,M,.discard.patchable_function_entries, where M is CONFIG_ARM64_FUNCTION_PREFIX_NOPS.

Gate CALL_OPS under CFI on ARM64_CFI_PERMITS_CALL_OPS, which needs clang 21 or newer and RUST off. rustc has its own flag for the prefix NOPs and this patch does not pass it, so Rust functions would have no prefix and a different hash offset.

M is 3 because the ops pointer needs an aligned 8-byte slot inside the prefix NOPs, and the 4-byte hash puts the NOPs at offset 4. A traced function, with the two entry NOPs from CC_FLAGS_FTRACE, then looks like this:

  func-16:            .word <hash>    // kCFI type hash
  func-12:            NOP
  func-08:            NOP             // ops pointer, 8 bytes
  func-04:            NOP             //
  func+00:    func:   NOP             // To be patched to MOV X9, LR
  func+04:            NOP             // To be patched to BL <caller>

Size of .text in vmlinux on a defconfig-based config with clang 21.1.4:

  Kernel                 || .text bytes | Delta       | Delta
  =======================++=============+=============+=======
  kCFI, base             ||  21,023,888 |             |
  kCFI, M = 3            ||  22,031,504 |  +1,007,616 | +4.8%
  -----------------------++-------------+-------------+-------

Numbers below are from a KVM guest on a Graviton4 host, v7.3-rc1 with and without this series. The workload is a fentry program on __arm64_sys_getpid, 20M calls per pass, six passes per boot, six boots, each cell the call with the program attached minus the call without it. The in-range rows are the same kernels booted with nokaslr.

  Kernel            | Trampoline   | Extra      || Per-call cost (ns)
                    | vs. BL range | ftrace_ops || Median | Min  | Max
  ==================+==============+============++========+======+======
  kCFI, base        | out of range |          0 ||   32.9 | 32.6 | 33.4
  kCFI, base        | out of range |         16 ||   92.6 | 92.4 | 96.3
  kCFI, base        | in range     |          0 ||   21.3 | 21.0 | 21.8
  ------------------+--------------+------------++--------+------+------
  kCFI, this series | out of range |          0 ||   22.7 | 22.0 | 22.9
  kCFI, this series | out of range |         16 ||   22.1 | 21.9 | 22.4
  kCFI, this series | in range     |          0 ||   22.4 | 22.1 | 22.6

------------------+--------------+------------++--------+------+------

Out of range this saves ~10 ns per call and the cost stops growing with extra ftrace_ops. In range both kernels branch straight to the trampoline and the numbers roughly match.

ftracetest and the BPF trampoline, struct_ops and kprobe_multi selftests pass with CFI enforcing.

[1] https://github.com/llvm/llvm-project/pull/131230

---
 arch/arm64/Kconfig                    | 15 ++++++++++++++-
 arch/arm64/Makefile                   | 12 +++++++++++-
 arch/arm64/kernel/pi/Makefile         |  2 ++
 arch/arm64/kernel/vdso/Makefile       |  2 +-
 drivers/firmware/efi/libstub/Makefile |  2 +-
 5 files changed, 29 insertions(+), 4 deletions(-)
arch/arm64/Kconfig +14 -1
index 9fbcf12a3808b..6e5fa009c11af 100644
@@ -190,7 +190,8 @@ config ARM64
 	select HAVE_DYNAMIC_FTRACE_WITH_DIRECT_CALLS \
 		if DYNAMIC_FTRACE_WITH_ARGS
 	select HAVE_DYNAMIC_FTRACE_WITH_CALL_OPS \
-		if (DYNAMIC_FTRACE_WITH_ARGS && !CFI && \
+		if (DYNAMIC_FTRACE_WITH_ARGS && \
+		    (!CFI || ARM64_CFI_PERMITS_CALL_OPS) && \
 		    (CC_IS_CLANG || !CC_OPTIMIZE_FOR_SIZE))
 	select FTRACE_MCOUNT_USE_PATCHABLE_FUNCTION_ENTRY \
 		if DYNAMIC_FTRACE_WITH_ARGS
@@ -276,8 +277,20 @@ config GCC_SUPPORTS_DYNAMIC_FTRACE_WITH_ARGS
 	def_bool CC_IS_GCC
 	depends on $(cc-option,-fpatchable-function-entry=2)
 
+config CC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
+	# The section argument needs clang 21 or later:
+	# https://github.com/llvm/llvm-project/pull/131230
+	def_bool $(cc-option,-fpatchable-function-entry=1$(comma)1$(comma).discard.patchable_function_entries)
+
+config ARM64_CFI_PERMITS_CALL_OPS
+	def_bool y
+	depends on CFI
+	depends on CC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
+	depends on !RUST
+
 config ARM64_FUNCTION_PREFIX_NOPS
 	int
+	default 3 if DYNAMIC_FTRACE_WITH_CALL_OPS && CFI
 	default 2 if DYNAMIC_FTRACE_WITH_CALL_OPS
 	default 0
 
arch/arm64/Makefile +11 -1
index 6b005c8fef706..653c1ed6ef38f 100644
@@ -142,7 +142,17 @@ CHECKFLAGS	+= -D__aarch64__
 
 ifeq ($(CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS),y)
   KBUILD_CPPFLAGS += -DCC_USING_PATCHABLE_FUNCTION_ENTRY
-  CC_FLAGS_FTRACE := -fpatchable-function-entry=4,2
+  prefix_nops := $(CONFIG_ARM64_FUNCTION_PREFIX_NOPS)
+  CC_FLAGS_FTRACE := -fpatchable-function-entry=$(shell expr $(prefix_nops) + 2),$(prefix_nops)
+  ifeq ($(CONFIG_CFI),y)
+    # Every object gets the prefix NOPs and no ftrace entry by default.
+    # CC_FLAGS_FTRACE comes later for traced objects and overrides the
+    # -fpatchable-function-entry.
+    CFI_PREFIX_CFLAGS := -fpatchable-function-entry=$(prefix_nops),$(prefix_nops),.discard.patchable_function_entries \
+			 -DCC_USING_PATCHABLE_FUNCTION_PREFIX=$(prefix_nops)
+    KBUILD_CFLAGS += $(CFI_PREFIX_CFLAGS)
+    export CFI_PREFIX_CFLAGS
+  endif
 else ifeq ($(CONFIG_DYNAMIC_FTRACE_WITH_ARGS),y)
   KBUILD_CPPFLAGS += -DCC_USING_PATCHABLE_FUNCTION_ENTRY
   CC_FLAGS_FTRACE := -fpatchable-function-entry=2
arch/arm64/kernel/pi/Makefile +2 -0
index be92d73c25b21..df9f78dd9daec 100644
@@ -18,6 +18,8 @@ CFLAGS_map_range.o += -mstrict-align
 KBUILD_CFLAGS	:= $(filter-out $(CC_FLAGS_SCS), $(KBUILD_CFLAGS))
 # disable LTO
 KBUILD_CFLAGS	:= $(filter-out $(CC_FLAGS_LTO), $(KBUILD_CFLAGS))
+# the discard section holds absolute relocations, which relacheck rejects
+KBUILD_CFLAGS	:= $(filter-out $(CFI_PREFIX_CFLAGS), $(KBUILD_CFLAGS))
 
 hostprogs	:= relacheck
 
arch/arm64/kernel/vdso/Makefile +1 -1
index 7dec05dd33b70..44f4a6622ccd2 100644
@@ -38,7 +38,7 @@ ccflags-y += -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO
 CC_FLAGS_REMOVE_VDSO := $(CC_FLAGS_FTRACE) -Os $(CC_FLAGS_SCS) \
 			$(RANDSTRUCT_CFLAGS) $(KSTACK_ERASE_CFLAGS) \
 			$(GCC_PLUGINS_CFLAGS) \
-			$(CC_FLAGS_LTO) $(CC_FLAGS_CFI) \
+			$(CC_FLAGS_LTO) $(CC_FLAGS_CFI) $(CFI_PREFIX_CFLAGS) \
 			-Wmissing-prototypes -Wmissing-declarations
 
 CC_FLAGS_ADD_VDSO := -O2 -mcmodel=tiny -fasynchronous-unwind-tables
drivers/firmware/efi/libstub/Makefile +1 -1
index 77a2b2d74f3f6..9fb4e23da4535 100644
@@ -53,7 +53,7 @@ KBUILD_CFLAGS := $(filter-out $(RANDSTRUCT_CFLAGS), $(KBUILD_CFLAGS))
 # remove SCS flags from all objects in this directory
 KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_SCS), $(KBUILD_CFLAGS))
 # disable CFI
-KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_CFI), $(KBUILD_CFLAGS))
+KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_CFI) $(CFI_PREFIX_CFLAGS), $(KBUILD_CFLAGS))
 # disable LTO
 KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_LTO), $(KBUILD_CFLAGS))
 
Signature · 1 line
2.52.0
#11 lore raw

PATCH v2 8/9 arm64: ftrace: Use five prefix NOPs on ThinLTO kernels with BTI

In reply to Jose Fernandez (Anthropic)

Default CONFIG_ARM64_FUNCTION_PREFIX_NOPS to 5 on ThinLTO kernels with BTI. Many functions there have a landing pad but no hash. That moves the entry point 4 bytes. The 8-byte slot lands on the landing pad and ftrace refuses the site. With five NOPs every function has a slot.

Commit d3359af21fc9e ("arm64: bti: Disable in-kernel BTI with recent versions of Clang") keeps BTI off on clang 21 or later, so this default does not trigger on a mainline build today. Josh Poimboeuf's series to bring it back is under review [1].

With five NOPs the series costs 7.4% of .text on a defconfig-based ThinLTO kernel with clang 21.1.4:

  Kernel                 || .text bytes | Delta       | Delta
  =======================++=============+=============+=======
  ThinLTO kCFI, base     ||  21,466,256 |             |
  ThinLTO kCFI, M = 5    ||  23,047,312 |  +1,581,056 | +7.4%
  -----------------------++-------------+-------------+-------

ftracetest results match with and without this series. The three failures on a ThinLTO kernel are pre-existing. The BPF trampoline, struct_ops and kprobe_multi selftests pass with CFI enforcing.

[1] https://lore.kernel.org/all/[email protected]/

---
 arch/arm64/Kconfig | 2 ++
 1 file changed, 2 insertions(+)
arch/arm64/Kconfig +2 -0
index 6e5fa009c11af..afa566e0fa86c 100644
@@ -290,6 +290,8 @@ config ARM64_CFI_PERMITS_CALL_OPS
 
 config ARM64_FUNCTION_PREFIX_NOPS
 	int
+	default 5 if DYNAMIC_FTRACE_WITH_CALL_OPS && CFI && \
+		     (LTO_CLANG_THIN || LTO_CLANG_THIN_DIST) && ARM64_BTI_KERNEL
 	default 3 if DYNAMIC_FTRACE_WITH_CALL_OPS && CFI
 	default 2 if DYNAMIC_FTRACE_WITH_CALL_OPS
 	default 0
Signature · 1 line
2.52.0
#12 lore raw

PATCH v2 9/9 arm64: ftrace: Allow CALL_OPS on kCFI kernels built with Rust

In reply to Jose Fernandez (Anthropic)

Pass -Zpatchable-function-entry=M,M,.discard.patchable_function_entries to rustc when CFI and CALL_OPS are both enabled, so Rust functions get the same prefix NOPs as C functions. The section argument needs Rust 1.98 [1]. Probe for it, and let ARM64_CFI_PERMITS_CALL_OPS accept RUST=y when the probe passes.

[1] https://github.com/rust-lang/rust/pull/157445

---
 arch/arm64/Kconfig  | 7 ++++++-
 arch/arm64/Makefile | 3 +++
 rust/Makefile       | 7 ++++++-
 3 files changed, 15 insertions(+), 2 deletions(-)
arch/arm64/Kconfig +6 -1
index afa566e0fa86c..cad2bdf3456ff 100644
@@ -282,11 +282,16 @@ config CC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
 	# https://github.com/llvm/llvm-project/pull/131230
 	def_bool $(cc-option,-fpatchable-function-entry=1$(comma)1$(comma).discard.patchable_function_entries)
 
+config RUSTC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
+	# The section argument needs Rust 1.98.0 or later:
+	# https://github.com/rust-lang/rust/pull/157445
+	def_bool $(rustc-option,-Zpatchable-function-entry=1$(comma)1$(comma).discard.patchable_function_entries)
+
 config ARM64_CFI_PERMITS_CALL_OPS
 	def_bool y
 	depends on CFI
 	depends on CC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
-	depends on !RUST
+	depends on !RUST || RUSTC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
 
 config ARM64_FUNCTION_PREFIX_NOPS
 	int
arch/arm64/Makefile +3 -0
index 653c1ed6ef38f..b23430e2b8567 100644
@@ -152,6 +152,9 @@ ifeq ($(CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS),y)
 			 -DCC_USING_PATCHABLE_FUNCTION_PREFIX=$(prefix_nops)
     KBUILD_CFLAGS += $(CFI_PREFIX_CFLAGS)
     export CFI_PREFIX_CFLAGS
+    # Rust functions are not patched by ftrace, but they are called indirectly
+    # from C and make indirect calls themselves, so they need the same prefix.
+    KBUILD_RUSTFLAGS += -Zpatchable-function-entry=$(prefix_nops),$(prefix_nops),.discard.patchable_function_entries
   endif
 else ifeq ($(CONFIG_DYNAMIC_FTRACE_WITH_ARGS),y)
   KBUILD_CPPFLAGS += -DCC_USING_PATCHABLE_FUNCTION_ENTRY
rust/Makefile +6 -1
index da1a7409d9845..b402ab768f729 100644
@@ -511,7 +511,12 @@ endif
 # prototypes for functions like `memcpy` -- if this flag is not passed,
 # `bindgen`-generated prototypes use `c_ulong` or `c_uint` depending on
 # architecture instead of generating `usize`.
-bindgen_c_flags_final = $(bindgen_c_flags_lto) -fno-builtin -D__BINDGEN__
+#
+# Do not pass -fpatchable-function-entry to bindgen: its libclang may not
+# support the section argument (Clang >= 21), and removing the flag does not
+# change the ABI.
+bindgen_c_flags_final = $(filter-out -fpatchable-function-entry=%, \
+	$(bindgen_c_flags_lto)) -fno-builtin -D__BINDGEN__
 
 # `--rust-target` points to our minimum supported Rust version.
 quiet_cmd_bindgen = BINDGEN $@
Signature · 1 line
2.52.0
#13 lore raw

Re: [PATCH v2 9/9] arm64: ftrace: Allow CALL_OPS on kCFI kernels built with Rust

This isn't a bug, but could the commit message mention that bindgen's C flags now drop -fpatchable-function-entry on all architectures, not just arm64 with CFI?
Quoted 41 lines
arch/arm64/Kconfig +6 -1
index afa566e0fa86..cad2bdf3456f 100644
@@ -282,11 +282,16 @@ config CC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
 	# https://github.com/llvm/llvm-project/pull/131230
 	def_bool $(cc-option,-fpatchable-function-entry=1$(comma)1$(comma).discard.patchable_function_entries)
 
+config RUSTC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
+	# The section argument needs Rust 1.98.0 or later:
+	# https://github.com/rust-lang/rust/pull/157445
+	def_bool $(rustc-option,-Zpatchable-function-entry=1$(comma)1$(comma).discard.patchable_function_entries)
+
 config ARM64_CFI_PERMITS_CALL_OPS
 	def_bool y
 	depends on CFI
 	depends on CC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
-	depends on !RUST
+	depends on !RUST || RUSTC_HAS_PATCHABLE_FUNCTION_ENTRY_SECTION
 
 config ARM64_FUNCTION_PREFIX_NOPS
 	int
arch/arm64/Makefile +3 -0
index 653c1ed6ef38..b23430e2b856 100644
@@ -152,6 +152,9 @@ ifeq ($(CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS),y)
 			 -DCC_USING_PATCHABLE_FUNCTION_PREFIX=$(prefix_nops)
     KBUILD_CFLAGS += $(CFI_PREFIX_CFLAGS)
     export CFI_PREFIX_CFLAGS
+    # Rust functions are not patched by ftrace, but they are called indirectly
+    # from C and make indirect calls themselves, so they need the same prefix.
+    KBUILD_RUSTFLAGS += -Zpatchable-function-entry=$(prefix_nops),$(prefix_nops),.discard.patchable_function_entries
   endif
 else ifeq ($(CONFIG_DYNAMIC_FTRACE_WITH_ARGS),y)
   KBUILD_CPPFLAGS += -DCC_USING_PATCHABLE_FUNCTION_ENTRY
rust/Makefile +0 -0
index da1a7409d984..b402ab768f72 100644

rust/Makefile endif · line 519

Quoted 10 lines
rust/Makefile +6 -1
@@ -511,7 +511,12 @@ endif
 # prototypes for functions like `memcpy` -- if this flag is not passed,
 # `bindgen`-generated prototypes use `c_ulong` or `c_uint` depending on
 # architecture instead of generating `usize`.
-bindgen_c_flags_final = $(bindgen_c_flags_lto) -fno-builtin -D__BINDGEN__
+#
+# Do not pass -fpatchable-function-entry to bindgen: its libclang may not
+# support the section argument (Clang >= 21), and removing the flag does not
+# change the ABI.
+bindgen_c_flags_final = $(filter-out -fpatchable-function-entry=%, \
+	$(bindgen_c_flags_lto)) -fno-builtin -D__BINDGEN__
                            ^^^^

This isn't a bug, but could the commit message mention that bindgen's C flags now drop -fpatchable-function-entry on all architectures, not just arm64 with CFI?

The change applies whenever any architecture passes -fpatchable-function-entry in CFLAGS (x86 CALL_PADDING, riscv, powerpc, loongarch, parisc, and arm64 ftrace). The reason for filtering it out (bindgen's libclang may be older than the kernel's Clang and may reject the section argument) is documented in the code comment, but the commit message only describes the arm64 kCFI pieces.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36069841267