Skip to contentSkip to conversation

Cancellations

PATCH New Kumar Kartikeya Dwivedi 1 participant 74 messages Dec 1 Page 2 of 2

Subsystems (21)
Networking Documentation x86 PowerPC +17 more subsystems
lore
Share & tools
lore
author maintainer
#53 lore raw

PATCH 53/73 bpf: Give the unwind label of a helper a second way in

In reply to Kumar Kartikeya Dwivedi

Currently the unwind label of a helper serves unwind_exit only: the helper releases what it holds and leaves to the unwind_goto after its own call. A callback that leaves with cancel_exit needs the same label, but the helper then has to leave to the cancel_goto after its call, or the cancellation would come out in a landing pad of the program. So the helper has to learn which insn its callback left with.

A flag in a register cannot tell it, because the helper is the C frame in which such a flag is lost. bpf_for_each_map_elem() calls the op of the map, which calls the callback, and what the op leaves in a register after its own unwind label is up to the compiler. The exception table cannot name a second label either, because a return address has one entry.

Tell the helper the way a caller is told, by the address that the callback returns to. The exception table entry of bpf_call_cb() now points to a stub with two entry points, BPF_CB_PAD_OFF and BPF_CB_CANCEL_OFF bytes from its start. On x86-64 the stub is:

nop
clc <- unwind_exit returns here
jnc 1f
stc <- cancel_exit returns here
1: sbb %ecx, %ecx kind: 0 if the carry flag is clear
jmp <unwind label>

bpf_call_cb() returns the result in a new argument, kind, and bpf_unwind_leave(kind) looks up the target of the same kind for the return address of the helper, with bpf_cancel_target() if kind is not 0. The stub is out of line and computes kind in rcx, which the call clobbers anyway, so the helper pays nothing for it when the callback returns. On arm64 each entry point branches to a C label of its own that sets kind, so that no register has to carry it.

bpf_for_each_map_elem() is two C frames. The op of the map leaves with bpf_unwind_leave(kind), which takes it to the matching entry point in the helper, and the helper leaves with the same kind. Only R0 of the callback gets through a helper, so no code may read R2 after the call of a helper as a value of the callback.

When the callback returns, the helpers run the same code as before on x86-64 with clang, with two exceptions: bpf_for_each_map_elem() is shorter, and bpf_find_vma() pays five more pushes and pops per call for fewer loads and stores. Nothing enters the second entry point yet. The verifier emits no cancel_exit, and the lookup of both JITs still returns the start of the stub, which runs into the first entry point.

---
 include/linux/bpf_unwind.h | 103 +++++++++++++++++++++++++++----------
 kernel/bpf/arraymap.c      |   8 +--
 kernel/bpf/bpf_iter.c      |  15 +++---
 kernel/bpf/hashtab.c       |  17 +++---
 kernel/bpf/helpers.c       |  11 ++--
 kernel/bpf/ringbuf.c       |  17 +++---
 kernel/bpf/task_iter.c     |  10 ++--
 7 files changed, 114 insertions(+), 67 deletions(-)
include/linux/bpf_unwind.h +75 -28
index 2a3bb47e2b10..10cef80cfb86 100644
@@ -6,18 +6,20 @@
  * The unwind label of a helper, which the identifiers call a pad.
  *
  * A helper that calls a callback is a C frame between the callback and the BPF code that called
- * the helper. For the callback to leave with unwind_exit, the helper calls it with bpf_call_cb()
- * and names a label, at which it continues when the callback does not return:
+ * the helper. For the callback to leave with unwind_exit or cancel_exit, the helper calls it with
+ * bpf_call_cb() and names a label, at which it continues when the callback does not return:
  *
- *		bpf_call_cb(cb, a1, a2, a3, a4, a5, r0, unwound);
+ *		bpf_call_cb(cb, a1, a2, a3, a4, a5, r0, kind, unwound);
  *		...
  *	unwound:
  *		rcu_read_unlock();		<- the helper releases what it holds
- *		bpf_unwind_leave();		<- and returns to the unwind_goto after its own
- *		return r0;			   call, with R0 of the callback alone
+ *		bpf_unwind_leave(kind);		<- and returns to the unwind_goto or cancel_goto
+ *		return r0;			   after its own call, with R0 of the callback alone
  *
- * The return address of the callback has an exception table entry, EX_TYPE_BPF, for the label.
- * unwind_exit of the callback finds the entry with bpf_unwind_target() and returns there.
+ * The return address of the callback has an exception table entry, EX_TYPE_BPF, that points to a
+ * stub with two entry points. unwind_exit returns to the one at BPF_CB_PAD_OFF and cancel_exit to
+ * the one at BPF_CB_CANCEL_OFF, see bpf_unwind_target() and bpf_cancel_target(). The stub sets
+ * 'kind' and jumps to the label. It is out of line, so a callback that returns costs nothing.
  *
  * A function with an unwind label must be:
  *  - noinline. bpf_unwind_leave() rewrites the return address of the function that it is in, so
@@ -83,6 +85,15 @@
 #define BPF_KCFI_CHECK(type)
 #endif
 
+/*
+ * The offsets of the two entry points in the stub. unwind_exit returns after a nop. A stack walk
+ * looks up the insn before a return address, and for a sample that is taken while the callback
+ * returns to the stub that has to be an insn of the stub. cancel_exit returns after the clc and
+ * the jnc.
+ */
+#define BPF_CB_PAD_OFF		1
+#define BPF_CB_CANCEL_OFF	4
+
 /*
  * The registers that the call clobbers are outputs, so that the compiler uses none of them for
  * another operand. r0 is rax after the call and at the label: the outputs of an asm goto are
@@ -90,8 +101,15 @@
  * before the call, never after it, so the return address stays the byte after the call. The
  * arguments are evaluated before the register variables are set, because a call among them,
  * instrumentation included, would clobber the variables.
+ *
+ * The stub is in a subsection after the code, where nothing falls into it. unwind_exit returns
+ * after the nop at 4, with the carry flag clear from there on. cancel_exit returns to 5, which
+ * sets the flag. sbb turns the flag into 'kind', in rcx, which the call clobbers anyway. objtool
+ * reaches 4 through the exception table and 5 as the fall-through of the jnc, although the jnc
+ * is always taken. The jnc is spelled in bytes so that its length does not depend on the
+ * assembler.
  */
-#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, unwound)		\
+#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, kind, unwound)		\
 do {										\
 	u64 __f = (u64)(long)(fn), __1 = (u64)(long)(a1), __2 = (u64)(long)(a2),	\
 	    __3 = (u64)(long)(a3), __4 = (u64)(long)(a4), __5 = (u64)(long)(a5);	\
@@ -99,13 +117,21 @@ do {										\
 	register u64 __a5 asm("r8") = __5;					\
 	register u64 __c5 asm("r8");						\
 	register u64 __c11 asm("r11");						\
-	u64 __c1, __c2, __c3, __c4;						\
+	u64 __c1, __c2, __c3;							\
 										\
 	asm_goto_output(BPF_KCFI_CHECK(type)					\
 		 "	" CALL_NOSPEC "\n"					\
 		 "1:\n"								\
-		 _ASM_EXTABLE_TYPE(1b, %l[unwound], EX_TYPE_BPF)		\
-		 : "=a"(r0), "=D"(__c1), "=S"(__c2), "=d"(__c3), "=c"(__c4),	\
+		 "	.subsection 1\n"					\
+		 "4:	nop\n"							\
+		 "	clc\n"							\
+		 "	.byte 0x73, 0x01\n"	/* jnc 6f */			\
+		 "5:	stc\n"							\
+		 "6:	sbb %%ecx, %%ecx\n"					\
+		 "	jmp %l[" __stringify(unwound) "]\n"			\
+		 "	.previous\n"						\
+		 _ASM_EXTABLE_TYPE(1b, 4b, EX_TYPE_BPF)				\
+		 : "=a"(r0), "=D"(__c1), "=S"(__c2), "=d"(__c3), "=c"(kind),	\
 		   "=r"(__c5), "=r"(__c11)					\
 		 : [thunk_target] "r"(__fn), "D"(__1), "S"(__2), "d"(__3),	\
 		   "c"(__4), "r"(__a5)						\
@@ -115,17 +141,18 @@ do {										\
 
 /*
  * Make the function that this is inlined into return to the target of the unwind_goto after its
- * call. The return address is the word below the canonical frame address. Nothing checks that a
- * target was found: after 'unwind_goto +0' the target is the return address itself, because the
- * JIT emits no code for unwind_goto.
+ * call, or of the cancel_goto if @kind, which the stub of bpf_call_cb() set, is not 0. The return
+ * address is the word below the canonical frame address. Nothing checks that a target was found:
+ * after 'unwind_goto +0' the target is the return address itself, because the JIT emits no code
+ * for unwind_goto.
  * The store is the last thing before the return, into the frame of the function itself, so a
  * compiler may take it for a dead store. Hence WRITE_ONCE().
  */
-static __always_inline void bpf_unwind_leave(void)
+static __always_inline void bpf_unwind_leave(u64 kind)
 {
 	unsigned long *slot = (unsigned long *)__builtin_dwarf_cfa() - 1;
 
-	WRITE_ONCE(*slot, bpf_unwind_target(*slot));
+	WRITE_ONCE(*slot, kind ? bpf_cancel_target(*slot) : bpf_unwind_target(*slot));
 }
 
 #elif defined(CONFIG_ARM64) && defined(CONFIG_CC_HAS_ASM_GOTO_OUTPUT)
@@ -166,15 +193,23 @@ static __always_inline void bpf_unwind_leave(void)
 #define BPF_CB_CLOBBER_X18	"x18",
 #endif
 
+/* The offsets of the two entry points in the stub: the second one is two insns in */
+#define BPF_CB_PAD_OFF		0
+#define BPF_CB_CANCEL_OFF	8
+
 /*
  * r0 is x0, which only a register variable can name, and gcc does not keep such a variable across
  * a call. KCOV puts a call at the head of each block, and an asm goto ends its block, so C code
  * after it would read x0 too late on either edge. So the assembly moves x0 to r0 itself, after
- * the call and where unwind_exit returns to, out of line. For the same reason the arguments are
- * evaluated before the register variables are set.
+ * the call and at both entry points. For the same reason the arguments are evaluated before the
+ * register variables are set.
+ * unwind_exit returns to 3 and cancel_exit to 4. Each branches to a C label of its own that sets
+ * 'kind'. A register for it would have to be one that the call keeps, and the helper would save
+ * that register also when the callback returns.
  */
-#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, unwound)		\
+#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, kind, unwound)		\
 do {										\
+	__label__ __prog, __cancel;						\
 	u64 __f = (u64)(long)(fn), __1 = (u64)(long)(a1), __2 = (u64)(long)(a2),	\
 	    __3 = (u64)(long)(a3), __4 = (u64)(long)(a4), __5 = (u64)(long)(a5);	\
 	register u64 __fn asm("x15") = __f;					\
@@ -195,7 +230,9 @@ do {										\
 		 "1:	mov %[ret], x0\n"					\
 		 "	.subsection 1\n"					\
 		 "3:	mov %[ret], x0\n"					\
-		 "	b %l[" __stringify(unwound) "]\n"			\
+		 "	b %l[__prog]\n"						\
+		 "4:	mov %[ret], x0\n"					\
+		 "	b %l[__cancel]\n"					\
 		 "	.previous\n"						\
 		 __ASM_EXTABLE_RAW("1b", "3b", __stringify(EX_TYPE_BPF), "0")	\
 		 : [ret] "=r"(r0), "=r"(__c0), "=r"(__c1), "=r"(__c2),		\
@@ -204,7 +241,14 @@ do {										\
 		   "r"(__a4)							\
 		 : "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",	\
 		   "x14", "x16", "x17", BPF_CB_CLOBBER_X18 "x30", "memory", "cc"	\
-		 : unwound);							\
+		 : __prog, __cancel);						\
+	break;									\
+__prog:										\
+	(kind) = 0;								\
+	goto unwound;								\
+__cancel:									\
+	(kind) = 1;								\
+	goto unwound;								\
 } while (0)
 
 /*
@@ -224,12 +268,12 @@ do {										\
  * 20 pushes first, so the copy is plain. The copy is read and written in assembly, because KASAN
  * poisons the shadow call stack.
  */
-static __always_inline void bpf_unwind_leave(void)
+static __always_inline void bpf_unwind_leave(u64 kind)
 {
 	unsigned long *slot = (unsigned long *)__builtin_frame_address(0) + 1;
 	unsigned long old = *slot;
 	unsigned long from = ptrauth_strip_kernel_insn_pac(old);
-	unsigned long to = bpf_unwind_target(from), sig = to;
+	unsigned long to = kind ? bpf_cancel_target(from) : bpf_unwind_target(from), sig = to;
 
 	WARN_ON_ONCE(to == from);
 #ifdef CONFIG_ARM64_PTR_AUTH_KERNEL
@@ -260,20 +304,23 @@ static __always_inline void bpf_unwind_leave(void)
 
 #else
 
-#define BPF_HAS_CB_PADS 0
+#define BPF_HAS_CB_PADS		0
+#define BPF_CB_PAD_OFF		0
+#define BPF_CB_CANCEL_OFF	0
 
 #define BPF_CB_PAD_TYPE(name, type)
 
-#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, unwound)		\
+#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, kind, unwound)		\
 do {										\
 	(r0) = ((bpf_callback_t)(void *)(fn))((u64)(long)(a1), (u64)(long)(a2),	\
 					      (u64)(long)(a3), (u64)(long)(a4),	\
 					      (u64)(long)(a5));			\
+	(kind) = 0;								\
 	if (0)									\
 		goto unwound;							\
 } while (0)
 
-static __always_inline void bpf_unwind_leave(void)
+static __always_inline void bpf_unwind_leave(u64 kind)
 {
 }
 
@@ -285,7 +332,7 @@ static __always_inline void bpf_unwind_leave(void)
  */
 BPF_CB_PAD_TYPE(__bpf_callback_fn, typeof(*(bpf_callback_t)0));
 
-#define bpf_call_cb(fn, a1, a2, a3, a4, a5, r0, unwound)			\
-	__bpf_call_cb(__bpf_callback_fn, fn, a1, a2, a3, a4, a5, r0, unwound)
+#define bpf_call_cb(fn, a1, a2, a3, a4, a5, r0, kind, unwound)			\
+	__bpf_call_cb(__bpf_callback_fn, fn, a1, a2, a3, a4, a5, r0, kind, unwound)
 
 #endif /* _LINUX_BPF_UNWIND_H */
kernel/bpf/arraymap.c +4 -4
index 15e9a18b4ec6..b0becb2abbd4 100644
@@ -807,7 +807,7 @@ static noinline notrace long bpf_for_each_array_elem(struct bpf_map *map, bpf_ca
 	u32 i, key, num_elems = 0;
 	struct bpf_array *array;
 	bool is_percpu;
-	u64 ret = 0;
+	u64 ret = 0, kind;
 	void *val;
 
 	cant_migrate();
@@ -824,7 +824,7 @@ static noinline notrace long bpf_for_each_array_elem(struct bpf_map *map, bpf_ca
 			val = array_map_elem_ptr(array, i);
 		num_elems++;
 		key = i;
-		bpf_call_cb(callback_fn, map, &key, val, callback_ctx, 0, ret, unwound);
+		bpf_call_cb(callback_fn, map, &key, val, callback_ctx, 0, ret, kind, unwound);
 		/* return value: 0 - continue, 1 - stop and return */
 		if (ret)
 			break;
@@ -833,8 +833,8 @@ static noinline notrace long bpf_for_each_array_elem(struct bpf_map *map, bpf_ca
 	return num_elems;
 
 unwound:
-	/* The callback left with unwind_exit: nothing to drop here */
-	bpf_unwind_leave();
+	/* The callback left with unwind_exit or cancel_exit. Nothing is held here. */
+	bpf_unwind_leave(kind);
 	return ret;
 }
 NOKPROBE_SYMBOL(bpf_for_each_array_elem);
kernel/bpf/bpf_iter.c +8 -7
index 57e1800a5741..350082f66da5 100644
@@ -760,14 +760,15 @@ BPF_CALL_x(4, noinline notrace, bpf_for_each_map_elem, struct bpf_map *, map, vo
 	   void *, callback_ctx, u64, flags)
 {
 #if BPF_HAS_CB_PADS
-	u64 ret;
+	u64 ret, kind;
 
 	__bpf_call_cb(__bpf_for_each_op, map->ops->map_for_each_callback, map, callback_fn,
-		      callback_ctx, flags, 0, ret, unwound);
+		      callback_ctx, flags, 0, ret, kind, unwound);
 	return ret;
 
 unwound:
-	bpf_unwind_leave();
+	/* The map function left the way the callback did, and so does the helper */
+	bpf_unwind_leave(kind);
 	return ret;
 #else
 	/* The fallback of __bpf_call_cb() calls through bpf_callback_t, and kCFI would trap */
@@ -790,7 +791,7 @@ BPF_CALL_x(4, noinline notrace, bpf_loop, u32, nr_loops, void *, callback_fn, vo
 	   u64, flags)
 {
 	bpf_callback_t callback = (bpf_callback_t)callback_fn;
-	u64 ret;
+	u64 ret, kind;
 	u32 i;
 
 	/* Note: these safety checks are also verified when bpf_loop
@@ -803,7 +804,7 @@ BPF_CALL_x(4, noinline notrace, bpf_loop, u32, nr_loops, void *, callback_fn, vo
 		return -E2BIG;
 
 	for (i = 0; i < nr_loops; i++) {
-		bpf_call_cb(callback, i, callback_ctx, 0, 0, 0, ret, unwound);
+		bpf_call_cb(callback, i, callback_ctx, 0, 0, 0, ret, kind, unwound);
 		/* return value: 0 - continue, 1 - stop and return */
 		if (ret)
 			return i + 1;
@@ -812,8 +813,8 @@ BPF_CALL_x(4, noinline notrace, bpf_loop, u32, nr_loops, void *, callback_fn, vo
 	return i;
 
 unwound:
-	/* The callback left with unwind_exit: the loop is over, and so is the helper */
-	bpf_unwind_leave();
+	/* The callback left with unwind_exit or cancel_exit. Nothing is held here. */
+	bpf_unwind_leave(kind);
 	return ret;
 }
 NOKPROBE_SYMBOL(bpf_loop);
kernel/bpf/hashtab.c +9 -8
index 690f5ad80cc8..3117339da751 100644
@@ -2530,7 +2530,7 @@ static noinline notrace long bpf_for_each_hash_elem(struct bpf_map *map, bpf_cal
 	struct bucket *b;
 	void *key, *val;
 	bool is_percpu;
-	u64 ret = 0;
+	u64 ret = 0, kind;
 
 	cant_migrate();
 
@@ -2557,7 +2557,8 @@ static noinline notrace long bpf_for_each_hash_elem(struct bpf_map *map, bpf_cal
 				val = htab_elem_value(elem, map->key_size);
 			}
 			num_elems++;
-			bpf_call_cb(callback_fn, map, key, val, callback_ctx, 0, ret, unwound);
+			bpf_call_cb(callback_fn, map, key, val, callback_ctx, 0, ret, kind,
+				    unwound);
 			/* return value: 0 - continue, 1 - stop and return */
 			if (ret) {
 				rcu_read_unlock();
@@ -2570,9 +2571,9 @@ static noinline notrace long bpf_for_each_hash_elem(struct bpf_map *map, bpf_cal
 	return num_elems;
 
 unwound:
-	/* The callback left with unwind_exit, inside the RCU section of the bucket */
+	/* The callback left with unwind_exit or cancel_exit: leave the RCU section of the bucket */
 	rcu_read_unlock();
-	bpf_unwind_leave();
+	bpf_unwind_leave(kind);
 	return ret;
 }
 NOKPROBE_SYMBOL(bpf_for_each_hash_elem);
@@ -3436,7 +3437,7 @@ static noinline notrace long bpf_each_rhash_elem(struct bpf_map *map, bpf_callba
 	void *prev_key = NULL;
 	struct rhtab_elem *elem;
 	int num_elems = 0;
-	u64 ret = 0;
+	u64 ret = 0, kind;
 
 	cant_migrate();
 
@@ -3454,7 +3455,7 @@ static noinline notrace long bpf_each_rhash_elem(struct bpf_map *map, bpf_callba
 			break;
 		num_elems++;
 		bpf_call_cb(callback_fn, map, elem->data, rhtab_elem_value(elem, map->key_size),
-			    callback_ctx, 0, ret, unwound);
+			    callback_ctx, 0, ret, kind, unwound);
 		if (ret)
 			break;
 
@@ -3465,9 +3466,9 @@ static noinline notrace long bpf_each_rhash_elem(struct bpf_map *map, bpf_callba
 	return num_elems;
 
 unwound:
-	/* The callback left with unwind_exit, under RCU */
+	/* The callback left with unwind_exit or cancel_exit: leave the RCU section */
 	rcu_read_unlock();
-	bpf_unwind_leave();
+	bpf_unwind_leave(kind);
 	return ret;
 }
 NOKPROBE_SYMBOL(bpf_each_rhash_elem);
kernel/bpf/helpers.c +5 -6
index 1c637c70b1da..a06ad655ac6e 100644
@@ -2846,7 +2846,7 @@ static __always_inline long __bpf_rbtree_add(struct bpf_rb_root *root,
 	struct rb_node *parent = NULL, *n = &node->rb_node;
 	bpf_callback_t cb = (bpf_callback_t)less;
 	bool leftmost = true;
-	u64 r0;
+	u64 r0, kind;
 
 	/* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
 	 * check the latter
@@ -2859,7 +2859,7 @@ static __always_inline long __bpf_rbtree_add(struct bpf_rb_root *root,
 
 	while (*link) {
 		parent = *link;
-		bpf_call_cb(cb, node, parent, 0, 0, 0, r0, unwound);
+		bpf_call_cb(cb, node, parent, 0, 0, 0, r0, kind, unwound);
 		if (r0) {
 			link = &parent->rb_left;
 		} else {
@@ -2875,13 +2875,12 @@ static __always_inline long __bpf_rbtree_add(struct bpf_rb_root *root,
 
 unwound:
 	/*
-	 * The comparator left with unwind_exit. The node is not in the tree, and
-	 * the caller has let go of it: unlink it for whoever else holds it, as
-	 * bpf_rb_root_free() does, and drop it, as the error path above does.
+	 * The comparator left with unwind_exit or cancel_exit, and the program has given up the
+	 * node. Clear the owner, so that others who hold the node can add it again, and drop it.
 	 */
 	smp_store_release(&node->owner, NULL);
 	__bpf_obj_drop_impl((void *)n - off, rec, false);
-	bpf_unwind_leave();
+	bpf_unwind_leave(kind);
 	return r0;
 }
 
kernel/bpf/ringbuf.c +8 -9
index 4aa7c78a6b6e..f3c16a464c71 100644
@@ -822,7 +822,8 @@ BPF_CALL_x(4, noinline notrace, bpf_user_ringbuf_drain, struct bpf_map *, map,
 	long samples, discarded_samples = 0, ret = 0;
 	bpf_callback_t callback = (bpf_callback_t)callback_fn;
 	u64 wakeup_flags = BPF_RB_NO_WAKEUP | BPF_RB_FORCE_WAKEUP;
-	bool unwound = false;
+	/* 0, or how the callback left: 1 after unwind_exit, 2 after cancel_exit */
+	u64 kind, unwound = 0;
 	int busy = 0;
 
 	if (unlikely(flags & ~wakeup_flags))
@@ -854,17 +855,15 @@ BPF_CALL_x(4, noinline notrace, bpf_user_ringbuf_drain, struct bpf_map *, map,
 		}
 
 		bpf_dynptr_init(&dynptr, sample, BPF_DYNPTR_TYPE_LOCAL, 0, size);
-		bpf_call_cb(callback, &dynptr, callback_ctx, 0, 0, 0, ret, unwound_at);
+		bpf_call_cb(callback, &dynptr, callback_ctx, 0, 0, 0, ret, kind, unwound_at);
 		if (0) {
 unwound_at:
 			/*
-			 * The callback left with unwind_exit. The sample is
-			 * consumed and counted like after a return, so that
-			 * the wakeup below is sent for it, and the helper
-			 * leaves through the door below, as the error paths
-			 * do, with the r0 of the callback.
+			 * The callback left with unwind_exit or cancel_exit. Consume and count the
+			 * sample as after a return, so that the wakeup is sent for it, then leave
+			 * the way the error paths do.
 			 */
-			unwound = true;
+			unwound = 1 + !!kind;
 		}
 		__bpf_user_ringbuf_sample_release(rb, size, flags);
 		if (unwound) {
@@ -885,7 +884,7 @@ BPF_CALL_x(4, noinline notrace, bpf_user_ringbuf_drain, struct bpf_map *, map,
 	else if (!(flags & BPF_RB_NO_WAKEUP) && samples > 0)
 		irq_work_queue(&rb->work);
 	if (unwound)
-		bpf_unwind_leave();
+		bpf_unwind_leave(unwound - 1);
 	return ret;
 }
 NOKPROBE_SYMBOL(bpf_user_ringbuf_drain);
kernel/bpf/task_iter.c +5 -5
index 3480f6d9f648..4ee51743d539 100644
@@ -763,7 +763,7 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, s
 	bool __maybe_unused mmput_needed = false;
 	struct mm_struct *mm;
 	int ret = -ENOENT;
-	u64 r0;
+	u64 r0, kind;
 
 	if (flags)
 		return -EINVAL;
@@ -817,7 +817,7 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, s
 		 * verifier checks it as an RCU read-side critical section.
 		 */
 		rcu_read_lock();
-		bpf_call_cb(callback_fn, task, vma, callback_ctx, 0, 0, r0, unwound);
+		bpf_call_cb(callback_fn, task, vma, callback_ctx, 0, 0, r0, kind, unwound);
 		rcu_read_unlock();
 		ret = 0;
 	}
@@ -831,8 +831,8 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, s
 
 unwound:
 	/*
-	 * The callback left with unwind_exit, under the mmap lock and in the
-	 * RCU section. The way out is the same as after a return.
+	 * The callback left with unwind_exit or cancel_exit. Leave the RCU section, drop the mmap
+	 * lock and put the mm, as after a return.
 	 */
 	rcu_read_unlock();
 	bpf_mmap_unlock_mm(work, mm);
@@ -840,7 +840,7 @@ BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, s
 	if (mmput_needed)
 		mmput_async(mm);
 #endif
-	bpf_unwind_leave();
+	bpf_unwind_leave(kind);
 	return r0;
 }
 NOKPROBE_SYMBOL(bpf_find_vma);
Signature · 1 line
2.53.1-Meta
author maintainer
#54 lore raw

PATCH 54/73 bpf, x86: Put the landing of unwind_goto after the function

In reply to Kumar Kartikeya Dwivedi

Currently the x86-64 JIT emits the landing of an unwind_goto right after the call, and every call that returns jumps over it. With a private stack the code is:

call foo
pop r9 <- exit returns here
jmp 1f
pop r9 <- unwind_exit returns here
jmp <target of unwind_goto>
1:

So each call with a landing pays a jump, for code that runs only when the callee unwinds. A cancel_goto is going to get a landing too, and the verifier is going to add a cancel_goto after every call of a function that the kernel can cancel.

Emit the landings after the last insn of the function instead, as the arm64 JIT does:

call foo
pop r9 <- exit returns here
...
leave; ret
pop r9 <- unwind_exit returns here
jmp <target of unwind_goto>

An unwind_goto now only records the bytes that follow the native call and its target, and do_jit() emits the recorded landings after the loop over the insns. An unwind_goto with nothing to redo has no landing, as before. The keys of the exception table entries do not change.

Three points need care:

- The landings have the same size in every pass of the JIT, because their jumps always have a 32 bit offset. So the image stops shrinking exactly when the body does.
- The exception table entries are written only when the image is allocated. The landings then start at addrs[insn_cnt], where the pass before ended the body.
- The length that do_jit() returns includes the landings, so jited_len covers them. A landing is entered by ret and left by a direct jump, so it needs no ENDBR.

private_stack_unwinds of verifier_unwind.c expects the new layout.

---
 arch/x86/net/bpf_jit_comp.c                   | 101 ++++++++++++++----
 .../selftests/bpf/progs/verifier_unwind.c     |   7 +-
 2 files changed, 87 insertions(+), 21 deletions(-)
arch/x86/net/bpf_jit_comp.c +82 -19
index 3a0143c4d212..19fb1b20c51d 100644
@@ -288,6 +288,18 @@ int bpf_arch_text_invalidate(void *dst, size_t len)
 	return IS_ERR_OR_NULL(text_poke_set(dst, 0xcc, len));
 }
 
+/*
+ * A LANDING: where unwind_exit of a callee comes back to when the call has code
+ * behind its native call, like 'pop r9'. That code, done once more, and a jump
+ * to the insn that unwind_goto goes to. The landings stand behind the body of
+ * the function, see do_jit().
+ */
+struct jit_landing {
+	u8 code[16];
+	u8 len;
+	int to;
+};
+
 struct jit_context {
 	int cleanup_addr; /* Epilogue code offset */
 
@@ -298,6 +310,14 @@ struct jit_context {
 	 */
 	int tail_call_direct_label;
 	int tail_call_indirect_label;
+
+	/*
+	 * Room for one landing per unwind_goto of the prog. Each pass fills it
+	 * again. It lives as long as addrs[]: the extra pass of a prog with
+	 * subprogs has it from the first call of bpf_int_jit_compile().
+	 */
+	struct jit_landing *landings;
+	int max_landings;
 };
 
 /* Maximum number of bytes emitted while JITing one eBPF insn */
@@ -2452,6 +2472,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 	/* the bytes emitted after the native call of the last call insn */
 	u8 after_call[16], *ret_addr;
 	int after_call_len = 0;
+	/* the number of landings in this pass, and their size in bytes so far */
+	int nr_landings = 0, tail = 0;
 	int err;
 
 	stack_depth = bpf_prog->aux->stack_depth;
@@ -3459,38 +3481,47 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 			/* unwind_goto. The verifier expanded may_goto. */
 		case BPF_JMP | BPF_JCOND:
-		case BPF_JMP32 | BPF_JCOND:
+		case BPF_JMP32 | BPF_JCOND: {
+			int to = i + bpf_jmp_offset(insn);
+			int target = addrs[to];
+			struct jit_landing *landing;
+
 			/* an access to arena is in front: no call, nothing to redo */
 			if (BPF_CLASS(insn[-1].code) != BPF_JMP)
 				after_call_len = 0;
-			if (!after_call_len) {
-				err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
-							 addrs[i - 1],
-							 addrs[i + bpf_jmp_offset(insn)]);
-				if (err)
-					return err;
-				break;
-			}
 			/*
 			 * What follows the native call, like 'pop r9', has to be
-			 * done on the way to the pad too:
+			 * done on the way to the pad too. Not in the way of what
+			 * returns: the landing goes behind the body of the
+			 * function, and the next insn follows the call.
 			 *   call foo
 			 *   pop r9      <- exit returns here
-			 *   jmp 1f
+			 *   ...
+			 *   leave; ret
+			 *   ...
 			 *   pop r9      <- unwind_exit returns here
 			 *   jmp pad
-			 * 1:
+			 * addrs[insn_cnt] is where the body ended in the pass before.
+			 * The entry is written when no insn moves any more.
 			 */
+			if (after_call_len) {
+				if (nr_landings >= ctx->max_landings) {
+					pr_err("bpf_jit: landings bug\n");
+					return -EFAULT;
+				}
+				landing = &ctx->landings[nr_landings++];
+				memcpy(landing->code, after_call, after_call_len);
+				landing->len = after_call_len;
+				landing->to = to;
+				target = addrs[insn_cnt] + tail;
+				tail += after_call_len + 5;
+			}
 			err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
-						 addrs[i - 1] - after_call_len, addrs[i - 1] + 2);
+						 addrs[i - 1] - after_call_len, target);
 			if (err)
 				return err;
-			EMIT2(0xEB, after_call_len + 5);
-			memcpy(prog, after_call, after_call_len);
-			prog += after_call_len;
-			EMIT1_off32(0xE9, addrs[i + bpf_jmp_offset(insn)] -
-					  (addrs[i - 1] + 2 + after_call_len + 5));
 			break;
+		}
 
 		case BPF_JMP | BPF_TAIL_CALL:
 			if (imm32)
@@ -3825,6 +3856,30 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		prog = temp;
 	}
 
+	/*
+	 * Emit the landings after the last insn. Their jumps always have a 32
+	 * bit offset, so they have the same size in every pass and the image
+	 * stops shrinking when the body does. addrs[insn_cnt] stays the end of
+	 * the body, and the returned length includes the landings.
+	 */
+	for (i = 0; i < nr_landings; i++) {
+		const struct jit_landing *landing = &ctx->landings[i];
+
+		memcpy(prog, landing->code, landing->len);
+		prog += landing->len;
+		EMIT1_off32(0xE9, addrs[landing->to] - (proglen + landing->len + 5));
+		ilen = prog - temp;
+		if (image) {
+			if (unlikely(proglen + ilen > oldproglen)) {
+				pr_err("bpf_jit: fatal error\n");
+				return -EFAULT;
+			}
+			memcpy(rw_image + proglen, temp, ilen);
+		}
+		proglen += ilen;
+		prog = temp;
+	}
+
 	if (image && excnt != bpf_prog->aux->num_exentries) {
 		pr_err("extable is not populated\n");
 		return -EFAULT;
@@ -4887,6 +4942,13 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	addrs = kvmalloc_objs(*addrs, prog->len + 1);
 	if (!addrs)
 		goto out_addrs;
+	for (i = 0; i < prog->len; i++)
+		ctx.max_landings += bpf_is_unwind_goto(&prog->insnsi[i]);
+	if (ctx.max_landings) {
+		ctx.landings = kvmalloc_objs(*ctx.landings, ctx.max_landings);
+		if (!ctx.landings)
+			goto out_addrs;
+	}
 
 	/*
 	 * Before first pass, make a rough estimation of addrs[]
@@ -4899,7 +4961,6 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	}
 	ctx.cleanup_addr = proglen;
 skip_init_addrs:
-
 	/*
 	 * Jumps are sized by the insns they jump over, which start at
 	 * their maximum size, so no insn grows from one pass to the
@@ -5019,6 +5080,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 			bpf_prog_fill_jited_linfo(prog, addrs + 1);
 out_addrs:
 		kvfree(addrs);
+		kvfree(ctx.landings);
 		if (!image && priv_stack_ptr) {
 			free_percpu(priv_stack_ptr);
 			prog->aux->priv_stack_ptr = NULL;
@@ -5123,6 +5185,7 @@ void bpf_jit_free(struct bpf_prog *prog)
 			bpf_jit_binary_pack_finalize(jit_data->header,
 						     jit_data->rw_header);
 			kvfree(jit_data->addrs);
+			kvfree(jit_data->ctx.landings);
 			kfree(jit_data);
 		}
 		prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset();
tools/testing/selftests/bpf/progs/verifier_unwind.c +5 -2
index b4d7dfdc675b..64fa6e1d3a32 100644
@@ -1198,7 +1198,9 @@ static unsigned long may_unwind_big_stack(void)
 
 /*
  * x86-64 keeps the pointer to the private stack in r9 and saves it around a call.
- * The value that is read back in the pad is there only when r9 is restored.
+ * The value that is read back in the pad is there only when r9 is restored: on the way of
+ * unwind_exit a landing behind the last insn of the prog does that. What returns goes on with
+ * the exit that follows the call.
  */
 SEC("raw_tp")
 __description("unwind: private stack, the callee unwinds")
@@ -1210,7 +1212,8 @@ __jited("	pushq	%r9")
 __jited("...") /* call depth accounting */
 __jited("	callq	0x{{.*}}")
 __jited("	popq	%r9")
-__jited("	jmp	L{{.*}}")
+__jited("L{{.*}}:	leave")
+__jited("...")
 __jited("	popq	%r9")
 __jited("	jmp	L{{.*}}")
 __arch_arm64
Signature · 1 line
2.53.1-Meta
author maintainer
#55 lore raw

PATCH 55/73 bpf, x86: Return to cancel_goto at cancel_exit

In reply to Kumar Kartikeya Dwivedi

Teach the x86-64 JIT the two insns. cancel_exit emits the code of unwind_exit with bpf_cancel_target() in place of bpf_unwind_target(). cancel_goto is an exception table entry for the call before it, like unwind_goto. It has a key of its own, so that unwind_exit never finds the entry of a cancel_goto, nor cancel_exit that of an unwind_goto. Where code follows the native call, each of the two has a landing after the function:

	call foo		   returns to ret_addr
	pop r9
	...
	leave; ret
	pop r9; jmp A		<- unwind_goto A: { .insn = ret_addr - 1 }
	pop r9; jmp B		<- cancel_goto B: { .insn = ret_addr - 2 }

These cases need care:

- No insn may start at a key, so that a fault cannot hit the entry. 'call *%rax' of callx has 2 bytes, so it gets an empty REX prefix when a cancel_goto follows it.
- The code of an access to arena can end in an insn of 2 bytes. A cancel_goto never follows such an access, and the JIT fails if it finds one there.
- The exception table is sorted by address. When a call has both insns, the entry of the cancel_goto is added second and takes the place of the entry of the unwind_goto, which moves up.
- The landing of a cancel_goto does not redo 'mov rsi, rdx' after a kfunc that returns 16 bytes, because R2 after cancel_exit is not the second half of what the kfunc returned.

The lookup is one function for both keys. For a callback that a helper called, it now adds the offset of the entry point to the address of the stub of bpf_call_cb(): BPF_CB_PAD_OFF or BPF_CB_CANCEL_OFF. Nothing runs the first byte of the x86-64 stub any more, and it becomes an int3. The jump of an optimized kprobe before the stub could cover a nop and end after the first entry point. Such a jump never covers an int3.

Both lookups become notrace and are put on the kprobe blacklist, because the kernel is going to find the program by the address that they return to. The verifier emits neither insn yet.

---
 arch/x86/net/bpf_jit_comp.c | 221 ++++++++++++++++++++++++++----------
 include/linux/bpf_unwind.h  |  14 ++-
 2 files changed, 168 insertions(+), 67 deletions(-)
arch/x86/net/bpf_jit_comp.c +160 -61
index 19fb1b20c51d..1c7bc301784f 100644
@@ -10,6 +10,7 @@
 #include <linux/if_vlan.h>
 #include <linux/bitfield.h>
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/bpf_verifier.h>
 #include <linux/memory.h>
 #include <linux/sort.h>
@@ -289,10 +290,8 @@ int bpf_arch_text_invalidate(void *dst, size_t len)
 }
 
 /*
- * A LANDING: where unwind_exit of a callee comes back to when the call has code
- * behind its native call, like 'pop r9'. That code, done once more, and a jump
- * to the insn that unwind_goto goes to. The landings stand behind the body of
- * the function, see do_jit().
+ * The landing of an unwind_goto or cancel_goto, see BPF_JCOND in do_jit(): the
+ * @len bytes of @code that follow the native call, and a jump to insn @to.
  */
 struct jit_landing {
 	u8 code[16];
@@ -312,9 +311,9 @@ struct jit_context {
 	int tail_call_indirect_label;
 
 	/*
-	 * Room for one landing per unwind_goto of the prog. Each pass fills it
-	 * again. It lives as long as addrs[]: the extra pass of a prog with
-	 * subprogs has it from the first call of bpf_int_jit_compile().
+	 * Room for one landing per unwind_goto and cancel_goto of the prog.
+	 * Each pass fills the array again. It is allocated and freed together
+	 * with addrs[], so the extra pass of a prog with subprogs has it too.
 	 */
 	struct jit_landing *landings;
 	int max_landings;
@@ -728,20 +727,29 @@ static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip)
 	*pprog = prog;
 }
 
-static void __emit_indirect_call(u8 **pprog, int reg, bool ereg)
+static void __emit_indirect_call(u8 **pprog, int reg, bool ereg, bool rex)
 {
 	u8 *prog = *pprog;
 
 	if (ereg)
 		EMIT1(0x41);
+	else if (rex)
+		EMIT1(0x40);
 
 	EMIT2(0xFF, 0xD0 + reg);
 
 	*pprog = prog;
 }
 
-/* call *bpf_reg */
-static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)
+/*
+ * call *bpf_reg
+ *
+ * @rex: a cancel_goto follows the call. Its extable entry is 2 bytes before the
+ * return address, and no insn may start there, see CANCEL_EXKEY. 'call *%rax'
+ * is 2 bytes long, so give it a REX prefix with no bits set, which only adds a
+ * byte. The call of a thunk is 5 bytes long.
+ */
+static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip, bool rex)
 {
 	u8 *prog = *pprog;
 	int reg = reg2hex[bpf_reg];
@@ -753,7 +761,7 @@ static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)
 		err = emit_call(&prog, its_thunk(reg + 8*ereg), ip);
 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
 		EMIT_LFENCE();
-		__emit_indirect_call(&prog, reg, ereg);
+		__emit_indirect_call(&prog, reg, ereg, rex);
 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
 		OPTIMIZER_HIDE_VAR(reg);
 		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
@@ -761,7 +769,7 @@ static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)
 		else
 			err = emit_call(&prog, &__x86_indirect_thunk_array[reg + 8*ereg], ip);
 	} else {
-		__emit_indirect_call(&prog, reg, ereg);
+		__emit_indirect_call(&prog, reg, ereg, rex);
 	}
 
 	*pprog = prog;
@@ -2349,11 +2357,31 @@ static void adjust_cmp_imm(u32 *op, s32 *imm)
  * replaces the return address of its frame with bpf_unwind_target() of it.
  * ret_addr - 1, because what follows the call can have an entry of its own.
  * No insn starts there, so a fault cannot hit the entry.
+ *
+ * unwind_goto can also follow an access to arena. ret_addr is then the end of
+ * the code of the access, and a fault in the access goes to the target, see
+ * bpf_fault_unwind_target().
+ *
+ * cancel_goto is the same for cancel_exit and bpf_cancel_target(). Its entry
+ * is at ret_addr - 2, because the unwind_goto of the same call has the one at
+ * ret_addr - 1. No insn starts there either: a call that cancel_goto follows
+ * is at least 3 bytes long, see emit_indirect_call(). cancel_goto never
+ * follows an access to arena, whose code can end in an insn of 2 bytes.
+ */
+#define UNWIND_EXKEY	1
+#define CANCEL_EXKEY	2
+
+/*
+ * Add the extable entry of an unwind_goto or a cancel_goto with the key @key.
+ *
+ * @after_unwind: the entry before this one is that of the unwind_goto of the
+ * same call. The table is sorted by address and the key of cancel_goto is the
+ * lower one, so the new entry takes that slot and the other one moves up.
  */
 static int add_unwind_exentry(struct bpf_prog *prog, u8 *image, u8 *rw_image, int *excnt,
-			      int ret_addr, int target)
+			      int ret_addr, int target, int key, bool after_unwind)
 {
-	struct exception_table_entry *ex;
+	struct exception_table_entry *ex, *rw;
 	s64 delta;
 
 	if (!prog->aux->extable)
@@ -2363,54 +2391,80 @@ static int add_unwind_exentry(struct bpf_prog *prog, u8 *image, u8 *rw_image, in
 		return -EFAULT;
 	}
 	ex = &prog->aux->extable[(*excnt)++];
-	delta = image + ret_addr - 1 - (u8 *)&ex->insn;
+	/* switch ex to rw buffer for writes */
+	rw = (void *)rw_image + ((void *)ex - (void *)image);
+	if (after_unwind) {
+		/* insn is relative to the address of the entry, which moves */
+		*rw = rw[-1];
+		rw->insn -= sizeof(*rw);
+		ex--;
+		rw--;
+	}
+	delta = image + ret_addr - key - (u8 *)&ex->insn;
 	if (!is_simm32(delta)) {
 		pr_err("extable->insn doesn't fit into 32-bit\n");
 		return -EFAULT;
 	}
-	/* switch ex to rw buffer for writes */
-	ex = (void *)rw_image + ((void *)ex - (void *)image);
-	ex->insn = delta;
-	ex->fixup = target - ret_addr;
-	ex->data = EX_TYPE_BPF;
+	rw->insn = delta;
+	rw->fixup = target - ret_addr;
+	rw->data = EX_TYPE_BPF;
 	return 0;
 }
 
 /*
- * The verifier made sure that unwind_goto follows a call in a prog. When the
- * kernel called an async callback, it's exit. A helper that calls a callback
- * has a pad when it wants one, see bpf_call_cb().
+ * Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with
+ * cancel_exit, @key CANCEL_EXKEY, returns to.
+ * The verifier made sure that unwind_goto follows a call in a prog, and
+ * cancel_goto where the callee has cancel_exit. When the kernel called an async
+ * callback, it's exit. A helper that calls a callback has a pad when it wants
+ * one, see bpf_call_cb().
  */
-u64 bpf_unwind_target(u64 ret_addr)
+static u64 unwind_target(u64 ret_addr, int key)
 {
 	const struct exception_table_entry *e;
 
-	e = search_bpf_extables(ret_addr - 1);
+	e = search_bpf_extables(ret_addr - key);
 	if (e)
 		return ret_addr + e->fixup;
 	/*
-	 * The pad of a helper that called a callback with bpf_call_cb(): its
-	 * entries are the EX_TYPE_BPF ones of the kernel and module tables.
-	 * Anything else at a return address is some caller's own fixup, and
-	 * what a JIT keyed there is a fixup of the insn after the call.
+	 * A helper that called the frame with bpf_call_cb() has an EX_TYPE_BPF
+	 * entry at the return address itself. An entry of another type there
+	 * is the fixup of the insn after some call. The entry points to the
+	 * stub of the helper's unwind label, which has one entry point for
+	 * unwind_exit and one for cancel_exit.
 	 */
 	e = search_kernel_exception_table(ret_addr);
 	if (!e)
 		e = search_module_extables(ret_addr);
 	if (e && (e->data & EX_DATA_TYPE_MASK) == EX_TYPE_BPF)
-		return (unsigned long)&e->fixup + e->fixup;
+		return (unsigned long)&e->fixup + e->fixup +
+		       (key == CANCEL_EXKEY ? BPF_CB_CANCEL_OFF : BPF_CB_PAD_OFF);
 	/*
 	 * No pad. That is how it ends when the kernel called an async callback
 	 * or the main prog of an extension: it's exit. A call in a prog of what
 	 * can unwind has unwind_goto behind it, which is an entry also when the
-	 * pad is the next insn. So a return address in a prog without an entry
-	 * is an unwind_exit that gets lost: the verifier sent it to a pad.
+	 * pad is the next insn, and cancel_goto behind a call of what has
+	 * cancel_exit. So a return address in a prog without an entry is an
+	 * unwind_exit or a cancel_exit that gets lost: the verifier sent it to
+	 * a pad.
 	 */
 	scoped_guard(rcu)
 		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
 	return ret_addr;
 }
 
+u64 notrace bpf_unwind_target(u64 ret_addr)
+{
+	return unwind_target(ret_addr, UNWIND_EXKEY);
+}
+NOKPROBE_SYMBOL(bpf_unwind_target);
+
+u64 notrace bpf_cancel_target(u64 ret_addr)
+{
+	return unwind_target(ret_addr, CANCEL_EXKEY);
+}
+NOKPROBE_SYMBOL(bpf_cancel_target);
+
 /*
  * Return where a program continues after a fault in an access to arena whose
  * code ends at @end: at the target of the unwind_goto after the access, or at
@@ -2418,16 +2472,31 @@ u64 bpf_unwind_target(u64 ret_addr)
  */
 u64 bpf_fault_unwind_target(u64 end)
 {
-	const struct exception_table_entry *e = search_bpf_extables(end - 1);
+	const struct exception_table_entry *e = search_bpf_extables(end - UNWIND_EXKEY);
 
 	return e ? end + e->fixup : end;
 }
 
 /*
- * unwind_exit: fix the return address of this frame. r0 and r2 are returned.
- * So is BPF_REG_ARENA_SP, when it's used.
+ * Return true if a cancel_goto follows @call, directly or after the unwind_goto
+ * of the call. @cnt insns follow @call in the prog.
+ */
+static bool call_has_cancel_goto(const struct bpf_insn *call, int cnt)
+{
+	if (cnt && bpf_is_unwind_goto(call + 1)) {
+		call++;
+		cnt--;
+	}
+	return cnt && bpf_is_cancel_goto(call + 1);
+}
+
+/*
+ * unwind_exit, cancel_exit: replace the return address of this frame with what
+ * @target returns for it, bpf_unwind_target() or bpf_cancel_target(). The
+ * epilogue then returns there. r0 and r2 are returned, so they are saved
+ * around the call. So is BPF_REG_ARENA_SP, when it's used.
  */
-static int emit_unwind_ret_addr(u8 **pprog, u8 *ip, bool arena_sp)
+static int emit_unwind_ret_addr(u8 **pprog, u8 *ip, bool arena_sp, void *target)
 {
 	u8 *prog = *pprog, *start = prog;
 
@@ -2435,7 +2504,7 @@ static int emit_unwind_ret_addr(u8 **pprog, u8 *ip, bool arena_sp)
 	if (arena_sp)
 		push_r9(&prog);
 	EMIT4(0x48, 0x8B, 0x7D, 0x08);		/* mov rdi, [rbp + 8] */
-	if (emit_rsb_call(&prog, bpf_unwind_target, ip + (prog - start)))
+	if (emit_rsb_call(&prog, target, ip + (prog - start)))
 		return -EINVAL;
 	EMIT4(0x48, 0x89, 0x45, 0x08);		/* mov [rbp + 8], rax */
 	if (arena_sp)
@@ -2471,7 +2540,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 	s32 arena_sp_off = 0;
 	/* the bytes emitted after the native call of the last call insn */
 	u8 after_call[16], *ret_addr;
-	int after_call_len = 0;
+	/* how many of them the landing of unwind_goto repeats, and that of cancel_goto */
+	int after_call_len = 0, after_call_cancel_len = 0;
 	/* the number of landings in this pass, and their size in bytes so far */
 	int nr_landings = 0, tail = 0;
 	int err;
@@ -3443,6 +3513,11 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				emit_sub_rsp(&prog, 8);
 			if (arena_sp && call_clobbers_arena_sp(insn))
 				emit_ldx(&prog, BPF_DW, BPF_REG_ARENA_SP, BPF_REG_FP, arena_sp_off);
+			/*
+			 * The landing of cancel_goto ends here: after cancel_exit RDX
+			 * is not the second half of what the kfunc returned.
+			 */
+			after_call_cancel_len = prog - ret_addr;
 			/*
 			 * A kfunc returning more than 8 bytes hands the second
 			 * half back in RDX (the native ABI's second return reg),
@@ -3470,54 +3545,75 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				push_r9(&prog);
 				ip += 2;
 			}
-			if (emit_indirect_call(&prog, insn->dst_reg, ip))
+			if (emit_indirect_call(&prog, insn->dst_reg, ip,
+					       call_has_cancel_goto(insn, insn_cnt - i)))
 				return -EINVAL;
 			ret_addr = prog;
 			if (priv_frame_ptr)
 				pop_r9(&prog);
-			after_call_len = prog - ret_addr;
+			after_call_len = after_call_cancel_len = prog - ret_addr;
 			memcpy(after_call, ret_addr, after_call_len);
 			break;
 
-			/* unwind_goto. The verifier expanded may_goto. */
+			/* unwind_goto, cancel_goto. The verifier expanded may_goto. */
 		case BPF_JMP | BPF_JCOND:
 		case BPF_JMP32 | BPF_JCOND: {
+			bool cancel_goto = bpf_is_cancel_goto(insn);
+			/* 'call; unwind_goto; cancel_goto', and this is the second one */
+			bool after_unwind = cancel_goto && i > 1 && bpf_is_unwind_goto(insn - 1);
+			int key = cancel_goto ? CANCEL_EXKEY : UNWIND_EXKEY;
 			int to = i + bpf_jmp_offset(insn);
 			int target = addrs[to];
+			/* how many bytes of after_call[] the landing of this insn repeats */
+			int len = cancel_goto ? after_call_cancel_len : after_call_len;
 			struct jit_landing *landing;
 
-			/* an access to arena is in front: no call, nothing to redo */
-			if (BPF_CLASS(insn[-1].code) != BPF_JMP)
-				after_call_len = 0;
+			if (BPF_CLASS(insn[-1 - after_unwind].code) != BPF_JMP) {
+				if (cancel_goto) {
+					pr_err("bpf_jit: cancel_goto follows no call\n");
+					return -EFAULT;
+				}
+				/* after an access to arena: no call, nothing to repeat */
+				after_call_len = after_call_cancel_len = len = 0;
+			}
 			/*
-			 * What follows the native call, like 'pop r9', has to be
-			 * done on the way to the pad too. Not in the way of what
-			 * returns: the landing goes behind the body of the
-			 * function, and the next insn follows the call.
+			 * Neither insn emits code here, only an extable entry for the
+			 * call before it, see UNWIND_EXKEY. Where code follows the
+			 * native call, like 'pop r9', the entry points to a landing,
+			 * which repeats that code and jumps to the target. The landings
+			 * go after the last insn, so that a call that returns does not
+			 * jump over them:
+			 *
 			 *   call foo
-			 *   pop r9      <- exit returns here
+			 *   pop r9                 <- exit returns here, to ret_addr
 			 *   ...
 			 *   leave; ret
-			 *   ...
-			 *   pop r9      <- unwind_exit returns here
-			 *   jmp pad
-			 * addrs[insn_cnt] is where the body ended in the pass before.
-			 * The entry is written when no insn moves any more.
+			 *   pop r9; jmp pad        <- unwind_exit returns here, key ret_addr - 1
+			 *   pop r9; jmp cancel_pad <- cancel_exit returns here, key ret_addr - 2
+			 *
+			 * The entry is written once the image is allocated. The landings
+			 * then start at addrs[insn_cnt], where the pass before ended the
+			 * body.
 			 */
-			if (after_call_len) {
+			if (len) {
 				if (nr_landings >= ctx->max_landings) {
 					pr_err("bpf_jit: landings bug\n");
 					return -EFAULT;
 				}
 				landing = &ctx->landings[nr_landings++];
-				memcpy(landing->code, after_call, after_call_len);
-				landing->len = after_call_len;
+				memcpy(landing->code, after_call, len);
+				landing->len = len;
 				landing->to = to;
 				target = addrs[insn_cnt] + tail;
-				tail += after_call_len + 5;
+				tail += len + 5;
 			}
+			/*
+			 * The return address of the native call: the code of the call
+			 * insn ends where the first goto after it begins.
+			 */
 			err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
-						 addrs[i - 1] - after_call_len, target);
+						 addrs[i - 1 - after_unwind] - after_call_len,
+						 target, key, after_unwind);
 			if (err)
 				return err;
 			break;
@@ -3792,7 +3888,10 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 		case BPF_JMP | BPF_EXIT:
 			if (src_reg == BPF_UNWIND_EXIT && bpf_prog_can_unwind(bpf_prog) &&
-			    emit_unwind_ret_addr(&prog, ip, arena_sp))
+			    emit_unwind_ret_addr(&prog, ip, arena_sp, bpf_unwind_target))
+				return -EINVAL;
+			if (src_reg == BPF_CANCEL_EXIT && bpf_prog_can_unwind(bpf_prog) &&
+			    emit_unwind_ret_addr(&prog, ip, arena_sp, bpf_cancel_target))
 				return -EINVAL;
 			if (seen_exit) {
 				jmp_offset = ctx->cleanup_addr - addrs[i] + moved;
@@ -4943,7 +5042,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	if (!addrs)
 		goto out_addrs;
 	for (i = 0; i < prog->len; i++)
-		ctx.max_landings += bpf_is_unwind_goto(&prog->insnsi[i]);
+		ctx.max_landings += bpf_is_pad_goto(&prog->insnsi[i]);
 	if (ctx.max_landings) {
 		ctx.landings = kvmalloc_objs(*ctx.landings, ctx.max_landings);
 		if (!ctx.landings)
include/linux/bpf_unwind.h +8 -6
index 10cef80cfb86..71512d96688b 100644
@@ -86,10 +86,12 @@
 #endif
 
 /*
- * The offsets of the two entry points in the stub. unwind_exit returns after a nop. A stack walk
- * looks up the insn before a return address, and for a sample that is taken while the callback
- * returns to the stub that has to be an insn of the stub. cancel_exit returns after the clc and
- * the jnc.
+ * The offsets of the two entry points in the stub. unwind_exit returns after an int3 that nothing
+ * runs. A stack walk looks up the insn before a return address, and for a sample that is taken
+ * while the callback returns to the stub that has to be an insn of the stub. It is not a nop,
+ * because the 5 byte jump of an optimized kprobe before the stub could cover a nop and end after
+ * the entry point. No such jump covers an int3, see copy_optimized_instructions(), or the jnc
+ * before the second entry point, where cancel_exit returns.
  */
 #define BPF_CB_PAD_OFF		1
 #define BPF_CB_CANCEL_OFF	4
@@ -103,7 +105,7 @@
  * instrumentation included, would clobber the variables.
  *
  * The stub is in a subsection after the code, where nothing falls into it. unwind_exit returns
- * after the nop at 4, with the carry flag clear from there on. cancel_exit returns to 5, which
+ * after the int3 at 4, with the carry flag clear from there on. cancel_exit returns to 5, which
  * sets the flag. sbb turns the flag into 'kind', in rcx, which the call clobbers anyway. objtool
  * reaches 4 through the exception table and 5 as the fall-through of the jnc, although the jnc
  * is always taken. The jnc is spelled in bytes so that its length does not depend on the
@@ -123,7 +125,7 @@ do {										\
 		 "	" CALL_NOSPEC "\n"					\
 		 "1:\n"								\
 		 "	.subsection 1\n"					\
-		 "4:	nop\n"							\
+		 "4:	int3\n"							\
 		 "	clc\n"							\
 		 "	.byte 0x73, 0x01\n"	/* jnc 6f */			\
 		 "5:	stc\n"							\
Signature · 1 line
2.53.1-Meta
author maintainer
#56 lore raw

PATCH 56/73 bpf, arm64: Return to cancel_goto at cancel_exit

In reply to Kumar Kartikeya Dwivedi

Teach the arm64 JIT the two insns, as on x86-64. cancel_exit emits the code of unwind_exit with bpf_cancel_fixup() in place of bpf_unwind_fixup(). cancel_goto is an exception table entry for the call before it, like unwind_goto, with a key of its own. After the call of a helper or a kfunc, each of the two has a landing after the epilogue, because a helper returns R0 in x0 alone:

	bl helper		   returns to ret_addr
	mov x8, x0
	...
	<epilogue>
	mov x8, x0; b A		<- unwind_goto A: { .insn = ret_addr - 1 }
	mov x8, x0; b B		<- cancel_goto B: { .insn = ret_addr - 2 }

Both keys are inside the four bytes of the bl. No insn starts there, so a fault cannot hit either entry.

Three cases need care:

- The exception table is sorted by address. When a call has both insns, the unwind_goto adds no entry itself. The cancel_goto after it adds both entries, its own first.
- The two landings of such a call stand in the order of the insns, which is the order in which build_landings() gets to them.
- A cancel_goto never follows an access to arena, and the JIT fails if it finds one there.

The lookup changes as on x86-64. It is one function for both keys, it adds BPF_CB_PAD_OFF or BPF_CB_CANCEL_OFF to the address of the stub of bpf_call_cb(), and both lookups become notrace and are put on the kprobe blacklist. The verifier emits neither insn yet.

---
 arch/arm64/net/bpf_jit_comp.c | 175 +++++++++++++++++++++++++---------
 1 file changed, 132 insertions(+), 43 deletions(-)
arch/arm64/net/bpf_jit_comp.c +132 -43
index 86f49bf96036..18ec626762f6 100644
@@ -10,6 +10,7 @@
 #include <linux/arm-smccc.h>
 #include <linux/bitfield.h>
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/cfi.h>
 #include <linux/extable.h>
 #include <linux/filter.h>
@@ -1655,11 +1656,14 @@ static int add_exception_handler(const struct bpf_verifier_env *env,
 	return 0;
 }
 
-/* unwind_goto after the call of a helper or a kfunc, which return r0 in x0 alone */
-static bool unwind_goto_after_helper(const struct bpf_insn *insn)
+/* Whether @insn, unwind_goto or cancel_goto, follows the call of a helper or a kfunc */
+static bool goto_after_helper(const struct bpf_insn *insn)
 {
 	const struct bpf_insn *call = insn - 1;
 
+	/* 'call; unwind_goto; cancel_goto' */
+	if (bpf_is_cancel_goto(insn) && bpf_is_unwind_goto(call))
+		call--;
 	return call->code == (BPF_JMP | BPF_CALL) && call->src_reg != BPF_PSEUDO_CALL;
 }
 
@@ -1674,8 +1678,15 @@ static bool unwind_goto_after_helper(const struct bpf_insn *insn)
  * a helper, see build_landings().
  * After an access to arena, ret_addr is the end of the code of the access, and
  * a fault in the access goes to the target, see bpf_fault_unwind_target().
+ *
+ * cancel_goto is the same for cancel_exit, with the entry at ret_addr - 2,
+ * because the unwind_goto of the same call has the one at ret_addr - 1. Both
+ * keys are inside the call insn. cancel_goto never follows an access to arena.
  */
-static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target)
+#define UNWIND_EXKEY	1
+#define CANCEL_EXKEY	2
+
+static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target, int key)
 {
 	struct exception_table_entry *ex;
 	off_t ins_offset;
@@ -1689,7 +1700,7 @@ static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target)
 		return -EINVAL;
 
 	ex = &ctx->prog->aux->extable[ctx->exentry_idx];
-	ins_offset = (long)&ctx->ro_image[ret_addr] - 1 - (long)&ex->insn;
+	ins_offset = (long)&ctx->ro_image[ret_addr] - key - (long)&ex->insn;
 	if (WARN_ON_ONCE(ins_offset >= 0 || ins_offset < INT_MIN))
 		return -ERANGE;
 
@@ -1704,10 +1715,39 @@ static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target)
 }
 
 /*
- * The landings of the pads after the calls of helpers and kfuncs, past the
- * epilogue, where nothing falls into them: 'mov x8, x0; b pad' each, see the
- * unwind_goto case of build_insn(). They go in after the body, when the pads
- * are placed and the entries are in, and each fills in the fixup of its entry.
+ * Add the extable entry of @insn, an unwind_goto or cancel_goto after a call
+ * that returns to @ret_addr. If the insn gets a landing, *@landing is the index
+ * of the entry, and build_landings() fills in the fixup.
+ */
+static int add_goto_exentry(struct jit_ctx *ctx, const struct bpf_insn *insn, int ret_addr,
+			    int *landing)
+{
+	int i = insn - ctx->prog->insnsi;
+	int target = ctx->offset[i + 1 + bpf_jmp_offset(insn)];
+
+	if (goto_after_helper(insn)) {
+		*landing = ctx->exentry_idx;
+		target = ret_addr;
+	}
+	return add_unwind_exentry(ctx, ret_addr, target,
+				  bpf_is_cancel_goto(insn) ? CANCEL_EXKEY : UNWIND_EXKEY);
+}
+
+/*
+ * Emit the landings after the epilogue. r0 is x8, so 'mov x8, x0' follows a
+ * call. A helper or a kfunc that leaves through its unwind label skips the mov,
+ * so an unwind_goto or cancel_goto after its call gets a landing, which does
+ * the mov and branches to the target:
+ *
+ *   bl helper                  returns to ret_addr
+ *   mov x8, x0
+ *   ...
+ *   <epilogue>
+ *   mov x8, x0; b pad          <- unwind_exit returns here, key ret_addr - 1
+ *   mov x8, x0; b cancel_pad   <- cancel_exit returns here, key ret_addr - 2
+ *
+ * build_insn() has added the entries. Each landing fills in the fixup of its
+ * entry.
  */
 static int build_landings(struct jit_ctx *ctx)
 {
@@ -1718,8 +1758,9 @@ static int build_landings(struct jit_ctx *ctx)
 		const struct bpf_insn *insn = &prog->insnsi[i];
 		int ret_addr, jmp_offset;
 
-		if (!bpf_is_unwind_goto(insn) || !unwind_goto_after_helper(insn))
+		if (!bpf_is_pad_goto(insn) || !goto_after_helper(insn))
 			continue;
+		/* unwind_goto emits no code, so this also holds for the cancel_goto after it */
 		ret_addr = ctx->offset[i] - 1;
 		if (ctx->image) {
 			struct exception_table_entry *ex;
@@ -1738,40 +1779,59 @@ static int build_landings(struct jit_ctx *ctx)
 }
 
 /*
- * The verifier made sure that unwind_goto follows a call in a prog. When the
- * kernel called an async callback, it's exit. A helper that calls a callback
- * has a pad when it wants one, see bpf_call_cb().
+ * Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with
+ * cancel_exit, @key CANCEL_EXKEY, returns to.
+ * The verifier made sure that unwind_goto follows a call in a prog, and
+ * cancel_goto where the callee has cancel_exit. When the kernel called an async
+ * callback, it's exit. A helper that calls a callback has a pad when it wants
+ * one, see bpf_call_cb().
  */
-u64 bpf_unwind_target(u64 ret_addr)
+static u64 unwind_target(u64 ret_addr, int key)
 {
 	const struct exception_table_entry *e;
 
-	e = search_bpf_extables(ret_addr - 1);
+	e = search_bpf_extables(ret_addr - key);
 	if (e)
 		return ret_addr + e->fixup;
 	/*
-	 * The pad of a helper that called a callback with bpf_call_cb(): its
-	 * entries are the EX_TYPE_BPF ones of the kernel and module tables.
-	 * Anything else at a return address is some caller's own fixup, and
-	 * what a JIT keyed there is a fixup of the insn after the call.
+	 * A helper that called the frame with bpf_call_cb() has an EX_TYPE_BPF
+	 * entry at the return address itself. An entry of another type there
+	 * is the fixup of the insn after some call. The entry points to the
+	 * stub of the helper's unwind label, which has one entry point for
+	 * unwind_exit and one for cancel_exit.
 	 */
 	e = search_kernel_exception_table(ret_addr);
 	if (!e)
 		e = search_module_extables(ret_addr);
 	if (e && e->type == EX_TYPE_BPF)
-		return (unsigned long)&e->fixup + e->fixup;
+		return (unsigned long)&e->fixup + e->fixup +
+		       (key == CANCEL_EXKEY ? BPF_CB_CANCEL_OFF : BPF_CB_PAD_OFF);
 	/*
 	 * No pad. That is how it ends when the kernel called an async callback
 	 * or the main prog of an extension: it's exit. A call in a prog of what
 	 * can unwind has unwind_goto behind it, which is an entry also when the
-	 * pad is the next insn. So a return address in a prog without an entry
-	 * is an unwind_exit that gets lost: the verifier sent it to a pad.
+	 * pad is the next insn, and cancel_goto behind a call of what has
+	 * cancel_exit. So a return address in a prog without an entry is an
+	 * unwind_exit or a cancel_exit that gets lost: the verifier sent it to
+	 * a pad.
 	 */
 	scoped_guard(rcu)
 		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
 	return ret_addr;
 }
 
+u64 notrace bpf_unwind_target(u64 ret_addr)
+{
+	return unwind_target(ret_addr, UNWIND_EXKEY);
+}
+NOKPROBE_SYMBOL(bpf_unwind_target);
+
+u64 notrace bpf_cancel_target(u64 ret_addr)
+{
+	return unwind_target(ret_addr, CANCEL_EXKEY);
+}
+NOKPROBE_SYMBOL(bpf_cancel_target);
+
 /*
  * Return where a program continues after a fault in an access to arena whose
  * code ends at @end: at the target of the unwind_goto after the access, or at
@@ -1779,7 +1839,7 @@ u64 bpf_unwind_target(u64 ret_addr)
  */
 u64 bpf_fault_unwind_target(u64 end)
 {
-	const struct exception_table_entry *e = search_bpf_extables(end - 1);
+	const struct exception_table_entry *e = search_bpf_extables(end - UNWIND_EXKEY);
 
 	return e ? end + e->fixup : end;
 }
@@ -1792,12 +1852,21 @@ static long bpf_unwind_fixup(u64 lr)
 	return bpf_unwind_target(ret_addr) - ret_addr;
 }
 
+/* The same for cancel_exit */
+static long bpf_cancel_fixup(u64 lr)
+{
+	u64 ret_addr = ptrauth_strip_kernel_insn_pac(lr);
+
+	return bpf_cancel_target(ret_addr) - ret_addr;
+}
+
 /*
- * unwind_exit: return to the pad. LR in the frame record is signed. Instead of
- * signing the address of the pad, let the epilogue authenticate LR as it is and
- * add the offset of the pad to it. r0 and r2 are returned.
+ * unwind_exit, cancel_exit: return to the pad. LR in the frame record is
+ * signed. Instead of signing the address of the pad, let the epilogue
+ * authenticate LR as it is and add the offset of the pad to it, which @fixup
+ * returns. r0 and r2 are returned.
  */
-static void emit_unwind_exit(struct jit_ctx *ctx)
+static void emit_unwind_exit(struct jit_ctx *ctx, long (*fixup)(u64 lr))
 {
 	const u8 tmp = bpf2a64[TMP_REG_1];
 	const u8 r0 = bpf2a64[BPF_REG_0];
@@ -1805,7 +1874,7 @@ static void emit_unwind_exit(struct jit_ctx *ctx)
 
 	emit(A64_PUSH(r0, r2, A64_SP), ctx);
 	emit(A64_LDR64I(A64_R(0), A64_FP, 8), ctx);
-	emit_call((u64)bpf_unwind_fixup, ctx);
+	emit_call((u64)fixup, ctx);
 	emit(A64_MOV(1, tmp, A64_R(0)), ctx);
 	emit(A64_POP(r0, r2, A64_SP), ctx);
 	build_epilogue(ctx, false, true);
@@ -2427,37 +2496,57 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		if (emit_bpf_tail_call(ctx))
 			return -EFAULT;
 		break;
-	/* unwind_goto. The verifier expanded may_goto. */
+	/* unwind_goto, cancel_goto. The verifier expanded may_goto. */
 	case BPF_JMP | BPF_JCOND:
 	case BPF_JMP32 | BPF_JCOND:
 	{
+		bool cancel_goto = bpf_is_cancel_goto(insn);
+		/* 'call; unwind_goto; cancel_goto', and this is the second one */
+		bool after_unwind = cancel_goto && bpf_is_unwind_goto(insn - 1);
+		int landing[2] = { -1, -1 };
 		int ret_addr = ctx->idx - 1;
-		int target = ctx->offset[i + 1 + bpf_jmp_offset(insn)];
+		int j;
 
 		/*
-		 * 'bl foo; mov x8, x0' is in front. After the call of a subprog
-		 * the pad doesn't miss the mov: r0 is x8 in the subprog too, its
-		 * epilogue copies x8 to x0 and leaves x8 as it is. A helper that
-		 * leaves to the pad returns r0 in x0 alone, so the pad after its
-		 * call is entered through a landing past the epilogue, see
-		 * build_landings(), which fills in the fixup of the entry.
+		 * The extable is sorted by address, and the entry of cancel_goto has
+		 * the lower one. So unwind_goto adds no entry when cancel_goto follows
+		 * it: the cancel_goto adds both entries, its own first.
 		 */
-		if (unwind_goto_after_helper(insn)) {
-			ctx->landing_ex[ctx->landing_idx++] = ctx->exentry_idx;
-			target = ret_addr;
-		} else if (BPF_CLASS(insn[-1].code) != BPF_JMP) {
+		if (!cancel_goto && i + 1 < ctx->prog->len && bpf_is_cancel_goto(insn + 1))
+			break;
+		if (BPF_CLASS(insn[-1 - after_unwind].code) != BPF_JMP) {
+			if (cancel_goto) {
+				pr_err_once("cancel_goto at insn %d follows no call\n", i);
+				return -EFAULT;
+			}
 			/* After an access to arena. Its last insn is the one that can fault. */
 			ret_addr = ctx->idx;
 		}
-		ret = add_unwind_exentry(ctx, ret_addr, target);
+		/*
+		 * Else 'bl foo; mov x8, x0' is in front. After the call of a subprog
+		 * the target doesn't miss the mov: r0 is x8 in the subprog too, and
+		 * its epilogue copies x8 to x0 and leaves x8 as it is. After the
+		 * call of a helper the entry points to a landing.
+		 */
+		ret = add_goto_exentry(ctx, insn, ret_addr, &landing[after_unwind]);
+		if (!ret && after_unwind)
+			ret = add_goto_exentry(ctx, insn - 1, ret_addr, &landing[0]);
 		if (ret)
 			return ret;
+		/* build_landings() emits the landings in the order of the insns */
+		for (j = 0; j < 2; j++)
+			if (landing[j] >= 0)
+				ctx->landing_ex[ctx->landing_idx++] = landing[j];
 		break;
 	}
 	/* function return */
 	case BPF_JMP | BPF_EXIT:
 		if (bpf_is_unwind_exit(insn) && bpf_prog_can_unwind(ctx->prog)) {
-			emit_unwind_exit(ctx);
+			emit_unwind_exit(ctx, bpf_unwind_fixup);
+			break;
+		}
+		if (bpf_is_cancel_exit(insn) && bpf_prog_can_unwind(ctx->prog)) {
+			emit_unwind_exit(ctx, bpf_cancel_fixup);
 			break;
 		}
 		/* Optimization: when last instruction is EXIT,
@@ -2812,8 +2901,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		goto out_off;
 
 	for (i = 1; i < prog->len; i++)
-		if (bpf_is_unwind_goto(&prog->insnsi[i]) &&
-		    unwind_goto_after_helper(&prog->insnsi[i]))
+		if (bpf_is_pad_goto(&prog->insnsi[i]) &&
+		    goto_after_helper(&prog->insnsi[i]))
 			nr_landings++;
 	if (nr_landings) {
 		ctx.landing_ex = kvzalloc_objs(int, nr_landings);
Signature · 1 line
2.53.1-Meta
author maintainer
#57 lore raw

PATCH 57/73 bpf: Use cancel_exit to leave a frame that the kernel cancels

In reply to Kumar Kartikeya Dwivedi

Currently the generated pads leave a function with unwind_exit. So where a caller has an unwind_goto of its own after the call, a cancellation enters the program's landing pad, and the program can continue running.

Emit cancel_exit and cancel_goto instead:

- A generated pad at a site leaves with cancel_exit, and so does the stack check of a recursive function. A function that only the kernel calls still leaves with exit.
- The verifier adds a cancel_goto after each call whose callee can be cancelled. It jumps to the generated pad of that call. Where the program has an unwind_goto after the call, the cancel_goto follows it.

  try {                       call wait
          v = wait();         unwind_goto catch  <- wait() threw on its own
  } catch (...) {             cancel_goto pad    <- wait() was cancelled
          v = 0;              ...
  }                    catch: ...
                              exit
                         pad: r0 = 0
                              exit

cancel_exit returns to a cancel_goto only, and unwind_exit to an unwind_goto only. So a cancellation enters no landing pad of the program, and none can end it. The program returns the value that the kernel chooses for its type.

What changes for programs that load today:

- A landing pad of the program that ran when a callee was cancelled no longer runs then, not even one that only cleans up and continues unwinding, such as a C++ destructor. The generated pad releases what the verifier knows the frame to hold. Later patches let a cancellation run such cleanup pads again.
- A call above a site is now a site itself, also where the program has an unwind_goto after it. A program is rejected if a frame holds something there that no generated pad can release.

In the main pass, a state whose callee did not return carries a mark. The new value BPF_CANCELLED says that the callee was cancelled. Such a state never takes the program's unwind_goto. Its frame is cancelled in turn at the call, a site of the new kind BPF_SITE_CANCEL_CALL. The verifier does not merge two states that differ in the mark, and the bits that record whether a function can unwind (did_unwind, can_unwind, must_unwind, unwinds_for_sure) each get a twin for cancellation.

The pads that the verifier generates for the program's own unwinding stay (BPF_SITE_CALL). Where a callee leaves with unwind_exit and the caller has no unwind_goto after the call, the verifier adds one, with a pad that leaves with unwind_exit in turn. Such a pad no longer serves a cancellation, so it is always on the way to a landing pad of the program. Until now it passed R0 on only in a program with bpf_throw(). Now the rule is the same in every program, and verifier.rst has it as a table:

- In a static function the pad passes on R0, a pointer as well as a number, and R2 if the function returns two registers.
- In a global function the pad passes nothing on, because the callers are verified separately and only see a scalar return value. R0 is the value that the kernel chooses for the program type.

These cases need care:

- R2 is 0 at every cancel_exit, so that the code after a cancel_goto reads nothing of the cancelled frame.
- The program's unwind_goto takes its 32 bit form where a cancel_goto follows it, so that the patch list never puts a jump between the two. If no state reached the program's unwind_goto, it is dead code, and the cancel_goto goes right after the call.
- Neither insn may be the target of a jump, because a JIT may put a landing where the insn is. bpf_check_unwind_gotos() reports as a verifier bug an unwind_goto or cancel_goto that jumps to one of the two, and any jump to a cancel_goto after an unwind_goto.
- The inlined bpf_loop() passes on a cancelled callback like one that left with unwind_exit, with four more insns.

The tests that expected the program's landing pad to catch a cancellation now expect the value that the kernel chooses. pad_forgets of verifier_budget loads, because the landing pad of the program that made it fail is no longer entered.

---
 Documentation/bpf/verifier.rst                |  92 ++++-
 include/linux/bpf_verifier.h                  | 149 ++++++-
 kernel/bpf/const_fold.c                       |  11 +-
 kernel/bpf/core.c                             |  20 +-
 kernel/bpf/fixups.c                           | 374 +++++++++++++-----
 kernel/bpf/pads.c                             | 235 +++++++----
 kernel/bpf/verifier.c                         | 372 +++++++++++------
 .../bpf/progs/pro_epilogue_arena_stack.c      |   2 +-
 .../bpf/progs/verifier_arena_stack.c          |  27 +-
 .../selftests/bpf/progs/verifier_budget.c     |  75 ++--
 .../selftests/bpf/progs/verifier_patch_list.c |   5 +-
 11 files changed, 956 insertions(+), 406 deletions(-)
Documentation/bpf/verifier.rst +73 -19
index ed72a57ed27b..8555d023dbaf 100644
@@ -749,7 +749,7 @@ if                                     the loop ends because
 =====================================  =========================================
 k of s is at most 2^32                 k grows in each trip and has a bound;
                                        the largest k + 1 is the *trip count*
-each trip runs ``may_goto``            it leaves the loop after some time or
+each trip runs ``may_goto``            it stops the loop after some time or
                                        some number of trips
 each trip takes from an iterator       an iterator has an end
 none of these holds                    the verifier adds ``may_goto``
@@ -915,10 +915,10 @@ Cancellation
 ============
 
 The kernel *cancels* a program when it has to end the program before the
-program returns by itself: a ``may_goto`` of the verifier is taken, the stack
-check of a recursive function fails, an access to arena faults, or the program
-calls ``bpf_throw()``. Each frame of the program then releases what it holds,
-and the program returns a value that the kernel chooses.
+program returns by itself: a ``may_goto`` is taken, the stack check of a
+recursive function fails, an access to arena faults, or the program calls
+``bpf_throw()``. Each frame of the program then releases what it holds, and the
+program returns a value that the kernel chooses.
 
 An insn at which the kernel can cancel the program is a *site*: one of these
 four insns, or a call whose callee can be cancelled. For each site the verifier
@@ -937,7 +937,9 @@ what the frame holds at the site and leaves the frame::
                                              exit
 
 When the time is up, ``may_goto`` jumps to the pad, and the program ends without
-getting to ``*p``.
+getting to ``*p``. A ``may_goto`` of the program is a site too, where a JIT
+gives it a time limit: when the time is up, the code at its target does not
+run. Where it counts trips, it stays a plain jump.
 
 The pad of a function that the kernel called ends in ``exit``. The main
 function returns the value that the kernel chooses for the program type, see
@@ -947,21 +949,22 @@ errno. It is 0 in the listings here. After ``bpf_throw()`` it is the argument
 of ``bpf_throw()``. If the program has an exception callback, the pad of the
 main function calls it with the value and returns what the callback returns.
 
-The pad of a function that the program called ends in ``unwind_exit``. That
-insn returns to the ``unwind_goto`` after the call, which jumps to the landing
+The pad of a function that the program called ends in ``cancel_exit``. That
+insn returns to the ``cancel_goto`` after the call, which jumps to the landing
 pad of the call in the caller. So the frames are cancelled one by one. When a
-callback is cancelled, its helper returns to the ``unwind_goto`` after its own
-call. The verifier adds the ``unwind_goto`` where the program has none.
+callback is cancelled, its helper returns to the ``cancel_goto`` after its own
+call. Only the verifier emits these two insns. ``cancel_goto`` is an entry of
+the exception table and no code, so a call that returns pays nothing for it.
 
 A function *cannot be cancelled* if it has neither ``exit`` nor a call of
 ``bpf_throw()``, or if the program is loaded without ``CAP_PERFMON``. A
-function that the program calls cannot be cancelled either if the JIT lacks
-``unwind_exit``, which only the JITs of x86-64 and arm64 have, or if its caller
-is a helper that cannot pass a cancellation on. In such a function a loop that
-needs a ``may_goto`` of the verifier, a recursion and ``bpf_throw()`` reject
-the program. An access to arena that faults is skipped there, in every function
-on a JIT without ``unwind_exit``, and where the verifier cannot generate a
-landing pad for it.
+function that the program calls cannot be cancelled either if the JIT lacks the
+two insns, which only the JITs of x86-64 and arm64 have, if its caller is a
+helper that cannot pass a cancellation on, or if its caller cannot be
+cancelled. In such a function a loop that needs a ``may_goto`` of the verifier,
+a recursion and ``bpf_throw()`` reject the program, and a ``may_goto`` of the
+program is a plain jump. An access to arena that faults is skipped there, and
+in every function on a JIT without the two insns.
 
 Landing pads
 ------------
@@ -1022,7 +1025,8 @@ callee returns with it, the caller holds it again, see ``hand_over_refs()``::
                                       pad: r1 = r6
                                            call bpf_task_release
                                            r0 = 0
-                                           unwind_exit
+                                           r2 = 0
+                                           cancel_exit
 
 The landing pad of the call releases nothing, and nothing is added at run time.
 A call hands over a pointer in one of ``R1`` - ``R5`` that the callee reads and
@@ -1078,6 +1082,55 @@ landing pad needs them, in these cases:
 Both are tried only where the program would be rejected without them, see
 `All passes`_.
 
+The program's own unwinding
+---------------------------
+
+A program can unwind by itself, as C++ and Rust do. ``unwind_exit`` leaves a
+function, and the ``unwind_goto`` after the call jumps to a landing pad that
+the program has. "Landing pad" alone is always one that the verifier generates.
+The program's landing pad is code like any other: it can catch and continue
+running. A cancelled program must not continue. So ``cancel_exit`` returns to a
+``cancel_goto`` only, and ``unwind_exit`` to an ``unwind_goto`` only. Where the
+program has an ``unwind_goto`` after a call, the ``cancel_goto`` follows it::
+
+  try {                       call wait
+          v = wait();         unwind_goto catch  <- wait() threw on its own
+  } catch (...) {             cancel_goto pad    <- wait() was cancelled
+          v = 0;              ...
+  }                    catch: ...
+                              exit
+                         pad: r0 = 0
+                              exit
+
+A cancellation enters no landing pad of the program, so the program cannot
+catch it.
+
+Where a callee leaves with ``unwind_exit`` and the caller has no
+``unwind_goto`` after the call, the verifier adds one, with a landing pad that
+releases what the frame holds and leaves with ``unwind_exit`` in turn. What a
+landing pad of the program further up reads depends on the functions in
+between:
+
+=====================================  =========================================
+the function in between                what gets through it
+=====================================  =========================================
+a static function                      ``R0`` as ``unwind_exit`` left it, a
+                                       pointer as well as a number, and ``R2``
+                                       if the function returns two registers
+a global function that has a landing   what that pad leaves at its
+pad of its own at the call             ``unwind_exit``: a number, or a pointer
+                                       to arena
+a global function without one          nothing: ``R0`` is the value that the
+                                       kernel chooses, see
+                                       ``bpf_cancelled_retval()``, and ``R2``
+                                       is 0 if the function returns two
+                                       registers
+=====================================  =========================================
+
+A global function is different because its callers are checked without it and
+only see a number as its return value. A compiler that wants an object to get
+through a global function gives the call there a landing pad of its own.
+
 After an error
 ==============
 
@@ -1451,7 +1504,8 @@ A landing pad has no barrier, and no speculative state is checked on the way to
 one. So only a program that is loaded with ``CAP_PERFMON`` gets landing pads
 and can have ``unwind_exit``, ``unwind_goto`` and ``bpf_throw()``. Without it
 no function can be cancelled, see `Cancellation`_: a loop that needs a
-``may_goto`` of the verifier and a recursion are rejected.
+``may_goto`` of the verifier and a recursion are rejected, and a ``may_goto``
+of the program is a plain jump.
 
 Some mechanisms depend on a capability. The last line is there because the cpu
 can go past the jump that a proof needs:
include/linux/bpf_verifier.h +128 -21

282 lines not on this page · raw message

kernel/bpf/const_fold.c +5 -6
index 17d208f1ed0e..2a5f15d22474 100644
@@ -300,13 +300,12 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 			struct const_arg_info *c = &ci[r];
 
 			/*
-			 * The revisit of a call with a callback that unwound
-			 * carries the r0 of the callback, see check_helper_call():
-			 * r0 is no constant of that insn.
+			 * A callback that unwinds goes back to the call of its helper with its own
+			 * R0, see check_helper_call(), so R0 is no constant before such a call. An
+			 * unwind_goto of the program need not follow: a generated pad passes R0 on
+			 * too, see bpf_pad_passes_on().
 			 */
-			if (r == BPF_REG_0 && i + 1 < insn_cnt &&
-			    bpf_is_sync_callback_calling_insn(&insns[i]) &&
-			    (bpf_is_unwind_goto(&insns[i + 1]) || env->has_throw))
+			if (r == BPF_REG_0 && bpf_is_sync_callback_calling_insn(&insns[i]))
 				continue;
 			switch (c->state) {
 			case CONST_ARG_CONST: {
kernel/bpf/core.c +14 -6
index 25fd3213d000..288963919afd 100644
@@ -437,6 +437,8 @@ static int patch_insn_target(const struct bpf_patch_image *img, const struct bpf
 		tgt = p->jmp_to;
 	} else if (idx + 1 == p->jmp2) {
 		tgt = p->jmp2_to;
+	} else if (idx + 1 == p->jmp3) {
+		tgt = p->jmp3_to;
 	} else if (idx == p->self) {
 		tgt = p->off + rel + 1;
 	} else {
@@ -561,6 +563,7 @@ int __bpf_patch_list_insert(struct bpf_patch_list *pl, const struct bpf_prog *pr
 		p->self += cnt;
 		p->jmp += p->jmp ? cnt : 0;
 		p->jmp2 += p->jmp2 ? cnt : 0;
+		p->jmp3 += p->jmp3 ? cnt : 0;
 	}
 	memcpy(insn, insns, cnt * sizeof(*insns));
 	p->len += cnt;
@@ -571,7 +574,7 @@ int __bpf_patch_list_insert(struct bpf_patch_list *pl, const struct bpf_prog *pr
 /*
  * 'insn' of the last patch goes to insn 'to' of the old image, however far that is.
  * With 'back' it goes to the last insns of the patch of insn 'to - 1'.
- * A patch has two such jumps at most, and the second one has no 'back'.
+ * A patch has three such jumps at most, and only the first one has 'back'.
  */
 void bpf_patch_list_jump(struct bpf_patch_list *pl, const struct bpf_insn *insn, u32 to, u32 back)
 {
@@ -580,13 +583,18 @@ void bpf_patch_list_jump(struct bpf_patch_list *pl, const struct bpf_insn *insn,
 
 	if (p->jmp) {
 		/*
-		 * There is no room for a third one, nor for 'back' of the second one. Such a jump
-		 * goes out of the program: bpf_patch_list_build() fails for it.
+		 * A patch has no room for a fourth jump, nor for 'back' of a later one. Make such a
+		 * jump lead out of the program, so that bpf_patch_list_build() fails.
 		 */
-		if (WARN_ON_ONCE(p->jmp2 || back))
+		if (WARN_ON_ONCE(p->jmp3 || back))
 			to = U32_MAX;
-		p->jmp2 = jmp;
-		p->jmp2_to = to;
+		if (p->jmp2) {
+			p->jmp3 = jmp;
+			p->jmp3_to = to;
+		} else {
+			p->jmp2 = jmp;
+			p->jmp2_to = to;
+		}
 		return;
 	}
 	p->jmp = jmp;
kernel/bpf/fixups.c +266 -108

564 lines not on this page · raw message

kernel/bpf/pads.c +160 -75

469 lines not on this page · raw message

kernel/bpf/verifier.c +245 -127

623 lines not on this page · raw message

tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c +1 -1
index e901282c53a3..2bb4261229dd 100644
@@ -83,7 +83,7 @@ __xlated("*(u64 *)(r12 -8) = 10")
 __xlated("...")
 __xlated("call pc+")
 /* a fault in the stack of the subprog unwinds */
-__xlated("unwind_goto pc+")
+__xlated("cancel_goto pc+")
 /* give the stack back, then the epilogue */
 __xlated("w12 += -16")
 __xlated("if w12 & 0x10 goto pc+5")
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +15 -12
index 5d22dfc6fdcb..2a3210a50678 100644
@@ -5,6 +5,8 @@
 #include "../../../include/linux/filter.h"
 #include "bpf_misc.h"
 
+#define __exception_cb(name) __attribute__((btf_decl_tag("exception_callback:" #name)))
+
 #if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64)
 
 struct {
@@ -218,10 +220,22 @@ static __naked __noinline __used long goes_down(void)
 	: __clobber_all);
 }
 
+/*
+ * The kernel unwinds the prog, and no code of the prog runs behind the call: what the prog returns
+ * is up to the exception callback, which runs when the frames are gone.
+ */
+__noinline int used_between_8k_and_32k(__u64 cookie)
+{
+	unsigned long used = last_r12 - first_r12;
+
+	return used >= 8192 && used <= 32736;
+}
+
 /* The check of a recursion looks at the kernel stack. It fails before 32K of arena are used. */
 SEC("syscall")
 __description("arena stack: recursion ends in the stack")
 __success __retval(1)
+__exception_cb(used_between_8k_and_32k)
 __naked void recursion(void)
 {
 	asm volatile (
@@ -230,23 +244,12 @@ __naked void recursion(void)
 	"r2 = %[first_r12] ll;"
 	"*(u64 *)(r2 + 0) = r1;"
 	"call goes_down;"
-	".8byte %[unwind_goto];"
-	"r1 = %[last_r12] ll;"
-	"r1 = *(u64 *)(r1 + 0);"
-	"r2 = %[first_r12] ll;"
-	"r2 = *(u64 *)(r2 + 0);"
-	"r1 -= r2;"
 	"r0 = 0;"
-	"if r1 < 8192 goto +2;"
-	"if r1 > 32736 goto +1;"
-	"r0 = 1;"
 	"exit;"
 	:
 	: __imm_addr(first_r12),
-	  __imm_addr(last_r12),
 	  __imm_insn(adj, ADJ(32)),
-	  __imm_insn(mov, MOV(BPF_REG_1)),
-	  __imm_insn(unwind_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0))
+	  __imm_insn(mov, MOV(BPF_REG_1))
 	: __clobber_all);
 }
 
tools/testing/selftests/bpf/progs/verifier_budget.c +46 -29

171 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_patch_list.c +3 -2
index 5516100dd2b0..5631df29d111 100644
@@ -416,7 +416,7 @@ __arch_x86_64
 __arch_arm64
 __success
 __xlated("27: call pc+10")
-__xlated("28: unwind_goto pc-15")
+__xlated("28: cancel_goto pc-15")
 __xlated("...")
 __xlated("37: exit")
 __xlated("38: r0 = ")
@@ -433,7 +433,8 @@ __xlated("56: if r1 != 0x0 goto pc-12")
 __xlated("57: r0 = 0")
 __xlated("58: exit")
 __xlated("59: r0 = 0")
-__xlated("60: unwind_exit")
+__xlated("60: r2 = 0")
+__xlated("61: cancel_exit")
 __naked void patch_list_insert_in_front(void)
 {
 	INSERT_IN_FRONT;
Signature · 1 line
2.53.1-Meta
author maintainer
#58 lore raw

PATCH 58/73 bpf: Check that a helper whose callback may unwind has an unwind label

In reply to Kumar Kartikeya Dwivedi

Currently the verifier knows which helpers and kfuncs have an unwind label from two lists that are kept by hand, helper_has_cb_pad() and kfunc_has_cb_pad(), and it takes every map_for_each_callback() op to have one. Nothing checks the lists against the functions.

A function that is in a list and has no unwind label is not noticed at run time. unwind_exit or cancel_exit of its callback looks up a return address in the text of the kernel and finds no exception table entry. That is no error for the lookup, because a frame that the kernel called, such as an async callback, has no entry either. So the callback returns to its helper as if it had not unwound, the program continues, and nothing warns.

Check when a program is loaded. Where the lists say that a call has an unwind label, check_cb_pad() looks for an exception table entry of bpf_call_cb() in the function that is called: the helper, the kfunc, and for bpf_for_each_map_elem() also the op of the map. If there is none, the load fails with a verifier bug. If bpf_find_vma() lost its label, the message would be:

verifier bug: bpf_find_vma has no landing pad for its callback

The message says "landing pad" where it means the unwind label.

func_has_cb_pad() finds the entry with what a JIT has already. It walks the exception table of the kernel, or of the module that has the function, and asks bpf_unwind_target() about every entry whose key is inside the function. The lookup returns another address only for an entry of bpf_call_cb().

The lists are trusted without a check in two cases:

- Without kallsyms, because the size of a function is not known.
- In a kernel whose JIT does not unwind, where no callback unwinds.

---
 arch/arm64/net/bpf_jit_comp.c | 13 +++---
 arch/x86/net/bpf_jit_comp.c   | 13 +++---
 include/linux/bpf_verifier.h  |  3 ++
 kernel/bpf/verifier.c         | 77 +++++++++++++++++++++++++++++++++--
 4 files changed, 88 insertions(+), 18 deletions(-)
arch/arm64/net/bpf_jit_comp.c +6 -7
index 18ec626762f6..c41e649c735f 100644
@@ -1807,13 +1807,12 @@ static u64 unwind_target(u64 ret_addr, int key)
 		return (unsigned long)&e->fixup + e->fixup +
 		       (key == CANCEL_EXKEY ? BPF_CB_CANCEL_OFF : BPF_CB_PAD_OFF);
 	/*
-	 * No pad. That is how it ends when the kernel called an async callback
-	 * or the main prog of an extension: it's exit. A call in a prog of what
-	 * can unwind has unwind_goto behind it, which is an entry also when the
-	 * pad is the next insn, and cancel_goto behind a call of what has
-	 * cancel_exit. So a return address in a prog without an entry is an
-	 * unwind_exit or a cancel_exit that gets lost: the verifier sent it to
-	 * a pad.
+	 * No entry: the kernel called the frame, as it calls an async callback
+	 * or the main prog of an extension, and the frame returns like exit.
+	 * In a prog, unwind_goto or cancel_goto follows every call whose callee
+	 * can leave this way, so a return address in a prog is a bug here. A
+	 * helper without an unwind label would not show: the verifier checks
+	 * for that at load time, see check_cb_pad().
 	 */
 	scoped_guard(rcu)
 		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
arch/x86/net/bpf_jit_comp.c +6 -7
index 1c7bc301784f..fc57ab6a238c 100644
@@ -2440,13 +2440,12 @@ static u64 unwind_target(u64 ret_addr, int key)
 		return (unsigned long)&e->fixup + e->fixup +
 		       (key == CANCEL_EXKEY ? BPF_CB_CANCEL_OFF : BPF_CB_PAD_OFF);
 	/*
-	 * No pad. That is how it ends when the kernel called an async callback
-	 * or the main prog of an extension: it's exit. A call in a prog of what
-	 * can unwind has unwind_goto behind it, which is an entry also when the
-	 * pad is the next insn, and cancel_goto behind a call of what has
-	 * cancel_exit. So a return address in a prog without an entry is an
-	 * unwind_exit or a cancel_exit that gets lost: the verifier sent it to
-	 * a pad.
+	 * No entry: the kernel called the frame, as it calls an async callback
+	 * or the main prog of an extension, and the frame returns like exit.
+	 * In a prog, unwind_goto or cancel_goto follows every call whose callee
+	 * can leave this way, so a return address in a prog is a bug here. A
+	 * helper without an unwind label would not show: the verifier checks
+	 * for that at load time, see check_cb_pad().
 	 */
 	scoped_guard(rcu)
 		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
include/linux/bpf_verifier.h +3 -0
index c500504cbfe1..6efe11f458b7 100644
@@ -1902,6 +1902,9 @@ struct bpf_verifier_env {
 	bool run_over_budget;		/* in one of its functions, see find_failing_path() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_needs_guard() */
+	/* the helpers and kfuncs whose unwind label was found, see check_cb_pad() */
+	unsigned long cb_pads[8];
+	u8 cb_pad_cnt;
 	bool pads_late;			/* a global subprog unwinds: see settle_late_unwinds() */
 	bool faults_late;		/* a site is not what it seemed: see check_arena_site() */
 	bool pad_releases;		/* see release_frame_resources() */
kernel/bpf/verifier.c +73 -4

101 lines not on this page · raw message

Signature · 1 line
2.53.1-Meta
author maintainer
#59 lore raw

PATCH 59/73 bpf: Find the landing pads of a program that can only clean up

In reply to Kumar Kartikeya Dwivedi

A cancelled frame leaves with cancel_exit and returns to the cancel_goto after its call, never to an unwind_goto. So a cancellation enters no landing pad of the program, not even one that could not catch it. Most landing pads that a C++ or Rust compiler emits are of that kind: they run destructors or drop glue and then unwind further with unwind_exit. When the kernel cancels the program in a callee, the destructor does not run, and what it does for the program is lost: a lock word in arena stays taken, memory in arena is not freed.

Call a landing pad of the program a cleanup pad if it can only clean up and continue unwinding. From its first insn,

- no path in the function reaches an insn that returns to the caller, which is exit, a tail call, LD_ABS or LD_IND, and
- some path reaches unwind_exit.

The goal is that a cancellation runs the cleanup pads of the frames that it leaves. A landing pad of the program that can continue running, such as a catch clause, is still never entered.

The same pad code then serves the program's own unwinding and a cancellation, so the frame has to remember which of the two is under way. It does so in a hidden word, the "cancelled" word of the frame:

what the program has what the verifier makes of it

    call foo                  call foo
    unwind_goto pad           unwind_goto stub
    ...                       cancel_goto entry
    pad: call dtor            ...
         unwind_exit          pad:   call dtor

gotol rest
stub: cancelled = 0 <- own unwinding
gotol pad
entry: cancelled = 1 <- cancellation
r0 = 0
gotol pad
rest: if cancelled == 0 goto +N
release what the frame still holds cancel_exit
unwind_exit

The stub runs when the callee left with unwind_exit, the entry when the callee was cancelled. The entry puts 0 into R0, where the program's own unwinding has the object that it threw. The code at rest, the remainder of the pad, replaces its unwind_exit. A frame that the program unwinds still leaves with unwind_exit. A cancelled frame leaves with cancel_exit and the value of the cancellation, which is the kernel's value or the cookie of bpf_throw(), so no landing pad of the program in a caller can catch it.

As the first step, find the cleanup pads. bpf_find_cleanup_pads() applies the two rules to the control flow graph and marks the unwind_goto of each cleanup pad ('cleanup_pad' in its aux data). The answer depends on the insns alone, so it is the same in every pass.

Some landing pads of the program need care:

- A tail call that is taken and an LD_ABS that fails leave the frame without an exit insn. The graph gives these insns an exit insn of the function as a successor, which can be an unwind_exit. So the first rule names the insns themselves, and that edge is not followed.
- The landing pad of a noexcept function calls std::terminate() and never reaches unwind_exit. The second rule leaves it out.
- Landing pads that share their last insns are judged one by one, each from its first insn. The landing pad of a try block can reach a handler, so it is no cleanup pad, even if it ends in the same unwind_exit as the landing pad of a destructor.

At log level 2 the verifier says for each landing pad of the program whether it "only resumes", which is a cleanup pad, "returns" or "has no unwind_exit". Nothing calls bpf_find_cleanup_pads() yet.

---
 include/linux/bpf_verifier.h |   3 +
 kernel/bpf/pads.c            | 114 +++++++++++++++++++++++++++++++++++
 2 files changed, 117 insertions(+)
include/linux/bpf_verifier.h +3 -0
index 6efe11f458b7..66771c403f95 100644
@@ -1373,6 +1373,8 @@ struct bpf_insn_aux_data {
 	u32 calls_callback:1;
 	/* true if some jump or call instruction targets this instruction */
 	u32 jump_target:1;
+	/* an unwind_goto of the program that leads to a cleanup pad, see bpf_find_cleanup_pads() */
+	u32 cleanup_pad:1;
 	/* it can read or write the frame of a caller, in a call with a known callee */
 	u32 reads_outer:1;
 	u32 writes_outer:1;
@@ -2500,6 +2502,7 @@ int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pa
 int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			int nr, const struct bpf_pad_note *note, struct bpf_insn *buf);
 void bpf_pads_log(struct bpf_verifier_env *env);
+int bpf_find_cleanup_pads(struct bpf_verifier_env *env);
 
 int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *dst_state,
 			    const struct bpf_verifier_state *src);
kernel/bpf/pads.c +114 -0

123 lines not on this page · raw message

Signature · 1 line
2.53.1-Meta
author maintainer
#60 lore raw

PATCH 60/73 bpf: Don't let hidden stack words turn on the private stack

In reply to Kumar Kartikeya Dwivedi

Currently the hidden words that the verifier adds for landing pads count as stack of the program when check_max_stack_depth() decides whether a function gets a private stack. One condition is that the stack, as the JIT rounds it, has 64 bytes or more, and a private stack makes the prologue and every call in the function more expensive. So one hidden word takes a function of 48 bytes to 56, which rounds to 64. Every function in which a cancellation enters a cleanup pad is going to have a hidden word of its own, the "cancelled" word.

Decide by what the insns of the program use. Record that stack_depth includes the hidden words ('hidden_in_depth'), and take them off before the depth is compared with BPF_PRIV_STACK_MIN_SIZE.

The slots of bpf_fastcall spills that were removed need the same. They stay in a frame that has hidden words below them, and so far they count as stack of the program there. Record that in 'fastcall_spills_gone', and count only what lies above them.

Where the hidden words are kept does not change: on the private stack of a function that has one, and on the kernel stack of any other.

---
 include/linux/bpf_verifier.h | 30 ++++++++++++++++++++++++++++++
 kernel/bpf/pads.c            |  7 ++-----
 kernel/bpf/verifier.c        | 29 ++++++++++++++++++++---------
 3 files changed, 52 insertions(+), 14 deletions(-)
include/linux/bpf_verifier.h +30 -0
index 66771c403f95..e578977518fb 100644
@@ -1574,6 +1574,11 @@ struct bpf_subprog_info {
 	bool ret_reg_pair: 1;
 	/* true if bpf_fastcall stack region is used by functions that can't be inlined */
 	bool keep_fastcall_stack: 1;
+	/*
+	 * Its bpf_fastcall spills are removed, but their slots stay in the frame, because the
+	 * hidden words are below them, see check_max_stack_depth()
+	 */
+	bool fastcall_spills_gone: 1;
 	bool changes_pkt_data: 1;
 	bool might_sleep: 1;
 	bool uses_arena_sp: 1;
@@ -1665,6 +1670,8 @@ struct bpf_subprog_info {
 	u8 owns_args;
 	/* its hidden slots and words take that many words of 8 bytes below its stack */
 	u8 hidden_words;
+	/* stack_depth includes the hidden words, see bpf_stack_take_hidden_words() */
+	bool hidden_in_depth: 1;
 	u8 code_stack_args;
 	/* the pad that releases nothing, for all accesses to arena with 'fault_unwinds'. 0: none */
 	u32 fault_pad;
@@ -1708,6 +1715,29 @@ static inline u32 bpf_stack_depth_with_slots(const struct bpf_subprog_info *sub)
 	return round_up(sub->stack_depth, BPF_REG_SIZE) + sub->hidden_words * BPF_REG_SIZE;
 }
 
+/*
+ * The hidden words become part of the stack of @sub for good. They are below the slots of its
+ * bpf_fastcall spills, so check_max_stack_depth() no longer cuts those slots off the frame.
+ */
+static inline void bpf_stack_take_hidden_words(struct bpf_subprog_info *sub)
+{
+	sub->stack_depth = bpf_stack_depth_with_slots(sub);
+	sub->hidden_in_depth = true;
+}
+
+/*
+ * How much stack the insns of the program use in @sub: without the hidden words, and without the
+ * slots of removed bpf_fastcall spills, which stay in a frame that has hidden words below them
+ */
+static inline u32 bpf_stack_depth_of_prog(const struct bpf_subprog_info *sub)
+{
+	if (!sub->hidden_in_depth)
+		return sub->stack_depth;
+	if (sub->fastcall_spills_gone)
+		return -sub->fastcall_stack_off;
+	return sub->stack_depth - sub->hidden_words * BPF_REG_SIZE;
+}
+
 static inline u16 bpf_in_stack_arg_cnt(const struct bpf_subprog_info *sub)
 {
 	if (sub->stack_args_from_code)
kernel/bpf/pads.c +2 -5
index e4a9f9600822..e84867527b71 100644
@@ -3476,11 +3476,8 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	/* all accesses of the program to its stack are known: the hidden words go below them */
 	for (s = 0; !env->faults_late && s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
-		if (!sub->hidden_words)
-			continue;
-		sub->stack_depth = bpf_stack_depth_with_slots(sub);
-		/* check_max_stack_depth() would put the stack of the callees there */
-		sub->keep_fastcall_stack = true;
+		if (sub->hidden_words)
+			bpf_stack_take_hidden_words(sub);
 	}
 	return 0;
 }
kernel/bpf/verifier.c +20 -9
index 76ba16991a24..99c7c1370211 100644
@@ -6345,10 +6345,21 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
 
 	find_subprog_properties(env, true);
 	/* see bpf_remove_fastcall_spills_fills() */
-	for (s = 0; s < env->subprog_cnt; s++)
-		for (int i = si[s].start; i < si[s + 1].start && !si[s].keep_fastcall_stack; i++)
-			if (env->insn_aux_data[i].fastcall_spills_num)
+	for (s = 0; s < env->subprog_cnt; s++) {
+		for (int i = si[s].start; i < si[s + 1].start && !si[s].keep_fastcall_stack; i++) {
+			if (!env->insn_aux_data[i].fastcall_spills_num)
+				continue;
+			/*
+			 * The hidden words lie below the slots of the removed spills, so the frame
+			 * cannot shrink: only record that the program no longer uses the slots.
+			 */
+			if (si[s].hidden_in_depth)
+				si[s].fastcall_spills_gone = true;
+			else
 				si[s].stack_depth = -si[s].fastcall_stack_off;
+			break;
+		}
+	}
 
 	for (int i = 0; i < env->subprog_cnt; i++) {
 		if (si[i].has_tail_call) {
@@ -6395,8 +6406,11 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
 		 * Request private stack support only if the subprog stack
 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
 		 * avoid jit penalty if the stack usage is small.
+		 * Only the stack that the insns of the program use counts: the hidden words of
+		 * the landing pads must not make a small function pay for a private stack.
 		 */
-		if (round_up_stack_depth(env, si[s].stack_depth) >= BPF_PRIV_STACK_MIN_SIZE) {
+		if (round_up_stack_depth(env, bpf_stack_depth_of_prog(&si[s])) >=
+		    BPF_PRIV_STACK_MIN_SIZE) {
 			si[s].priv_stack_mode = PRIV_STACK_ADAPTIVE;
 			env->prog->aux->jits_use_priv_stack = true;
 		}
@@ -6426,11 +6440,8 @@ static int try_max_stack_depth(struct bpf_verifier_env *env, bool with_slots)
 		return -ENOMEM;
 	for (s = 0; with_slots && s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
-		if (!sub->hidden_words)
-			continue;
-		sub->stack_depth = bpf_stack_depth_with_slots(sub);
-		/* or check_max_stack_depth() takes the spills of bpf_fastcall off the stack */
-		sub->keep_fastcall_stack = true;
+		if (sub->hidden_words)
+			bpf_stack_take_hidden_words(sub);
 	}
 	env->log.level = 0;
 	err = check_max_stack_depth(env);
Signature · 1 line
2.53.1-Meta
author maintainer
#61 lore raw

PATCH 61/73 bpf: Add a landing pad per site for frames that are cancelled already

In reply to Kumar Kartikeya Dwivedi

At each site the verifier records what the frame holds (struct bpf_pad_plan) and generates one landing pad from the record.

Once a cancellation runs cleanup pads, a frame can reach a site while it is cancelled already: a destructor that the cleanup pad calls faults in arena, loops until its time is up, or calls a function that is cancelled in turn. Give the states of such a frame a record and a landing pad of their own at the site, selected by the new flag BPF_SITE_CANCELLED on the kind of the site. A cancelled frame differs in three ways:

- It leaves with cancel_exit at every kind of site, or with exit in a function that only the kernel calls. At a call that the program's own unwinding returns to, it passes nothing on in R0.
- It leaves with the value of the cancellation that is under way. In a program with bpf_throw() its landing pad loads that value from the value word and stores nothing there.
- It does not hold what a frame holds that reaches the same insn without being cancelled.

Also let struct pad_buf record where each landing pad ends, and find a landing pad with the same insns by a hash. The code that is going to stand around a cleanup pad does not end in a single exit insn, which is how collect_pads() finds the end of a landing pad so far.

No state leaves a cancelled frame at a site yet. No functional change.

---
 include/linux/bpf_verifier.h |  25 ++++++-
 kernel/bpf/fixups.c          | 122 +++++++++++++++++++++++++++--------
 kernel/bpf/pads.c            |  36 +++++++----
 kernel/bpf/verifier.c        |   3 +
 4 files changed, 143 insertions(+), 43 deletions(-)
include/linux/bpf_verifier.h +22 -3
index e578977518fb..9dd68c7a29fd 100644
@@ -469,15 +469,33 @@ enum bpf_site_kind {
 	BPF_SITE_MAY_GOTO,	/* a may_goto of the program, see check_may_goto_site() */
 	/* a call whose callee was cancelled, with or without an unwind_goto of the program */
 	BPF_SITE_CANCEL_CALL,
+	/*
+	 * A flag on top of a kind: the frame that reaches the site is cancelled already. Such
+	 * frames have a plan and a landing pad of their own at the site.
+	 */
+	BPF_SITE_CANCELLED = 0x10,
 };
 
+static inline enum bpf_site_kind bpf_site_base(enum bpf_site_kind kind)
+{
+	return kind & ~BPF_SITE_CANCELLED;
+}
+
+static inline bool bpf_site_is_cancelled(enum bpf_site_kind kind)
+{
+	return kind & BPF_SITE_CANCELLED;
+}
+
 /* The site is a call whose callee did not return: it left with unwind_exit or was cancelled */
 static inline bool bpf_site_is_call(enum bpf_site_kind kind)
 {
-	return kind == BPF_SITE_CALL || kind == BPF_SITE_CANCEL_CALL;
+	return bpf_site_base(kind) == BPF_SITE_CALL || bpf_site_base(kind) == BPF_SITE_CANCEL_CALL;
 }
 
-/* The kernel cancels the frame at a site of @kind */
+/*
+ * The kernel cancels the frame at a site of @kind. That includes a call in a frame that is
+ * cancelled already whose callee left with unwind_exit.
+ */
 static inline bool bpf_site_is_cancel(enum bpf_site_kind kind)
 {
 	return kind != BPF_SITE_CALL;
@@ -2460,7 +2478,8 @@ static inline bool bpf_pad_passes_on(const struct bpf_verifier_env *env, int sub
 static inline bool bpf_site_has_value(const struct bpf_verifier_env *env, int subprog,
 				      enum bpf_site_kind kind)
 {
-	if (bpf_pad_rethrows(env, subprog, kind))
+	/* a frame that is cancelled already has the value in its value word */
+	if (bpf_site_is_cancelled(kind) || bpf_pad_rethrows(env, subprog, kind))
 		return false;
 	return env->has_throw && (bpf_site_is_call(kind) || kind == BPF_SITE_THROW);
 }
kernel/bpf/fixups.c +94 -28

189 lines not on this page · raw message

kernel/bpf/pads.c +24 -12
index e84867527b71..6969abb66250 100644
@@ -2350,7 +2350,10 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < pad_enters(plan, class); i++)
 			buf[n++] = enter_call(class);
-	if (plan_saves_value(env, plan, subprog)) {
+	if (bpf_site_is_cancelled(plan->kind) && env->has_throw) {
+		/* the value of the first cancellation, which the entry of the cleanup pad stored */
+		buf[n++] = BPF_LDX_MEM(BPF_DW, dst, BPF_REG_FP, value_off);
+	} else if (plan_saves_value(env, plan, subprog)) {
 		buf[n++] = BPF_LDX_MEM(BPF_DW, dst, BPF_REG_FP, value_off);
 		if (pair)
 			buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_FP,
@@ -2455,6 +2458,9 @@ bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan
 	const struct bpf_subprog_info *sub;
 	int s;
 
+	/* the frame was being unwound when it got to the site: what began that is asked */
+	if (bpf_site_is_cancelled(plan->kind))
+		return false;
 	if (!bpf_site_is_call(plan->kind))
 		return plan->kind != BPF_SITE_FAULT && plan->kind != BPF_SITE_MAY_GOTO;
 	/* the callees came back cancelled or with unwind_exit, by the kind of the site */
@@ -2525,8 +2531,8 @@ static const char * const site_kind[] = {
  */
 static u16 kinds_of_plan(const struct bpf_pad_plan *plan, u16 kinds)
 {
-	return plan->kind == BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT
-						  : kinds & LEFT_AT_UNWIND_EXIT;
+	return bpf_site_base(plan->kind) == BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT
+								 : kinds & LEFT_AT_UNWIND_EXIT;
 }
 
 /*
@@ -2565,7 +2571,7 @@ static int sites_of_subprogs(struct bpf_verifier_env *env)
 					if (!plan->used)
 						continue;
 					if (!bpf_site_is_call(plan->kind)) {
-						kinds |= BIT(plan->kind);
+						kinds |= BIT(bpf_site_base(plan->kind));
 						continue;
 					}
 					bpf_pad_for_each_callee(plan, c)
@@ -2713,7 +2719,7 @@ static int slot_words(const struct bpf_pad_note *note)
 /* Does the pad of @plan run in a frame that has set up its hidden slots? */
 static bool plan_has_slots(const struct bpf_pad_plan *plan)
 {
-	return plan->kind != BPF_SITE_RECURSION && !plan->conflict;
+	return bpf_site_base(plan->kind) != BPF_SITE_RECURSION && !plan->conflict;
 }
 
 /* Does @plan have room for @slots releases instead of those that it has of @group? */
@@ -3247,9 +3253,13 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	};
 	int j;
 
-	/* a call has one for what the kernel unwinds, and one for unwind_exit of the program */
-	verbose(env, "landing pad of %s at %d%s: ", site_kind[plan->kind], i,
-		plan->kind == BPF_SITE_CALL ? " for unwind_exit" : "");
+	/*
+	 * A call can have a pad for a cancellation and one for the program's unwind_exit. Every
+	 * site can have one more for the frames that are cancelled already.
+	 */
+	verbose(env, "landing pad of %s at %d%s%s: ", site_kind[bpf_site_base(plan->kind)], i,
+		bpf_site_base(plan->kind) == BPF_SITE_CALL ? " for unwind_exit" : "",
+		bpf_site_is_cancelled(plan->kind) ? " in a frame that the kernel unwinds" : "");
 	for (j = plan->nr_ents - 1; !plan->conflict && j >= 0; j--)
 		print_ent(env, &plan->ents[j]);
 	if (plan->conflict)
@@ -3300,7 +3310,7 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,
 		       const struct bpf_pad_plan *plan, enum bpf_site_kind kind)
 {
-	sub->left_at |= bpf_site_is_call(kind) ? sites_below(env, plan) : BIT(kind);
+	sub->left_at |= bpf_site_is_call(kind) ? sites_below(env, plan) : BIT(bpf_site_base(kind));
 }
 
 /* Did bpf_pad_skip_faults() walk @sub, and has no call in or below it got a new callee since? */
@@ -3448,7 +3458,8 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 				continue;
 			err = settle_plan(env, plan);
 			sub = bpf_find_containing_subprog(env, i);
-			if (!err && plan_saves_value(env, plan, sub - env->subprog_info))
+			if (!err && (plan_saves_value(env, plan, sub - env->subprog_info) ||
+				     (bpf_site_is_cancelled(plan->kind) && env->has_throw)))
 				err = take_value_word(env, sub);
 			if (err < 0)
 				return err;
@@ -3575,7 +3586,7 @@ static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct
 		bpf_pad_for_each_callee(plan, s)
 			sub[s].asks_args |= sub[s].releases_args;
 	}
-	if (plan->kind != BPF_SITE_CANCEL_CALL)
+	if (bpf_site_base(plan->kind) != BPF_SITE_CANCEL_CALL)
 		return;
 	bpf_pad_for_each_callee(plan, s)
 		sub[s].below_conflict = true;
@@ -3621,7 +3632,8 @@ static void note_causes_below(struct bpf_verifier_env *env)
 			break;
 		for (i = sub[s].start; i < sub[s + 1].start; i++) {
 			for (below = aux[i].pad_plans; below; below = below->next) {
-				if (below->kind != BPF_SITE_CANCEL_CALL || !below->visited)
+				if (bpf_site_base(below->kind) != BPF_SITE_CANCEL_CALL ||
+				    !below->visited)
 					continue;
 				/*
 				 * The frame is left at this call, whatever what it calls
kernel/bpf/verifier.c +3 -0
index 99c7c1370211..5b0700660bcf 100644
@@ -22444,6 +22444,9 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
 {
 	int s;
 
+	/* A cancelled frame came through an entry, which the program may not keep. */
+	if (bpf_site_is_cancelled(plan->kind))
+		return false;
 	switch (plan->kind) {
 	case BPF_SITE_GUARD:
 		return !bpf_flow_guard_is_guess(env, insn_idx);
Signature · 1 line
2.53.1-Meta
author maintainer
#62 lore raw

PATCH 62/73 bpf: Verify a cleanup pad for a frame that is cancelled

In reply to Kumar Kartikeya Dwivedi

Currently a state that returns from a call cancelled is cancelled in turn at that call, through the generated pad, whatever landing pad the program has there. Before a cancellation can run a cleanup pad, the verifier has to check the pad for the cancelled frame: with 0 in R0, and with what the frame holds when its callee is cancelled.

Add that to the main pass. Nothing calls bpf_find_cleanup_pads() yet, so no program is verified differently.

When a cancelled state returns to a call whose unwind_goto leads to a cleanup pad, in a function that can be cancelled, enter_cleanup_pad() marks the frame as cancelled (BPF_FRAME_CANCELLED), puts 0 into R0 and takes the jump of the unwind_goto. The mark is never cleared, and the verifier does not merge two states that differ in it. So the cleanup pad is verified a second time, and an error on that path rejects the program like any other. The log names the path:

from 16 to the landing pad at 20 of func#1: the kernel unwinds

A cancelled frame never returns to its caller. It has two ways out. Both leave with cancel_exit, or with exit in a function that only the kernel calls, and with the value of the cancellation:

- It reaches the unwind_exit of the pad. The program has released what it wanted to, and the remainder releases what the frame still holds. For that the unwind_exit is a site of the new kind BPF_SITE_REMAINDER.
- It reaches a site inside the pad: a destructor loops until its time is up, faults in arena, calls bpf_throw() or calls a function that is cancelled in turn. The frame leaves through the landing pad that the site has for frames that are cancelled already, and the rest of the cleanup does not run.

The call itself gets a record of the new kind BPF_SITE_CANCEL_ENTRY, which says that its cancel_goto leads to the entry of the cleanup pad.

Some cases need care:

- exit, a tail call and LD_ABS cannot be reached from a cleanup pad, so a cancelled frame at one of them is a verifier bug.
- A cleanup pad can jump back before its call, so a cancelled frame need not run cleanup code only. The verifier relies on one thing: no insn that the frame can reach returns to the caller.
- If a callee of the pad leaves with unwind_exit, the unwind_goto that the pad has for it is taken and the frame stays cancelled. If the callee is cancelled and its call has a cleanup pad of its own, the frame continues in that pad.
- In a program with bpf_throw() the entry has to keep the value that cancel_exit left in R0, so R0 must be a number at the call. bpf_throw() in a cancelled frame drops its cookie, because the frame has its value already.
- A function that is verified separately for a call out of a cancelled frame is kept apart from its other calls (BPF_FRAME_BELOW). The pad passes other arguments than the rest of the program does.
- A function can turn out to be one that cannot be cancelled after a state entered a cleanup pad in it. The pass is then repeated and enters no cleanup pad in that function.

A cleanup pad that a cancellation can reach is entered, or the program is rejected. So a cancelled frame that has no landing pad, at a site inside the cleanup pad or at its unwind_exit, is an error of the pass as at any site. bpf_pads_settle() raises it when the pass is over, because only then is it known whether the program has the entry that the frame came through. It now looks at all sites before it raises the first error, so that the next pass can react to every one. If a cancelled frame has no landing pad because of a reference, the callees of the calls of its function that lead to a cleanup pad ask for a hand-over, see ask_below_cleanup_pads().

A cancellation can also reach a cleanup pad only because two calls are verified together: a callee whose loop has a trip count for each call and none for both is cancelled when its time is up. An error that follows can be anywhere, and the pass that keeps the two calls apart has none. So after a pass with any error, note_entered() marks every function in which a state entered a cleanup pad, and the next pass keeps apart the calls after which a state did. No verdict rests on the marks. Only a load that is rejected pays for them, in load time up to the limit on the cost of a rejected load.

---
 include/linux/bpf_verifier.h |  43 ++++-
 kernel/bpf/fixups.c          |  36 +++-
 kernel/bpf/pads.c            | 321 +++++++++++++++++++++++++++--------
 kernel/bpf/verifier.c        | 229 ++++++++++++++++++++++---
 4 files changed, 521 insertions(+), 108 deletions(-)
include/linux/bpf_verifier.h +41 -2
index 9dd68c7a29fd..1e87200119bc 100644
@@ -469,6 +469,13 @@ enum bpf_site_kind {
 	BPF_SITE_MAY_GOTO,	/* a may_goto of the program, see check_may_goto_site() */
 	/* a call whose callee was cancelled, with or without an unwind_goto of the program */
 	BPF_SITE_CANCEL_CALL,
+	/*
+	 * Such a call whose unwind_goto leads to a cleanup pad. The frame does not leave: its
+	 * cancel_goto leads to the entry of the cleanup pad, see enter_cleanup_pad().
+	 */
+	BPF_SITE_CANCEL_ENTRY,
+	/* an unwind_exit of the program in a cancelled frame: the remainder replaces it */
+	BPF_SITE_REMAINDER,
 	/*
 	 * A flag on top of a kind: the frame that reaches the site is cancelled already. Such
 	 * frames have a plan and a landing pad of their own at the site.
@@ -481,15 +488,17 @@ static inline enum bpf_site_kind bpf_site_base(enum bpf_site_kind kind)
 	return kind & ~BPF_SITE_CANCELLED;
 }
 
+/* The frame that reaches the site is cancelled already */
 static inline bool bpf_site_is_cancelled(enum bpf_site_kind kind)
 {
-	return kind & BPF_SITE_CANCELLED;
+	return (kind & BPF_SITE_CANCELLED) || kind == BPF_SITE_REMAINDER;
 }
 
 /* The site is a call whose callee did not return: it left with unwind_exit or was cancelled */
 static inline bool bpf_site_is_call(enum bpf_site_kind kind)
 {
-	return bpf_site_base(kind) == BPF_SITE_CALL || bpf_site_base(kind) == BPF_SITE_CANCEL_CALL;
+	return bpf_site_base(kind) == BPF_SITE_CALL || bpf_site_base(kind) == BPF_SITE_CANCEL_CALL ||
+	       kind == BPF_SITE_CANCEL_ENTRY;
 }
 
 /*
@@ -807,6 +816,7 @@ struct bpf_func_state {
 	bool in_rcu_callback_fn;
 	/* parent_id of the args that are gone when this frame returns */
 	u32 frame_id;
+	u32 cancelled;	/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */
 	/*
 	 * Bit f: the frame, or a subprog that returned to it, released a lock or irq flags of
 	 * frame f. If the frame returns, a store after its call clears the hidden slot. If not,
@@ -903,6 +913,22 @@ struct bpf_equations {
 	u32 clean_sym_cnt;	/* after the last bpf_equations_clean() */
 };
 
+/* The marks in 'cancelled' of struct bpf_func_state */
+enum {
+	/* The frame is cancelled and runs a cleanup pad, see enter_cleanup_pad(). Never cleared. */
+	BPF_FRAME_CANCELLED = 1,
+	/*
+	 * The first frame of a function that is verified separately, for a call out of a frame
+	 * that has a mark. It only keeps the function apart from its other calls.
+	 */
+	BPF_FRAME_BELOW = 2,
+};
+
+static inline bool bpf_frame_is_cancelled(const struct bpf_func_state *frame)
+{
+	return frame->cancelled & BPF_FRAME_CANCELLED;
+}
+
 /* 'unwound' of struct bpf_verifier_state: how the callee left when it did not return */
 enum {
 	/*
@@ -1665,11 +1691,20 @@ struct bpf_subprog_info {
 	bool made_calls: 1;
 	/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */
 	bool below_conflict: 1;
+	/*
+	 * scratch of bpf_pads_note_causes(): a cancelled frame of it got no landing pad because
+	 * of a reference, see ask_below_cleanup_pads()
+	 */
+	bool cleanup_pad_ref_conflict: 1;
 	/*
 	 * In this pass the verifier merged states in a callee of it that differ in which
 	 * references the arguments of the call had, see bpf_pad_states_meet()
 	 */
 	bool arg_refs_differ: 1;
+	/* it has an unwind_goto that leads to a cleanup pad, see bpf_find_cleanup_pads() */
+	bool has_cleanup_pads: 1;
+	/* a cancellation enters one of its cleanup pads, see bpf_mark_subprogs_that_unwind() */
+	bool enters_cleanup_pads: 1;
 	/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
 	u16 left_at;
 	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
@@ -1688,6 +1723,8 @@ struct bpf_subprog_info {
 	u8 owns_args;
 	/* its hidden slots and words take that many words of 8 bytes below its stack */
 	u8 hidden_words;
+	/* take_value_word() found no room for the value word, in this bpf_pads_settle() */
+	bool no_value_word: 1;
 	/* stack_depth includes the hidden words, see bpf_stack_take_hidden_words() */
 	bool hidden_in_depth: 1;
 	u8 code_stack_args;
@@ -2525,6 +2562,8 @@ size_t bpf_pad_plans_free(struct bpf_insn_aux_data *aux);
 void bpf_pads_new_round(struct bpf_verifier_env *env);
 void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, bool save);
 size_t bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt);
+struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
+				   const struct bpf_verifier_state *st, int call_idx);
 struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 				   const struct bpf_verifier_state *st, int insn_idx,
 				   enum bpf_site_kind kind);
kernel/bpf/fixups.c +28 -8
index e3f7e5b37bc5..b00a011fa66c 100644
@@ -659,6 +659,10 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 {
 	int s;
 
+	/* without 'enters_cleanup_pads' no frame of the function is cancelled already */
+	if (bpf_site_is_cancelled(plan->kind) &&
+	    !bpf_find_containing_subprog(env, i)->enters_cleanup_pads)
+		return false;
 	switch (bpf_site_base(plan->kind)) {
 	case BPF_SITE_GUARD:
 		return env->insn_aux_data[i].loop_guard;
@@ -674,12 +678,15 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 				return true;
 		return false;
 	case BPF_SITE_CANCEL_CALL:
+	case BPF_SITE_CANCEL_ENTRY:
 		if (!plan->visited)
 			return false;
 		bpf_pad_for_each_callee(plan, s)
 			if (env->subprog_info[s].can_cancel)
 				return true;
 		return false;
+	case BPF_SITE_REMAINDER:
+		return plan->visited;
 	case BPF_SITE_FAULT:
 		return !env->insn_aux_data[i].fault_skips;
 	case BPF_SITE_MAY_GOTO:
@@ -690,13 +697,16 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 }
 
 /*
- * The main pass looked at more ways to unwind than the program has in the end: a loop that has a
- * trip count after all has no may_goto. Find the subprogs that get cancel_exit: those that are left
- * at a site where the kernel unwinds. And those that get unwind_exit: they have a call with no
- * unwind_goto, to which unwind_exit of the program comes back. A call is a site if it calls one of
- * them: of one kind, of the other, or of both. The main pass asks the same when a global subprog
- * unwinds, see settle_late_unwinds(). The main program leaves with exit: it is marked for
- * bpf_check_attach_target(), see bpf_insert_sites().
+ * Decide how each subprog can be left, from the sites that the program keeps:
+ *
+ *   can_cancel           the kernel can cancel it at a site: it gets cancel_exit
+ *   can_unwind           unwind_exit of a callee comes back to a call of it that has no
+ *                        unwind_goto: it gets unwind_exit
+ *   enters_cleanup_pads  a cancellation enters one of its cleanup pads
+ *
+ * A call is a site only if a callee has the matching bit, so the walk repeats until nothing
+ * changes. The main program leaves with exit but is marked too, for bpf_check_attach_target().
+ * With @in_pass the main pass asks the same question and is charged for the walk.
  */
 int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 {
@@ -706,6 +716,8 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 	bool changed, unwinds, cancels;
 	int i, k, s, err;
 
+	for (s = 0; s < env->subprog_cnt; s++)
+		env->subprog_info[s].enters_cleanup_pads = false;
 	do {
 		changed = false;
 		/* callees come first: only callx and a cycle of calls take more than one round */
@@ -716,6 +728,12 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 		for (k = 0; k < env->subprog_cnt; k++) {
 			s = env->subprog_topo_order[k];
 			sub = &env->subprog_info[s];
+			for (i = sub->start; sub->has_cleanup_pads && !sub->enters_cleanup_pads &&
+			     i < sub[1].start; i++) {
+				plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+				if (plan && bpf_site_is_used(env, i, plan))
+					sub->enters_cleanup_pads = changed = true;
+			}
 			if ((sub->can_unwind && sub->can_cancel) || (s && !sub->bail_unwinds))
 				continue;
 			unwinds = sub->can_unwind;
@@ -724,7 +742,9 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 				cancels |= aux[i].loop_guard ||
 					   (aux[i].fault_empty && !aux[i].fault_skips);
 				for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-					if (!bpf_site_is_used(env, i, plan))
+					/* at an entry the frame continues in its cleanup pad */
+					if (plan->kind == BPF_SITE_CANCEL_ENTRY ||
+					    !bpf_site_is_used(env, i, plan))
 						continue;
 					if (bpf_site_is_cancel(plan->kind))
 						cancels = true;
kernel/bpf/pads.c +247 -74

511 lines not on this page · raw message

kernel/bpf/verifier.c +205 -24

381 lines not on this page · raw message

Signature · 1 line
2.53.1-Meta
author maintainer
#63 lore raw

PATCH 63/73 bpf: Reject a program whose cleanup pad a cancellation cannot enter

In reply to Kumar Kartikeya Dwivedi

A cleanup pad that a cancellation can reach is entered, or the program is rejected. The verifier never skips one silently: a destructor that does not run shows only when the kernel cancels the program, under load, as a lock word in arena that stays locked. Two things are missing for that rule: the hidden words that a cancelled frame needs, and a log that names the cleanup pad that a rejection is about.

Give every function in which a cancellation enters a cleanup pad its "cancelled" word, and in a program with bpf_throw() the value word. take_cleanup_pad_words() takes them after all other hidden words, so they never take the room of a word that the program needs in order to load. A function whose stack has no room for them rejects the program.

A landing pad for a cancelled frame asks for no hidden slots, because a path that only a cancellation takes must not cost the normal path a store. It does use the hidden slots that the function has for another site. So code that needs a hidden slot, such as a loop in an RCU section that only one path enters, rejects the program when a cancelled frame can reach it.

state_is_in_cleanup_pad() tells a state that has a cancelled frame, or that runs a function which such a frame called. Its calls hand no reference over and clear no hidden slot of a caller. So what such a state releases of a caller costs the functions on the stack their hidden slots for that kind of resource.

bpf_pad_log() now prints a line before the conflict that says what a cleanup pad has to do with it, for example (one line in the log):

the kernel would enter the landing pad at 18 of the call at 11: what the pad leaves at unwind_exit at 27 cannot be released

A frame does not know which entry it came through. So the log names the first cleanup pad of the function that reaches the insn on the control flow graph and counts the others, in a walk that runs for the log only and is not charged. Where a cleanup pad may have released or overwritten what a caller holds, the log names the callee and says "may", because it is not known which pad did it.

At the unwind_exit of a cleanup pad only R0 is live. So the remainder can release sections, a lock at a constant address, an object in the stack of the frame, a pointer in R0 and what is in hidden slots. A pointer in R6-R9 that the cleanup pad does not release still rejects the program.

---
 include/linux/bpf_verifier.h |  15 ++
 kernel/bpf/pads.c            | 448 +++++++++++++++++++++++++++++------
 kernel/bpf/verifier.c        |  11 +-
 3 files changed, 399 insertions(+), 75 deletions(-)
include/linux/bpf_verifier.h +15 -0
index 1e87200119bc..aa204e909579 100644
@@ -626,6 +626,9 @@ struct bpf_pad_plan {
 	bool visited;
 	bool used;			/* the program keeps the site, see bpf_pads_mark_used() */
 	bool failed;			/* a state made the conflict an error of the pass */
+	/* for bpf_pad_log(): a state came from a cancelled frame or below one, and one did not */
+	bool from_cleanup_pad;
+	bool from_normal;
 	/*
 	 * How many sections of each class the frame has entered since its call. Less than 0: it
 	 * has left that many sections of its callers, and the pad enters them again.
@@ -642,6 +645,8 @@ struct bpf_pad_plan {
 	/* enum bpf_pad_conflict: no location has a pointer. No error if a hidden slot has it. */
 	u8 no_place;
 	u8 no_irq_place;		/* the same for irq flags in the stack of a caller */
+	/* the groups that it asked hidden slots for, bits by enum bpf_pad_group: settle_slots() */
+	u8 asked_slots;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
@@ -1577,6 +1582,11 @@ struct bpf_subprog_info {
 	 * The value word: its landing pads keep the value there over their calls.
 	 */
 	s16 value_off;
+	/*
+	 * The "cancelled" word of a function in which a cancellation enters a cleanup pad: 0 from
+	 * the first insn of the function on, 1 once the frame is cancelled.
+	 */
+	s16 cancelled_off;
 	/*
 	 * The pending word: an argument waits there over the call of a subprog, the address of irq
 	 * flags that the subprog saves or a pointer that it releases, see bpf_pad_note_return()
@@ -1709,6 +1719,11 @@ struct bpf_subprog_info {
 	u16 left_at;
 	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
 	u8 no_slots: 4;
+	/*
+	 * Of those, the groups that it lost because a state in a cleanup pad for a cancellation
+	 * released something of a caller. For the log, see bpf_pad_log().
+	 */
+	u8 no_slots_cleanup_pad: 4;
 	/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */
 	u8 slots: 4;
 	/*
kernel/bpf/pads.c +381 -67

605 lines not on this page · raw message

kernel/bpf/verifier.c +3 -8
index 834d0b0a9ea9..31b1bac012fa 100644
@@ -22586,14 +22586,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		stuck = plan->conflict == BPF_CONFLICT_CANNOT_UNWIND ||
 			plan->conflict == BPF_CONFLICT_NO_EXIT;
 		/*
-		 * There is no other way out. Not for may_goto of the program, an access to arena
-		 * and a call above them either, but in a subprog that cannot unwind, and whether
-		 * it is one may be found later in the pass. Then this error was none, see
-		 * do_check_all().
-		 * It is an error also where a landing pad of the program that the kernel entered
-		 * has a part in it: what came back to the call left a frame below through such
-		 * a pad, or the state got here out of one, in a function that the pad calls.
-		 * The kernel enters the pad or the program is rejected.
+		 * A missing landing pad is an error, unless the frame cannot be cancelled and the
+		 * site can be skipped. If the function turns out later in the pass to be one that
+		 * cannot be cancelled, do_check_all() drops the error.
 		 */
 		if (plan->conflict && certain && (bpf_pad_must_unwind(env, plan) || !stuck)) {
 			bpf_pad_log(env, insn_idx, plan);
Signature · 1 line
2.53.1-Meta
author maintainer
#64 lore raw

PATCH 64/73 bpf: Find the code that a cleanup pad can reach

In reply to Kumar Kartikeya Dwivedi

The "cancelled" word is going to be written only where a frame enters a landing pad of the program: by the stub and by the entry. That is enough only if no frame reaches code that reads the word without passing one of the two. So the verifier has to know which code a frame can run on either side of those two edges. Find that out on the control flow graph, in bpf_find_cleanup_pads():

- Pad code is what can be reached from the first insn of a cleanup pad. A cancelled frame starts there and follows edges of the graph, so it runs pad code and nothing else.
- The normal path is what can be reached from the first insn of the function without the jump of an unwind_goto.
- The rest is the program's landing pad of a typed catch, until it returns to the normal path or joins pad code. No cancelled frame runs it.

call a normal path
unwind_goto 1f
call b
unwind_goto 2f
exit
2: if r0 != 7 goto 3f a typed catch
r0 = 0
exit
1: call dtor pad code
3: unwind_exit

A function is mixed if one of its insns is pad code and on the normal path as well: the normal path falls into a cleanup pad or jumps to it, a cleanup pad jumps back before its call, or the function has no exit. In any other function a frame gets from the normal path into pad code in two ways only: by the jump of an unwind_goto, and through an entry.

A tail call, LD_ABS or LD_IND has an edge to the exit insn that stands for its return. That edge is not followed, as in the search for cleanup pads. The exit is often the unwind_exit that the cleanup pads end in, and a tail call on the normal path would make the function mixed for no reason.

The result depends on the insns alone. Nothing reads it yet.

---
 include/linux/bpf_verifier.h |   4 ++
 kernel/bpf/pads.c            | 125 +++++++++++++++++++++++++++++------
 2 files changed, 110 insertions(+), 19 deletions(-)
include/linux/bpf_verifier.h +4 -0
index aa204e909579..97892d66274e 100644
@@ -1424,6 +1424,8 @@ struct bpf_insn_aux_data {
 	u32 jump_target:1;
 	/* an unwind_goto of the program that leads to a cleanup pad, see bpf_find_cleanup_pads() */
 	u32 cleanup_pad:1;
+	/* pad code: a cleanup pad of its function reaches the insn, see bpf_find_cleanup_pads() */
+	u32 cleanup_pad_code:1;
 	/* it can read or write the frame of a caller, in a call with a known callee */
 	u32 reads_outer:1;
 	u32 writes_outer:1;
@@ -1713,6 +1715,8 @@ struct bpf_subprog_info {
 	bool arg_refs_differ: 1;
 	/* it has an unwind_goto that leads to a cleanup pad, see bpf_find_cleanup_pads() */
 	bool has_cleanup_pads: 1;
+	/* "mixed": an insn of it is pad code and on the normal path, see bpf_find_cleanup_pads() */
+	bool cleanup_pads_mixed: 1;
 	/* a cancellation enters one of its cleanup pads, see bpf_mark_subprogs_that_unwind() */
 	bool enters_cleanup_pads: 1;
 	/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
kernel/bpf/pads.c +106 -19

154 lines not on this page · raw message

Signature · 1 line
2.53.1-Meta
author maintainer
#65 lore raw

PATCH 65/73 bpf: Emit the stub, the entry and the remainder of a cleanup pad

In reply to Kumar Kartikeya Dwivedi

Currently the verifier can check a cleanup pad for a cancelled frame, but it emits none of the code around the pad. Emit the code of the listing in "bpf: Find the landing pads of a program that can only clean up": the stub, the entry, the remainder, and the second landing pad of a site that a cancelled frame can reach. No program gets any of it until bpf_find_cleanup_pads() is called.

In a program without bpf_throw(), with V for the kernel's value:

stub: cancelled = 0 rest: ax = cancelled

         gotol pad                        if ax == 0 goto +3
  entry: cancelled = 1                    r0 = V
         r0 = 0                           r2 = 0
         gotol pad                        cancel_exit

unwind_exit

The "cancelled" word is written only on the two edges that take a frame from the normal path into a landing pad of the program:

- The callee left with unwind_exit. The unwind_goto after the call leads to a stub, which clears the word and jumps to the program's landing pad. A JIT takes the target of unwind_goto from the offset of the insn alone, so no JIT changes.
- The callee was cancelled. The cancel_goto of the call leads to the entry and not to a generated pad. The entry sets the word without reading it first. In a program with bpf_throw() it also stores R0, the value of the cancellation, in the value word.

Nothing on the normal path writes the word, and a function does not clear it at its first insn. What a function pays on the normal path is the word itself and the stack frame that it needs: a function that had no stack gets one. Two kinds of code are different:

- A call in pad code can be made by a frame that is cancelled already. Its unwind_goto gets no stub. A stub would clear the word, the frame would leave with the program's unwind_exit, and a landing pad of the program in a caller could catch the cancellation. Its entry tests the word and stores only if it is 0, so the first cancellation decides what the program returns.
- A mixed function clears the word at its first insn, with one store per call. It has no stub, and all its entries test. There code that reads the word can be reached from the first insn without passing a stub or an entry. The store stands before the first insn, where a jump back to that insn does not reach it.

An unwind_exit that a cancelled frame can reach becomes a jump to the remainder. There a cancelled frame runs the landing pad that the verifier generated for the unwind_exit, and a frame that the program unwinds runs unwind_exit as before.

A site that a frame can reach both cancelled and not has two landing pads and one target. The target is a test of the word with both pads after it, unless the two have the same insns. That includes an access to arena at which nothing is held. Such accesses share one landing pad per function, which loads V, and a cancelled frame needs the value of its cancellation, so the access gets an unwind_goto of its own.

The word is never read before it is written. Only pad code reads it: an entry after a call in pad code, the test before the two landing pads of a site, and the remainder. In a function that is not mixed, a frame gets from the normal path into pad code only through a stub or an entry that stores. This matters because a frame finds in the word what an earlier frame left there, and code that reads 1 treats the frame as cancelled.

So every unwind_goto of the program whose target is not dead code gets a stub, unless its call is in pad code, also where the program's landing pad is no cleanup pad: a typed catch that does not match joins pad code. The emission fails the load with a verifier bug unless each unwind_goto has a stub exactly where it needs one, every reader of the word is pad code, and the main pass saw no cancelled frame take an unwind_goto that has a stub or reach an entry that does not test.

Code with the same insns is shared, as landing pads are, except for an entry, which jumps to its own cleanup pad. The new code has no nospec barrier, like the landing pads: a program with unwind_goto is loaded with CAP_PERFMON.

---
 include/linux/bpf_verifier.h |  39 ++-
 kernel/bpf/fixups.c          | 601 ++++++++++++++++++++++++++++-------
 kernel/bpf/pads.c            |  90 +++++-
 kernel/bpf/verifier.c        |  54 +---
 4 files changed, 621 insertions(+), 163 deletions(-)
include/linux/bpf_verifier.h +36 -3
index 97892d66274e..93147a22c81e 100644
@@ -649,6 +649,13 @@ struct bpf_pad_plan {
 	u8 asked_slots;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
+	/* BPF_SITE_CANCEL_ENTRY: its entry need not test the "cancelled" word: collect_pads() */
+	bool untested;
+	/*
+	 * BPF_SITE_CANCEL_ENTRY: a frame that was cancelled already reached the entry, so its call
+	 * is in pad code. collect_pads() checks that against the control flow graph.
+	 */
+	bool cancelled_visit;
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
 	/* before[i]: bits of the entries that entry i must stand before, see put_before() */
 	u8 before[BPF_PAD_MAX_ENTS];
@@ -738,6 +745,9 @@ struct bpf_pad_note {
 	u8 entry: 1;
 };
 
+/* 'clear_stub' of an unwind_goto that gets no stub */
+#define BPF_CLEAR_STUB_NONE	U32_MAX
+
 /* The plans and the notes of an insn in the snapshot of a pass, see bpf_pads_move() */
 struct bpf_pads_moved {
 	struct bpf_pad_plan *plans;
@@ -1403,6 +1413,11 @@ struct bpf_insn_aux_data {
 	u64 fault_unwinds:1; /* in the final program a fault goes to 'fault_pad' of the subprog */
 	u64 unwind_goto_follows:1; /* the verifier added an unwind_goto after the insn */
 	u64 cancel_goto_follows:1; /* the verifier added a cancel_goto after the insn */
+	/*
+	 * An unwind_goto of the program: a cancelled frame took its jump, so its call is in pad
+	 * code. collect_stubs() checks that the control flow graph says the same.
+	 */
+	u64 cancelled_takes:1;
 	);
 
 	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
@@ -1429,6 +1444,11 @@ struct bpf_insn_aux_data {
 	/* it can read or write the frame of a caller, in a call with a known callee */
 	u32 reads_outer:1;
 	u32 writes_outer:1;
+	/*
+	 * An unwind_goto of the program: 1 + the offset of its stub in the pads of the subprog, see
+	 * collect_stubs(). BPF_CLEAR_STUB_NONE: no stub, its call is in pad code. 0: not decided.
+	 */
+	u32 clear_stub;
 	/*
 	 * Per-instruction summary of stack slots in the current frame
 	 * that this instruction may write, may read, and that are live before it.
@@ -1585,8 +1605,9 @@ struct bpf_subprog_info {
 	 */
 	s16 value_off;
 	/*
-	 * The "cancelled" word of a function in which a cancellation enters a cleanup pad: 0 from
-	 * the first insn of the function on, 1 once the frame is cancelled.
+	 * The "cancelled" word: 1 in a frame that runs a cleanup pad for a cancellation, 0 in one
+	 * that runs it for the program's own unwinding. Only the stubs and the entries of the
+	 * function write it, or the first insn of a mixed function.
 	 */
 	s16 cancelled_off;
 	/*
@@ -1783,6 +1804,15 @@ static inline void bpf_subprog_set_stuck(struct bpf_subprog_info *sub, enum bpf_
 	sub->stuck_insn = insn_idx;
 }
 
+/*
+ * Does the first insn of @sub clear its "cancelled" word? Only in a mixed function, see
+ * bpf_pad_entry_insns(). In any other function the stubs and the entries write the word.
+ */
+static inline bool bpf_subprog_clears_cancelled(const struct bpf_subprog_info *sub)
+{
+	return sub->cancelled_off && sub->cleanup_pads_mixed;
+}
+
 /* The stack depth of @sub with its hidden slots and words */
 static inline u32 bpf_stack_depth_with_slots(const struct bpf_subprog_info *sub)
 {
@@ -2603,7 +2633,10 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env);
 bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan);
 int bpf_hidden_slots_fit(struct bpf_verifier_env *env);
 int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad_note **notes);
-int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, struct bpf_insn *buf);
+int bpf_pad_entry_insns(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
+			int nr, struct bpf_insn *buf);
+int bpf_pad_cancel_entry_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			       int subprog, struct bpf_insn *buf);
 int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			 int nr, const struct bpf_pad_note *note, struct bpf_insn *buf);
 int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
kernel/bpf/fixups.c +489 -112

777 lines not on this page · raw message

kernel/bpf/pads.c +82 -8

128 lines not on this page · raw message

kernel/bpf/verifier.c +14 -40

67 lines not on this page · raw message

Signature · 1 line
2.53.1-Meta
author maintainer
#66 lore raw

PATCH 66/73 bpf: Let the entry of a cleanup pad save the pointers of the frame

In reply to Kumar Kartikeya Dwivedi

Currently the remainder of a cleanup pad can release little. A release needs the pointer in a register or stack slot that is live, and at the unwind_exit of the pad only R0 is. So a task in R6 that the cleanup pad does not release rejects the program.

Add save words: hidden words of the frame in which the entry keeps the pointers that the frame holds in R6-R9 or in a stack slot. With a task in R6 and one save word:

entry: cancelled = 1 rest: ax = cancelled

         r0 = r6                            if ax == 0 goto +6
         *(u64 *)(r10 - 16) = r0            r1 = *(u64 *)(r10 - 16)
         r0 = 0                             if r1 == 0 goto +1
         gotol pad                          call bpf_task_release
                                            r0 = V
                                            r2 = 0
                                            cancel_exit
                                            unwind_exit

Where the frame leaves, the state says what it still holds, and the save word is one more location of the pointer. The rules, see visit_saves():

- Only a pointer is saved. The address of irq flags, an iterator or a dynptr in the stack of a caller is not, because the pad can write to those slots. Nor is the address of a lock that only a register has. The cleanup pad has to release these itself, unless they have a location where the frame leaves.
- Word j is for the j-th reference that the frame holds at the call. A word without a pointer is cleared, so calls at which the frame holds one object and two can share a remainder.
- A word keeps its pointer when the cleanup pad releases the object. A pad that releases on one of two paths only is rejected, as before.
- A word holds one kind of object in all frames of a function. The type of the pointer says what releases it, and no register may have the pointer any more where the frame leaves.
- If the states at a call do not agree on what the frame holds, or a word would get a second kind of object, the entry of that call saves nothing and the pass is repeated. Each pass asks again, because the answer depends on what the pass keeps apart.
- An entry that tests the "cancelled" word saves only if the word is 0, and a call hands over no reference that has a save word.

On the normal path a function pays in stack only: 8 bytes per save word, 8 words at most. bpf_hidden_slots_settle() now asks once for all subprogs whether the hidden words fit, and per subprog only if not.

---
 include/linux/bpf_verifier.h |  51 +++-
 kernel/bpf/fixups.c          |  10 +-
 kernel/bpf/pads.c            | 553 ++++++++++++++++++++++++++++++-----
 kernel/bpf/states.c          |   1 +
 kernel/bpf/verifier.c        |  52 +++-
 5 files changed, 581 insertions(+), 86 deletions(-)
include/linux/bpf_verifier.h +47 -4
index 93147a22c81e..46d186628e2a 100644
@@ -385,6 +385,8 @@ struct bpf_reference_state {
 	u32 diag_id;	/* finds the acquire in the report of a leak, it is not renumbered */
 	/* the insn that brought it into its frame: insn_idx, or a call that returned with it */
 	int origin;
+	/* 1 + the save word of the frame that has the pointer, 0 if none, see bpf_pad_enter() */
+	u8 saved;
 	union {
 		/* For REF_TYPE_PTR. Compared and hashed as 8 bytes, see same_refs(): no holes. */
 		struct {
@@ -544,6 +546,7 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_CALLER_SAVED,
 	BPF_CONFLICT_NO_VALUE,
 	BPF_CONFLICT_NO_ROOM,
+	BPF_CONFLICT_SAVES_DIFFER,
 };
 
 /* How a subprog was found to be one that cannot be cancelled, see 'stuck' of bpf_subprog_info */
@@ -567,6 +570,8 @@ enum bpf_stuck_by {
 #define BPF_PAD_MAX_INSNS	(BPF_PAD_MAX_ENTS * (2 * BPF_PAD_MAX_ARGS + 2) + \
 				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 5)
 #define BPF_PAD_MAX_CANDS	6
+/* The most save words of a function, see 'save_off' of struct bpf_subprog_info */
+#define BPF_PAD_MAX_SAVES	BPF_PAD_MAX_ENTS
 /*
  * The most insns that keep hidden slots up to date at one call: nine for each of at most
  * BPF_PAD_MAX_ENTS slots, five that compare and clear it and four that find a free one. Three per
@@ -580,6 +585,8 @@ enum bpf_place_loc {
 	BPF_PLACE_SPILL,	/* 8 bytes of the stack of the frame */
 	BPF_PLACE_MAP_VALUE,	/* the address of the only value of a map */
 	BPF_PLACE_IMM,		/* not a pointer: the constant 'delta', the flags of a release */
+	/* save word 'at' of a cancelled frame, a BPF_PLACE_SPILL after take_cancelled_words() */
+	BPF_PLACE_SAVED,
 };
 
 /* A location: where a landing pad finds the pointer that a release takes */
@@ -594,9 +601,17 @@ struct bpf_pad_place {
 /* The registers and the stack slots of a frame that are 0 */
 struct bpf_pad_nulls {
 	u16 regs;
+	u16 unsaved;		/* the save words in which the entry stored no pointer */
 	DECLARE_BITMAP(slots, MAX_BPF_STACK_SLOTS);
 };
 
+/* The kind of pointer that a save word holds in all frames of a function: what releases it */
+struct bpf_pad_save {
+	struct bpf_insn release;
+	u32 obj_type;
+	bool set;
+};
+
 /* One release of a landing pad: a resource of the frame, the call and where its arguments are */
 struct bpf_pad_ent {
 	u32 origin;		/* the lowest 'origin' of the references that it stands for */
@@ -606,6 +621,8 @@ struct bpf_pad_ent {
 	u8 class;		/* enum bpf_pad_class */
 	bool rcu;		/* an iterator that RCU protects: it is destroyed first */
 	bool always;		/* all states hold it */
+	/* BPF_SITE_CANCEL_ENTRY: 1 + the save word where the entry keeps the pointer, 0 if none */
+	u8 word;
 	/* per argument of the call: the locations that all states share. The pad uses the first. */
 	u8 nr_cands[BPF_PAD_MAX_ARGS];
 	struct bpf_pad_place cand[BPF_PAD_MAX_ARGS][BPF_PAD_MAX_CANDS];
@@ -647,8 +664,12 @@ struct bpf_pad_plan {
 	u8 no_irq_place;		/* the same for irq flags in the stack of a caller */
 	/* the groups that it asked hidden slots for, bits by enum bpf_pad_group: settle_slots() */
 	u8 asked_slots;
+	/* BPF_SITE_CANCEL_ENTRY: why the entry cannot save pointers, an enum bpf_pad_conflict */
+	u8 no_saves;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
+	/* BPF_SITE_CANCEL_ENTRY: 'ents' are what the frame holds at the call, see visit_saves() */
+	bool saves;
 	/* BPF_SITE_CANCEL_ENTRY: its entry need not test the "cancelled" word: collect_pads() */
 	bool untested;
 	/*
@@ -831,7 +852,12 @@ struct bpf_func_state {
 	bool in_rcu_callback_fn;
 	/* parent_id of the args that are gone when this frame returns */
 	u32 frame_id;
-	u32 cancelled;	/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */
+	u16 cancelled;	/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */
+	/*
+	 * Bit per save word: the entry stored a pointer there when the frame was cancelled. The
+	 * other words are 0. A word keeps its pointer when the cleanup pad releases the object.
+	 */
+	u16 saved_mask;
 	/*
 	 * Bit f: the frame, or a subprog that returned to it, released a lock or irq flags of
 	 * frame f. If the frame returns, a store after its call clears the hidden slot. If not,
@@ -1425,6 +1451,11 @@ struct bpf_insn_aux_data {
 	u32 acquires:1; /* a reference or a lock */
 	u32 releases:1;
 	u32 fault_full:1; /* an access to arena: its plan records every state */
+	/*
+	 * An unwind_goto of the program: the entry of its cleanup pad saves no pointers, because
+	 * the states at the call did not agree in an earlier pass, see settle_entries()
+	 */
+	u32 entry_saves_nothing:1;
 
 	/* below flags are initialized once */
 	u32 bb_end:1; /* last instruction of a basic block */
@@ -1615,6 +1646,11 @@ struct bpf_subprog_info {
 	 * flags that the subprog saves or a pointer that it releases, see bpf_pad_note_return()
 	 */
 	s16 pend_off;
+	/* the first save word, the others are above it, see bpf_pad_enter() */
+	s16 save_off;
+	u8 save_words;
+	/* what each save word holds in a cancelled frame, in this pass */
+	struct bpf_pad_save saves[BPF_PAD_MAX_SAVES];
 	u32 insns_total;
 	u32 insns_self;
 	/* offsets in range [stack_depth .. fastcall_stack_off)
@@ -2013,6 +2049,8 @@ struct bpf_verifier_env {
 	bool ref_conflict;
 	bool handed_back;		/* what was handed over was taken back, see try_more() */
 	bool pass_again;		/* the pass is repeated, see pass_needs_restart() */
+	bool saves_again;		/* because what an entry saves changed: settle_entries() */
+	bool ask_hidden_slots;		/* per subprog from now on, see bpf_hidden_slots_fit() */
 	bool fallthrough_first;		/* see find_failing_path() */
 	bool run_has_guess;		/* see run_path_sensitive() */
 	u32 failing_path_budget_shift;	/* see func_failing_path_budget() */
@@ -2042,7 +2080,10 @@ struct bpf_verifier_env {
 	unsigned long cb_pads[8];
 	u8 cb_pad_cnt;
 	bool pads_late;			/* a global subprog unwinds: see settle_late_unwinds() */
+	bool saves_late;		/* what an entry saves changed, see settle_entries() */
 	bool faults_late;		/* a site is not what it seemed: see check_arena_site() */
+	bool hidden_slots_unasked;	/* see bpf_hidden_slots_fit() */
+	bool slots_late;		/* no room for hidden words: bpf_hidden_slots_settle() */
 	bool pad_releases;		/* see release_frame_resources() */
 	bool calls_joined;		/* see flow_may_add_instance() */
 	bool extra_values;		/* a state can have constants that no run has */
@@ -2611,8 +2652,8 @@ size_t bpf_pad_plans_free(struct bpf_insn_aux_data *aux);
 void bpf_pads_new_round(struct bpf_verifier_env *env);
 void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, bool save);
 size_t bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt);
-struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
-				   const struct bpf_verifier_state *st, int call_idx);
+struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+				   int call_idx);
 struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 				   const struct bpf_verifier_state *st, int insn_idx,
 				   enum bpf_site_kind kind);
@@ -2632,11 +2673,13 @@ bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_d
 void bpf_pads_note_causes(struct bpf_verifier_env *env);
 bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan);
 int bpf_hidden_slots_fit(struct bpf_verifier_env *env);
+int bpf_hidden_slots_settle(struct bpf_verifier_env *env);
 int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad_note **notes);
 int bpf_pad_entry_insns(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			int nr, struct bpf_insn *buf);
 int bpf_pad_cancel_entry_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
-			       int subprog, struct bpf_insn *buf);
+			       int subprog, struct bpf_insn *buf, struct bpf_insn_aux_data *aux);
+int bpf_pad_check_saves(struct bpf_verifier_env *env, int s);
 int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			 int nr, const struct bpf_pad_note *note, struct bpf_insn *buf);
 int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
kernel/bpf/fixups.c +7 -3
index 75d3349624d1..9aa61815e201 100644
@@ -875,8 +875,8 @@ struct pad_unit {
 	struct bpf_pad_plan *cancelled;
 };
 
-/* The most insns that a unit has */
-#define PAD_UNIT_MAX_INSNS	(2 * (BPF_PAD_MAX_INSNS + 4) + 3)
+/* The most insns of a unit. An entry has up to four per save word. */
+#define PAD_UNIT_MAX_INSNS	(2 * (BPF_PAD_MAX_INSNS + 4) + 3 + 4 * BPF_PAD_MAX_SAVES)
 
 /*
  * Do the two records of @unit give the same landing pad? Both pads are emitted into @buf to
@@ -940,7 +940,7 @@ static int emit_unit(struct bpf_verifier_env *env, int s, enum bpf_site_kind bas
 	int n = 0, len;
 
 	if (base == BPF_SITE_CANCEL_ENTRY) {
-		n += bpf_pad_cancel_entry_insns(env, unit->plan, s, buf + n);
+		n += bpf_pad_cancel_entry_insns(env, unit->plan, s, buf + n, aux + n);
 		buf[n++] = BPF_JMP32_A(0);
 		return n;
 	}
@@ -1092,6 +1092,10 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	bool unwinds, cancelled;
 
 	pads->nr = pads->cnt = pads->stubs = 0;
+	/* the entries and the remainders have to agree on the save words */
+	n = sub->save_words ? bpf_pad_check_saves(env, s) : 0;
+	if (n)
+		return n;
 	n = collect_stubs(env, s, pads);
 	if (n < 0)
 		return n;
kernel/bpf/pads.c +478 -75

729 lines not on this page · raw message

kernel/bpf/states.c +1 -0
index 9201e3cbc448..7eb9a3609080 100644
@@ -493,6 +493,7 @@ static bool same_refs(const struct bpf_verifier_state *a, const struct bpf_verif
 
 	for (i = 0; i < a->acquired_refs; i++)
 		if (a->refs[i].type != b->refs[i].type || a->refs[i].id != b->refs[i].id ||
+		    a->refs[i].saved != b->refs[i].saved ||
 		    memcmp(&a->refs[i].ptr, &b->refs[i].ptr, sizeof(u64)))
 			return false;
 	return true;
kernel/bpf/verifier.c +48 -4

96 lines not on this page · raw message

Signature · 1 line
2.53.1-Meta
author maintainer
#67 lore raw

PATCH 67/73 bpf: Run the cleanup pads of a program when the kernel cancels it

In reply to Kumar Kartikeya Dwivedi

Currently everything that a cancellation needs to run a cleanup pad is in place, but nothing calls bpf_find_cleanup_pads(), so no unwind_goto is marked as leading to a cleanup pad.

Call it from bpf_check(), before the main pass. For a program this means:

- When the kernel cancels the program in a subprog or in a callback, the code at the target of the unwind_goto after the call runs if it is a cleanup pad. R0 is 0 at the target.
- The unwind_exit that this code ends in leaves with the value of the cancellation, whatever is in R0, and no unwind_goto is taken for it. The cancellation continues in the same way with each caller.
- A cancellation still cannot be caught. A landing pad of the program that can continue running is not entered, and a cancelled frame never returns to its caller.
- A cleanup pad is verified a second time, for the cancelled frame. An error on that path rejects the program, also one that loaded before.

A cancellation point inside a cleanup pad behaves as follows:

- If the pad runs for the program's own unwinding, a cancellation starts there as anywhere else.
- If the pad already runs for a cancellation, the frame leaves at that point through a generated pad. The rest of that cleanup does not run, and the program still returns the value of the first cancellation. A call that has a cleanup pad of its own is different: the frame continues in that pad.
- After a time-out the time stays up, so a loop in cleanup code ends at its first may_goto. After a fault in arena, bpf_throw() or a recursion that is too deep, a cleanup pad is not cut short this way.

A program can count on a cleanup pad where a cancellation reaches it. The pad is entered, or the program is rejected and the log says why:

- The stack of the function has no room for the hidden words.
- The verifier cannot release what the frame still holds after the cleanup pad, or at a site that the frame reaches in the pad or in a function that the pad calls. A cancelled frame gets no hidden slots of its own.
- The cleanup pad changes what a caller holds in a way that the generated pad of the caller cannot follow. It unlocks a lock or leaves an RCU section of the caller on some paths only, writes to its irq flags, or releases what a function on the stack needs a hidden slot for.

The destructors of a frame do not run on a cancellation in these cases, and in no other:

- The program's landing pad can return or never reaches unwind_exit: a catch clause, and the landing pad of a noexcept function. Destructors that such a landing pad runs before that do not run either.
- The function cannot be cancelled.
- The frame is the one in which the cancellation starts: the frame of the loop, of the access to arena, of the recursion check or of bpf_throw(). Inlining decides which frame that is.
- The call of a frame above it has no unwind_goto, because the callee is noexcept or nounwind or was inlined.

A function in which a cancellation enters a cleanup pad has hidden words in its frame, and a function that had no stack gets one. Only a mixed function also pays a store per call.

verifier.rst now describes cleanup pads, the "cancelled" word and the save words, and the uapi comment of BPF_UNWIND_GOTO says when the code at its target runs for a cancellation. No existing test changes.

---
 Documentation/bpf/verifier.rst | 109 ++++++++++++++++++++++++++++++++-
 include/uapi/linux/bpf.h       |  17 +++++
 kernel/bpf/verifier.c          |   4 ++
 tools/include/uapi/linux/bpf.h |  17 +++++
 4 files changed, 144 insertions(+), 3 deletions(-)
Documentation/bpf/verifier.rst +106 -3
index 8555d023dbaf..2acb05e996fd 100644
@@ -1032,7 +1032,8 @@ The landing pad of the call releases nothing, and nothing is added at run time.
 A call hands over a pointer in one of ``R1`` - ``R5`` that the callee reads and
 that cannot be NULL. It does not hand over an iterator, a dynptr, a reference
 that was made from another one, or one that another one was made from. It hands
-nothing over to a recursive function or to a callback.
+nothing over to a recursive function or to a callback, nor while a frame on the
+stack is cancelled already, see `Cleanup pads`_.
 
 The program is still rejected if the callee has no location for the pointer at
 one of its sites, if a landing pad of the callee would release under a lock of
@@ -1102,8 +1103,8 @@ program has an ``unwind_goto`` after a call, the ``cancel_goto`` follows it::
                          pad: r0 = 0
                               exit
 
-A cancellation enters no landing pad of the program, so the program cannot
-catch it.
+A cancellation enters a landing pad of the program only if that pad cannot
+catch it, see `Cleanup pads`_.
 
 Where a callee leaves with ``unwind_exit`` and the caller has no
 ``unwind_goto`` after the call, the verifier adds one, with a landing pad that
@@ -1131,6 +1132,106 @@ A global function is different because its callers are checked without it and
 only see a number as its return value. A compiler that wants an object to get
 through a global function gives the call there a landing pad of its own.
 
+Cleanup pads
+------------
+
+A *cleanup pad* is a landing pad of the program that can only clean up and
+continue unwinding. It runs a destructor of C++ or drop glue of Rust. Two rules
+decide it, see ``bpf_find_cleanup_pads()``. From the first insn of the pad,
+
+- no path in the function reaches an insn that returns to the caller: ``exit``,
+  a tail call, ``LD_ABS`` or ``LD_IND``,
+- some path reaches ``unwind_exit``.
+
+A cancellation runs the cleanup pads of the frames that it leaves. The same
+code then serves the program's own unwinding and a cancellation, so the frame
+remembers which of the two is under way in a hidden word of its stack, the
+"cancelled" word::
+
+  what the program has      what the verifier makes of it
+
+    call foo                  call foo
+    unwind_goto pad           unwind_goto stub
+    ...                       cancel_goto entry
+    pad: call dtor            ...
+         unwind_exit          pad:   call dtor
+                                     gotol rest
+                              stub:  cancelled = 0    <- own unwinding
+                                     gotol pad
+                              entry: cancelled = 1    <- cancellation
+                                     r0 = 0
+                                     gotol pad
+                              rest:  if cancelled == 0 goto +N
+                                     release what the frame still holds
+                                     cancel_exit
+                                     unwind_exit
+
+The entry puts 0 into ``R0``, where the program's own unwinding has the object
+that it threw. The code at ``rest``, the remainder of the pad, replaces its
+``unwind_exit``. A frame that the program unwinds still leaves with
+``unwind_exit``. A cancelled frame leaves with ``cancel_exit`` and the value of
+the cancellation, whatever is in ``R0``. So no landing pad of the program in a
+caller can catch the cancellation, and it continues in the same way with each
+caller.
+
+Nothing on the normal path writes the "cancelled" word. A function in which a
+cancellation enters a cleanup pad pays for its hidden words in stack, and a
+function that had no stack gets one. A function also pays one store per call,
+which clears the word at its entry, if its normal path falls into a cleanup pad
+or jumps to it, or if a cleanup pad jumps back before its call.
+
+The verifier checks a cleanup pad a second time, for the cancelled frame: with
+0 in ``R0``, and with what the frame holds when its callee is cancelled, see
+``enter_cleanup_pad()``. An error on that path rejects the program.
+
+The remainder releases what the frame still holds after the cleanup pad. Only
+``R0`` is live at the ``unwind_exit`` of the pad. So the entry keeps the
+pointers that the frame holds in ``R6`` - ``R9`` or in stack slots in hidden
+*save words*, at most 8, see ``visit_saves()``. Only a pointer is saved. The
+cleanup pad itself has to release irq flags, an iterator or a dynptr in the
+stack of a caller, and a lock whose address only a register holds. If the
+states at a call do not agree on what the frame holds, the entry of that call
+saves nothing, and the remainder releases only what has a location at the
+``unwind_exit``.
+
+A cleanup pad can have sites of its own. If the pad runs for the program's own
+unwinding, a cancellation starts there as anywhere else. If the pad already
+runs for a cancellation, the frame leaves at that site through a landing pad.
+The rest of the cleanup pad does not run, and the program still returns the
+value of the first cancellation. A call that has a cleanup pad of its own is
+different: the frame continues in that pad. After a time-out the time stays
+up, so a loop in a cleanup pad ends at its first ``may_goto``. After a fault in
+arena, ``bpf_throw()`` or a recursion that is too deep, a cleanup pad is not
+cut short this way.
+
+A program can count on a cleanup pad where a cancellation reaches it: the pad
+is entered, or the program is rejected. The log then has a line with "the
+kernel would enter", which names the cleanup pad where the verifier knows which
+one it is. The program is rejected in these cases:
+
+- The stack of the function has no room for the hidden words.
+- The verifier cannot release what the frame still holds after the cleanup pad,
+  or at a site that the frame reaches in the pad or in a function that the pad
+  calls. A cancelled frame gets no hidden slots of its own.
+- The cleanup pad changes what a caller holds in a way that the landing pad of
+  the caller cannot follow. It unlocks a lock or leaves an RCU section of the
+  caller on some paths only, writes to its irq flags, or releases what a
+  function on the stack needs a hidden slot for.
+
+The destructors of a frame do not run on a cancellation in these cases, and in
+no other:
+
+- The program's landing pad can return, or never reaches ``unwind_exit``: a
+  catch clause, and the landing pad of a ``noexcept`` function, which ends in
+  ``std::terminate()``. Destructors that such a landing pad runs before that
+  do not run either.
+- The function cannot be cancelled.
+- The frame is the one in which the cancellation starts: the frame of the loop,
+  of the access to arena, of the recursion check or of ``bpf_throw()``.
+  Inlining decides which frame that is.
+- The call of a frame above it has no ``unwind_goto``, because the callee is
+  ``noexcept`` or ``nounwind`` or was inlined.
+
 After an error
 ==============
 
@@ -1702,6 +1803,8 @@ budget              a limit on the cost of one step
 cancel              the kernel ends the program before it returns by itself, and
                     each frame releases what it holds
 checked             the bytes of a packet that are known to be before its end
+cleanup pad         a landing pad of the program that can only clean up and
+                    continue unwinding
 control_deps        xregs whose value flows to a jump that can skip an unproven
                     insn
 correlated          two branches: one tests a result that the other one stored
include/uapi/linux/bpf.h +17 -0
index 95b41ae6584d..bd793db5489d 100644
@@ -66,6 +66,23 @@ enum bpf_cond_pseudo_jmp {
 	 * Follows a call of a bpf subprog, callx, or a call of a helper or kfunc
 	 * that calls a callback. Taken when the subprog or the callback left with
 	 * BPF_EXIT that has src_reg == BPF_UNWIND_EXIT.
+	 * When the kernel cancels the program in the subprog or the callback,
+	 * for a loop that is out of time, a recursion that is too deep, a fault
+	 * in arena or bpf_throw(), the code at the target runs too if it is a
+	 * cleanup pad: no path from the target gets to BPF_EXIT without
+	 * BPF_UNWIND_EXIT, to a tail call or to BPF_LD_ABS or BPF_LD_IND, and
+	 * some path gets to BPF_EXIT with BPF_UNWIND_EXIT. R0 is 0 at the
+	 * target then. That BPF_EXIT leaves with the value of the cancellation
+	 * whatever is in R0, and no BPF_UNWIND_GOTO is taken for it: the
+	 * cancellation continues in the same way with each caller.
+	 * A program can count on a cleanup pad where a cancellation reaches it:
+	 * the pad is entered, or the program is rejected and the log says why.
+	 * A cancellation does not reach it in a function that cannot be
+	 * cancelled, in the function in which the cancellation starts, and at a
+	 * call that has no BPF_UNWIND_GOTO. And when the time of the program is
+	 * up, a loop in a cleanup pad ends at its first may_goto: what follows
+	 * the loop does not run.
+	 * See Documentation/bpf/verifier.rst.
 	 */
 	BPF_UNWIND_GOTO = 1,
 };
kernel/bpf/verifier.c +4 -0
index ada65af7e4a3..bd76774ca60f 100644
@@ -27489,6 +27489,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	ret = bpf_find_cleanup_pads(env);
+	if (ret < 0)
+		goto skip_full_check;
+
 	ret = bpf_flow_place_guards(env);
 	if (ret < 0)
 		goto skip_full_check;
tools/include/uapi/linux/bpf.h +17 -0
index 95b41ae6584d..bd793db5489d 100644
@@ -66,6 +66,23 @@ enum bpf_cond_pseudo_jmp {
 	 * Follows a call of a bpf subprog, callx, or a call of a helper or kfunc
 	 * that calls a callback. Taken when the subprog or the callback left with
 	 * BPF_EXIT that has src_reg == BPF_UNWIND_EXIT.
+	 * When the kernel cancels the program in the subprog or the callback,
+	 * for a loop that is out of time, a recursion that is too deep, a fault
+	 * in arena or bpf_throw(), the code at the target runs too if it is a
+	 * cleanup pad: no path from the target gets to BPF_EXIT without
+	 * BPF_UNWIND_EXIT, to a tail call or to BPF_LD_ABS or BPF_LD_IND, and
+	 * some path gets to BPF_EXIT with BPF_UNWIND_EXIT. R0 is 0 at the
+	 * target then. That BPF_EXIT leaves with the value of the cancellation
+	 * whatever is in R0, and no BPF_UNWIND_GOTO is taken for it: the
+	 * cancellation continues in the same way with each caller.
+	 * A program can count on a cleanup pad where a cancellation reaches it:
+	 * the pad is entered, or the program is rejected and the log says why.
+	 * A cancellation does not reach it in a function that cannot be
+	 * cancelled, in the function in which the cancellation starts, and at a
+	 * call that has no BPF_UNWIND_GOTO. And when the time of the program is
+	 * up, a loop in a cleanup pad ends at its first may_goto: what follows
+	 * the loop does not run.
+	 * See Documentation/bpf/verifier.rst.
 	 */
 	BPF_UNWIND_GOTO = 1,
 };
Signature · 1 line
2.53.1-Meta
author maintainer
#68 lore raw

PATCH 68/73 bpf: End the path at a call of a global subprog that never returns

In reply to Kumar Kartikeya Dwivedi

Currently the verifier continues after every call of a global subprog. A global subprog that unwinds on every path never returns, and such functions are common in C++: std::throw_with_nested() is an inline template, which makes it a weak function. A compiler puts what it likes after the call, most often the program's landing pad of that very call:

call throw_with_nested
unwind_goto +0
call dtor <- the landing pad
r0 = 0
unwind_exit

The verifier checks that landing pad for a frame that falls out of the call, which no frame does, and rejects the program when the code is wrong for that state. A cleanup pad there also makes the function mixed.

bpf_compute_might_return() computes for every subprog whether a path from its first insn reaches an exit insn, a tail call, LD_ABS or LD_IND. A path ends at unwind_exit, at a call of bpf_throw() or __bpf_trap(), and at a call of a subprog that does not return, where it continues only at the target of an unwind_goto after that call. A function that calls itself on every path does not return.

In check_func_call(), end the path at a call of a global subprog that does not return. The code after the call becomes dead code unless another path reaches it. Three more changes go with this:

- The search for pad code does not follow the edge from a call of a subprog that does not return, static or global, to the insn after it. A cleanup pad there no longer makes the function mixed.
- A trap, 'goto pc-1', now stays after every such call where the code after it is dead. So far that took an unwind_goto or cancel_goto after the call, or a program without CAP_PERFMON. Should a return ever get there, it finds a trap and not code that was verified for another path.
- The insn after such a call reads R6-R9 and the stack of the frame, for liveness only, as a call of bpf_throw() does. Without an unwind_goto of the program there, the frame leaves through a generated pad, which finds the pointers of the frame in what is live at that insn. The insn is dead code and reads nothing, so a task in R6 needed a hidden slot or rejected the program. An insn that is a jump target is not changed.

A program that was rejected for the code after such a call now loads. R6-R9 and the stack stay live up to such a call, which costs load time.

---
 include/linux/bpf_verifier.h |  13 +++++
 kernel/bpf/cfg.c             | 107 +++++++++++++++++++++++++++++++++++
 kernel/bpf/fixups.c          |  14 ++++-
 kernel/bpf/liveness.c        |  35 +++++++++++-
 kernel/bpf/pads.c            |  29 +++++-----
 kernel/bpf/verifier.c        |  20 ++++++-
 6 files changed, 197 insertions(+), 21 deletions(-)
include/linux/bpf_verifier.h +13 -0
index 46d186628e2a..f71f116f74f3 100644
@@ -1670,6 +1670,8 @@ struct bpf_subprog_info {
 	bool in_recursion: 1; /* recursive, or a recursive subprog gets to it */
 	bool addr_taken: 1; /* callx calls nothing else */
 	bool via_callx: 1; /* callx calls it */
+	/* a path from its first insn returns to the caller, see bpf_compute_might_return() */
+	bool might_return: 1;
 	bool tail_call_reachable: 1;
 	bool has_ld_abs: 1;
 	bool is_cb: 1;
@@ -3007,6 +3009,15 @@ u32 bpf_vlog_alignment(u32 pos);
 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn);
 
 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off);
+
+/* A tail call that is taken and an LD_ABS or LD_IND that fails leave the subprog like exit */
+static inline bool bpf_insn_has_hidden_exit(const struct bpf_insn *insn)
+{
+	return (bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call) ||
+	       (BPF_CLASS(insn->code) == BPF_LD &&
+		(BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND));
+}
+
 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog);
 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
 
@@ -3044,11 +3055,13 @@ u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);
 
 int bpf_find_subprog(struct bpf_verifier_env *env, int off);
 bool bpf_is_throw_kfunc(struct bpf_insn *insn);
+bool bpf_is_trap_kfunc(struct bpf_insn *insn);
 int bpf_compute_const_regs(struct bpf_verifier_env *env);
 int bpf_prune_dead_branches(struct bpf_verifier_env *env);
 int bpf_check_cfg(struct bpf_verifier_env *env);
 void bpf_free_subprog_jts(struct bpf_verifier_env *env);
 int bpf_compute_postorder(struct bpf_verifier_env *env);
+int bpf_compute_might_return(struct bpf_verifier_env *env);
 
 struct bpf_map_desc {
 	struct bpf_map *ptr;
kernel/bpf/cfg.c +107 -0

113 lines not on this page · raw message

kernel/bpf/fixups.c +11 -3
index 9aa61815e201..c2497b4fc953 100644
@@ -1748,8 +1748,8 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
 	struct bpf_insn *insn = env->prog->insnsi;
 	const int insn_cnt = env->prog->len;
-	bool unwinds, calls;
-	int i;
+	bool unwinds, calls, traps;
+	int i, callee;
 
 	for (i = 0; i < insn_cnt; i++, insn++) {
 		unwinds = bpf_is_pad_goto(insn) && aux_data[i + 1 + bpf_jmp_offset(insn)].seen;
@@ -1759,8 +1759,16 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 		 * its cancel_exit needs cancel_goto.
 		 * The cpu predicts that it returns to what follows, or speculates to an exit.
 		 * Don't let the removal of dead code put something else there.
+		 * After a call of a subprog that does not return, see bpf_compute_might_return(),
+		 * the trap is kept whoever loads the program: should a return ever get there, it
+		 * must not find code that was verified for another path.
 		 */
-		if ((unwinds || (calls && !env->bypass_spec_v1)) && !aux_data[i + 1].seen) {
+		traps = calls && !env->bypass_spec_v1;
+		if (calls && !traps && bpf_pseudo_call(insn)) {
+			callee = bpf_find_subprog(env, i + insn->imm + 1);
+			traps = callee >= 0 && !env->subprog_info[callee].might_return;
+		}
+		if ((unwinds || traps) && !aux_data[i + 1].seen) {
 			memcpy(insn + 1, &trap, sizeof(trap));
 			aux_data[i + 1].zext_dst = false;
 			aux_data[i + 1].seen = env->check_cnt;
kernel/bpf/liveness.c +32 -3
index 93f8d1686496..7ebcd369d229 100644
@@ -392,9 +392,7 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
 	 * from the subprogram, which is a hidden edge to its exit. A subprogram
 	 * with neither an exit insn nor bpf_throw() has no exit to model.
 	 */
-	if (unlikely((bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call) ||
-		     (BPF_CLASS(insn->code) == BPF_LD &&
-		      (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)))) {
+	if (unlikely(bpf_insn_has_hidden_exit(insn))) {
 		u32 exit_idx = bpf_find_containing_subprog(env, idx)->exit_idx;
 
 		if (exit_idx != U32_MAX)
@@ -1860,6 +1858,26 @@ static int record_arg_access(struct bpf_verifier_env *env,
 	return err;
 }
 
+/*
+ * Is the insn at @idx dead code after a call of a subprog that does not return, see
+ * bpf_compute_might_return()? The callee comes back to the call only when it unwinds or is
+ * cancelled. The frame then leaves through a generated pad, which finds the pointers of the frame
+ * in what is live at this insn. So for liveness the insn reads what the pad may read, as a call of
+ * bpf_throw() does. That does not apply where the program has an unwind_goto there, nor where a
+ * jump leads to the insn.
+ */
+static bool behind_call_without_return(struct bpf_verifier_env *env, int idx)
+{
+	const struct bpf_insn *insns = env->prog->insnsi;
+	int callee;
+
+	if (!idx || !bpf_pseudo_call(&insns[idx - 1]) || bpf_is_unwind_goto(&insns[idx]) ||
+	    bpf_is_jump_target(env, idx))
+		return false;
+	callee = bpf_find_subprog(env, idx + insns[idx - 1].imm);
+	return callee >= 0 && !env->subprog_info[callee].might_return;
+}
+
 /* Record stack access for a given 'at' state of helper/kfunc/global subprog 'insn' */
 static int record_call_access(struct bpf_verifier_env *env,
 			      struct func_instance *instance,
@@ -2213,6 +2231,13 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 		if (err)
 			goto err_free;
 
+		/* the generated pad of the call may read any stack slot of the frame */
+		if (behind_call_without_return(env, idx)) {
+			err = mark_stack_read_all(env, instance, instance->depth, idx, true);
+			if (err)
+				goto err_free;
+		}
+
 		if (BPF_CLASS(insn->code) == BPF_JMP && BPF_OP(insn->code) == BPF_CALL) {
 			err = record_call_access(env, instance, at_in[i], idx);
 			if (err)
@@ -2842,6 +2867,10 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env,
 		break;
 	}
 
+	/* the generated pad of the call may take a pointer from R6-R9 */
+	if (behind_call_without_return(env, insn - env->prog->insnsi))
+		use |= mask_widen(GENMASK(BPF_REG_9, BPF_REG_6));
+
 	info->def = def;
 	info->use = use;
 }
kernel/bpf/pads.c +15 -14
index d016bfdc53cb..8c77525f4967 100644
@@ -4728,10 +4728,7 @@ static bool insn_returns(const struct bpf_insn *insn)
 {
 	if (insn->code == (BPF_JMP | BPF_EXIT))
 		return !bpf_is_unwind_exit(insn);
-	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call)
-		return true;
-	return BPF_CLASS(insn->code) == BPF_LD &&
-	       (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND);
+	return bpf_insn_has_hidden_exit(insn);
 }
 
 /*
@@ -4757,16 +4754,11 @@ static bool insn_returns(const struct bpf_insn *insn)
  * call, or the function has no exit. In any other function a frame gets from the normal path into
  * pad code in two ways only: by the jump of an unwind_goto, and through an entry.
  *
- * A function is MIXED, 'cleanup_pads_mixed', if one of its insns is pad code and on the normal path
- * as well: a pad that the normal path falls into or jumps to, a pad that goes back in front of its
- * call, or to the first insn of its function, any pad of a function that has no exit. In every
- * other function the two share no insn, and a frame gets from the normal path into pad code in two
- * ways only: by the jump of unwind_goto, when a callee left with unwind_exit, and through the entry
- * of a pad, when the kernel unwound the callee.
- *
- * The exit that stands for the return of a tail call or of LD_ABS is no edge here, as it is none
- * where the pads are judged: it can be unwind_exit of the code that resumes, and a tail call on
- * the normal path would make every such function mixed.
+ * Two edges are not followed. One goes from a tail call, LD_ABS or LD_IND to the exit insn that
+ * stands for its return, which is often the unwind_exit of the cleanup pads. The other goes from
+ * the call of a subprog that does not return, see bpf_compute_might_return(), to the insn after it,
+ * where a compiler often puts the cleanup pad of that call. A trap stands there if that code is
+ * dead, see bpf_opt_hard_wire_dead_code_branches().
  */
 static int find_pad_code(struct bpf_verifier_env *env)
 {
@@ -4801,6 +4793,15 @@ static int find_pad_code(struct bpf_verifier_env *env)
 			if (!test_bit(i, pad) && !test_bit(i, normal))
 				continue;
 			insn = &insns[i];
+			s = bpf_pseudo_call(insn) ? bpf_find_subprog(env, i + 1 + insn->imm) : -1;
+			if (s >= 0 && !env->subprog_info[s].might_return) {
+				/* the callee does not return: only its landing pad follows */
+				t = i + 1 < len && bpf_is_unwind_goto(insn + 1) ?
+				    i + 2 + bpf_jmp_offset(insn + 1) : -1;
+				if (t >= 0 && test_bit(i, pad) && !__test_and_set_bit(t, pad))
+					changed = true;
+				continue;
+			}
 			succ = bpf_insn_successors(env, i);
 			cnt = insn_returns(insn) ? min(succ->cnt, 1) : succ->cnt;
 			for (t = 0; t < cnt; t++) {
kernel/bpf/verifier.c +19 -1
index bd76774ca60f..d154a7891d07 100644
@@ -12621,6 +12621,13 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 						 BPF_REG_0);
 		}
 
+		/*
+		 * The callee never returns, see bpf_compute_might_return(). Only the states that
+		 * were pushed above come back from the call, so this path ends.
+		 */
+		if (!env->subprog_info[subprog].might_return)
+			return PROCESS_BPF_EXIT;
+
 		/* continue with next insn after call */
 		return 0;
 	}
@@ -15713,6 +15720,12 @@ bool bpf_is_throw_kfunc(struct bpf_insn *insn)
 	       insn->imm == special_kfunc_list[KF_bpf_throw];
 }
 
+bool bpf_is_trap_kfunc(struct bpf_insn *insn)
+{
+	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+	       insn->imm == special_kfunc_list[KF___bpf_trap];
+}
+
 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
 {
 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
@@ -16567,7 +16580,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		mark_reg_unknown(env, regs, BPF_REG_0);
 		reg_set_srange32(&regs[BPF_REG_0], -MAX_ERRNO, -1);
 		reg_bounds_sync(&regs[BPF_REG_0]);
-	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
+	} else if (bpf_is_trap_kfunc(insn)) {
 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
 		return -EFAULT;
 	}
@@ -27469,6 +27482,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	/* needs the topological order of the subprogs, callees first */
+	ret = bpf_compute_might_return(env);
+	if (ret < 0)
+		goto skip_full_check;
+
 	/* what no JIT can run is reported first */
 	ret = mark_recursive_subprogs(env);
 	if (ret < 0)
Signature · 1 line
2.53.1-Meta
author maintainer
#69 lore raw

PATCH 69/73 bpf: Tell struct_ops when a program was cancelled

In reply to Kumar Kartikeya Dwivedi

Currently the kernel code that calls a struct_ops program cannot tell a program that was cancelled from one that ran to its end. A cancelled struct_ops program returns 0, and what 0 means is up to the struct_ops. For ops.select_cpu() of sched_ext it is a CPU. The work of the program is also left half done. When ops.enqueue() of sched_ext faults in arena before it queues its task, the task is in no queue, and sched_ext keeps calling the scheduler until its watchdog finds a task that has not run.

Add a callback, ->cancelled(), to struct bpf_struct_ops. In a program of a struct_ops that sets it, the landing pad that returns to the kernel calls it after all frames have released what they held:

pad: r1 = r6
call bpf_task_release
+ r1 = prog->aux
+ call bpf_prog_report_cancelled <- calls st_ops->unwound(prog)

       r0 = 0
       exit

Only landing pads that end with exit get the call. They belong to the functions that only the kernel calls: the main program, and an async callback for which the verifier finds no caller in the program. Every other landing pad ends with cancel_exit, and the cancellation continues in the caller.

Three cases need care:

- An async callback that may have a caller in the program has landing pads that end with cancel_exit. When the kernel called such a callback and cancels it, the struct_ops is not told yet.
- The landing pads of the exception callback make no call. The landing pad of the main program that calls it has called ->cancelled() before.
- The call is also made where the program's own unwinding ends the program, at a call without unwind_goto to which an unwind_exit comes back. An unwinding that the program catches is not reported.

->cancelled() runs in the context of the kernel code that called the program, with the locks that this code holds, and it can be reentered. It must not sleep or take a lock that is held around a call of a program.

An async callback can run when no struct_ops map holds the module of the struct_ops any more. So a struct_ops program now holds a reference on that module, and drops it after the grace period that waits for the program to stop running. A module therefore cannot be unloaded while a program of one of its struct_ops is loaded, also when no struct_ops map exists.

---
 include/linux/bpf.h          | 13 +++++++++++++
 include/linux/bpf_verifier.h |  7 ++++---
 include/linux/filter.h       |  1 +
 kernel/bpf/core.c            | 12 ++++++++++++
 kernel/bpf/pads.c            | 34 +++++++++++++++++++++++++++++++++-
 kernel/bpf/syscall.c         |  7 ++++++-
 kernel/bpf/verifier.c        |  8 ++++++++
 7 files changed, 77 insertions(+), 5 deletions(-)
include/linux/bpf.h +13 -0
index a8e9d12dbe80..269ad54faf5b 100644
@@ -2297,6 +2297,18 @@ struct btf_member;
  *	      reason, if this callback is not defined, the check is skipped as
  *	      the struct_ops map will have final verification performed in
  *	      @reg.
+ * @cancelled: A callback that is invoked when an invocation of a program of
+ *	       this struct_ops, an op or an async callback of one, was unwound
+ *	       up to the kernel, before the invocation returns. No path of the
+ *	       program chose what it returns then: it is 0, NULL for a pointer,
+ *	       or what bpf_throw() was passed. A struct_ops that cannot take
+ *	       this for the result of an op reacts here. The callback runs in
+ *	       the context of the program, which for an op is that of its caller
+ *	       with the locks that it holds, and it can be reentered. It must
+ *	       not sleep and must not take a lock that is held around a call of
+ *	       an op: it notes the event and defers the rest. A program of the
+ *	       struct_ops holds a reference on @owner for as long as it lives,
+ *	       so the callback is there whenever one runs.
  * @cfi_stubs: Pointer to a structure of stub functions for CFI. These stubs
  *	       provide the correct Control Flow Integrity hashes for the
  *	       trampolines generated by BPF struct_ops.
@@ -2333,6 +2345,7 @@ struct bpf_struct_ops {
 	void (*unreg)(void *kdata, struct bpf_link *link);
 	int (*update)(void *kdata, void *old_kdata, struct bpf_link *link);
 	int (*validate)(void *kdata);
+	void (*cancelled)(const struct bpf_prog *prog);
 	void *cfi_stubs;
 	struct module *owner;
 	const char *name;
include/linux/bpf_verifier.h +4 -3
index f71f116f74f3..112354168ce7 100644
@@ -561,14 +561,15 @@ enum bpf_stuck_by {
 
 /*
  * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument, a test and
- * the call. The 5 are two insns that save the value, two that load the value, and 'r2 = 0'.
- * emit_pad() adds the insn that leaves the frame, or the call of the exception callback.
+ * the call. The 8 are two insns that save the value, three that tell the struct_ops, two that
+ * load the value, and 'r2 = 0'. emit_pad() adds the insn that leaves the frame, or the call of
+ * the exception callback.
  */
 #define BPF_PAD_MAX_SECTIONS	8
 #define BPF_PAD_MAX_ENTS	8
 #define BPF_PAD_MAX_ARGS	2
 #define BPF_PAD_MAX_INSNS	(BPF_PAD_MAX_ENTS * (2 * BPF_PAD_MAX_ARGS + 2) + \
-				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 5)
+				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 8)
 #define BPF_PAD_MAX_CANDS	6
 /* The most save words of a function, see 'save_off' of struct bpf_subprog_info */
 #define BPF_PAD_MAX_SAVES	BPF_PAD_MAX_ENTS
include/linux/filter.h +1 -0
index 74e61ef02285..16ab07f41aae 100644
@@ -1505,6 +1505,7 @@ void bpf_timed_may_goto_check_time(const struct bpf_prog *prog);
 void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved);
 void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved);
 u64 bpf_prog_report_recursion(void);
+u64 bpf_prog_report_cancelled(struct bpf_prog_aux *aux);
 bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id);
 
 static inline bool bpf_dump_raw_ok(const struct cred *cred)
kernel/bpf/core.c +12 -0
index 288963919afd..588800956bea 100644
@@ -4138,6 +4138,18 @@ u64 bpf_prog_report_recursion(void)
 	return 0;
 }
 
+/*
+ * Called by the landing pad that ends an invocation, when the frames have released what they held.
+ * What the value of an unwound op means is up to the struct_ops. This is the context of the
+ * program, with the locks of the caller of the op: see what ->cancelled() may do.
+ * Only programs of a struct_ops that has the callback call it, see bpf_pad_insns().
+ */
+u64 bpf_prog_report_cancelled(struct bpf_prog_aux *aux)
+{
+	aux->st_ops->cancelled(aux->prog);
+	return 0;
+}
+
 u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *p)
 {
 	u64 time = ktime_get_mono_fast_ns();
kernel/bpf/pads.c +33 -1
index 8c77525f4967..df0c8b211048 100644
@@ -2593,6 +2593,31 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan
 	return n;
 }
 
+/*
+ * The kernel called @subprog, and its pads end the invocation with exit: the main program, whose
+ * unwind_exit is exit to the JITs as well, see bpf_prog_can_unwind(), and an async callback that
+ * cannot leave unwound, see unwind_exit_insn(). They tell a struct_ops that wants to know, see
+ * bpf_prog_report_cancelled().
+ * An async callback that can leave unwound has callers in the program, or is expected to. It has
+ * one pad for all its frames, which ends in cancel_exit, or in unwind_exit for what the program
+ * unwinds, and cannot tell who called. Such a pad tells nobody.
+ * A pad that ends the invocation tells whatever its site is: also the pad of a call without
+ * unwind_goto to which unwind_exit of a callee came back, which is an unwind of the program's own.
+ * That tells about more than the kernel has stopped, and it misses nothing that the kernel has: such
+ * a pad of the main program calls the exception callback, which the kernel can unwind in turn, and
+ * the pads of that callback tell nobody.
+ * The exception callback is called by a pad of the main program, which has told already.
+ */
+static bool pad_reports(const struct bpf_verifier_env *env, int subprog)
+{
+	const struct bpf_struct_ops *st_ops = env->prog->aux->st_ops;
+	const struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+
+	if (!st_ops || !st_ops->cancelled || sub->is_exception_cb)
+		return false;
+	return !subprog || (sub->is_async_cb && !sub->bail_unwinds);
+}
+
 /*
  * Does the pad of a site of @kind in @subprog pass R2 on with R0, see bpf_pad_passes_on()? Only in
  * a subprog that returns two registers. Its other pads leave with 0 in R2.
@@ -2608,7 +2633,8 @@ static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_
 {
 	return (bpf_site_has_value(env, subprog, plan->kind) ||
 		bpf_pad_passes_on(env, subprog, plan->kind)) &&
-	       (plan->nr_ents || plan->sections[BPF_PAD_RCU] || plan->sections[BPF_PAD_PREEMPT]);
+	       (plan->nr_ents || plan->sections[BPF_PAD_RCU] || plan->sections[BPF_PAD_PREEMPT] ||
+		pad_reports(env, subprog));
 }
 
 
@@ -2620,6 +2646,7 @@ static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_
 int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan, int subprog,
 		  struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
 {
+	struct bpf_insn ld_aux[2] = { BPF_LD_IMM64(BPF_REG_1, (long)env->prog->aux) };
 	int value_off = env->subprog_info[subprog].value_off;
 	int src = bpf_site_value_reg(plan->kind), dst = BPF_REG_0;
 	bool passes_on = bpf_pad_passes_on(env, subprog, plan->kind);
@@ -2645,6 +2672,11 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < pad_enters(plan, class); i++)
 			buf[n++] = enter_call(class);
+	if (pad_reports(env, subprog)) {
+		buf[n++] = ld_aux[0];
+		buf[n++] = ld_aux[1];
+		buf[n++] = BPF_EMIT_KERNEL_CALL(bpf_prog_report_cancelled);
+	}
 	if (bpf_site_is_cancelled(plan->kind) && env->has_throw) {
 		/* the value of the first cancellation, which the entry of the cleanup pad stored */
 		buf[n++] = BPF_LDX_MEM(BPF_DW, dst, BPF_REG_FP, value_off);
kernel/bpf/syscall.c +6 -1
index 70112c2c1e40..15738dc042a3 100644
@@ -2463,6 +2463,9 @@ static void __bpf_prog_put_rcu(struct rcu_head *rcu)
 {
 	struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
 
+	/* A prog that ran until now may have called ->cancelled(), which is code of the module */
+	if (aux->prog->type == BPF_PROG_TYPE_STRUCT_OPS)
+		module_put(aux->mod);
 	btf_put(aux->btf);
 	kvfree(aux->jited_linfo);
 	kvfree(aux->linfo);
@@ -2490,7 +2493,9 @@ static void __bpf_prog_put_rcu_tasks(struct rcu_head *rcu)
 
 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
 {
-	module_put(prog->aux->mod);
+	/* A struct_ops prog keeps its module over the grace period, see __bpf_prog_put_rcu() */
+	if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
+		module_put(prog->aux->mod);
 	bpf_free_kfunc_tab(prog->aux->kfunc_tab);
 	kfree(prog->aux->ctx_arg_info);
 	if (prog->aux->attach_btf)
kernel/bpf/verifier.c +8 -0
index d154a7891d07..4506ff1fbcbf 100644
@@ -25643,6 +25643,14 @@ static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
 
 	prog->aux->st_ops = st_ops;
 	prog->aux->attach_st_ops_member_off = member_off;
+	/*
+	 * The program holds the module of its struct_ops for as long as it lives: an async callback
+	 * of the program can run when no struct_ops map holds the module any more.
+	 */
+	if (env->attach_btf_mod) {
+		__module_get(env->attach_btf_mod);
+		prog->aux->mod = env->attach_btf_mod;
+	}
 
 	prog->aux->attach_func_proto = func_proto;
 	prog->aux->attach_func_name = mname;
Signature · 1 line
2.53.1-Meta
author maintainer
#70 lore raw

PATCH 70/73 bpf: Tell struct_ops when cancel_exit returns to the kernel

In reply to Kumar Kartikeya Dwivedi

Currently ->cancelled() of a struct_ops is called only by landing pads that end with exit. An async callback that may have a caller in the program has landing pads that end with cancel_exit. When the kernel called such a callback and cancels it, nobody tells the struct_ops:

  static int tick(void *map, int *key, struct elem *e)
  {
          while (!ready)          <- the time of the loop is up
                  ;
          return 0;
  }

bpf_timer_set_callback(&e->timer, tick); the kernel calls tick()
tick(&timers, &key, e); and so does the program

The landing pad of tick() ends with cancel_exit for both callers. When the program called tick(), cancel_exit returns to the cancel_goto after the call, and a landing pad of the main program tells the struct_ops. When the timer called tick(), cancel_exit finds no cancel_goto and returns to the kernel like exit.

The verifier also assumes a caller in the program for an async callback that calls itself, that has an unwind_exit, or whose address is not loaded directly before the call of the helper that stores it.

cancel_exit looks up its return address at run time. When it finds no cancel_goto and no unwind label of a helper there, and the address is in no BPF program, the kernel called the frame. Call ->cancelled() at that point, through the new bpf_prog_cancelled_to_kernel(). Every cancellation that ends a program now calls ->cancelled() exactly once.

The JITed code of cancel_exit calls the lookup from the frame that it leaves, so the lookup returns into the program, and bpf_prog_ksym_find() finds the program from that address. A kretprobe or an fexit trampoline would replace the address, so the lookup functions are notrace and on the kprobe blacklist. That now includes the two that the arm64 JIT calls.

Two cases need care:

- An unwind_exit of the program that returns to the kernel does not call ->cancelled(). The program chose this way out, as it chooses exit.
- Every helper passes a cancellation on from its unwind label. Kernel code that calls a program with bpf_call_cb() and ends the cancellation there has to call ->cancelled() itself.

---
 arch/arm64/net/bpf_jit_comp.c | 45 +++++++++++++++++++++++------------
 arch/x86/net/bpf_jit_comp.c   | 30 +++++++++++++++--------
 include/linux/bpf_unwind.h    |  4 +++-
 include/linux/filter.h        |  1 +
 kernel/bpf/core.c             | 37 ++++++++++++++++++++++++----
 kernel/bpf/pads.c             | 21 +++++++---------
 6 files changed, 95 insertions(+), 43 deletions(-)
arch/arm64/net/bpf_jit_comp.c +30 -15
index c41e649c735f..c3547c7e4c55 100644
@@ -1779,16 +1779,18 @@ static int build_landings(struct jit_ctx *ctx)
 }
 
 /*
- * Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with
- * cancel_exit, @key CANCEL_EXKEY, returns to.
- * The verifier made sure that unwind_goto follows a call in a prog, and
- * cancel_goto where the callee has cancel_exit. When the kernel called an async
- * callback, it's exit. A helper that calls a callback has a pad when it wants
- * one, see bpf_call_cb().
+ * Return where a frame with the return address @ret_addr returns to when it
+ * leaves with unwind_exit (@key is UNWIND_EXKEY) or cancel_exit (CANCEL_EXKEY).
+ *
+ * @ip is the return address of the lookup. It is in the frame itself when an
+ * insn of a prog asks, and in a helper for bpf_unwind_leave(). A kretprobe, the
+ * function graph tracer and an fexit trampoline replace it, so the callers are
+ * notrace and on the kprobe blacklist.
  */
-static u64 unwind_target(u64 ret_addr, int key)
+static u64 unwind_target(u64 ret_addr, int key, unsigned long ip)
 {
 	const struct exception_table_entry *e;
+	bool lost;
 
 	e = search_bpf_extables(ret_addr - key);
 	if (e)
@@ -1815,19 +1817,27 @@ static u64 unwind_target(u64 ret_addr, int key)
 	 * for that at load time, see check_cb_pad().
 	 */
 	scoped_guard(rcu)
-		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
+		lost = bpf_prog_ksym_find(ret_addr - 1);
+	/*
+	 * A cancelled frame that returns to the kernel ends the invocation, and
+	 * only here is that known, so tell the struct_ops. unwind_exit is the
+	 * program's own way out, like exit, and is not reported. See
+	 * bpf_prog_cancelled_to_kernel().
+	 */
+	if (!WARN_ON_ONCE(lost) && key == CANCEL_EXKEY)
+		bpf_prog_cancelled_to_kernel(ip);
 	return ret_addr;
 }
 
 u64 notrace bpf_unwind_target(u64 ret_addr)
 {
-	return unwind_target(ret_addr, UNWIND_EXKEY);
+	return unwind_target(ret_addr, UNWIND_EXKEY, _RET_IP_);
 }
 NOKPROBE_SYMBOL(bpf_unwind_target);
 
 u64 notrace bpf_cancel_target(u64 ret_addr)
 {
-	return unwind_target(ret_addr, CANCEL_EXKEY);
+	return unwind_target(ret_addr, CANCEL_EXKEY, _RET_IP_);
 }
 NOKPROBE_SYMBOL(bpf_cancel_target);
 
@@ -1843,21 +1853,26 @@ u64 bpf_fault_unwind_target(u64 end)
 	return e ? end + e->fixup : end;
 }
 
-/* The offset that the epilogue adds to LR once it is authenticated */
-static long bpf_unwind_fixup(u64 lr)
+/*
+ * unwind_exit calls this with the signed LR of its frame. Return the offset
+ * that the epilogue adds to LR after it has authenticated it.
+ */
+static notrace long bpf_unwind_fixup(u64 lr)
 {
 	u64 ret_addr = ptrauth_strip_kernel_insn_pac(lr);
 
-	return bpf_unwind_target(ret_addr) - ret_addr;
+	return unwind_target(ret_addr, UNWIND_EXKEY, _RET_IP_) - ret_addr;
 }
+NOKPROBE_SYMBOL(bpf_unwind_fixup);
 
 /* The same for cancel_exit */
-static long bpf_cancel_fixup(u64 lr)
+static notrace long bpf_cancel_fixup(u64 lr)
 {
 	u64 ret_addr = ptrauth_strip_kernel_insn_pac(lr);
 
-	return bpf_cancel_target(ret_addr) - ret_addr;
+	return unwind_target(ret_addr, CANCEL_EXKEY, _RET_IP_) - ret_addr;
 }
+NOKPROBE_SYMBOL(bpf_cancel_fixup);
 
 /*
  * unwind_exit, cancel_exit: return to the pad. LR in the frame record is
arch/x86/net/bpf_jit_comp.c +20 -10
index fc57ab6a238c..c3edda0392fd 100644
@@ -2412,16 +2412,18 @@ static int add_unwind_exentry(struct bpf_prog *prog, u8 *image, u8 *rw_image, in
 }
 
 /*
- * Where a frame that leaves with unwind_exit, @key UNWIND_EXKEY, or with
- * cancel_exit, @key CANCEL_EXKEY, returns to.
- * The verifier made sure that unwind_goto follows a call in a prog, and
- * cancel_goto where the callee has cancel_exit. When the kernel called an async
- * callback, it's exit. A helper that calls a callback has a pad when it wants
- * one, see bpf_call_cb().
+ * Return where a frame with the return address @ret_addr returns to when it
+ * leaves with unwind_exit (@key is UNWIND_EXKEY) or cancel_exit (CANCEL_EXKEY).
+ *
+ * @ip is the return address of the lookup. It is in the frame itself when an
+ * insn of a prog asks, and in a helper for bpf_unwind_leave(). A kretprobe, the
+ * function graph tracer and an fexit trampoline replace it, so the callers are
+ * notrace and on the kprobe blacklist.
  */
-static u64 unwind_target(u64 ret_addr, int key)
+static u64 unwind_target(u64 ret_addr, int key, unsigned long ip)
 {
 	const struct exception_table_entry *e;
+	bool lost;
 
 	e = search_bpf_extables(ret_addr - key);
 	if (e)
@@ -2448,19 +2450,27 @@ static u64 unwind_target(u64 ret_addr, int key)
 	 * for that at load time, see check_cb_pad().
 	 */
 	scoped_guard(rcu)
-		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
+		lost = bpf_prog_ksym_find(ret_addr - 1);
+	/*
+	 * A cancelled frame that returns to the kernel ends the invocation, and
+	 * only here is that known, so tell the struct_ops. unwind_exit is the
+	 * program's own way out, like exit, and is not reported. See
+	 * bpf_prog_cancelled_to_kernel().
+	 */
+	if (!WARN_ON_ONCE(lost) && key == CANCEL_EXKEY)
+		bpf_prog_cancelled_to_kernel(ip);
 	return ret_addr;
 }
 
 u64 notrace bpf_unwind_target(u64 ret_addr)
 {
-	return unwind_target(ret_addr, UNWIND_EXKEY);
+	return unwind_target(ret_addr, UNWIND_EXKEY, _RET_IP_);
 }
 NOKPROBE_SYMBOL(bpf_unwind_target);
 
 u64 notrace bpf_cancel_target(u64 ret_addr)
 {
-	return unwind_target(ret_addr, CANCEL_EXKEY);
+	return unwind_target(ret_addr, CANCEL_EXKEY, _RET_IP_);
 }
 NOKPROBE_SYMBOL(bpf_cancel_target);
 
include/linux/bpf_unwind.h +3 -1
index 71512d96688b..2c0d1a327533 100644
@@ -34,7 +34,9 @@
  * which follows bpf_call_cb(), must not fault or have a fixup of its own.
  *
  * Without asm goto outputs, and on other architectures, bpf_call_cb() is a plain call and
- * BPF_HAS_CB_PADS is 0: the verifier rejects a callback that can unwind.
+ * BPF_HAS_CB_PADS is 0: the verifier rejects a callback that can unwind. Kernel code that ends a
+ * cancellation at its label, without bpf_unwind_leave(), has to tell the struct_ops itself, see
+ * bpf_prog_cancelled_to_kernel().
  */
 
 #include <linux/bug.h>
include/linux/filter.h +1 -0
index 16ab07f41aae..3b91990512c7 100644
@@ -1506,6 +1506,7 @@ void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_g
 void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved);
 u64 bpf_prog_report_recursion(void);
 u64 bpf_prog_report_cancelled(struct bpf_prog_aux *aux);
+void bpf_prog_cancelled_to_kernel(unsigned long ip);
 bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id);
 
 static inline bool bpf_dump_raw_ok(const struct cred *cred)
kernel/bpf/core.c +33 -4
index 588800956bea..023606ae570c 100644
@@ -4139,10 +4139,10 @@ u64 bpf_prog_report_recursion(void)
 }
 
 /*
- * Called by the landing pad that ends an invocation, when the frames have released what they held.
- * What the value of an unwound op means is up to the struct_ops. This is the context of the
- * program, with the locks of the caller of the op: see what ->cancelled() may do.
- * Only programs of a struct_ops that has the callback call it, see bpf_pad_insns().
+ * Tell the struct_ops that its program was cancelled. A landing pad that ends the program with
+ * exit calls this after all frames have released what they held. Only a program of a struct_ops
+ * that has ->cancelled() gets the call, see pad_reports() in pads.c. It runs in the context of the
+ * program, with the locks of the kernel code that called the program.
  */
 u64 bpf_prog_report_cancelled(struct bpf_prog_aux *aux)
 {
@@ -4150,6 +4150,35 @@ u64 bpf_prog_report_cancelled(struct bpf_prog_aux *aux)
 	return 0;
 }
 
+/*
+ * Tell the struct_ops that its program was cancelled, where cancel_exit returns to the kernel.
+ * bpf_cancel_target() of a JIT calls this when it finds no cancel_goto and no unwind label of a
+ * helper at the return address of the frame, and that address is in no program. The frame is an
+ * async callback that may also have callers in the program. Its landing pads end in cancel_exit
+ * for every caller, so they cannot make the call, see pad_reports() in pads.c. Together with
+ * bpf_prog_report_cancelled(), a cancellation that ends a program calls ->cancelled() exactly once.
+ *
+ * @ip is in the code that asked. If that is a helper, in bpf_unwind_leave(), nothing is done. An
+ * unwind_exit of the program that returns to the kernel does not get here: the program chose that
+ * way out, as it chooses exit. Kernel code that calls a program with bpf_call_cb() and does not
+ * pass a cancellation on has to call ->cancelled() itself.
+ */
+void bpf_prog_cancelled_to_kernel(unsigned long ip)
+{
+	const struct bpf_struct_ops *st_ops;
+	struct bpf_prog *prog;
+
+	scoped_guard(rcu)
+		prog = bpf_prog_ksym_find(ip);
+	if (!prog)
+		return;
+	/* The frame keeps the program alive. The struct_ops is that of the main program. */
+	prog = prog->aux->main_prog_aux->prog;
+	st_ops = prog->aux->st_ops;
+	if (st_ops && st_ops->cancelled)
+		st_ops->cancelled(prog);
+}
+
 u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *p)
 {
 	u64 time = ktime_get_mono_fast_ns();
kernel/bpf/pads.c +8 -13
index df0c8b211048..a1d93af26bb9 100644
@@ -2594,19 +2594,14 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan
 }
 
 /*
- * The kernel called @subprog, and its pads end the invocation with exit: the main program, whose
- * unwind_exit is exit to the JITs as well, see bpf_prog_can_unwind(), and an async callback that
- * cannot leave unwound, see unwind_exit_insn(). They tell a struct_ops that wants to know, see
- * bpf_prog_report_cancelled().
- * An async callback that can leave unwound has callers in the program, or is expected to. It has
- * one pad for all its frames, which ends in cancel_exit, or in unwind_exit for what the program
- * unwinds, and cannot tell who called. Such a pad tells nobody.
- * A pad that ends the invocation tells whatever its site is: also the pad of a call without
- * unwind_goto to which unwind_exit of a callee came back, which is an unwind of the program's own.
- * That tells about more than the kernel has stopped, and it misses nothing that the kernel has: such
- * a pad of the main program calls the exception callback, which the kernel can unwind in turn, and
- * the pads of that callback tell nobody.
- * The exception callback is called by a pad of the main program, which has told already.
+ * Does a pad of @subprog tell the struct_ops that the program was cancelled, see
+ * bpf_prog_report_cancelled()? Only a pad that ends the invocation with exit does, at every kind of
+ * site: in the main program, and in an async callback that cannot leave with cancel_exit.
+ *
+ * An async callback that may have a caller in the program has pads that end in cancel_exit and
+ * cannot tell who called. There cancel_exit itself reports when it returns to the kernel, see
+ * bpf_prog_cancelled_to_kernel(). The exception callback does not report: the pad of the main
+ * program that calls it has reported already.
  */
 static bool pad_reports(const struct bpf_verifier_env *env, int subprog)
 {
Signature · 1 line
2.53.1-Meta
author maintainer
#71 lore raw

PATCH 71/73 bpf: Let a struct_ops say what a cancelled program returns

In reply to Kumar Kartikeya Dwivedi

Currently a cancelled struct_ops program returns 0, or NULL for a pointer. The verifier chooses the value by the program type, and all struct_ops programs have one type. What 0 means is up to the member. For Qdisc_ops::enqueue() it is NET_XMIT_SUCCESS, so the sender is told that the packet is on its way. A cancelled enqueue() did not queue the packet, and its landing pad frees the packet if the program still holds it.

Add a callback, ->cancelled_retval(), to struct bpf_struct_ops. The verifier calls it at load time with the program, and the callback returns the value for the member that the program is attached to, or 0. The value becomes a constant in the program, so it must depend on nothing but the member.

The verifier does not run check_return_code() on the value. So it asks only about a member that returns an integer, for which every value is accepted. A member that returns nothing or a pointer keeps 0, and so does a struct_ops without the callback.

Implement the callback for bpf_qdisc:

enqueue() NET_XMIT_DROP
init() -ECANCELED. With 0, qdisc_create() would attach a qdisc
whose init() was cancelled halfway. With the error it calls destroy() and frees the qdisc, as for any init() that fails.

The other struct_ops in the tree keep 0 for every member:

- For hid_bpf, 0 lets hid-core handle the event or the request as it does without a program.
- bpf_tcp_ops, smc_hs_ctrl and io_uring have no member that returns an errno.
- For sched_ext a cancelled program is a failure of the scheduler as a whole, which ->cancelled() can report.
- binfmt_misc_ops::load() returns an errno, and 0 lets the exec continue. -ECANCELED would suit it, but that choice belongs to its owners.
- tcp_congestion_ops needs values of its own and is not changed here.

---
 include/linux/bpf.h   | 34 ++++++++++++++++++++++------------
 kernel/bpf/verifier.c | 22 +++++++++++++++++++++-
 net/sched/bpf_qdisc.c | 21 +++++++++++++++++++++
 3 files changed, 64 insertions(+), 13 deletions(-)
include/linux/bpf.h +22 -12
index 269ad54faf5b..6eaff33dab09 100644
@@ -2297,18 +2297,27 @@ struct btf_member;
  *	      reason, if this callback is not defined, the check is skipped as
  *	      the struct_ops map will have final verification performed in
  *	      @reg.
- * @cancelled: A callback that is invoked when an invocation of a program of
- *	       this struct_ops, an op or an async callback of one, was unwound
- *	       up to the kernel, before the invocation returns. No path of the
- *	       program chose what it returns then: it is 0, NULL for a pointer,
- *	       or what bpf_throw() was passed. A struct_ops that cannot take
- *	       this for the result of an op reacts here. The callback runs in
- *	       the context of the program, which for an op is that of its caller
- *	       with the locks that it holds, and it can be reentered. It must
- *	       not sleep and must not take a lock that is held around a call of
- *	       an op: it notes the event and defers the rest. A program of the
- *	       struct_ops holds a reference on @owner for as long as it lives,
- *	       so the callback is there whenever one runs.
+ * @cancelled: A callback that is invoked when the kernel has cancelled a
+ *	       program of this struct_ops, or an async callback of one: it
+ *	       ended the program early, at a loop that ran out of time, a
+ *	       recursion that is too deep, a fault in arena or bpf_throw(). The
+ *	       program has released what it held but has not finished its work.
+ *	       It is about to return the value of @cancelled_retval, or the
+ *	       argument of bpf_throw(). The callback is passed the main program.
+ *	       It runs in the context of the code that called the program, with
+ *	       the locks that this code holds, and it can be reentered. It must
+ *	       not sleep or take a lock that is held around a call of a
+ *	       program. A program holds a reference on @owner, so the callback
+ *	       can run when no struct_ops map is left.
+ * @cancelled_retval: A callback that the verifier invokes when it loads a
+ *		      program. It returns the value that the program returns
+ *		      when the kernel cancels it, for a member where 0 would be
+ *		      wrong, and 0 otherwise. The member is
+ *		      prog->aux->attach_st_ops_member_off. The value becomes a
+ *		      constant in the program, so it must depend on nothing but
+ *		      the member. The callback is invoked only for a member that
+ *		      returns an integer. If it is not defined, a cancelled
+ *		      program returns 0.
  * @cfi_stubs: Pointer to a structure of stub functions for CFI. These stubs
  *	       provide the correct Control Flow Integrity hashes for the
  *	       trampolines generated by BPF struct_ops.
@@ -2346,6 +2355,7 @@ struct bpf_struct_ops {
 	int (*update)(void *kdata, void *old_kdata, struct bpf_link *link);
 	int (*validate)(void *kdata);
 	void (*cancelled)(const struct bpf_prog *prog);
+	int (*cancelled_retval)(const struct bpf_prog *prog);
 	void *cfi_stubs;
 	struct module *owner;
 	const char *name;
kernel/bpf/verifier.c +21 -1
index 4506ff1fbcbf..65e0f96031ee 100644
@@ -22173,6 +22173,23 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
 	return enter_callback(env, false, NULL);
 }
 
+/*
+ * The value that a cancelled struct_ops program returns. The struct_ops chooses it for the member
+ * that @prog is attached to, see bpf_struct_ops.cancelled_retval. It is asked only about a member
+ * that returns an integer, for which check_return_code() accepts every value. A member that
+ * returns void or a pointer keeps 0.
+ */
+static int struct_ops_cancelled_retval(const struct bpf_prog *prog)
+{
+	const struct bpf_struct_ops *st_ops = prog->aux->st_ops;
+	const struct btf_type *proto = prog->aux->attach_func_proto;
+
+	if (!st_ops->cancelled_retval || !proto->type ||
+	    btf_type_resolve_ptr(prog->aux->attach_btf, proto->type, NULL))
+		return 0;
+	return st_ops->cancelled_retval(prog);
+}
+
 /*
  * The value that a cancelled program returns to the kernel. No code of the program chose it, so it
  * is the value that refuses, drops or changes nothing. That is 0, except for:
@@ -22180,7 +22197,8 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
  *	tc					TC_ACT_SHOT, 0 is TC_ACT_OK
  *	lwt, flow dissector			BPF_DROP, 0 is BPF_OK
  *	syscall					-ECANCELED, 0 tells user space that all was done
- *	lsm, the hook returns an errno		-EPERM, 0 lets the operation go on
+ *	struct_ops				what the struct_ops chooses for the member, or 0
+ *	lsm, the hook returns an errno		-EPERM, 0 allows the operation
  *	the range is [1, 1]			1, hooks that cannot refuse
  *
  * Each is a value that check_return_code() accepts. It has to be, because no state is checked with
@@ -22220,6 +22238,8 @@ int bpf_cancelled_retval(struct bpf_verifier_env *env)
 	default:
 		break;
 	}
+	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
+		return struct_ops_cancelled_retval(prog);
 	if (get_func_retval_range(prog, &range) && range.minval < 0)
 		return -EPERM;
 	if (!program_returns_void(env) && return_retval_range(env, &range) && range.minval > 0)
net/sched/bpf_qdisc.c +21 -0
index 5098cf5a487c..4b274c76163a 100644
@@ -453,6 +453,26 @@ static int bpf_qdisc_validate(void *kdata)
 	return 0;
 }
 
+/* What a program returns when the kernel cancels it, which ends the program
+ * early, for example at a loop that runs out of time:
+ *
+ * ->enqueue()	NET_XMIT_DROP. The program may not have queued the packet, and
+ *		the kernel has freed the packet if the program still held it.
+ * ->init()	-ECANCELED, so that qdisc_create() calls ->destroy() and frees
+ *		the qdisc, as for any ->init() that fails.
+ * ->dequeue() returns NULL. ->reset() and ->destroy() return nothing.
+ */
+static int bpf_qdisc_cancelled_retval(const struct bpf_prog *prog)
+{
+	u32 moff = prog->aux->attach_st_ops_member_off;
+
+	if (moff == offsetof(struct Qdisc_ops, enqueue))
+		return NET_XMIT_DROP;
+	if (moff == offsetof(struct Qdisc_ops, init))
+		return -ECANCELED;
+	return 0;
+}
+
 static int Qdisc_ops__enqueue(struct sk_buff *skb__ref, struct Qdisc *sch,
 			      struct sk_buff **to_free)
 {
@@ -492,6 +512,7 @@ static struct bpf_struct_ops bpf_Qdisc_ops = {
 	.unreg = bpf_qdisc_unreg,
 	.validate = bpf_qdisc_validate,
 	.check_member = bpf_qdisc_check_member,
+	.cancelled_retval = bpf_qdisc_cancelled_retval,
 	.init_member = bpf_qdisc_init_member,
 	.init = bpf_qdisc_init,
 	.name = "Qdisc_ops",
Signature · 1 line
2.53.1-Meta
author maintainer
#72 lore raw

PATCH 72/73 bpf: Give cancelled tcp_congestion_ops programs values that TCP can take

In reply to Kumar Kartikeya Dwivedi

Currently a cancelled program of tcp_congestion_ops returns 0, and TCP cannot take 0 from every member. A congestion control that is reno, built from the kfuncs of the kernel, shows it on a connection over loopback when the kernel cancels one of its programs:

- ->undo_cwnd() returns the window for a loss that TCP takes back. The window becomes 0, and tcp_snd_cwnd_set() warns.
- ->ssthresh() returns the slow start threshold. When the recovery is over, TCP sets the window to it, and the same warning fires. Then ->cong_avoid() of the program calls tcp_reno_cong_avoid(), and tcp_cong_avoid_ai() divides by the window:

    Oops: divide error: 0000 [#1] SMP
    RIP: 0010:tcp_cong_avoid_ai+0x50/0x90

- ->sndbuf_expand() returns the factor by which TCP sizes the send buffer. With 0 the buffer keeps its first size, 16384 bytes where the same connection with reno has 2626560.

Implement ->cancelled_retval() for tcp_congestion_ops. The value is a constant in the program, and the value that fits is in the socket. No constant is right, so give each member the least value that TCP can work with:

  ->ssthresh()       2  the least that tcp_reno_ssthresh() returns
  ->undo_cwnd()      1  the window that TCP itself sets after a timeout
  ->tso_segs()       1  what tcp_tso_segs() makes of 0 today
  ->sndbuf_expand()  2  the factor that TCP uses when the member is not

set

The price is a slow connection. After a cancelled ->undo_cwnd() it continues with a window of one segment, and after a cancelled ->ssthresh() the recovery ends with a window of two. The other programs of the congestion control grow the window again if they still run.

The values do not apply to bpf_throw(), whose cookie is what the program returns. A program that returns 0 from these members that way, or with its own return, has a bug of its own.

The other members return nothing. No program can implement ->get_info().

---
 net/ipv4/bpf_tcp_ca.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
net/ipv4/bpf_tcp_ca.c +31 -0
index 2a71dc81562f..4b9ea3058b6f 100644
@@ -256,6 +256,36 @@ static int bpf_tcp_ca_validate(void *kdata)
 	return tcp_validate_congestion_control(kdata);
 }
 
+/* What a program returns when the kernel cancels it, which ends the program
+ * early, for example at a loop that runs out of time. The value is a constant,
+ * and TCP cannot take 0 from every program, so each one returns the least
+ * value that TCP can work with:
+ *
+ * ->ssthresh()		2, the least that tcp_reno_ssthresh() returns. With 0
+ *			the window is 0 when a recovery is over, and
+ *			tcp_cong_avoid_ai() divides by the window.
+ * ->undo_cwnd()	1, the window that TCP itself sets after a timeout.
+ * ->tso_segs()		1, which is what tcp_tso_segs() makes of 0.
+ * ->sndbuf_expand()	2, the factor that tcp_sndbuf_expand() uses without
+ *			this callback. With 0 the send buffer does not grow.
+ *
+ * The other programs return nothing, and no program can be ->get_info().
+ */
+static int bpf_tcp_ca_cancelled_retval(const struct bpf_prog *prog)
+{
+	switch (prog->aux->attach_st_ops_member_off) {
+	case offsetof(struct tcp_congestion_ops, ssthresh):
+		return 2;
+	case offsetof(struct tcp_congestion_ops, undo_cwnd):
+		return 1;
+	case offsetof(struct tcp_congestion_ops, tso_segs):
+		return 1;
+	case offsetof(struct tcp_congestion_ops, sndbuf_expand):
+		return 2;
+	}
+	return 0;
+}
+
 static u32 bpf_tcp_ca_ssthresh(struct sock *sk)
 {
 	return 0;
@@ -338,6 +368,7 @@ static struct bpf_struct_ops bpf_tcp_congestion_ops = {
 	.init_member = bpf_tcp_ca_init_member,
 	.init = bpf_tcp_ca_init,
 	.validate = bpf_tcp_ca_validate,
+	.cancelled_retval = bpf_tcp_ca_cancelled_retval,
 	.name = "tcp_congestion_ops",
 	.cfi_stubs = &__bpf_ops_tcp_congestion_ops,
 	/* The struct_ops's function may switch to another struct_ops.
Signature · 1 line
2.53.1-Meta
author maintainer
#73 lore raw

PATCH 73/73 sched_ext: Treat a cancelled program as a scheduler error

In reply to Kumar Kartikeya Dwivedi

The kernel can now cancel a BPF program. It ends the program early at a loop that runs out of time, at a fault in arena or at bpf_throw(). The program returns a default value, which is 0 for a program of a scheduler, and does not finish its work.

Currently sched_ext keeps calling a scheduler whose program was cancelled, until the watchdog finds a task that has not run:

  void BPF_STRUCT_OPS(cs_enqueue, struct task_struct *p, u64 flags)
  {
          nr_enqueued++;          <- in arena, the page is gone
          scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, slice, flags);
  }

ops.enqueue() is cancelled at the fault, and the task gets into no queue. A cancelled ops.select_cpu() returns 0, which is a CPU, and a cancelled ops.init_task() returns 0, which is success.

The BPF core calls ->cancelled() of struct bpf_struct_ops when a program of the struct_ops was cancelled. Implement it for sched_ext_ops and sched_ext_ops_cid. It finds the scheduler of the program with scx_prog_sched() and calls scx_error() for it, so the error goes exactly where scx_bpf_error() of that program would go. The first cancelled program disables the scheduler, with a runtime error:

program <name> (ops.<member>, id <id>) was unwound, see its stderr stream

The stderr stream of the program says why the kernel cancelled it.

->cancelled() runs in the context of the cancelled program. scx_error() is safe there: it takes no lock and can be called under the rq lock, in a timer callback and in NMI.

Two things stay as they are:

- The callbacks of the scheduler are still called until the disable path has finished, as after scx_bpf_error() today.
- A cancelled program for which scx_prog_sched() finds no scheduler is not reported.

---
 kernel/sched/ext/ext.c | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
kernel/sched/ext/ext.c +21 -0
index efa1d01d03af..3a5928e1a500 100644
@@ -9435,6 +9435,25 @@ static int bpf_scx_validate(void *kdata)
 	return 0;
 }
 
+/*
+ * @prog, an op of a scheduler or an async callback of one, was unwound.
+ * The op returns 0 without having computed it, which would be taken for a
+ * CPU or for success, so this is as fatal to the scheduler as scx_bpf_error().
+ * The rq lock of the op's caller may be held here. scx_error() only
+ * claims the exit and leaves the disabling to irq_work and the helper kthread.
+ */
+static void bpf_scx_cancelled(const struct bpf_prog *prog)
+{
+	struct scx_sched *sch;
+
+	guard(rcu)();
+
+	sch = scx_prog_sched(prog->aux);
+	if (sch)
+		scx_error(sch, "program %s (ops.%s, id %u) was unwound, see its stderr stream",
+			  prog->aux->name, prog->aux->attach_func_name, prog->aux->id);
+}
+
 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
@@ -9528,6 +9547,7 @@ static struct bpf_struct_ops bpf_sched_ext_ops = {
 	.init = bpf_scx_init,
 	.update = bpf_scx_update,
 	.validate = bpf_scx_validate,
+	.cancelled = bpf_scx_cancelled,
 	.name = "sched_ext_ops",
 	.owner = THIS_MODULE,
 	.cfi_stubs = &__bpf_ops_sched_ext_ops
@@ -9605,6 +9625,7 @@ static struct bpf_struct_ops bpf_sched_ext_ops_cid = {
 	.init = bpf_scx_init,
 	.update = bpf_scx_update,
 	.validate = bpf_scx_validate,
+	.cancelled = bpf_scx_cancelled,
 	.name = "sched_ext_ops_cid",
 	.owner = THIS_MODULE,
 	.cfi_stubs = &__bpf_ops_sched_ext_ops_cid
Signature · 1 line
2.53.1-Meta