Skip to contentSkip to conversation

Cancellations

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

Subsystems (21)
Networking Documentation x86 PowerPC +17 more subsystems
lore
Share & tools
lore

Kumar Kartikeya Dwivedi

author maintainer
#0 lore raw

cover Cancellations

The BPF runtime today uses a mix of static analysis and bespoke runtime checks to guarantee safety while reducing proof obligations for BPF programs, in order to permit more flexibility. Often, the runtime encounters cases where the program has entered an error state, and continuing it is futile. Examples of such instances include a loop runs past its time slice, a recursion gets too deep, an access to arena faults, or the program calls bpf_throw().

Today, every case is handled differently. A may_goto that the verifier adds to a loop only leaves the loop, so the code after the loop has to be safe without the loop's result. A may_goto of the program (can_loop, cond_break) jumps to code that continues with half a result. A load from arena that faults reads 0 and the program continues. bpf_throw() is rejected while the program holds anything. Recursion checks also do not halt the execution of a program.

Instead, it would be useful to have a core runtime primitive to halt the execution of the program at a given point, reclaim all resources it has acquired during its execution, and optionally, eject it from the system when supported.

Prior attempts [0][1][2] have aimed at various approaches to resolve this problem with varying semantics (short-circuiting constructs like loops that delay program execution and steer execution to exit, or use object tables generated during verification to feed to the runtime unwinder).

In this series, we take the approach of treating all of the instances above as points where a program will halt execution or abort, and treat them using a unified cancellations mechanism.

When a program is cancelled, every frame on the stack releases what it holds, and the program returns a value chosen for its type, such as TC_ACT_SHOT for tc or -EPERM for an LSM hook that returns an errno. The exception callback can be used to override the return value as a final resort.

The verifier generates the code that cleans up. An insn at which a program can be cancelled is a site: a may_goto, the stack check of a recursive function, an access to arena, a call of bpf_throw(), and every call whose callee can be cancelled. For each site the verifier emits a landing pad after the body of the function. The pad releases what the frame holds at the site and leaves the frame:

	bpf_rcu_read_lock();			   call bpf_rcu_read_lock
	do {					1: ...
		p = bpf_map_lookup_elem(...);	   call bpf_map_lookup_elem
	} while (!p);				   may_goto pad
	v = *p;					   if r0 == 0 goto 1b
	bpf_rcu_read_unlock();			   ...
	return v;				   exit
					      pad: call bpf_rcu_read_unlock
						   r0 = 0
						   exit

A pad takes each pointer from the register or stack slot where the program keeps it, which costs nothing at run time. This works when every path to the site keeps the pointer in the same location. When the paths disagree, or only some of them hold the resource, the function gets a hidden stack slot, and stores that the verifier emits record the resource when it is acquired and clear the slot when it is released. When a callee releases a reference of its caller, the call hands the reference over where it can, and the callee owns it from its entry, without stores.

Frames are unwound one at a time, and there is no stack walk. A cancelled frame leaves with cancel_exit and returns to the cancel_goto after its call, which jumps to the pad of the caller. Only the verifier emits these two insns. They mirror unwind_exit and unwind_goto, which a program uses for its own unwinding in C++ or Rust, and like them they are exception table entries that cost nothing when the callee returns. They are a separate pair because a landing pad of the program is ordinary code that may catch and continue running, and a cancelled program must not continue. A call can therefore end in three ways: the callee returns, unwinds, or is cancelled. The caller tells them apart by where the callee returns to. A flag in a register would not do, because it is lost in the C frame of a helper such as bpf_loop() that sits between a callback and its caller.

A program with landing pads of its own still gets to clean up. A pad that can only clean up and continue unwinding, such as a C++ destructor or Rust drop glue, runs when its frame is cancelled, and generated code then releases what the frame still holds. A pad that can catch is skipped, and a generated pad runs in its place.

A struct_ops is told when one of its programs was cancelled and can say what such a program returns. sched_ext treats a cancelled program as an error of the scheduler.

A program is cancelled in this way only if it is loaded with CAP_PERFMON, because landing pads are not hardened against speculation, and only on x86-64 and arm64.

Patches 1-4 are fixes and preparation. Patches 5-10 give the helpers that call a callback an unwind label, so that a callback can be unwound through the helper. Patches 11-22 add the landing pads: RCU and preemption sections, locks and irq flags, references, iterators and dynptrs, calls of subprogs and of helpers with a callback. Patches 23-31 add hidden stack slots and handle calls that acquire or release for their caller, including the hand-over of a reference. Patches 32-37 cancel a program at a fault in arena. Patches 38-47 make bpf_throw() cancel the program through the landing pads and remove the exception boundary from the JITs and the stack walk. Patches 48-51 cancel a program at its own may_goto and add verifier log lines. Patches 52-58 add cancel_goto and cancel_exit. Patches 59-68 run the cleanup pads of a program on a cancellation. Patches 69-73 tell a struct_ops about a cancelled program, choose return values for tcp_congestion_ops, and make sched_ext raise a scheduler error.

[0]: https://lore.kernel.org/bpf/[email protected]
[1]: https://lore.kernel.org/bpf/[email protected]
[2]: https://lore.kernel.org/bpf/[email protected]

Alexei Starovoitov (21):
bpf: Drop the edge after bpf_throw() from the control flow graph
bpf: Let a state leave its frame at may_goto without an exit insn
bpf: Emit landing pads that leave RCU sections
bpf: Release locks and irq flags in landing pads
bpf: Add unwind_goto after calls of subprogs
bpf: Let the kernel cancel a program in a global subprog
bpf: Let the kernel cancel a frame that holds references
bpf: Let a may_goto that the verifier adds go to its landing pad only
bpf: Use hidden slots for a pointer that has no location at a site
bpf: Give unwind_goto a 32 bit offset and prepare it for arena
accesses
bpf, arm64: Go to the landing pad when an access to arena faults
bpf: Let a register be the location of a lock in a global variable
bpf: Share one landing pad among accesses to arena where nothing is
held
bpf: Refuse freplace on a function that can unwind
bpf: Let landing pads pass on the value of unwind_exit
bpf: Make bpf_throw() cancel the program through landing pads bpf, x86: Remove the exception boundary
bpf, arm64: Remove the exception boundary
s390/bpf: Remove the exception boundary
powerpc64/bpf: Remove the exception boundary
bpf: Remove the stack walk of bpf_throw()

Kumar Kartikeya Dwivedi (52):
bpf: Refuse a program that is too large for bpf_prog->pages
bpf: Require CAP_PERFMON for unwind_exit and unwind_goto
bpf: Reject bpf_percpu_obj_drop() of a type with special fields
bpf: Let a helper call its callback with an unwind label bpf, x86, arm64: Add landings that redo what follows a helper call
bpf: Let a callback unwind out of a helper that has an unwind label
bpf: Let the inlined bpf_loop pass on a callback that unwinds
bpf: Give the helpers that call a callback an unwind label
bpf: Let the comparator of bpf_rbtree_add unwind
bpf: Choose what a cancelled program returns by its type
bpf: Release references in landing pads
bpf: Release iterators and dynptrs in landing pads
bpf: Check pointers for NULL in landing pads
bpf: Add unwind_goto after helpers with a callback
bpf: Record why a callee is cancelled when its call gets no landing
pad
bpf: Record what each call acquires and releases
bpf: Add hidden stack slots for landing pads
bpf: Restore the sections of the call when a frame is cancelled
bpf: Let hidden slots follow what a subprog does for its caller
bpf: Let a callee hold a reference that its call hands over
bpf: Let a call clear the hidden slot of what its callee releases
bpf: Give a callee a hidden slot for the reference that it is handed bpf, x86: Go to the landing pad when an access to arena faults
bpf: Cancel a program at a fault in arena
bpf: Keep R0, R6-R9 and the stack live at a call of bpf_throw()
bpf: Keep a reference of the caller that a function finds NULL
bpf: Find at a site that a frame holds more than a landing pad
releases
bpf: Cancel the program when the time of its own may_goto is up
bpf: Reject a program that has no landing pad for a fault in arena
bpf: Log why a call is a site and which functions cannot be cancelled
bpf: Add cancel_goto and cancel_exit, which only the verifier emits
bpf: Give the unwind label of a helper a second way in bpf, x86: Put the landing of unwind_goto after the function bpf, x86: Return to cancel_goto at cancel_exit
bpf, arm64: Return to cancel_goto at cancel_exit
bpf: Use cancel_exit to leave a frame that the kernel cancels
bpf: Check that a helper whose callback may unwind has an unwind label
bpf: Find the landing pads of a program that can only clean up
bpf: Don't let hidden stack words turn on the private stack
bpf: Add a landing pad per site for frames that are cancelled already
bpf: Verify a cleanup pad for a frame that is cancelled
bpf: Reject a program whose cleanup pad a cancellation cannot enter
bpf: Find the code that a cleanup pad can reach
bpf: Emit the stub, the entry and the remainder of a cleanup pad
bpf: Let the entry of a cleanup pad save the pointers of the frame
bpf: Run the cleanup pads of a program when the kernel cancels it
bpf: End the path at a call of a global subprog that never returns
bpf: Tell struct_ops when a program was cancelled
bpf: Tell struct_ops when cancel_exit returns to the kernel
bpf: Let a struct_ops say what a cancelled program returns
bpf: Give cancelled tcp_congestion_ops programs values that TCP can
take
sched_ext: Treat a cancelled program as a scheduler error

 Documentation/bpf/verifier.rst                |  420 +-
 arch/arm64/net/bpf_jit_comp.c                 |  456 +-
 arch/powerpc/net/bpf_jit.h                    |    2 -
 arch/powerpc/net/bpf_jit_comp.c               |    7 -
 arch/powerpc/net/bpf_jit_comp64.c             |  145 +-
 arch/s390/net/bpf_jit_comp.c                  |   47 +-
 arch/x86/net/bpf_jit_comp.c                   |  499 +-
 include/linux/bpf.h                           |   45 +-
 include/linux/bpf_unwind.h                    |  342 ++
 include/linux/bpf_verifier.h                  |  929 ++-
 include/linux/btf.h                           |    6 +
 include/linux/filter.h                        |   71 +-
 include/uapi/linux/bpf.h                      |   20 +-
 kernel/bpf/Makefile                           |    2 +-
 kernel/bpf/arena.c                            |   28 +-
 kernel/bpf/arraymap.c                         |   14 +-
 kernel/bpf/bpf_iter.c                         |   37 +-
 kernel/bpf/btf.c                              |   43 +
 kernel/bpf/cfg.c                              |  107 +
 kernel/bpf/const_fold.c                       |   22 +-
 kernel/bpf/core.c                             |  149 +-
 kernel/bpf/disasm.c                           |   13 +-
 kernel/bpf/failing_path.c                     |   14 +-
 kernel/bpf/fixups.c                           | 1397 ++++-
 kernel/bpf/flow.c                             |  107 +-
 kernel/bpf/hashtab.c                          |   33 +-
 kernel/bpf/helpers.c                          |  111 +-
 kernel/bpf/join.c                             |   15 +-
 kernel/bpf/liveness.c                         |   95 +-
 kernel/bpf/pads.c                             | 4958 +++++++++++++++++
 kernel/bpf/precision.c                        |   56 +-
 kernel/bpf/ringbuf.c                          |   23 +-
 kernel/bpf/states.c                           |   20 +-
 kernel/bpf/syscall.c                          |   11 +-
 kernel/bpf/task_iter.c                        |   22 +-
 kernel/bpf/verifier.c                         | 2363 ++++++--
 kernel/sched/ext/ext.c                        |   21 +
 net/ipv4/bpf_tcp_ca.c                         |   31 +
 net/sched/bpf_qdisc.c                         |   21 +
 scripts/gdb/linux/bpf.py                      |    4 +-
 tools/include/uapi/linux/bpf.h                |   20 +-
 tools/testing/selftests/bpf/DENYLIST.s390x    |    1 +
 .../testing/selftests/bpf/bpf_experimental.h  |   20 +-
 .../selftests/bpf/prog_tests/arena_stack.c    |    6 +-
 .../selftests/bpf/prog_tests/exceptions.c     |   34 +-
 .../selftests/bpf/prog_tests/may_goto_far.c   |   23 +-
 .../testing/selftests/bpf/prog_tests/stream.c |    3 +-
 .../selftests/bpf/prog_tests/timed_may_goto.c |   89 +-
 .../selftests/bpf/prog_tests/unwind_attach.c  |   15 +-
 .../selftests/bpf/progs/arena_atomics.c       |   96 +-
 .../selftests/bpf/progs/arena_stack_throw.c   |    1 -
 .../bpf/progs/compute_live_registers.c        |    8 +-
 .../selftests/bpf/progs/exceptions_fail.c     |   37 +-
 .../selftests/bpf/progs/jit_insns_arena.c     |   20 +-
 .../selftests/bpf/progs/may_goto_priv_stack.c |    8 +-
 .../selftests/bpf/progs/plain_c_arena_htab.c  |    2 +
 .../bpf/progs/plain_c_arena_strsearch.c       |    2 +
 .../bpf/progs/plain_c_rbtree_search_kptr.c    |    6 -
 .../bpf/progs/plain_c_verifier_arena_large.c  |    2 +
 .../bpf/progs/pro_epilogue_arena_stack.c      |    2 +
 .../selftests/bpf/progs/res_spin_lock_fail.c  |    2 +
 tools/testing/selftests/bpf/progs/stream.c    |   16 +-
 .../selftests/bpf/progs/timed_may_goto.c      |  332 +-
 .../selftests/bpf/progs/timed_may_goto_ext.c  |   22 +-
 .../selftests/bpf/progs/timed_may_goto_user.c |  169 +-
 .../selftests/bpf/progs/verifier_arena.c      |   38 +-
 .../bpf/progs/verifier_arena_large.c          |   51 +-
 .../bpf/progs/verifier_arena_stack.c          |   85 +-
 .../selftests/bpf/progs/verifier_barrier.c    |  141 +-
 .../bpf/progs/verifier_bpf_fastcall.c         |   12 +-
 .../selftests/bpf/progs/verifier_budget.c     |  667 +--
 .../selftests/bpf/progs/verifier_cfg.c        |    4 +-
 .../selftests/bpf/progs/verifier_equations.c  |   11 +-
 .../bpf/progs/verifier_iterating_callbacks.c  |   25 +-
 .../bpf/progs/verifier_jumps_ahead.c          |    2 +-
 .../selftests/bpf/progs/verifier_ldsx.c       |   12 +-
 .../bpf/progs/verifier_linked_scalars.c       |    7 +-
 .../selftests/bpf/progs/verifier_loop_latch.c |   14 -
 .../selftests/bpf/progs/verifier_loop_walk.c  |    2 +
 .../selftests/bpf/progs/verifier_may_goto_1.c |   17 +-
 .../selftests/bpf/progs/verifier_passes.c     |   72 +-
 .../selftests/bpf/progs/verifier_patch_list.c |  101 +-
 .../bpf/progs/verifier_private_stack.c        |   36 +-
 .../selftests/bpf/progs/verifier_stack_arg.c  |    8 +-
 .../selftests/bpf/progs/verifier_stack_ptr.c  |    2 +-
 .../selftests/bpf/progs/verifier_trip_count.c |   26 +-
 .../selftests/bpf/progs/verifier_unwind.c     |   32 +-
 tools/testing/selftests/bpf/verifier/calls.c  |    1 +
 88 files changed, 12435 insertions(+), 2573 deletions(-)
 create mode 100644 include/linux/bpf_unwind.h
 create mode 100644 kernel/bpf/pads.c

base-commit: 0dbb0bea76960c41194677d39da65cdfd9f813ad

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

PATCH 1/73 bpf: Refuse a program that is too large for bpf_prog->pages

Currently nothing limits the size that a program reaches when it is rewritten. bpf_prog->pages is a u16, and bpf_prog_realloc() stores the page count of the new size there without a check. Above 65535 pages the count wraps. bpf_prog_lock_ro() then protects only that many pages, and bpf_prog_clone_create() copies only that many, so constant blinding reads past the end of its clone. With 4K pages the count wraps at about 33.5M insns. No rewrite is known to add that many today.

Refuse a program that 'pages' cannot count. Every rewrite of the verifier and constant blinding build the new image in bpf_patch_list_build(). Let it return -E2BIG for an image of more than BPF_PROG_MAX_LEN insns, before anything of that size is allocated. A rewrite of the verifier then fails the load, with the reason in the log. Constant blinding treats it like its other errors: the program is interpreted where that is possible, and the load fails where it is not.

Let bpf_prog_alloc_no_stats() and bpf_prog_realloc(), the two functions that set 'pages', return NULL for a size that it cannot count, so that no other caller can make the count wrap.

---
 include/linux/filter.h |  4 ++++
 kernel/bpf/core.c      | 14 +++++++++++++-
 kernel/bpf/fixups.c    |  3 +++
 3 files changed, 20 insertions(+), 1 deletion(-)
include/linux/filter.h +4 -0
index 06f128632d5c..5f038006ecbc 100644
@@ -1247,6 +1247,10 @@ static inline unsigned int bpf_prog_size(unsigned int proglen)
 		   offsetof(struct bpf_prog, insns[proglen]));
 }
 
+/* The most insns that a program has room for: bpf_prog->pages counts its pages in 16 bits */
+#define BPF_PROG_MAX_LEN \
+	((U16_MAX * PAGE_SIZE - offsetof(struct bpf_prog, insnsi)) / sizeof(struct bpf_insn))
+
 bool bpf_prog_has_arena_insns(const struct bpf_prog *prog);
 
 /*
kernel/bpf/core.c +13 -1
index facb0d6d2e8d..b1c8c246dc25 100644
@@ -109,6 +109,9 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 	struct bpf_prog *fp;
 
 	size = round_up(size, __PAGE_SIZE);
+	/* fp->pages cannot count more */
+	if (size / PAGE_SIZE > U16_MAX)
+		return NULL;
 	fp = __vmalloc(size, gfp_flags);
 	if (fp == NULL)
 		return NULL;
@@ -269,6 +272,9 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
 	pages = size / PAGE_SIZE;
 	if (pages <= fp_old->pages)
 		return fp_old;
+	/* fp->pages cannot count more */
+	if (pages > U16_MAX)
+		return NULL;
 
 	fp = __vmalloc(size, gfp_flags);
 	if (fp) {
@@ -668,6 +674,8 @@ static int patch_image_relax(struct bpf_patch_image *img, u32 *tgt)
 	/* like kvmalloc(): the size of a prog fits into 32 bits */
 	if (map[cnt] > INT_MAX / sizeof(*insns))
 		return -ENOMEM;
+	if (map[cnt] > BPF_PROG_MAX_LEN)
+		return -E2BIG;
 	insns = kvrealloc(insns, array_size(map[cnt], sizeof(*insns)), BPF_VERIFIER_GFP);
 	if (!insns)
 		return -ENOMEM;
@@ -697,7 +705,9 @@ static int patch_image_relax(struct bpf_patch_image *img, u32 *tgt)
  * its patch, img->new_tgt[] to where jumps to it land, both map a removed insn
  * to the next one that stays. img->new_linfo[] is there when insns are
  * removed, see patch_image_map_linfo(). On -EFAULT, img->bad is the old insn
- * whose jump is wrong. No list has both removed and inserted insns.
+ * whose jump is wrong. On -E2BIG, the image would have more than
+ * BPF_PROG_MAX_LEN insns, and nothing of that size was allocated.
+ * No list has both removed and inserted insns.
  */
 int bpf_patch_list_build(const struct bpf_patch_list *pl, const struct bpf_prog *prog,
 			 struct bpf_patch_image *img)
@@ -725,6 +735,8 @@ int bpf_patch_list_build(const struct bpf_patch_list *pl, const struct bpf_prog
 		}
 	}
 	img->short_cnt = img->new_cnt = cnt + img->grow;
+	if (img->new_cnt > BPF_PROG_MAX_LEN)
+		return -E2BIG;
 
 	if (img->del && prog->aux->nr_linfo) {
 		err = patch_image_map_linfo(img, prog);
kernel/bpf/fixups.c +3 -0
index a7116e2cb7d6..ad0ea7803332 100644
@@ -533,6 +533,9 @@ int bpf_patch_list_commit(struct bpf_verifier_env *env)
 	if (verifier_bug_if(err == -EFAULT, env, "insn %u jumps out of the program",
 			    img.bad))
 		goto out;
+	if (err == -E2BIG)
+		verbose(env, "BPF program is too large after the rewrites: more than %lu insns\n",
+			BPF_PROG_MAX_LEN);
 	if (err)
 		goto out;
 
Signature · 1 line
2.53.1-Meta
author maintainer
#2 lore raw

PATCH 2/73 bpf: Require CAP_PERFMON for unwind_exit and unwind_goto

In reply to Kumar Kartikeya Dwivedi

Currently a program that has unwind_exit or unwind_goto loads without CAP_PERFMON. unwind_exit changes its return address, so the cpu mispredicts the return and runs the code after unwind_goto with the R0 of unwind_exit. For such a loader the verifier checks that path as a speculative state.

Later patches make the verifier generate the code that releases what a frame holds when the frame is unwound. That code tests whether a call has to be made and passes kernel pointers as arguments, and the verifier checks no speculative state in it. Instead of hardening it for a loader without CAP_PERFMON, keep such a loader away from it.

Require CAP_PERFMON for a program that unwinds, as for a program that uses an arena, and remove the speculative path after unwind_goto. The test is bpf_may_unwind(). It needs allow_ptr_leaks, bypass_spec_v1 and bypass_spec_v4 all set, because each comes from its own query of the capability.

A program that has unwind_exit or unwind_goto and loads today without CAP_PERFMON is now rejected with "CAP_PERFMON is required to unwind".

---
 include/linux/bpf_verifier.h                  | 10 +++++++++
 kernel/bpf/verifier.c                         | 21 +++++--------------
 .../selftests/bpf/progs/verifier_unwind.c     | 12 ++++-------
 3 files changed, 19 insertions(+), 24 deletions(-)
include/linux/bpf_verifier.h +10 -0
index 50b3f8ab9720..c48584a960e9 100644
@@ -1571,6 +1571,16 @@ static inline bool bpf_ret_reg_pair(struct bpf_verifier_env *env, int subprog)
 	return subprog_info(env, subprog)->ret_reg_pair;
 }
 
+/*
+ * No speculative state is verified on the way to a landing pad or in one, so a program may unwind
+ * only if it is loaded with CAP_PERFMON and neither mitigation applies to it. The three flags come
+ * from three queries of the capability, which need not give the same answer.
+ */
+static inline bool bpf_may_unwind(const struct bpf_verifier_env *env)
+{
+	return env->allow_ptr_leaks && env->bypass_spec_v1 && env->bypass_spec_v4;
+}
+
 struct bpf_call_summary {
 	u8 arg_slot_cnt;
 	/* the last of them are filled in by the verifier, the prog doesn't pass them */
kernel/bpf/verifier.c +5 -16
index 18c59ae784eb..c725fd09490c 100644
@@ -3396,6 +3396,10 @@ static int check_unwind_insns(struct bpf_verifier_env *env)
 	}
 	if (!seen)
 		return 0;
+	if (!bpf_may_unwind(env)) {
+		verbose(env, "CAP_PERFMON is required to unwind\n");
+		return -EPERM;
+	}
 	if (!bpf_jit_supports_unwind() || bpf_prog_is_offloaded(env->prog->aux)) {
 		verbose(env, "JIT does not support unwinding\n");
 		return -ENOTSUPP;
@@ -16609,13 +16613,7 @@ static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
 static void need_nospec(struct bpf_verifier_env *env, u32 idx)
 {
 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[idx];
-	struct bpf_insn *insn = &env->prog->insnsi[idx];
 
-	/* nothing fits between it and the call */
-	if (bpf_is_unwind_goto(insn)) {
-		need_nospec(env, idx + 1);
-		return need_nospec(env, idx + insn->off + 1);
-	}
 	note_pessimized_insn(env, idx);
 	aux->nospec = true;
 	aux->alu_state = 0;
@@ -19333,15 +19331,6 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 		if (!env->cur_state->unwound)
 			return 0;
 		env->cur_state->unwound = false;
-		/*
-		 * unwind_exit changed its return address, so the return is
-		 * mispredicted and what follows unwind_goto runs speculatively.
-		 */
-		if (!env->bypass_spec_v1) {
-			err = sanitize_speculative_path(env, NULL, *insn_idx + 1, *insn_idx);
-			if (err)
-				return err;
-		}
 		*insn_idx += insn->off;
 		return 0;
 	}
@@ -21507,7 +21496,7 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 	return err;
 }
 
-/* The states that the insn pushed go where they were pushed to. */
+/* Deliver the states that the insn pushed: to their next insn, or out of their frame at a site. */
 static int flow_drain(struct bpf_verifier_env *env)
 {
 	struct bpf_verifier_stack_elem *elem;
tools/testing/selftests/bpf/progs/verifier_unwind.c +4 -8
index 596e5e0301e5..be3992ed8eed 100644
@@ -527,21 +527,17 @@ static unsigned long ctx_or_unwind(void)
 
 /*
  * unwind_exit changes its return address, so the cpu mispredicts the return and
- * runs what follows unwind_goto with r0 of unwind_exit.
+ * runs what follows unwind_goto with r0 of unwind_exit. No speculative state is
+ * verified there: the insns need CAP_PERFMON.
  */
 SEC("socket")
-__description("unwind: what follows unwind_goto runs speculatively")
+__description("unwind: unwind_exit and unwind_goto need CAP_PERFMON")
 __arch_x86_64
 __arch_arm64
 __load_if_JITed()
 __success __retval(50) /* 64 without the ethernet header */
-__success_unpriv __retval_unpriv(50)
+__failure_unpriv __msg_unpriv("CAP_PERFMON is required to unwind")
 __caps_unpriv(CAP_BPF)
-#ifdef SPEC_V1
-__xlated_unpriv("unwind_goto pc+{{.*}}")
-__xlated_unpriv("nospec") /* inserted to prevent `R0 invalid mem access 'scalar'` */
-__xlated_unpriv("r0 = *(u32 *)(r0 +{{.*}})")
-#endif
 __naked int speculative_fall_through(void)
 {
 	asm volatile (
Signature · 1 line
2.53.1-Meta
author maintainer
#3 lore raw

PATCH 3/73 bpf: Reject bpf_percpu_obj_drop() of a type with special fields

In reply to Kumar Kartikeya Dwivedi

A map value or an allocated object can have a __percpu_kptr field to a type with special fields. No such per-cpu object exists, because bpf_percpu_obj_new() refuses the type, so the field is always NULL. But a program can take the pointer out of the field and then has to drop it:

struct val { struct bpf_spin_lock lock; };
struct elem { struct val __percpu_kptr *pc; };

  p = bpf_kptr_xchg(&e->pc, NULL);
  if (p)
          bpf_percpu_obj_drop(p);

For this call check_kfunc_call() records the btf_struct_meta of the type, and bpf_fixup_kfunc_call() expects none. The load fails with -EFAULT and "verifier bug: NULL kptr_struct_meta expected at insn_idx 13".

Reject the call in check_kfunc_call() instead. The program is rejected as before, now with -EINVAL and without the warning of a verifier bug. The type with the field is still accepted, because refusing the field would reject maps that load today.

Fixes 36d8bdf75a93 ("bpf: Add alloc/xchg/direct_access support for local percpu kptr")
---
 kernel/bpf/verifier.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
kernel/bpf/verifier.c +10 -0
index c725fd09490c..89fd40ce1bca 100644
@@ -15952,6 +15952,16 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		}
 	}
 
+	/*
+	 * bpf_percpu_obj_new() refuses a type that has special fields, so no such object exists.
+	 * A program can still take the pointer out of a __percpu_kptr field, where it is NULL.
+	 */
+	if (is_bpf_percpu_obj_drop_kfunc(meta.func_id) &&
+	    btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id)) {
+		verbose(env, "bpf_percpu_obj_drop type must not contain special fields\n");
+		return -EINVAL;
+	}
+
 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
 					 set_rbtree_add_callback_state);
Signature · 1 line
2.53.1-Meta
author maintainer
#4 lore raw

PATCH 4/73 bpf: Drop the edge after bpf_throw() from the control flow graph

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

bpf_throw() never returns, but the control flow graph has an edge from the call to the insn after it. A loop whose only exit is bpf_assert() then looks endless and is rejected with "loop at insn 6 never exits":

  for (i = 0; ; i++) {             3: if r6 < 16 goto 6
          bpf_assert(i < 16);      4: r1 = 0
          sum += arr[i];           5: call bpf_throw
  }                                6: ...
                                   9: if r6 < 16 goto 6
                                  10: goto 4

The edge from 5 to 6 puts the insns 4, 5 and 10 into the loop, so the jump at 9 does not leave it. The main pass never takes that edge. Drop it. The jump at 9 then leaves the loop and gives it a trip count.

The call of bpf_throw() is now an exit of its function in the graph. So exit_idx, where the hidden edge of a tail call or a failed LD_ABS goes, can be a call of bpf_throw(). An unproven call of bpf_throw() ends its path.

A loop whose only exit is bpf_throw(), 'for (;;) if (!x) bpf_throw(3);', is rejected in the same way today. Now the verifier adds a may_goto to it. In a function without an exit insn that may_goto only leaves the loop, as today, and the program continues at the call of bpf_throw().

Fixes 5395aa9bbeb5 ("bpf: Verify programs as a fixpoint over the control flow graph")
---
 include/linux/bpf_verifier.h                     |  4 ++--
 kernel/bpf/liveness.c                            |  6 +++++-
 kernel/bpf/verifier.c                            | 10 ++++++++--
 tools/testing/selftests/bpf/progs/verifier_cfg.c |  4 ++--
 4 files changed, 17 insertions(+), 7 deletions(-)
include/linux/bpf_verifier.h +2 -2
index c48584a960e9..b8617d364f9c 100644
@@ -1161,8 +1161,8 @@ struct bpf_subprog_info {
 	u32 linfo_idx; /* The idx to the main_prog->aux->linfo */
 	u32 postorder_start; /* The idx to the env->cfg.insn_postorder */
 	/*
-	 * Index of one of the BPF_EXIT instructions in this subprogram, or
-	 * U32_MAX when it has none.
+	 * Index of one of the BPF_EXIT instructions in this subprogram, of a
+	 * call of bpf_throw() when it has none, or U32_MAX.
 	 */
 	u32 exit_idx;
 	u32 callx_edge; /* 1 + the first of its env->callx_edges, 0 if none */
kernel/bpf/liveness.c +5 -1
index 23a66b22393d..2c93798e1f15 100644
@@ -384,6 +384,10 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
 		return jt;
 	}
 
+	/* bpf_throw() does not return: the insn after the call is no successor */
+	if (unlikely(insn->code == (BPF_JMP | BPF_CALL) && bpf_is_throw_kfunc(insn)))
+		return succ;
+
 	opcode_info = &opcode_info_tbl[BPF_CLASS(insn->code) | BPF_OP(insn->code)];
 	insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
 	if (opcode_info->can_fallthrough)
@@ -395,7 +399,7 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
 	/*
 	 * tail_call upon success and ld_{abs,ind} upon load failure return
 	 * from the subprogram, which is a hidden edge to its exit. A subprogram
-	 * without an exit insn has no exit to model.
+	 * 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 &&
kernel/bpf/verifier.c +8 -2
index 89fd40ce1bca..f10f3660208f 100644
@@ -3289,8 +3289,12 @@ static int check_subprogs(struct bpf_verifier_env *env)
 
 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
 			goto next;
-		if (BPF_OP(code) == BPF_CALL)
+		if (BPF_OP(code) == BPF_CALL) {
+			/* exit_idx is a call of bpf_throw() if the subprog has no exit insn */
+			if (bpf_is_throw_kfunc(&insn[i]) && subprog[cur_subprog].exit_idx == U32_MAX)
+				subprog[cur_subprog].exit_idx = i;
 			goto next;
+		}
 		if (BPF_OP(code) == BPF_EXIT) {
 			subprog[cur_subprog].exit_idx = i;
 			goto next;
@@ -21642,7 +21646,9 @@ static int skip_unproven_insn(struct bpf_verifier_env *env, const struct bpf_ins
 	if (class == BPF_LD || ((class == BPF_JMP || class == BPF_JMP32) &&
 				!bpf_helper_call(insn) && !bpf_pseudo_kfunc_call(insn)))
 		return PROCESS_BPF_EXIT;
-	if (class == BPF_JMP && call_writes_held(env, insn))
+	/* nothing follows bpf_throw(), see bpf_insn_successors() */
+	if (class == BPF_JMP && (call_writes_held(env, insn) ||
+				 bpf_is_throw_kfunc((struct bpf_insn *)insn)))
 		return PROCESS_BPF_EXIT;
 	/* what it stores can be read */
 	for_each_set_bit(spi, cur_aux(env)->may_write_mask, bpf_stack_nr_slots(frame)) {
tools/testing/selftests/bpf/progs/verifier_cfg.c +2 -2
index e97e89ba3d68..719d35d0dfab 100644
@@ -224,8 +224,8 @@ extern void bpf_throw(__u64 cookie) __ksym;
 
 /*
  * The subprogram leaves through the tail call or the exception and never
- * reaches an exit insn, so the hidden edge of the tail call has no exit to
- * point at. The stack access makes the liveness pass walk the subprogram,
+ * reaches an exit insn: the hidden edge of the tail call points at the call of
+ * bpf_throw(). The stack access makes the liveness pass walk the subprogram,
  * and the loop compiles to a single jump back onto itself.
  */
 __noinline __used
Signature · 1 line
2.53.1-Meta
author maintainer
#5 lore raw

PATCH 5/73 bpf: Let a helper call its callback with an unwind label

In reply to Kumar Kartikeya Dwivedi

Currently a callback of bpf_loop() or of another helper cannot unwind. The helper is a C frame between the callback and the BPF code that called the helper. unwind_exit of the callback would find no unwind_goto at its return address and return like exit, and the helper would continue as if the callback had returned. The callback cannot skip the frame of the helper either, because the helper holds things that only its own code releases, such as the mmap lock in bpf_find_vma().

Add the unwind label of a helper. It is a C label in the helper at which the helper continues when its callback leaves with unwind_exit. The identifiers call it a pad (BPF_HAS_CB_PADS). A helper that a program calls with 'call helper; unwind_goto pad' uses it like this:

        rcu_read_lock();
        bpf_call_cb(cb, a1, a2, a3, a4, a5, r0, unwound);
        rcu_read_unlock();
        return 0;
  unwound:                      <- 1. unwind_exit of cb returns here
        rcu_read_unlock();      <- 2. the helper releases what it holds
        bpf_unwind_leave();     <- 3. makes the helper return to 'pad'
        return r0;

bpf_call_cb() calls the callback from inline assembly and adds an exception table entry at the return address that points to the label. unwind_exit of the callback looks up its return address as before, finds that entry and returns to the label. The callee-saved registers and the stack are as after a return, and r0 is the R0 of the callback.

bpf_unwind_leave() replaces the return address of the helper with what bpf_unwind_target() gives for it, which is the target of the unwind_goto after the call of the helper. So the helper leaves the way a subprog leaves at unwind_exit, with the R0 that the callback unwound with. The slot of the return address is found where the compiler keeps it, so a helper pays nothing on the path on which nothing unwinds. One cost
remains: on x86-64 clang reaches the slot through a frame pointer, so with clang a function with an unwind label gets one.

A function with an unwind label must be:

- noinline. bpf_unwind_leave() rewrites the return address of the function that it is in. So the label has to be in the function that the BPF code called, or in one that such a function called through bpf_call_cb(). A body that two kfuncs share has to be inlined into both.
- notrace and on the kprobe blacklist. An fexit or fmod_ret trampoline, the function graph tracer, an fprobe and a kretprobe put a return address of their own into the slot, and bpf_unwind_target() would find nothing for it.

The exception table entry of bpf_call_cb() has the type EX_TYPE_BPF and is keyed at the return address itself, because objtool wants the key to be an insn. The JITs key their entries for unwind_goto one byte earlier. So bpf_unwind_target(), which the JITs and the helpers now share, searches the tables of the BPF programs first, as before. Then it searches the tables of the kernel and of the modules for the return address itself, and takes only an entry of the type EX_TYPE_BPF there.

Two cases need care:

- fixup_exception() searches the same tables. So the insn at the key must be one that cannot fault and has no fixup of its own. On x86-64 that is the insn after bpf_call_cb() in the helper. On arm64 it is a mov of the assembly itself.
- When bpf_unwind_target() finds nothing, unwind_exit returns like exit. That is right when the kernel called the function: an async callback, or the main program of an extension. It is a bug when BPF code called it, so bpf_unwind_target() now warns once when such a return address is inside a program.

All of this needs asm goto with outputs. Without it, and on every architecture other than x86-64 and arm64, bpf_call_cb() is a plain call and BPF_HAS_CB_PADS is 0, so that the verifier can keep rejecting a callback that unwinds there.

Nothing calls bpf_call_cb() yet. A helper that leaves from its label skips the code that a JIT emits after the native call of the helper, and the JITs have to handle that first. Later patches also rely on the labels when the kernel ends a program inside a callback, for example at a loop whose time is up.

---
 arch/arm64/net/bpf_jit_comp.c |  41 ++++-
 arch/x86/net/bpf_jit_comp.c   |  34 +++-
 include/linux/bpf_unwind.h    | 289 ++++++++++++++++++++++++++++++++++
 include/linux/filter.h        |   1 +
 kernel/bpf/core.c             |  10 ++
 5 files changed, 365 insertions(+), 10 deletions(-)
 create mode 100644 include/linux/bpf_unwind.h
arch/arm64/net/bpf_jit_comp.c +36 -5
index 85008d55233e..0108b66b5619 100644
@@ -1734,16 +1734,47 @@ static int add_unwind_exentry(struct jit_ctx *ctx, int pad)
 	return 0;
 }
 
-static long bpf_unwind_fixup(u64 lr)
+/*
+ * 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().
+ */
+u64 bpf_unwind_target(u64 ret_addr)
 {
 	const struct exception_table_entry *e;
 
-	e = search_bpf_extables(ptrauth_strip_kernel_insn_pac(lr) - 1);
+	e = search_bpf_extables(ret_addr - 1);
+	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.
+	 */
+	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;
 	/*
-	 * The verifier made sure that unwind_goto follows a call in a prog. When
-	 * the kernel called an async callback, it's exit.
+	 * 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.
 	 */
-	return e ? e->fixup : 0;
+	scoped_guard(rcu)
+		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
+	return ret_addr;
+}
+
+/* The offset that the epilogue adds to LR once it is authenticated */
+static long bpf_unwind_fixup(u64 lr)
+{
+	u64 ret_addr = ptrauth_strip_kernel_insn_pac(lr);
+
+	return bpf_unwind_target(ret_addr) - ret_addr;
 }
 
 /*
arch/x86/net/bpf_jit_comp.c +29 -5
index 2b2a81e02cfc..5558dbc80669 100644
@@ -2374,15 +2374,39 @@ static int add_unwind_exentry(struct bpf_prog *prog, u8 *image, u8 *rw_image, in
 	return 0;
 }
 
-static u64 bpf_unwind_target(u64 ret_addr)
+/*
+ * 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().
+ */
+u64 bpf_unwind_target(u64 ret_addr)
 {
-	const struct exception_table_entry *e = search_bpf_extables(ret_addr - 1);
+	const struct exception_table_entry *e;
 
+	e = search_bpf_extables(ret_addr - 1);
+	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.
+	 */
+	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;
 	/*
-	 * The verifier made sure that unwind_goto follows a call in a prog. When
-	 * the kernel called an async callback, it's exit.
+	 * 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.
 	 */
-	return e ? ret_addr + e->fixup : ret_addr;
+	scoped_guard(rcu)
+		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
+	return ret_addr;
 }
 
 /*
include/linux/bpf_unwind.h new file +289 -0

289 lines not on this page · raw message

include/linux/filter.h +1 -0
index 5f038006ecbc..4aad10c3c8e9 100644
@@ -1400,6 +1400,7 @@ bool bpf_jit_supports_callx(void);
 bool bpf_jit_supports_kfunc_ret_reg_pair(void);
 bool bpf_jit_supports_unwind(void);
 bool bpf_jit_supports_hmul(void);
+u64 bpf_unwind_target(u64 ret_addr);
 bool bpf_jit_supports_stack_args(void);
 bool bpf_jit_supports_arena_args(void);
 bool bpf_jit_supports_far_kfunc_call(void);
kernel/bpf/core.c +10 -0
index b1c8c246dc25..2b1d655aa070 100644
@@ -3821,6 +3821,16 @@ bool __weak bpf_jit_supports_hmul(void)
 	return false;
 }
 
+/*
+ * Where unwind_exit returns to: the target of the unwind_goto after the call if the caller has
+ * one, and where exit returns to otherwise. A JIT that supports unwinding overrides this. Without
+ * such a JIT no callback unwinds, so no helper asks.
+ */
+u64 __weak bpf_unwind_target(u64 ret_addr)
+{
+	return ret_addr;
+}
+
 /*
  * How this arch places a by-value kfunc argument, or NULL for one that has
  * not opted in and so only takes an argument of a single eightbyte, which
Signature · 1 line
2.53.1-Meta
author maintainer
#6 lore raw

PATCH 6/73 bpf, x86, arm64: Add landings that redo what follows a helper call

In reply to Kumar Kartikeya Dwivedi

A helper that leaves through bpf_unwind_leave() returns to the target of the unwind_goto after its call. It skips the code that the JIT emits after the native call, which the program needs done before it continues at the target:

- arm64: R0 is x8, so a call is 'bl foo; mov x8, x0'. After a subprog the mov is not missed, because the epilogue of the subprog leaves R0 in x8 as well as in x0. A helper returns R0 in x0 alone.
- x86-64: the JIT emits 'pop r9' with a private stack, 'mov rsi, rdx' after a kfunc that returns a pair of registers, and in a program that has its stack in arena 'sub rsp, 8' after a kfunc with stack arguments and the reload of the arena stack pointer.

On x86-64 the helper would not even find the target. bpf_unwind_leave() looks up the return address of the helper, but except for 'pop r9' the JIT keys the exception table entry of unwind_goto at the end of all the code of the call insn. The helper would return to the code after the call as if the callback had returned, on a path that the verifier never checked.

Add landings. A landing is native code that a JIT emits for an unwind_goto. The exception table entry points to the landing, the landing does again what follows the native call, and then it jumps to the target of the unwind_goto. A landing is not a landing pad: it only repeats code of the JIT and jumps on.

The x86-64 JIT already has a landing for 'pop r9', in line, which the normal path jumps over. Make it general. The JIT keeps the bytes that it emits after the native call, none of which depends on its address, and emits them again in the landing:

call foo <- its last byte is the key of the table entry
pop r9 <- foo returns here
jmp 1f
pop r9 <- the landing, the fixup of the table entry
jmp target
1:

On arm64 an unwind_goto after the call of a helper or a kfunc gets the landing 'mov x8, x0; b target'. build_landings() emits the landings after the epilogue, so the normal path is unchanged.

After a call that no code follows, and on arm64 after the call of a subprog, unwind_goto emits no code, as before. The verifier accepts no unwind_goto after the call of a helper yet.

---
 arch/arm64/net/bpf_jit_comp.c | 98 +++++++++++++++++++++++++++++++----
 arch/x86/net/bpf_jit_comp.c   | 27 +++++++---
 include/linux/bpf_unwind.h    |  4 +-
 3 files changed, 110 insertions(+), 19 deletions(-)
arch/arm64/net/bpf_jit_comp.c +87 -11
index 0108b66b5619..fe41871e3d1c 100644
@@ -84,6 +84,8 @@ struct jit_ctx {
 	int epilogue_offset;
 	int *offset;
 	int exentry_idx;
+	int *landing_ex;	/* the extable entry of each landing, see build_landings() */
+	int landing_idx;
 	int nr_used_callee_reg;
 	u8 used_callee_reg[8]; /* r6~r9, fp, arena_vm_start */
 	__le32 *image;
@@ -1695,19 +1697,24 @@ static int add_exception_handler(const struct bpf_insn *insn,
 	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)
+{
+	const struct bpf_insn *call = insn - 1;
+
+	return call->code == (BPF_JMP | BPF_CALL) && call->src_reg != BPF_PSEUDO_CALL;
+}
+
 /*
  * There is no branch for unwind_goto, only an extable entry
- *   { .insn = ret_addr - 1, .fixup = pad - ret_addr }
- * where ret_addr is the return address of the call in front of it. unwind_exit
- * adds .fixup to its LR.
+ *   { .insn = ret_addr - 1, .fixup = target - ret_addr }
+ * where ret_addr is the return address of the call in front of it, and target
+ * the pad, or the way into it. unwind_exit adds .fixup to its LR.
  * 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.
- * 'bl foo; mov x8, x0' is in front of unwind_goto. The pad doesn't miss the mov:
- * r0 is x8 and the epilogue of the callee copies it to x0 and leaves x8 as it is.
  */
-static int add_unwind_exentry(struct jit_ctx *ctx, int pad)
+static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target)
 {
-	int ret_addr = ctx->idx - 1;
 	struct exception_table_entry *ex;
 	off_t ins_offset;
 
@@ -1727,13 +1734,47 @@ static int add_unwind_exentry(struct jit_ctx *ctx, int pad)
 	/* switch ex to rw buffer for writing */
 	ex = (void *)ctx->image + ((void *)ex - (void *)ctx->ro_image);
 	ex->insn = ins_offset;
-	ex->fixup = (ctx->offset[pad] - ret_addr) * AARCH64_INSN_SIZE;
+	ex->fixup = (target - ret_addr) * AARCH64_INSN_SIZE;
 	ex->type = EX_TYPE_BPF;
 
 	ctx->exentry_idx++;
 	return 0;
 }
 
+/*
+ * 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.
+ */
+static int build_landings(struct jit_ctx *ctx)
+{
+	const struct bpf_prog *prog = ctx->prog;
+	int i, k = 0;
+
+	for (i = 1; i < prog->len; i++) {
+		const struct bpf_insn *insn = &prog->insnsi[i];
+		int ret_addr, jmp_offset;
+
+		if (!bpf_is_unwind_goto(insn) || !unwind_goto_after_helper(insn))
+			continue;
+		ret_addr = ctx->offset[i] - 1;
+		if (ctx->image) {
+			struct exception_table_entry *ex;
+
+			ex = &prog->aux->extable[ctx->landing_ex[k]];
+			ex = (void *)ctx->image + ((void *)ex - (void *)ctx->ro_image);
+			ex->fixup = (ctx->idx - ret_addr) * AARCH64_INSN_SIZE;
+		}
+		k++;
+		emit(A64_MOV(1, bpf2a64[BPF_REG_0], A64_R(0)), ctx);
+		jmp_offset = ctx->offset[i + 1 + insn->off] - ctx->idx;
+		check_imm26(jmp_offset);
+		emit(A64_B(jmp_offset), ctx);
+	}
+	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
@@ -2414,10 +2455,27 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		break;
 	/* unwind_goto. The verifier expanded may_goto. */
 	case BPF_JMP | BPF_JCOND:
-		ret = add_unwind_exentry(ctx, i + 1 + off);
+	{
+		int ret_addr = ctx->idx - 1;
+		int target = ctx->offset[i + 1 + off];
+
+		/*
+		 * '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.
+		 */
+		if (unwind_goto_after_helper(insn)) {
+			ctx->landing_ex[ctx->landing_idx++] = ctx->exentry_idx;
+			target = ret_addr;
+		}
+		ret = add_unwind_exentry(ctx, ret_addr, target);
 		if (ret)
 			return ret;
 		break;
+	}
 	/* function return */
 	case BPF_JMP | BPF_EXIT:
 		if (bpf_is_unwind_exit(insn) && bpf_prog_can_unwind(ctx->prog)) {
@@ -2725,7 +2783,9 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	u8 *ro_image_ptr;
 	int body_idx;
 	int exentry_idx;
+	int nr_landings = 0;
 	int out_cnt;
+	int i;
 
 	if (!prog->jit_requested)
 		return prog;
@@ -2773,6 +2833,16 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	if (ctx.tb == NULL)
 		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]))
+			nr_landings++;
+	if (nr_landings) {
+		ctx.landing_ex = kvzalloc_objs(int, nr_landings);
+		if (ctx.landing_ex == NULL)
+			goto out_off;
+	}
+
 	if (bpf_prog_uses_arena_insns(prog)) {
 		ctx.user_vm_start = bpf_arena_get_user_vm_start(prog->aux->arena);
 		ctx.arena_vm_start = bpf_arena_get_kern_vm_start(prog->aux->arena);
@@ -2803,6 +2873,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 
 	ctx.epilogue_offset = ctx.idx;
 	build_epilogue(&ctx, was_classic, false);
+	if (build_landings(&ctx))
+		goto out_off;
 	build_plt(&ctx);
 
 	extable_align = __alignof__(struct exception_table_entry);
@@ -2836,6 +2908,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 skip_init_ctx:
 	ctx.idx = 0;
 	ctx.exentry_idx = 0;
+	ctx.landing_idx = 0;
 	ctx.write = true;
 
 	build_prologue(&ctx, was_classic);
@@ -2851,6 +2924,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 
 	ctx.epilogue_offset = ctx.idx;
 	ctx.exentry_idx = exentry_idx;
+	ctx.landing_idx = 0;
 	ctx.idx = body_idx;
 	ctx.write = true;
 
@@ -2860,6 +2934,8 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		goto out_free_hdr;
 
 	build_epilogue(&ctx, was_classic, false);
+	if (build_landings(&ctx))
+		goto out_free_hdr;
 	build_plt(&ctx);
 
 	/* Extra pass to validate JITed code. */
@@ -2901,8 +2977,6 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	prog->jited_len = prog_size - cfi_get_offset();
 
 	if (!prog->is_func || extra_pass) {
-		int i;
-
 		/* offset[prog->len] is the size of program */
 		for (i = 0; i <= prog->len; i++)
 			ctx.offset[i] *= AARCH64_INSN_SIZE;
@@ -2921,6 +2995,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		}
 		kvfree(ctx.offset);
 		kvfree(ctx.tb);
+		kvfree(ctx.landing_ex);
 out_priv_stack:
 		kfree(jit_data);
 		prog->aux->jit_data = NULL;
@@ -4024,6 +4099,7 @@ void bpf_jit_free(struct bpf_prog *prog)
 			bpf_jit_binary_pack_finalize(jit_data->ro_header, jit_data->header);
 			kvfree(jit_data->ctx.offset);
 			kvfree(jit_data->ctx.tb);
+			kvfree(jit_data->ctx.landing_ex);
 			kfree(jit_data);
 		}
 		prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset();
arch/x86/net/bpf_jit_comp.c +20 -7
index 5558dbc80669..4a934bab9c79 100644
@@ -2455,6 +2455,9 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 	/* it has to be saved around calls of helpers and kfuncs */
 	bool arena_sp_save = arena_sp && calls_clobber_arena_sp(bpf_prog);
 	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;
 	int err;
 
 	stack_depth = bpf_prog->aux->stack_depth;
@@ -3443,6 +3446,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			ip += x86_call_depth_emit_accounting(&prog, func, ip);
 			if (emit_call(&prog, func, ip))
 				return -EINVAL;
+			ret_addr = prog;
 			if (priv_frame_ptr)
 				pop_r9(&prog);
 			if (arena_sp_args)
@@ -3457,6 +3461,10 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			 */
 			if (fm && fm->ret_size > 8)
 				emit_mov_reg(&prog, true, BPF_REG_2, BPF_REG_3);
+			after_call_len = prog - ret_addr;
+			if (WARN_ON_ONCE(after_call_len > sizeof(after_call)))
+				return -EFAULT;
+			memcpy(after_call, ret_addr, after_call_len);
 			break;
 		}
 
@@ -3474,13 +3482,16 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			}
 			if (emit_indirect_call(&prog, insn->dst_reg, ip))
 				return -EINVAL;
+			ret_addr = prog;
 			if (priv_frame_ptr)
 				pop_r9(&prog);
+			after_call_len = prog - ret_addr;
+			memcpy(after_call, ret_addr, after_call_len);
 			break;
 
 			/* unwind_goto. The verifier expanded may_goto. */
 		case BPF_JMP | BPF_JCOND:
-			if (!priv_frame_ptr) {
+			if (!after_call_len) {
 				err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
 							 addrs[i - 1], addrs[i + insn->off]);
 				if (err)
@@ -3488,8 +3499,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				break;
 			}
 			/*
-			 * 'pop r9' after the call has to be done on the way to
-			 * the pad too:
+			 * What follows the native call, like 'pop r9', has to be
+			 * done on the way to the pad too:
 			 *   call foo
 			 *   pop r9      <- exit returns here
 			 *   jmp 1f
@@ -3498,12 +3509,14 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			 * 1:
 			 */
 			err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
-						 addrs[i - 1] - 2, addrs[i - 1] + 2);
+						 addrs[i - 1] - after_call_len, addrs[i - 1] + 2);
 			if (err)
 				return err;
-			EMIT2(0xEB, 7);
-			pop_r9(&prog);
-			EMIT1_off32(0xE9, addrs[i + insn->off] - (addrs[i - 1] + 9));
+			EMIT2(0xEB, after_call_len + 5);
+			memcpy(prog, after_call, after_call_len);
+			prog += after_call_len;
+			EMIT1_off32(0xE9, addrs[i + insn->off] -
+					  (addrs[i - 1] + 2 + after_call_len + 5));
 			break;
 
 		case BPF_JMP | BPF_TAIL_CALL:
include/linux/bpf_unwind.h +3 -1
index 097e540b1844..2a3bb47e2b10 100644
@@ -209,7 +209,9 @@ do {										\
 
 /*
  * See x86-64 above. The return address is the second word of the frame record. A missing target
- * is a bug: the helper would return as if the callback had returned.
+ * is a bug: the helper would return as if the callback had returned. It shows as a target that
+ * is the return address itself, which no unwind_goto gives here, because after the call of a
+ * helper the JIT emits a landing for it.
  *
  * With pointer authentication the return address is signed with the stack pointer at entry, so
  * the new one is signed the same way. pacia1716 is a hint, a nop without pointer authentication,
Signature · 1 line
2.53.1-Meta
author maintainer
#7 lore raw

PATCH 7/73 bpf: Let a callback unwind out of a helper that has an unwind label

In reply to Kumar Kartikeya Dwivedi

Currently the verifier rejects a callback that reaches unwind_exit with "callback cannot unwind". A helper that calls its callback with bpf_call_cb() can now pass the unwinding on: it leaves from its unwind label to the unwind_goto after its own call, with the R0 of the callback.

Treat the call of a helper or kfunc whose callback can unwind like the call of a subprog that can unwind: unwind_goto may follow the call, and it has to follow when the callback can unwind. Here cb is the callback of bpf_loop():

call bpf_loop <- 1. enters cb 3. visited again
unwind_goto +1 <- 4. taken
exit
r0 += 41 <- R0 is 5 here
exit
cb:
r0 = 5
unwind_exit <- 2. back to the call, marked unwound

The verifier models the call of a helper with a callback as a loop: each time the callback exits, the state goes back to the call insn. A state that leaves the callback with unwind_exit goes back too, marked state->unwound, because the helper has effects of its own on its way out:
bpf_rbtree_add(), for example, takes the node from the program whichever way it leaves. On this second visit the call starts no further iteration, applies the effects of the helper and keeps R0 as the callback left it. The marked state then takes the unwind_goto.

check_cb_unwind() checks the call where the verifier enters a callback that can unwind, in this order:

- No unwind_goto follows the call: "no unwind_goto after the call of bpf_loop()", -EINVAL.
- The kernel has no unwind labels (BPF_HAS_CB_PADS is 0): "callback cannot unwind: the helpers have no pads", -ENOTSUPP. This comes second, so that a missing unwind_goto gets the same message on every kernel.
- This helper has no unwind label: "callback cannot unwind", -EINVAL. helper_has_cb_pad() and kfunc_has_cb_pad() list those that have one. Both lists are empty, so every such program is still rejected.

The code at the target of unwind_goto gets R0 in the state that the callback unwound with, as after the call of a subprog. The helper passes that value on bit for bit, so the range of a callback's return value does not apply to it, and a pointer keeps its type and its reference. What a callback can leave in R0 this way it can already store through callback_ctx.

These cases need care:

- The dynptr of bpf_user_ringbuf_drain() and the key of an array element live in the frame of the helper. The exit of the callback invalidates them and everything derived from them, in R0 too.
- A callback passes on R0 alone, whatever its prototype says. R2 stays the caller's, because the second visit of the call reads an argument there.
- A callback can unwind without an unwind_exit of its own. The check of the stack at the start of a recursive subprog leaves with unwind_exit when unwind_goto follows every call of the subprog that the verifier found before the main pass (bail_unwinds). The call of a helper that takes its callback from an array of function addresses in read-only data is not among them. So check_cb_unwind() asks the new bpf_subprog_unwinds(): can_unwind, or recursive with bail_unwinds.
- No speculative state gets to unwind_exit of a callback. Only a load without CAP_PERFMON has such states, and its program has no unwind_exit.

One hole is known and stays open. The vma that bpf_find_vma() gives its callback is valid only under the mmap lock, and a callback that unwinds with the vma in R0 passes it to code that runs without the lock. A callback can do the same today when it stores the vma through callback_ctx. Either way the program holds a PTR_TO_BTF_ID without a trust flag, and loads through it are fault-safe and can return stale data. One fix has to close both, and it is not part of this series.

Liveness, the backward slice from an unproven insn and constant folding learn that R0 flows through a call with a callback when unwind_goto follows the call.

---
 include/linux/bpf_verifier.h                  |  10 ++
 include/uapi/linux/bpf.h                      |   3 +-
 kernel/bpf/const_fold.c                       |   9 ++
 kernel/bpf/liveness.c                         |   7 +
 kernel/bpf/precision.c                        |  12 +-
 kernel/bpf/verifier.c                         | 147 +++++++++++++++---
 tools/include/uapi/linux/bpf.h                |   3 +-
 .../selftests/bpf/progs/verifier_unwind.c     |   2 +-
 8 files changed, 168 insertions(+), 25 deletions(-)
include/linux/bpf_verifier.h +10 -0
index b8617d364f9c..117c3a3f7cbb 100644
@@ -1234,6 +1234,16 @@ struct bpf_subprog_info {
 	u16 max_out_stack_arg_cnt;
 };
 
+/*
+ * The subprog can leave with unwind_exit, so a helper that calls it needs an unwind label, see
+ * check_cb_unwind(). A recursive subprog counts before it has the insn: its stack check gets one
+ * after the main pass.
+ */
+static inline bool bpf_subprog_unwinds(const struct bpf_subprog_info *sub)
+{
+	return sub->can_unwind || (sub->recursive && sub->bail_unwinds);
+}
+
 static inline u16 bpf_in_stack_arg_cnt(const struct bpf_subprog_info *sub)
 {
 	if (sub->stack_args_from_code)
include/uapi/linux/bpf.h +2 -1
index 28904c6f0787..95b41ae6584d 100644
@@ -63,7 +63,8 @@ enum bpf_mul_variant {
 enum bpf_cond_pseudo_jmp {
 	BPF_MAY_GOTO = 0,
 	/*
-	 * Follows a call of a bpf subprog. Taken when the subprog left with
+	 * 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.
 	 */
 	BPF_UNWIND_GOTO = 1,
kernel/bpf/const_fold.c +9 -0
index 3310a55afa3b..1524166cf6db 100644
@@ -311,6 +311,15 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 		for (r = BPF_REG_0; r < ARRAY_SIZE(aux->const_reg_vals); r++) {
 			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.
+			 */
+			if (r == BPF_REG_0 && i + 1 < insn_cnt &&
+			    bpf_is_sync_callback_calling_insn(&insns[i]) &&
+			    bpf_is_unwind_goto(&insns[i + 1]))
+				continue;
 			switch (c->state) {
 			case CONST_ARG_CONST: {
 				u64 val = c->val;
kernel/bpf/liveness.c +7 -0
index 2c93798e1f15..f6456e5be5fd 100644
@@ -2832,6 +2832,13 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env,
 			 */
 			if (bpf_is_callx(insn))
 				use = dst;
+			/*
+			 * A callback that unwinds goes back to the call of its helper, see
+			 * check_helper_call(). R0 of the callback has to get through the call to
+			 * the target of the unwind_goto, so it is live before the call.
+			 */
+			if (bpf_is_sync_callback_calling_insn(insn) && bpf_is_unwind_goto(insn + 1))
+				use |= r0;
 			break;
 		default:
 			def = 0;
kernel/bpf/precision.c +9 -3
index 33b180b35c88..f2ef763684f4 100644
@@ -767,7 +767,7 @@ static bool compute_insn_deps(struct bpf_verifier_env *env, unsigned long *masks
 	u16 use = aux->use_regs, def = aux->def_regs, args = 0;
 	bool changed = false, stores, reads, loads, call, held_after;
 	struct taken_funcs *taken = &env->precision->taken;
-	u8 class = BPF_CLASS(insn->code), needs;
+	u8 class = BPF_CLASS(insn->code), needs, cb_ret;
 	u16 ptrs = 0;
 	int t, callee;
 
@@ -818,8 +818,14 @@ static bool compute_insn_deps(struct bpf_verifier_env *env, unsigned long *masks
 		reads = is_seed;
 		needs = ret[callee];
 	} else if (callee > 0) {
-		reads |= compute_call_deps(env, masks, ret, callee, needs & ~RET_REGS, &held,
-					   &changed);
+		/*
+		 * The callback returns to the helper, so R0 after the call is the helper's. With an
+		 * unwind_goto after the call it can also be R0 of a callback that unwound, see
+		 * check_cb_unwind().
+		 */
+		cb_ret = bpf_is_unwind_goto(insn + 1) ? BIT(BPF_REG_0) : 0;
+		reads |= compute_call_deps(env, masks, ret, callee, needs & ~(RET_REGS & ~cb_ret),
+					   &held, &changed);
 		needs = ret[callee];
 	} else if (bpf_is_callx(insn) || aux->calls_callback) {
 		changed |= needs & ~taken->needs;
kernel/bpf/verifier.c +128 -19

275 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +2 -1
index 28904c6f0787..95b41ae6584d 100644
@@ -63,7 +63,8 @@ enum bpf_mul_variant {
 enum bpf_cond_pseudo_jmp {
 	BPF_MAY_GOTO = 0,
 	/*
-	 * Follows a call of a bpf subprog. Taken when the subprog left with
+	 * 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.
 	 */
 	BPF_UNWIND_GOTO = 1,
tools/testing/selftests/bpf/progs/verifier_unwind.c +1 -1
index be3992ed8eed..6fd8e56485ed 100644
@@ -929,7 +929,7 @@ __description("unwind: callback unwinds")
 __arch_x86_64
 __arch_arm64
 __load_if_JITed()
-__failure __msg("callback cannot unwind")
+__failure __msg("no unwind_goto after the call of bpf_loop()")
 __naked int callback_unwinds(void)
 {
 	asm volatile (
Signature · 1 line
2.53.1-Meta
author maintainer
#8 lore raw

PATCH 8/73 bpf: Let the inlined bpf_loop pass on a callback that unwinds

In reply to Kumar Kartikeya Dwivedi

The verifier inlines bpf_loop() when the flags are zero and the callback is the same at every visit of the call. The inlined loop is BPF insns, so there is no helper and no unwind label. unwind_exit of the callback would find no unwind_goto after its call and return to the loop like exit, and the loop would continue.

Give the inlined loop insns that pass an unwinding callback on. An unwind_goto follows the call of the callback. Its target is four insns that restore R6-R8, which the loop uses for its own variables, and jump to the target of the unwind_goto after the call of bpf_loop(), with R0 as the callback left it. That is the path that the verifier checked. The new insns are marked with +:

before after

    if r1 <= MAX goto +2         if r1 <= MAX goto +6
    r0 = -E2BIG                  r0 = -E2BIG
    goto end                     goto end

spill r6 - r8 + pad: fill r6 - r8
loop: + gotol <target of the caller>
call cb spill r6 - r8
... loop:
fill r6 - r8 call cb
end: + unwind_goto pad
...
fill r6 - r8
end:

The unwind_goto that followed the call of bpf_loop() follows no call after the inlining and becomes a jump to the next insn. The patch that inlines the loop now has two insns whose target is outside the patch, the call of the callback and the jump to the target of the caller, so struct bpf_insn_patch gets room for a second one (jmp2, jmp2_to).

An inlined loop gets the new insns only when all of this holds:

- The callback can unwind. bpf_subprog_unwinds() is asked, because a recursive callback gets its check of the stack after the inlining.
- An unwind_goto follows the call of bpf_loop(). The verifier requires none when it never saw the loop run its callback.
- The verifier visited the target of that unwind_goto. Otherwise the target is dead code, which is removed after the inlining, and a jump into it would end up at whatever follows.

The verifier still rejects a callback of bpf_loop() that unwinds, so nothing takes the new jump yet.

---
 include/linux/bpf_verifier.h |  2 ++
 kernel/bpf/core.c            | 20 ++++++++++--
 kernel/bpf/fixups.c          | 59 +++++++++++++++++++++++++++++++-----
 3 files changed, 71 insertions(+), 10 deletions(-)
include/linux/bpf_verifier.h +2 -0
index 117c3a3f7cbb..3f6de7caa0ad 100644
@@ -1321,6 +1321,8 @@ struct bpf_insn_patch {
 	u32 jmp;		/* 1 + insn of the patch that goes to insn 'jmp_to', 0 if none */
 	u32 jmp_to;
 	u32 jmp_back;		/* or to that many insns in front of the patch of it */
+	u32 jmp2;		/* 1 + one more insn of the patch, which goes to 'jmp2_to' */
+	u32 jmp2_to;
 	struct bpf_insn orig;	/* the replaced insn when the patch was queued */
 };
 
kernel/bpf/core.c +17 -3
index 2b1d655aa070..87262e4d4c0c 100644
@@ -435,6 +435,8 @@ static int patch_insn_target(const struct bpf_patch_image *img, const struct bpf
 
 	if (idx + 1 == p->jmp) {
 		tgt = p->jmp_to;
+	} else if (idx + 1 == p->jmp2) {
+		tgt = p->jmp2_to;
 	} else if (idx == p->self) {
 		tgt = p->off + rel + 1;
 	} else {
@@ -558,6 +560,7 @@ int __bpf_patch_list_insert(struct bpf_patch_list *pl, const struct bpf_prog *pr
 		p->target += cnt;
 		p->self += cnt;
 		p->jmp += p->jmp ? cnt : 0;
+		p->jmp2 += p->jmp2 ? cnt : 0;
 	}
 	memcpy(insn, insns, cnt * sizeof(*insns));
 	p->len += cnt;
@@ -568,14 +571,25 @@ 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 one such jump.
+ * A patch has two such jumps at most, and the second one has no 'back'.
  */
 void bpf_patch_list_jump(struct bpf_patch_list *pl, const struct bpf_insn *insn, u32 to, u32 back)
 {
 	struct bpf_insn_patch *p = &pl->patches[pl->cnt - 1];
+	u32 jmp = insn - &pl->insns[p->start] + 1;
 
-	WARN_ON_ONCE(p->jmp);
-	p->jmp = insn - &pl->insns[p->start] + 1;
+	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.
+		 */
+		if (WARN_ON_ONCE(p->jmp2 || back))
+			to = U32_MAX;
+		p->jmp2 = jmp;
+		p->jmp2_to = to;
+		return;
+	}
+	p->jmp = jmp;
 	p->jmp_to = to;
 	p->jmp_back = back;
 }
kernel/bpf/fixups.c +52 -7

101 lines not on this page · raw message

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

PATCH 9/73 bpf: Give the helpers that call a callback an unwind label

In reply to Kumar Kartikeya Dwivedi

Currently the verifier rejects a callback of a helper when the callback can unwind, because no helper has an unwind label.

Give the four helpers that call a callback an unwind label, and add them to helper_has_cb_pad(). From here on the verifier accepts a callback of theirs that unwinds when unwind_goto follows the call. Each helper calls its callback with bpf_call_cb(). At its label it releases what it holds while the callback runs, calls bpf_unwind_leave() and returns the R0 of the callback:

- bpf_loop() holds nothing.
- bpf_for_each_map_elem() calls the map operation map_for_each_callback, which calls the callback. The three functions that implement the operation get the label. The one of the array holds nothing. Those of the hash and the rhash maps run the callback in an RCU section and leave it at the label.
- bpf_find_vma() runs the callback under the mmap lock and in an RCU section. At the label it leaves the RCU section, drops the lock and puts the mm of another task, as it does after a return.
- bpf_user_ringbuf_drain() runs the callback with the busy bit set and with a sample that it has peeked. At the label it consumes the sample and counts it, because the wakeup at the end is sent for samples that were consumed. Then it leaves the loop the way the error paths do, which clears the busy bit and sends the wakeup.

bpf_for_each_map_elem() itself needs a label only for a map that the verifier does not know. When the verifier knows the map, it replaces the call of the helper with a call of the operation, and the operation leaves from its label to the unwind_goto after that call. Otherwise the helper calls the operation, which calls the callback: two C frames. So the helper calls the operation the way it would call a callback, with an unwind label of its own, which the operation leaves to. The operation is not a bpf_callback_t, so the helper uses __bpf_call_cb(), which takes the type for the kCFI check of the call.

On a kernel without unwind labels (BPF_HAS_CB_PADS is 0) the helper keeps the plain call through the pointer of the operation. The fallback of __bpf_call_cb() calls through the type of a callback, and the kCFI check would trap on that.

---
 kernel/bpf/arraymap.c                         | 12 +++++--
 kernel/bpf/bpf_iter.c                         | 34 +++++++++++++++++--
 kernel/bpf/hashtab.c                          | 28 ++++++++++-----
 kernel/bpf/ringbuf.c                          | 24 +++++++++++--
 kernel/bpf/task_iter.c                        | 22 ++++++++++--
 kernel/bpf/verifier.c                         | 12 +++++--
 .../selftests/bpf/progs/verifier_unwind.c     |  1 +
 7 files changed, 112 insertions(+), 21 deletions(-)
kernel/bpf/arraymap.c +9 -3
index 508706d0c360..15e9a18b4ec6 100644
@@ -3,6 +3,7 @@
  * Copyright (c) 2016,2017 Facebook
  */
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/btf.h>
 #include <linux/err.h>
 #include <linux/slab.h>
@@ -800,7 +801,7 @@ static const struct bpf_iter_seq_info iter_seq_info = {
 	.seq_priv_size		= sizeof(struct bpf_iter_seq_array_map_info),
 };
 
-static long bpf_for_each_array_elem(struct bpf_map *map, bpf_callback_t callback_fn,
+static noinline notrace long bpf_for_each_array_elem(struct bpf_map *map, bpf_callback_t callback_fn,
 				    void *callback_ctx, u64 flags)
 {
 	u32 i, key, num_elems = 0;
@@ -823,15 +824,20 @@ static long bpf_for_each_array_elem(struct bpf_map *map, bpf_callback_t callback
 			val = array_map_elem_ptr(array, i);
 		num_elems++;
 		key = i;
-		ret = callback_fn((u64)(long)map, (u64)(long)&key,
-				  (u64)(long)val, (u64)(long)callback_ctx, 0);
+		bpf_call_cb(callback_fn, map, &key, val, callback_ctx, 0, ret, unwound);
 		/* return value: 0 - continue, 1 - stop and return */
 		if (ret)
 			break;
 	}
 
 	return num_elems;
+
+unwound:
+	/* The callback left with unwind_exit: nothing to drop here */
+	bpf_unwind_leave();
+	return ret;
 }
+NOKPROBE_SYMBOL(bpf_for_each_array_elem);
 
 static u64 array_map_mem_usage(const struct bpf_map *map)
 {
kernel/bpf/bpf_iter.c +31 -3
index 2bb110e0867d..57e1800a5741 100644
@@ -5,6 +5,7 @@
 #include <linux/anon_inodes.h>
 #include <linux/filter.h>
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/bpf_verifier.h>
 #include <linux/rcupdate_trace.h>
 
@@ -748,11 +749,32 @@ int bpf_iter_run_prog(struct bpf_prog *prog, void *ctx)
 	return ret == 0 ? 0 : -EAGAIN;
 }
 
-BPF_CALL_4(bpf_for_each_map_elem, struct bpf_map *, map, void *, callback_fn,
+/*
+ * A map_for_each_callback function has an unwind label of its own and leaves from it the way a
+ * callback does. So the helper calls it like a callback, with the kCFI check for its own type.
+ * When the verifier knows the map, the program calls the function directly.
+ */
+BPF_CB_PAD_TYPE(__bpf_for_each_op, typeof(*((struct bpf_map_ops *)0)->map_for_each_callback));
+
+BPF_CALL_x(4, noinline notrace, bpf_for_each_map_elem, struct bpf_map *, map, void *, callback_fn,
 	   void *, callback_ctx, u64, flags)
 {
+#if BPF_HAS_CB_PADS
+	u64 ret;
+
+	__bpf_call_cb(__bpf_for_each_op, map->ops->map_for_each_callback, map, callback_fn,
+		      callback_ctx, flags, 0, ret, unwound);
+	return ret;
+
+unwound:
+	bpf_unwind_leave();
+	return ret;
+#else
+	/* The fallback of __bpf_call_cb() calls through bpf_callback_t, and kCFI would trap */
 	return map->ops->map_for_each_callback(map, callback_fn, callback_ctx, flags);
+#endif
 }
+NOKPROBE_SYMBOL(bpf_for_each_map_elem);
 
 const struct bpf_func_proto bpf_for_each_map_elem_proto = {
 	.func		= bpf_for_each_map_elem,
@@ -764,7 +786,7 @@ const struct bpf_func_proto bpf_for_each_map_elem_proto = {
 	.arg4_type	= ARG_ANYTHING,
 };
 
-BPF_CALL_4(bpf_loop, u32, nr_loops, void *, callback_fn, void *, callback_ctx,
+BPF_CALL_x(4, noinline notrace, bpf_loop, u32, nr_loops, void *, callback_fn, void *, callback_ctx,
 	   u64, flags)
 {
 	bpf_callback_t callback = (bpf_callback_t)callback_fn;
@@ -781,14 +803,20 @@ BPF_CALL_4(bpf_loop, u32, nr_loops, void *, callback_fn, void *, callback_ctx,
 		return -E2BIG;
 
 	for (i = 0; i < nr_loops; i++) {
-		ret = callback((u64)i, (u64)(long)callback_ctx, 0, 0, 0);
+		bpf_call_cb(callback, i, callback_ctx, 0, 0, 0, ret, unwound);
 		/* return value: 0 - continue, 1 - stop and return */
 		if (ret)
 			return i + 1;
 	}
 
 	return i;
+
+unwound:
+	/* The callback left with unwind_exit: the loop is over, and so is the helper */
+	bpf_unwind_leave();
+	return ret;
 }
+NOKPROBE_SYMBOL(bpf_loop);
 
 const struct bpf_func_proto bpf_loop_proto = {
 	.func		= bpf_loop,
kernel/bpf/hashtab.c +20 -8
index b8491105430a..690f5ad80cc8 100644
@@ -3,6 +3,7 @@
  * Copyright (c) 2016 Facebook
  */
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/btf.h>
 #include <linux/jhash.h>
 #include <linux/filter.h>
@@ -2517,7 +2518,7 @@ static const struct bpf_iter_seq_info iter_seq_info = {
 	.seq_priv_size		= sizeof(struct bpf_iter_seq_hash_map_info),
 };
 
-static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
+static noinline notrace long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
 				   void *callback_ctx, u64 flags)
 {
 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
@@ -2556,8 +2557,7 @@ static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_
 				val = htab_elem_value(elem, map->key_size);
 			}
 			num_elems++;
-			ret = callback_fn((u64)(long)map, (u64)(long)key,
-					  (u64)(long)val, (u64)(long)callback_ctx, 0);
+			bpf_call_cb(callback_fn, map, key, val, callback_ctx, 0, ret, unwound);
 			/* return value: 0 - continue, 1 - stop and return */
 			if (ret) {
 				rcu_read_unlock();
@@ -2568,7 +2568,14 @@ static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_
 	}
 out:
 	return num_elems;
+
+unwound:
+	/* The callback left with unwind_exit, inside the RCU section of the bucket */
+	rcu_read_unlock();
+	bpf_unwind_leave();
+	return ret;
 }
+NOKPROBE_SYMBOL(bpf_for_each_hash_elem);
 
 static u64 htab_map_mem_usage(const struct bpf_map *map)
 {
@@ -3422,7 +3429,7 @@ static void rhtab_map_seq_show_elem(struct bpf_map *map, void *key, struct seq_f
 	seq_putc(m, '\n');
 }
 
-static long bpf_each_rhash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
+static noinline notrace long bpf_each_rhash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
 				void *callback_ctx, u64 flags)
 {
 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
@@ -3446,10 +3453,8 @@ static long bpf_each_rhash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
 		if (IS_ERR(elem))
 			break;
 		num_elems++;
-		ret = callback_fn((u64)(long)map,
-				  (u64)(long)elem->data,
-				  (u64)(long)rhtab_elem_value(elem, map->key_size),
-				  (u64)(long)callback_ctx, 0);
+		bpf_call_cb(callback_fn, map, elem->data, rhtab_elem_value(elem, map->key_size),
+			    callback_ctx, 0, ret, unwound);
 		if (ret)
 			break;
 
@@ -3458,7 +3463,14 @@ static long bpf_each_rhash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
 	rcu_read_unlock();
 
 	return num_elems;
+
+unwound:
+	/* The callback left with unwind_exit, under RCU */
+	rcu_read_unlock();
+	bpf_unwind_leave();
+	return ret;
 }
+NOKPROBE_SYMBOL(bpf_each_rhash_elem);
 
 static u64 rhtab_map_mem_usage(const struct bpf_map *map)
 {
kernel/bpf/ringbuf.c +22 -2
index 447863ece26a..4aa7c78a6b6e 100644
@@ -1,5 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/btf.h>
 #include <linux/err.h>
 #include <linux/irq_work.h>
@@ -814,13 +815,14 @@ static void __bpf_user_ringbuf_sample_release(struct bpf_ringbuf *rb, size_t siz
 	smp_store_release(&rb->consumer_pos, consumer_pos + rounded_size);
 }
 
-BPF_CALL_4(bpf_user_ringbuf_drain, struct bpf_map *, map,
+BPF_CALL_x(4, noinline notrace, bpf_user_ringbuf_drain, struct bpf_map *, map,
 	   void *, callback_fn, void *, callback_ctx, u64, flags)
 {
 	struct bpf_ringbuf *rb;
 	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;
 	int busy = 0;
 
 	if (unlikely(flags & ~wakeup_flags))
@@ -852,8 +854,23 @@ BPF_CALL_4(bpf_user_ringbuf_drain, struct bpf_map *, map,
 		}
 
 		bpf_dynptr_init(&dynptr, sample, BPF_DYNPTR_TYPE_LOCAL, 0, size);
-		ret = callback((uintptr_t)&dynptr, (uintptr_t)callback_ctx, 0, 0, 0);
+		bpf_call_cb(callback, &dynptr, callback_ctx, 0, 0, 0, ret, 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.
+			 */
+			unwound = true;
+		}
 		__bpf_user_ringbuf_sample_release(rb, size, flags);
+		if (unwound) {
+			samples++;
+			goto schedule_work_return;
+		}
 	}
 	ret = samples - discarded_samples;
 
@@ -867,8 +884,11 @@ BPF_CALL_4(bpf_user_ringbuf_drain, struct bpf_map *, map,
 		irq_work_queue(&rb->work);
 	else if (!(flags & BPF_RB_NO_WAKEUP) && samples > 0)
 		irq_work_queue(&rb->work);
+	if (unwound)
+		bpf_unwind_leave();
 	return ret;
 }
+NOKPROBE_SYMBOL(bpf_user_ringbuf_drain);
 
 const struct bpf_func_proto bpf_user_ringbuf_drain_proto = {
 	.func		= bpf_user_ringbuf_drain,
kernel/bpf/task_iter.c +19 -3
index 2ee7b3b3c10b..3480f6d9f648 100644
@@ -6,6 +6,7 @@
 #include <linux/pid_namespace.h>
 #include <linux/fs.h>
 #include <linux/filter.h>
+#include <linux/bpf_unwind.h>
 #include <linux/bpf_mem_alloc.h>
 #include <linux/btf_ids.h>
 #include <linux/mm_types.h>
@@ -754,7 +755,7 @@ static struct bpf_iter_reg task_vma_reg_info = {
 	.show_fdinfo		= bpf_iter_task_show_fdinfo,
 };
 
-BPF_CALL_5(bpf_find_vma, struct task_struct *, task, u64, start,
+BPF_CALL_x(5, noinline notrace, bpf_find_vma, struct task_struct *, task, u64, start,
 	   bpf_callback_t, callback_fn, void *, callback_ctx, u64, flags)
 {
 	struct mmap_unlock_irq_work *work;
@@ -762,6 +763,7 @@ BPF_CALL_5(bpf_find_vma, struct task_struct *, task, u64, start,
 	bool __maybe_unused mmput_needed = false;
 	struct mm_struct *mm;
 	int ret = -ENOENT;
+	u64 r0;
 
 	if (flags)
 		return -EINVAL;
@@ -815,8 +817,7 @@ BPF_CALL_5(bpf_find_vma, struct task_struct *, task, u64, start,
 		 * verifier checks it as an RCU read-side critical section.
 		 */
 		rcu_read_lock();
-		callback_fn((u64)(long)task, (u64)(long)vma,
-			    (u64)(long)callback_ctx, 0, 0);
+		bpf_call_cb(callback_fn, task, vma, callback_ctx, 0, 0, r0, unwound);
 		rcu_read_unlock();
 		ret = 0;
 	}
@@ -827,7 +828,22 @@ BPF_CALL_5(bpf_find_vma, struct task_struct *, task, u64, start,
 		mmput_async(mm);
 #endif
 	return ret;
+
+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.
+	 */
+	rcu_read_unlock();
+	bpf_mmap_unlock_mm(work, mm);
+#ifdef CONFIG_MMU
+	if (mmput_needed)
+		mmput_async(mm);
+#endif
+	bpf_unwind_leave();
+	return r0;
 }
+NOKPROBE_SYMBOL(bpf_find_vma);
 
 const struct bpf_func_proto bpf_find_vma_proto = {
 	.func		= bpf_find_vma,
kernel/bpf/verifier.c +10 -2
index 4b65f537668c..ca8e6fad617d 100644
@@ -11453,10 +11453,18 @@ static void leave_callback(struct bpf_func_state *caller)
 		leave_loops(caller, caller->loop_stack_cnt - 1);
 }
 
-/* The helper calls its callback with a pad, see bpf_call_cb(). None yet. */
+/* The helper has an unwind label for its callback (a "pad" in identifiers), see bpf_call_cb() */
 static bool helper_has_cb_pad(enum bpf_func_id func_id)
 {
-	return false;
+	switch (func_id) {
+	case BPF_FUNC_loop:
+	case BPF_FUNC_for_each_map_elem:
+	case BPF_FUNC_find_vma:
+	case BPF_FUNC_user_ringbuf_drain:
+		return true;
+	default:
+		return false;
+	}
 }
 
 /* The kfunc calls its callback with a pad. None yet. */
tools/testing/selftests/bpf/progs/verifier_unwind.c +1 -0
index 6fd8e56485ed..668e1d1b94b4 100644
@@ -924,6 +924,7 @@ static unsigned long cb_unwinds(void)
 	);
 }
 
+/* bpf_loop() has a pad for it, so what's missing is the one after the call */
 SEC("tc")
 __description("unwind: callback unwinds")
 __arch_x86_64
Signature · 1 line
2.53.1-Meta
author maintainer
#10 lore raw

PATCH 10/73 bpf: Let the comparator of bpf_rbtree_add unwind

In reply to Kumar Kartikeya Dwivedi

Currently the verifier rejects a comparator of bpf_rbtree_add() that can unwind, because the kfunc has no unwind label. Give bpf_rbtree_add() and bpf_rbtree_add_impl() one, and add them to kfunc_has_cb_pad().

When the comparator unwinds, the node is not in the tree, and the program has let go of it: the kfunc consumes the node whichever way it returns. So at the label the kfunc drops the node and leaves with the R0 of the comparator. The lock of the tree is the caller's and stays held.

In the kfuncs:

- The node is unlinked before the drop, by clearing node->owner. If somebody else holds a reference, the node survives the drop, and with its owner still poisoned every later add would refuse it.
- Both kfuncs get the body inlined, because the label has to be in the function that the BPF code called. A call from bpf_rbtree_add_impl() to bpf_rbtree_add() is a tail jump on x86-64 but a real call on arm64.
- Both return long instead of int, which would cut the R0 of the comparator to 32 bits. The change shows in BTF. libbpf takes integers of any width as compatible, so a program that declares int still loads.

In the verifier, the second visit of the call after the comparator unwound releases the reference to the node, where a return turns it into a non-owning reference. It also invalidates all non-owning references, as an unlock does, because the comparator was given the node as one and may have unwound with it in R0.

The drop at the label runs the destructors of the fields of the node, under the lock of the tree. So when the comparator can unwind (bpf_subprog_unwinds()), the verifier rejects two kinds of programs:

- A tracing program that can run in NMI context, on a type with NMI unsafe fields. That is the rule of bpf_obj_drop().
- Any program, on a type with a list head, an rb root or a referenced kptr. Under a lock a program can call nothing that releases an object, and the drop must not do what the program could not. The destructor of a list head, for example, takes the lock in the node, and all bpf_spin_locks of a cpu keep the irq flags in one per-cpu word:

bpf_spin_lock(&tree_lock) word = flags of the program
bpf_rbtree_add(), the comparator unwinds
bpf_obj_free_fields(node)
bpf_spin_lock(&node->lock) word = 'off'
bpf_spin_unlock(&node->lock)
bpf_spin_unlock(&tree_lock) restores 'off', irqs stay off

---
 kernel/bpf/helpers.c  | 55 ++++++++++++++++++++++++----------
 kernel/bpf/verifier.c | 69 ++++++++++++++++++++++++++++++++++++++-----
 2 files changed, 100 insertions(+), 24 deletions(-)
kernel/bpf/helpers.c +39 -16
index 7b3e10a4a97e..bc6f2a8da05e 100644
@@ -2,6 +2,7 @@
 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  */
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/btf.h>
 #include <linux/bpf-cgroup.h>
 #include <linux/cgroup.h>
@@ -2832,17 +2833,20 @@ __bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
 	return (struct bpf_rb_node *)n;
 }
 
-/* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
- * program
+/*
+ * Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
+ * program. The unwind label has to be in the function that the BPF code
+ * called, so the body is inlined into both kfuncs.
  */
-static int __bpf_rbtree_add(struct bpf_rb_root *root,
-			    struct bpf_rb_node_kern *node,
-			    void *less, struct btf_record *rec, u64 off)
+static __always_inline long __bpf_rbtree_add(struct bpf_rb_root *root,
+					     struct bpf_rb_node_kern *node,
+					     void *less, struct btf_record *rec, u64 off)
 {
 	struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node;
 	struct rb_node *parent = NULL, *n = &node->rb_node;
 	bpf_callback_t cb = (bpf_callback_t)less;
 	bool leftmost = true;
+	u64 r0;
 
 	/* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
 	 * check the latter
@@ -2855,7 +2859,8 @@ static int __bpf_rbtree_add(struct bpf_rb_root *root,
 
 	while (*link) {
 		parent = *link;
-		if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) {
+		bpf_call_cb(cb, node, parent, 0, 0, 0, r0, unwound);
+		if (r0) {
 			link = &parent->rb_left;
 		} else {
 			link = &parent->rb_right;
@@ -2867,6 +2872,17 @@ static int __bpf_rbtree_add(struct bpf_rb_root *root,
 	rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost);
 	WRITE_ONCE(node->owner, root);
 	return 0;
+
+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.
+	 */
+	smp_store_release(&node->owner, NULL);
+	__bpf_obj_drop_impl((void *)n - off, rec, false);
+	bpf_unwind_leave();
+	return r0;
 }
 
 /**
@@ -2880,25 +2896,32 @@ static int __bpf_rbtree_add(struct bpf_rb_root *root,
  * Insert @node into @root using @less. The verifier rewrites @meta and @off;
  * BPF programs do not set them.
  *
- * Return: 0 on success, or %-EINVAL if @node is already linked in a tree.
+ * Return: 0 on success, or %-EINVAL if @node is already linked in a tree. If
+ * @less unwinds or is cancelled, the kfunc drops @node and leaves the same way,
+ * with the R0 of @less.
  */
-__bpf_kfunc int bpf_rbtree_add(struct bpf_rb_root *root,
-			       struct bpf_rb_node *node,
-			       bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
-			       struct btf_struct_meta *meta,
-			       u64 off)
+__bpf_kfunc notrace long bpf_rbtree_add(struct bpf_rb_root *root,
+				struct bpf_rb_node *node,
+				bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
+				struct btf_struct_meta *meta,
+				u64 off)
 {
 	struct bpf_rb_node_kern *n = (void *)node;
 
 	return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
 }
+NOKPROBE_SYMBOL(bpf_rbtree_add);
 
-__bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
-				    bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
-				    void *meta__ign, u64 off)
+__bpf_kfunc notrace long bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
+				     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
+				     void *meta__ign, u64 off)
 {
-	return bpf_rbtree_add(root, node, less, meta__ign, off);
+	struct btf_struct_meta *meta = meta__ign;
+	struct bpf_rb_node_kern *n = (void *)node;
+
+	return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
 }
+NOKPROBE_SYMBOL(bpf_rbtree_add_impl);
 
 __bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root)
 {
kernel/bpf/verifier.c +61 -8

109 lines not on this page · raw message

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

PATCH 11/73 bpf: Let a state leave its frame at may_goto without an exit insn

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

When the time of a program is up, a may_goto of the verifier ends its function where it can, with 'r0 = 0; exit' or 'r0 = 0; unwind_exit'. The verifier emits these insns after the main pass. Currently, in the main pass, an exit insn that the function happens to have (bail_insn) stands for them:

before after

     may_goto --.                    may_goto --> unwind_frame()
     ...        | R0 = 0             ...
     exit     <-'                    exit

The edge on the left is not in the control flow graph, so constant folding has a special case for it. And one exit insn cannot stand for code that first releases what the frame holds, which later patches emit there.

Add unwind_frame(). It does to the state what an exit does, at the may_goto, and passes on what remains as an exit does: to the caller, to the calls that wait for a function that is verified separately, or nowhere if the kernel called the frame. The stack check of a recursive function exits its frame the same way.

Remove bail_insn. Its other users take exit_idx, an exit insn or else a call of bpf_throw(). A function with neither still cannot be exited this way. If a check of the exit fails, for example the range of the return value, the error is recorded at the may_goto. Tests that pin a state at an exit insn, or the number of processed insns, change with that.

---
 include/linux/bpf_verifier.h                  |  7 +-
 kernel/bpf/const_fold.c                       | 11 +--
 kernel/bpf/failing_path.c                     |  5 +-
 kernel/bpf/liveness.c                         |  6 +-
 kernel/bpf/precision.c                        |  4 +-
 kernel/bpf/verifier.c                         | 82 +++++++++++++++----
 .../selftests/bpf/progs/verifier_equations.c  |  2 +-
 .../selftests/bpf/progs/verifier_stack_ptr.c  |  2 +-
 .../selftests/bpf/progs/verifier_trip_count.c | 10 +--
 9 files changed, 88 insertions(+), 41 deletions(-)
include/linux/bpf_verifier.h +3 -4
index 3f6de7caa0ad..2d214bc24db1 100644
@@ -1229,7 +1229,6 @@ struct bpf_subprog_info {
 	/* some call of it is not followed by unwind_goto */
 	bool plain_call: 1;
 	u8 code_stack_args;
-	int bail_insn; /* an exit of it, for the main pass. -1 if there is none */
 	u16 stack_arg_cnt; /* incoming + max outgoing */
 	u16 max_out_stack_arg_cnt;
 };
@@ -2209,10 +2208,10 @@ struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
  * Where the program goes from may_goto and from the checks that the verifier adds:
  * - May_goto before a jump goes where the jump goes, with the registers and the stack
  *   as they are before the jump. bpf_insn_successors() has that edge.
- * - A subprog that is out of budget goes to bail_insn, an exit. No such edge.
+ * - A subprog that is out of budget is left at once, see unwind_frame(). No insn of it follows.
  * - May_goto before the header of a loop goes to where the loops around it are left: from
- *   @idx to what is returned here, -1 if there is none. No such edge either. The registers
- *   and the stack are what they are before @idx.
+ *   @idx to what is returned here, -1 if there is none. No such edge. The registers and the
+ *   stack are what they are before @idx.
  *
  * The main pass looks at the states that go there. What is computed from the graph before
  * the main pass has to take these edges into account where the main pass relies on it:
kernel/bpf/const_fold.c +4 -7
index 1524166cf6db..1a7e521a4b92 100644
@@ -267,14 +267,11 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 
 		for (r = 0; r < MAX_BPF_REG; r++)
 			ci_in[start][r] = unknown;
-		/*
-		 * The subprog gets there from where it is out of budget too, see
-		 * push_unwind_exit(). That is not an edge of the graph.
-		 */
-		for (r = 0; r < MAX_BPF_REG && env->subprog_info[i].bail_insn >= 0; r++)
-			ci_in[env->subprog_info[i].bail_insn][r] = unknown;
 	}
-	/* The same from the head of a loop to where the loop is left, once the loops are known. */
+	/*
+	 * The program gets from the head of a loop to where the loop is left, once the loops are
+	 * known. That is not an edge of the graph.
+	 */
 	for (i = 0; i < insn_cnt; i++) {
 		t = bpf_head_guard_target(env, i);
 		for (r = 0; r < MAX_BPF_REG && t >= 0; r++)
kernel/bpf/failing_path.c +3 -2
index 677ec4236226..26469e41f04a 100644
@@ -70,9 +70,10 @@ static int compute_hops(struct bpf_verifier_env *env)
 				/* see check_loop_guard() and check_recursion_guard() */
 				if (aux->guard_place)
 					changed |= shorter_via(prec, n, aux->guard_to);
+				/* the function is left there, see unwind_frame() */
 				if ((aux->guard_place || (sub[s].cycle && n == sub[s].start)) &&
-				    sub[s].bail_insn >= 0)
-					changed |= shorter_via(prec, n, sub[s].bail_insn);
+				    sub[s].exit_idx != U32_MAX)
+					changed |= shorter(&prec->hops_to_exit[n], 0);
 				if (!bpf_calls_function(env, n))
 					continue;
 				t = bpf_insn_callee(env, n);
kernel/bpf/liveness.c +3 -3
index f6456e5be5fd..4d04d17603ae 100644
@@ -2991,10 +2991,10 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
 		 */
 		insn_aux[i].zext_dst = def32 >= 0 && (mask_hi(out) & BIT(def32));
 	}
-	/* the exit that stands for 'r0 = 0; exit' may be dead code, see push_unwind_exit() */
+	/* unwind_frame() compares states at this exit of the subprog, which may be dead code */
 	for (i = 0; i < env->subprog_cnt; i++)
-		if (env->subprog_info[i].bail_insn >= 0)
-			insn_aux[env->subprog_info[i].bail_insn].live_regs_before |=
+		if (env->subprog_info[i].exit_idx != U32_MAX)
+			insn_aux[env->subprog_info[i].exit_idx].live_regs_before |=
 				BIT(BPF_REG_0) | (bpf_ret_reg_pair(env, i) ? BIT(BPF_REG_2) : 0);
 
 	/*
kernel/bpf/precision.c +2 -2
index f2ef763684f4..225dabbd4e70 100644
@@ -920,9 +920,9 @@ int bpf_compute_deps(struct bpf_verifier_env *env, unsigned long *masks,
 			s = env->subprog_topo_order[k];
 			bits = prec->func[s].words * BITS_PER_LONG;
 			for (i = sub[s].postorder_start; i <= sub[s + 1].postorder_start; i++) {
-				/* it can be dead code, see push_unwind_exit() */
+				/* it can be dead code, see unwind_frame() */
 				idx = i < sub[s + 1].postorder_start ? env->cfg.insn_postorder[i] :
-				      sub[s].bail_insn;
+				      sub[s].exit_idx;
 				if (idx < 0)
 					break;
 				bitmap_zero(in, bits);
kernel/bpf/verifier.c +66 -16

154 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_equations.c +1 -1
index e88d6ff0ca8e..66786aae3664 100644
@@ -1433,7 +1433,7 @@ __naked void name(void)							\
 	:: __imm(bpf_get_prandom_u32) : __clobber_all);			\
 }
 
-STEPS(steps_one_walk, __success __log_level(4) __msg("processed 15 insns"), "")
+STEPS(steps_one_walk, __success __log_level(4) __msg("processed 14 insns"), "")
 /* the last write gives r6 its value again, and one path goes around that write */
 STEPS(steps_wrong_guess,
       __failure __msg("invalid write to stack"),
tools/testing/selftests/bpf/progs/verifier_stack_ptr.c +1 -1
index d030a8c52da5..8ec967ce8258 100644
@@ -603,7 +603,7 @@ __msg("R7=fp(smin=smin32=-64,smax=smax32=-8")
 __msg("R7=fp-16 R8=fp-16 loop_stack=5")
 /* back-edge state goes no further because {-16} is within [-72, -16]. */
 __msg("from 8 to 5: pruned")
-__msg("processed 16 insns")
+__msg("processed 15 insns")
 __naked void stack_ptr_subrange_in_loop(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_trip_count.c +5 -5
index d298db135aad..70a2a549f115 100644
@@ -2098,8 +2098,8 @@ __msg("1: (15) if r0 == 0x3 goto pc+2")
 __msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,{{.*}})")
 __msg("2: (07) r0 += 1                       ; R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,{{.*}})")
 __msg("3: (05) goto pc-3")
-/* or 0: pass 0 takes the edge of may_goto */
-__msg("from 1 to 4: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=3,{{.*}}step=0+3)")
+/* the edge of may_goto that pass 0 takes does not go through the exit */
+__msg("from 1 to 4: R0=3")
 __msg("4: (95) exit")
 __msg("processed 5 insns")
 __naked void pre_cond_je1(void)
@@ -2238,7 +2238,7 @@ __log_level(2)
 __flag(BPF_F_TEST_STATE_FREQ)
 __msg(RANGE("1", "R0", 0, 3))
 __msg("loop at 1 has trip count 4{{$}}")
-__msg("4: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=3,{{.*}}step=0+3)")
+__msg("4: R0=3")
 __naked void pre_cond_je32(void)
 {
 	asm volatile ("					\
@@ -5664,14 +5664,14 @@ __naked void threshold_after_inner_loop(void)
 	:: __imm(bpf_ktime_get_ns), __imm_addr(a1m) : __clobber_all)
 
 SEC("socket")
-__success __log_level(4) __msg("processed 12 insns")
+__success __log_level(4) __msg("processed 11 insns")
 __naked void unknown_sum_body_once(void)
 {
 	SUM_FROM("r0");
 }
 
 SEC("socket")
-__success __log_level(4) __msg("processed 24 insns")
+__success __log_level(4) __msg("processed 23 insns")
 __naked void known_sum_three_trips(void)
 {
 	SUM_FROM("0");
Signature · 1 line
2.53.1-Meta
author maintainer
#12 lore raw

PATCH 12/73 bpf: Choose what a cancelled program returns by its type

In reply to Kumar Kartikeya Dwivedi

When the time of a program is up, a may_goto of the verifier ends the main program with 'r0 = 0; exit'. The kernel has cancelled the program: it ended the program before the program's own code returned, so no code of the program chose the return value. For an LSM hook that returns an errno, 0 means "allowed": a program that denies on every path lets setpriority() succeed when its loop runs too long. In the same way a tc program whose every path drops lets the packet pass.

Add bpf_cancelled_retval(), which gives the value that a cancelled program returns to the kernel: the one that refuses, drops or changes nothing. It is always a value that check_return_code() accepts:

  program type                      0 means              returns
  tc, act, tcx, netkit              TC_ACT_OK: passes    TC_ACT_SHOT
  lwt_in, out, xmit, seg6local      BPF_OK: passes       BPF_DROP
  flow dissector                    BPF_OK: the keys     BPF_DROP
                                    are taken as is
  syscall                           all was done         -ECANCELED
  LSM hook that returns an errno    allowed              -EPERM
  hooks with the range [1, 1]       not valid            1
  xdp                               XDP_ABORTED: drops   XDP_ABORTED
  netfilter                         NF_DROP: drops       NF_DROP
  sk_skb, sk_msg, sk_reuseport,     SK_DROP: drops       SK_DROP

sk_lookup
socket filter, cgroup skb, sock, drops or denies 0
sock_addr, device, sysctl,
sockopt
every other type 0

The hooks with the range [1, 1] are cgroup/recvmsg4, getsockname4 and their like, and lsm_cgroup on a void hook. The main program returns the value, and so does the exception callback. An extension returns the value of the program type that it extends. A subprog and an async callback keep 'r0 = 0'.

What changes for programs that load today:

- A program on an LSM hook fails one operation when its time is up, a tc or lwt program drops one packet, and a syscall program returns -ECANCELED.
- At a hook with the range [1, 1], in the exception callback and in the main program of an extension, may_goto left the loop until now. Now it ends the program.
- An extension whose main program has unwind_exit no longer loads. It could unwind into the program that it extends, which was verified without it.

Three values can be wrong in a way that is not known at load time: a cls_bpf classifier that is not in direct-action mode takes 2 for a class, a stream parser of sk_skb takes 0 for a message that is not complete, and a socket filter that selects a socket of a reuseport group takes 0 for the first socket. A struct_ops program returns 0, which its caller may take for success. A later patch lets a struct_ops choose the value.

---
 include/linux/bpf_verifier.h                  |  4 +-
 include/linux/filter.h                        |  5 +-
 kernel/bpf/fixups.c                           |  2 +-
 kernel/bpf/verifier.c                         | 95 +++++++++++++------
 .../selftests/bpf/prog_tests/unwind_attach.c  |  6 +-
 .../selftests/bpf/progs/verifier_barrier.c    |  2 +-
 .../selftests/bpf/progs/verifier_budget.c     |  7 +-
 tools/testing/selftests/bpf/verifier/calls.c  |  1 +
 8 files changed, 82 insertions(+), 40 deletions(-)
include/linux/bpf_verifier.h +2 -2
index 2d214bc24db1..bc5c9b13fc64 100644
@@ -610,8 +610,6 @@ struct bpf_verifier_state {
 	);
 	u32 curframe;
 	bool in_sleepable;
-	/* a global function or an extension, and what it calls: exit of frame 0 is not the end */
-	bool callers_unknown;
 	/* The callee left with unwind_exit. Next insn is unwind_goto. */
 	bool unwound;
 	/*
@@ -619,6 +617,7 @@ struct bpf_verifier_state {
 	 * and their packet pointers are not in the state, see bpf_flow_return().
 	 */
 	bool changed_pkt_data;
+	u8 unused;	/* the join_key has no holes */
 	);
 	/* Not zero in a function that is verified on its own, see bpf_flow_call() */
 	u32 instance_id;
@@ -2226,6 +2225,7 @@ static inline int bpf_head_guard_target(const struct bpf_verifier_env *env, int
 	return aux->guard_at_header ? aux->guard_to : -1;
 }
 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
+int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog);
 
 /* The first field that ends behind 'off'. The fields are sorted and do not overlap. */
 static inline u32 btf_record_first_field(const struct btf_record *rec, s64 off)
include/linux/filter.h +2 -3
index 4aad10c3c8e9..5e30a4e70660 100644
@@ -306,8 +306,7 @@ static inline bool bpf_is_unwind_exit(const struct bpf_insn *insn)
 }
 
 /*
- * The caller of the main prog doesn't tell unwind_exit from exit. An extension
- * is different: its caller is the caller of the subprog that it replaced.
+ * The caller of the main prog doesn't tell unwind_exit from exit.
  * An exception callback returns from the frame of the main prog. After freplace
  * or a tail call it returns to a prog that wasn't verified with the callback.
  */
@@ -315,7 +314,7 @@ static inline bool bpf_prog_can_unwind(const struct bpf_prog *prog)
 {
 	if (prog->aux->exception_cb)
 		return false;
-	return bpf_is_subprog(prog) || prog->type == BPF_PROG_TYPE_EXT;
+	return bpf_is_subprog(prog);
 }
 
 static inline bool insn_is_zext(const struct bpf_insn *insn)
kernel/bpf/fixups.c +1 -1
index f3faa7c300ec..54dcfb3faa42 100644
@@ -577,7 +577,7 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
 
 	if (!env->bypass_spec_v1)
 		buf[n++] = BPF_ST_NOSPEC();
-	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, 0);
+	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env, s));
 	if (bpf_ret_reg_pair(env, s))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
 	buf[n] = BPF_EXIT_INSN();
kernel/bpf/verifier.c +67 -28

166 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/unwind_attach.c +2 -4
index 37e03b3e0ee8..674c5272cf75 100644
@@ -103,12 +103,10 @@ void test_unwind_attach(void)
 	/* unwind_exit would return to the trampoline */
 	attach(tgt_fd, "global_unwinds", "fexit_unwind",
 	       "Only fentry can attach to global_unwinds", 0);
-	/* An extension leaves either way, like what it replaced */
 	attach(tgt_fd, "global_unwinds", "freplace_returns", NULL, 9);
-	attach(tgt_fd, "global_unwinds", "freplace_unwinds", NULL, 13);
-	/* There is no unwind_goto after the call */
+	/* Nothing unwinds from an extension into the prog that it extends */
 	attach(plain_fd, "global_never_unwinds", "freplace_unwinds",
-	       "Extension program can unwind, while original does not", 0);
+	       "unwind_exit in the main program of an extension", 0);
 	ASSERT_EQ(run(tgt_fd), 15, "retval");
 
 	/*
tools/testing/selftests/bpf/progs/verifier_barrier.c +1 -1
index bc12cc17f0f2..2cf55613406d 100644
@@ -136,7 +136,7 @@ __success SPECULATES __success_unpriv
 __xlated_unpriv("r0 = 1")
 __xlated_unpriv("exit")
 __xlated_unpriv("nospec")
-__xlated_unpriv("r0 = 0")
+__xlated_unpriv("r0 = 2")
 __xlated_unpriv("exit")
 #endif
 __naked void unwind_exit(void)
tools/testing/selftests/bpf/progs/verifier_budget.c +6 -1
index 1bef19db503b..4f38518de92a 100644
@@ -121,10 +121,15 @@ __naked void loop_in_main_rcu(void)
 
 /* 0 is not what this prog may return */
 SEC("cgroup/recvmsg4")
-__description("budget: a loop in the main prog that cannot return 0 is left")
+__description("budget: a loop in the main prog that can only return 1 ends it with 1")
 __arch_x86_64
 __arch_arm64
 __success
+__xlated("...")
+__xlated("r0 = 1")
+__xlated("exit")
+__xlated("r0 = 1")
+__xlated("exit")
 __naked void loop_in_main_retval(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/verifier/calls.c +1 -0
index 6f621c69ff00..d1bf9922a306 100644
@@ -599,6 +599,7 @@
 	},
 	.prog_type = BPF_PROG_TYPE_SCHED_CLS,
 	.result = ACCEPT,
+	.retval = 2, /* TC_ACT_SHOT */
 },
 {
 	"calls: using r0 returned by callee",
Signature · 1 line
2.53.1-Meta
author maintainer
#13 lore raw

PATCH 13/73 bpf: Emit landing pads that leave RCU sections

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently the kernel can cancel a program only in a frame that holds nothing. In a frame that holds something, the may_goto that the verifier adds to a loop leaves the loop when the time is up, and the code after the loop has to be safe with whatever the loop left behind:

  bpf_rcu_read_lock();
  do { p = bpf_map_lookup_elem(&map, &key); } while (!p);
  v = *p;         <- R0 invalid mem access 'map_value_or_null'
  bpf_rcu_read_unlock();

Generate the code that is missing. A site is an insn at which the kernel can cancel the program. A landing pad is code that the verifier generates for a site: it releases what the frame holds there and leaves the frame. '+' marks what the verifier adds:

bpf_rcu_read_lock(); call bpf_rcu_read_lock
do { 1: ...

          p = bpf_map_lookup_elem(...);         call bpf_map_lookup_elem
  } while (!p);                          +      may_goto pad
  v = *p;                                       if r0 == 0 goto 1b
  bpf_rcu_read_unlock();                        r6 = *(u64 *)(r0 + 0)
  return v;                                     call bpf_rcu_read_unlock

r0 = r6
exit
+ pad: call bpf_rcu_read_unlock
+ r0 = 0
+ exit

When the time is up, may_goto jumps to the pad, and the program ends without getting to '*p'.

For now the sites are a may_goto that the verifier adds and the stack check at the start of a recursive function. A pad leaves the RCU sections and the sections with preemption disabled that its frame entered, and nothing of the callers. Then it leaves the frame the way the function ends at such a site today. The main program returns the value of its program type. A function that has an unwind_goto after every call of it leaves with 'r0 = 0; unwind_exit', and any other function with 'r0 = 0; exit'.

The code at the target of an unwind_goto of the program is called the program's landing pad here. A C++ or Rust compiler emits it, and it is verified like any other code. "Landing pad" alone is always one that the verifier generates.

The verifier does not verify a landing pad, and no insn stands for it in the main pass. When a state leaves its frame at a site, unwind_frame() records what the frame holds and does to the state what the pad will do. After the main pass, bpf_insert_sites() appends the pads of a function after its last insn. A pad is a fixed list of calls, so it has to be right for every state at its site.

Three points need care:

- A state that was pruned or joined on the way never gets to the site. The pad is right for it too, because a pad depends only on what the verifier compares before it lets one state stand for another. Two states are pruned or joined only if they are in the same numbers of sections.
- When two states at a site have entered different numbers of sections, the verifier cannot generate one pad for both. That is an error of the pass, like an insn that the pass could not prove, and a later pass that keeps more states apart may not have it. If it stays, the program is rejected. A later patch lifts this.

landing pad of may_goto at 7: conflict: the number of sections differs

- No speculative state is verified on the way to a pad, and a pad has no nospec barrier. So only a program that is loaded with CAP_PERFMON gets landing pads.

What changes for programs that load today:

- Where may_goto left a loop in an RCU or preempt section and the program continued, the program now ends. In a frame that holds anything else, may_goto still leaves the loop.
- Without CAP_PERFMON the kernel no longer cancels a program at a may_goto of the verifier, not even in the main program. may_goto leaves the loop, and the program no longer loads if the code after the loop needs the result of the jump that leaves the loop.

---
 include/linux/bpf_verifier.h                  |  64 +++-
 kernel/bpf/Makefile                           |   2 +-
 kernel/bpf/fixups.c                           | 149 ++++++--
 kernel/bpf/pads.c                             | 319 ++++++++++++++++++
 kernel/bpf/precision.c                        |   4 +-
 kernel/bpf/verifier.c                         | 186 +++++++---
 .../selftests/bpf/progs/verifier_barrier.c    |  44 ---
 .../selftests/bpf/progs/verifier_budget.c     |  59 ++--
 .../selftests/bpf/progs/verifier_loop_latch.c |  14 -
 .../selftests/bpf/progs/verifier_passes.c     |  22 +-
 10 files changed, 673 insertions(+), 190 deletions(-)
 create mode 100644 kernel/bpf/pads.c
include/linux/bpf_verifier.h +63 -1
index bc5c9b13fc64..e9db40421411 100644
@@ -444,6 +444,48 @@ static inline u64 bpf_xreg(u32 frameno, u32 xregno)
  *                                        |  widened |----+
  *                                        +----------+
  */
+/* Landing pads that the verifier generates, see the head comment of kernel/bpf/pads.c */
+
+/* The kinds of site. An insn has at most one site of a kind. */
+enum bpf_site_kind {
+	BPF_SITE_GUARD,		/* a may_goto that the verifier adds before the insn */
+	BPF_SITE_RECURSION,	/* the stack check at the first insn of a recursive subprog */
+};
+
+/* The classes of resources that a landing pad releases */
+enum bpf_pad_class {
+	/* Sections. A state only counts them. */
+	BPF_PAD_RCU,		/* bpf_rcu_read_lock() */
+	BPF_PAD_PREEMPT,	/* bpf_preempt_disable() */
+	BPF_PAD_NR_SECTIONS,
+};
+
+/* Why the verifier cannot generate one landing pad for all states that reach a site */
+enum bpf_pad_conflict {
+	BPF_NO_CONFLICT,
+	BPF_CONFLICT_SECTIONS_DIFFER,
+	BPF_CONFLICT_TOO_MUCH,
+	BPF_CONFLICT_NO_RELEASE,
+};
+
+/* The limits of a landing pad. The 3 of BPF_PAD_MAX_INSNS are the insns that leave the frame. */
+#define BPF_PAD_MAX_SECTIONS	8
+#define BPF_PAD_MAX_INSNS	(BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 3)
+/*
+ * The plan of a site: what a frame holds when it leaves there, and so what the landing pad
+ * releases. bpf_pad_visit() records each state whose frame leaves at the site. One landing pad
+ * has to be right for all of them, and 'conflict' says why the verifier cannot generate it.
+ */
+struct bpf_pad_plan {
+	struct bpf_pad_plan *next;	/* of the same insn */
+	u8 kind;			/* enum bpf_site_kind */
+	u8 conflict;			/* enum bpf_pad_conflict */
+	bool visited;
+	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
+	/* the pad starts that many insns after the last insn of the subprog, once it is emitted */
+	u32 pad;
+};
+
 struct loop_stack_entry {
 	struct bpf_loop *loop;
 	struct bpf_header_state *header_state;	/* see failing_path_trip() */
@@ -1073,6 +1115,8 @@ struct bpf_insn_aux_data {
 	struct bpf_loop *loop;
 	/* the call of a callback, or the first insn of a recursive function */
 	struct bpf_loop *callback_loop, *recursion_loop;
+	/* the plans of the sites at this insn that the pass has reached */
+	struct bpf_pad_plan *pad_plans;
 };
 
 /*
@@ -1893,11 +1937,29 @@ int bpf_flow_edge_unproven(struct bpf_verifier_env *env, struct bpf_verifier_sta
 #define BPF_EXIT_NEEDS_CALLER	1	/* verify the call in the frames of the caller */
 int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		    const struct bpf_verifier_state *exit, int call_idx);
-int bpf_insert_loop_guards(struct bpf_verifier_env *env);
+int bpf_insert_sites(struct bpf_verifier_env *env);
 bool bpf_insn_is_iter_next(struct bpf_verifier_env *env, struct bpf_insn *insn);
 bool bpf_insn_leaves_loop(struct bpf_verifier_env *env, int h, int n);
 int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
 
+/* pads.c */
+struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_site_kind kind);
+struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx,
+				      enum bpf_site_kind kind);
+void 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_pad_plan **plans, bool save);
+void bpf_pads_free_moved(struct bpf_pad_plan **plans, u32 cnt);
+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);
+int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan, int subprog,
+		  struct bpf_insn *buf);
+void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan);
+int bpf_pads_settle(struct bpf_verifier_env *env);
+bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
+void bpf_pads_log(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);
 void bpf_charge_state(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
kernel/bpf/Makefile +1 -1
index 03f0539490c9..199c8635a71f 100644
@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_
 obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
 obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o check_btf.o flow.o join.o
+obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o check_btf.o flow.o join.o pads.o
 obj-$(CONFIG_BPF_SYSCALL) += equation.o
 obj-$(CONFIG_BPF_SYSCALL) += equation_join.o
 obj-$(CONFIG_BPF_SYSCALL) += precision.o
kernel/bpf/fixups.c +120 -29

207 lines not on this page · raw message

kernel/bpf/pads.c new file +319 -0

319 lines not on this page · raw message

kernel/bpf/precision.c +2 -2
index 225dabbd4e70..042ae3ddef92 100644
@@ -668,7 +668,7 @@ static void note_unproven_after_pass(struct bpf_verifier_env *env, u32 idx)
 	suspect_loops_of_insn(env, idx);
 }
 
-/* check_after_pass() found an error. Which insns caused it? */
+/* check_after_pass() or bpf_pads_settle() found an error. Which insns caused it? */
 void bpf_find_unproven_after_pass(struct bpf_verifier_env *env)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
@@ -678,7 +678,7 @@ void bpf_find_unproven_after_pass(struct bpf_verifier_env *env)
 	for (i = 0; i < env->subprog_cnt; i++)
 		note_unproven_after_pass(env, env->subprog_info[i].deepest_insn);
 	for (i = 0; i < env->prog->len; i++, insn++, aux++) {
-		if (aux->pessimized) {
+		if (aux->pessimized || bpf_pads_conflict(aux)) {
 			note_unproven_after_pass(env, i);
 		} else if (aux->seen && (bpf_calls_function(env, i) || is_stack_arg_st(insn) ||
 					 is_stack_arg_stx(insn))) {
kernel/bpf/verifier.c +134 -52

349 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_barrier.c +0 -44

62 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_budget.c +21 -38

110 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_loop_latch.c +0 -14
index e1281d00b431..967ba9c2a295 100644
@@ -534,20 +534,6 @@ NO_COUNT("more: a back edge that doesn't test the flag")
 LOOP(more_back_edge, "w8 = 0;",
      MORE(UP_TO(2047), RND "if w0 == 3 goto 5f;") "goto 9f; 5: if w8 == 2048 goto 1b;")
 
-/* A nested loop can get may_goto. It goes where a jump of that loop goes, whatever the flag is. */
-NO_COUNT("more: the way out leads through a nested loop")
-LOOP(more_nested, "w8 = 0; call %[bpf_rcu_read_lock];",
-     "w8 += 1; w9 = 0; if w8 > 2047 goto 2f; w9 = 1;"
-     "2: if w9 == 5 goto 4f; if w9 != 0 goto 3f; if w9 == 0 goto 8f; 3: goto 2b;"
-     "4: if w8 <= w7 goto 1b; 8: call %[bpf_rcu_read_unlock];")
-
-/* May_goto at the head of the first loop goes to 7 with w9 = 1. The program gets there with 0. */
-NO_COUNT("more: a flag that is a constant without may_goto")
-LOOP(more_stale, "call %[bpf_rcu_read_lock];" RND "w4 = w0; w8 = 0; w9 = 0;"
-     "5: if w4 == 0 goto 6f; w9 = 0; if w4 == 1 goto 7f; w9 = 1; goto 5b; 6: w9 = 1; goto 5b; 7:",
-     "w5 = w9; w8 += 1; if w8 > 2047 goto 2f; w5 = 1;"
-     "2: if w8 > w7 goto 8f; if w5 != 0 goto 1b; 8: call %[bpf_rcu_read_unlock];")
-
 NO_COUNT("a flag, another way to the jump that counts")
 LOOP(flag_two_ways, "w8 = -2048;",
      "w8 += 1; w2 = 0; if r7 != 0 goto 3f; w2 = 1; 3: if w8 == 0 goto 2f; w2 = 0; 2: if w2 != 1 goto 1b;")
tools/testing/selftests/bpf/progs/verifier_passes.c +13 -9
index 8d42c250d24e..8938135698b4 100644
@@ -1829,9 +1829,11 @@ __naked void spilled_iv_is_no_guess(void)
 }
 
 /*
- * With @bound 7 no execution disables preemption. The joined state does, and then may_goto of
- * the loop at 3 cannot return 0. It goes to the load, with r0 = NULL.
- * With @bound 8 an execution with r6 == 8 disables preemption, so the error is real.
+ * With @bound 7 no execution disables preemption. The joined state does, and then the landing
+ * pad of may_goto of the loop at 3 has two numbers of sections to leave: a conflict. A pass
+ * that keeps r6 apart has none.
+ * With @bound 8 an execution with r6 == 8 disables preemption, once for each trip of the loop
+ * at 2, so the conflict is real.
  */
 #define GUARD_OF_THE_JOIN(bound)					\
 	asm volatile (							\
@@ -1867,7 +1869,7 @@ __naked void spilled_iv_is_no_guess(void)
 	:: OPS, __imm(bpf_preempt_disable) : __clobber_all)
 
 SEC("tc")
-__description("failing_path: a joined state selects the target of may_goto")
+__description("failing_path: a joined state is in a section at may_goto")
 __success
 __naked void guess_takes_target_of_join(void)
 {
@@ -1875,17 +1877,19 @@ __naked void guess_takes_target_of_join(void)
 }
 
 SEC("tc")
-__description("failing_path: a real state selects the target of may_goto")
-__failure __msg("R0 invalid mem access 'map_value_or_null'") __msg("this path has a guess")
+__description("failing_path: a real state is in a section at may_goto")
+__failure
+__msg("landing pad of may_goto at {{[0-9]+}}: conflict: the number of sections differs")
+__not_msg("this path has a guess")
 __naked void guess_takes_real_target(void)
 {
 	GUARD_OF_THE_JOIN(8);
 }
 
 SEC("tc")
-__description("failing_path: level 2 marks a path with a guess")
-__failure __log_level(2) __msg("path-sensitive run after pass 0")
-__msg("this path has a guess") __msg("pass 1")
+__description("failing_path: level 2 has the path-sensitive run and the next pass")
+__failure __log_level(2) __msg("path-sensitive run after pass 0") __msg("pass 1")
+__msg("landing pad of may_goto at {{[0-9]+}}: conflict: the number of sections differs")
 __naked void guess_in_level_2(void)
 {
 	GUARD_OF_THE_JOIN(8);
Signature · 1 line
2.53.1-Meta
author maintainer
#14 lore raw

PATCH 14/73 bpf: Release locks and irq flags in landing pads

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a landing pad can only leave sections. In a frame that holds a lock or saved irq flags, a may_goto of the verifier still leaves the loop:

  bpf_spin_lock(&v->lock);
  do { i = v->idx; } while (i >= 4);
  r = v->t[i];                    <- rejected: i can be anything
  bpf_spin_unlock(&v->lock);

Let the pad release what bpf_spin_lock(), bpf_res_spin_lock(), bpf_res_spin_lock_irqsave() and bpf_local_irq_save() acquired:

pad: r1 = r6

       call bpf_spin_unlock
       r0 = 0; exit

The release takes the address of the lock or of the irq flags. The pad loads it from a location: a register or a stack slot of the program that holds the address at the site, plus a constant.

  lock       R6-R9 or a stack slot with a pointer    r1 = r6
             into the map value or the object        r1 += 8
             a global variable                       r1 = lock ll
  irq flags  the stack of the frame                  r1 = r10

r1 += -16
the stack of a caller: R6-R9 or a r1 = r7
stack slot with a pointer to them

A location has to be live at the site, because later passes reuse dead registers and remove dead stores. The slot of a bpf_fastcall spill is not a location either: its store can be removed too.

All states at a site have to hold the same locks and irq flags, acquired in the same order and each with a location in common. A pad releases the youngest first. Otherwise the verifier cannot generate the pad, and the program is rejected. The log says, for example, "conflict: no place has the handle on all paths". A later patch lifts the case where no location holds the address on all paths.

What changes for programs that load today: where may_goto left a loop under a lock or with irq flags saved and the program continued, the program now ends, or is rejected as above. In a frame that holds a reference, may_goto still leaves the loop.

---
 include/linux/bpf_verifier.h |  51 +++-
 kernel/bpf/fixups.c          |  55 +++-
 kernel/bpf/pads.c            | 470 ++++++++++++++++++++++++++++++++++-
 kernel/bpf/verifier.c        |  54 +++-
 4 files changed, 598 insertions(+), 32 deletions(-)
include/linux/bpf_verifier.h +48 -3
index e9db40421411..d40bd855c539 100644
@@ -382,6 +382,8 @@ struct bpf_reference_state {
 	 */
 	int insn_idx;
 	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;
 	union {
 		/* For REF_TYPE_PTR */
 		struct {
@@ -458,6 +460,11 @@ enum bpf_pad_class {
 	BPF_PAD_RCU,		/* bpf_rcu_read_lock() */
 	BPF_PAD_PREEMPT,	/* bpf_preempt_disable() */
 	BPF_PAD_NR_SECTIONS,
+	/* Each of the others is an entry of refs[], and its release takes a pointer */
+	BPF_PAD_IRQ = BPF_PAD_NR_SECTIONS, /* bpf_local_irq_save() */
+	BPF_PAD_RES_LOCK,	/* bpf_res_spin_lock() */
+	BPF_PAD_RES_LOCK_IRQ,	/* bpf_res_spin_lock_irqsave(): two of refs[], one release */
+	BPF_PAD_SPIN_LOCK,	/* bpf_spin_lock() */
 };
 
 /* Why the verifier cannot generate one landing pad for all states that reach a site */
@@ -466,11 +473,47 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_SECTIONS_DIFFER,
 	BPF_CONFLICT_TOO_MUCH,
 	BPF_CONFLICT_NO_RELEASE,
+	BPF_CONFLICT_NOT_ALWAYS_HELD,
+	BPF_CONFLICT_NO_PLACE,
+	BPF_CONFLICT_ORDER_DIFFERS,
 };
 
-/* The limits of a landing pad. The 3 of BPF_PAD_MAX_INSNS are the insns that leave the frame. */
+/*
+ * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument and the
+ * call. The 3 are the insns that leave the frame.
+ */
 #define BPF_PAD_MAX_SECTIONS	8
-#define BPF_PAD_MAX_INSNS	(BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 3)
+#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 + 1) + \
+				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 3)
+#define BPF_PAD_MAX_CANDS	6
+
+/* The kinds of location */
+enum bpf_place_loc {
+	BPF_PLACE_REG,		/* a register. R10: the pointer is an address in the stack */
+	BPF_PLACE_SPILL,	/* 8 bytes of the stack of the frame */
+	BPF_PLACE_MAP_VALUE,	/* the address of the only value of a map */
+};
+
+/* A location: where a landing pad finds the pointer that a release takes */
+struct bpf_pad_place {
+	u8 loc;			/* enum bpf_place_loc */
+	s16 at;			/* number of the register | offset from R10 | index in used_maps */
+	s32 delta;		/* the location has the pointer plus 'delta' */
+};
+
+/* 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 */
+	int ref;		/* its index in refs[] of the state that is being recorded, or -1 */
+	struct bpf_insn release; /* the call that releases it */
+	u8 class;		/* enum bpf_pad_class */
+	/* 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];
+};
+
 /*
  * The plan of a site: what a frame holds when it leaves there, and so what the landing pad
  * releases. bpf_pad_visit() records each state whose frame leaves at the site. One landing pad
@@ -482,6 +525,8 @@ struct bpf_pad_plan {
 	u8 conflict;			/* enum bpf_pad_conflict */
 	bool visited;
 	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
+	u8 nr_ents;
+	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
 	/* the pad starts that many insns after the last insn of the subprog, once it is emitted */
 	u32 pad;
 };
@@ -1954,7 +1999,7 @@ 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);
 int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan, int subprog,
-		  struct bpf_insn *buf);
+		  struct bpf_insn *buf, struct bpf_insn_aux_data *aux);
 void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan);
 int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
kernel/bpf/fixups.c +42 -13

112 lines not on this page · raw message

kernel/bpf/pads.c +461 -9

553 lines not on this page · raw message

kernel/bpf/verifier.c +47 -7

105 lines not on this page · raw message

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

PATCH 15/73 bpf: Add unwind_goto after calls of subprogs

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a subprog can leave with unwind_exit only if the program has an unwind_goto after every call of it. A program in plain C has none, so the kernel cannot cancel it inside a subprog. A may_goto that the verifier adds to a loop of a subprog leaves the loop, and the stack check of a recursive subprog returns 0 to a caller that continues:

  static long wait(void)
  {
          do { p = bpf_map_lookup_elem(&map, &key); } while (!p);
          return *p;      <- R0 invalid mem access 'map_value_or_null'
  }

Add the unwind_goto that is missing, and a landing pad for the caller. The pad of the callee leaves with unwind_exit, and the unwind_goto after the call takes the cancellation to the pad of the caller. '+' marks what the verifier adds:

wait: main:
1: ... call bpf_rcu_read_lock

  +      may_goto pad ------.            call wait
         if r0 == 0 goto 1b | .-> +      unwind_goto pad -----------.
         ...                | |          ...                        |
         exit               | |          exit                       |

+ pad: r0 = 0 <-----------' | + pad: call bpf_rcu_read_unlock <-'
+ unwind_exit ---------' + r0 = 0; exit

A call is a third kind of site. In the main pass, a state that comes back from a call or a callx with unwind_exit and finds no unwind_goto after the call is treated like a state at a may_goto. The verifier records what the caller holds and releases it in the state, and the state leaves the frame of the caller in turn. The pad of a call runs after the call, so its locations are what is live at the next insn: R6-R9 and the stack. A call that has an unwind_goto of the program keeps it, and the state goes to the program's landing pad.

Every static subprog that the program calls can now leave with unwind_exit, where the JIT supports unwinding and the program is loaded with CAP_PERFMON. The main pass takes more edges of may_goto than the program has in the end, because a loop that turns out to have a trip count gets no may_goto. So bpf_insert_sites() first finds the subprogs in which the program can still be cancelled. Only they get unwind_exit, and only their calls get an unwind_goto and a landing pad.

A caller cannot continue after a call whose callee was cancelled. If the kernel cannot cancel the caller at the call, the program is rejected with "landing pad of call at 5: conflict: the frame cannot unwind". That is the case when:

- the frame holds a reference. No landing pad releases one yet;
- the frame belongs to a callback of a helper, or to a function that such a callback calls and that has no unwind_exit of its own. The verifier adds no unwind_goto after the call of a helper yet, so there a may_goto still leaves the loop;
- the frame belongs to a global subprog that has no unwind_exit of its own. A later patch lifts this;
- the function has neither an exit insn nor a call of bpf_throw().

What changes for programs that load today:

- When a loop has run too long in a static subprog, or a recursion is too deep, the program ends with the value of its program type. Until now the subprog left its loop or returned 0, and the caller continued with a result that nobody computed.
- Only fentry can attach to a subprog that can unwind. That now holds for each subprog in which the program can be cancelled, and for its callers.
- A subprog with unwind_exit of its own that is called without unwind_goto was an error. Now the verifier adds the unwind_goto, and the unwinding goes through the pad of the caller like a cancellation.
- A recursive function that leaves a section of its caller and enters one of its own is rejected: the pad of the call cannot tell which section is held.

Cost on x86-64: unwind_exit is 17 bytes longer than exit. unwind_goto is 12 bytes of exception table and no code, or 9 bytes of code as well where code follows the native call, as with a private stack.

One test changes in a way that the list above does not explain. recursion of verifier_barrier.c, a recursive function that is in an RCU section on some paths only, loaded and is now rejected with "loop at insn 12 acquires more than it releases". A later patch removes that test.

---
 include/linux/bpf_verifier.h                  |  33 +-
 kernel/bpf/fixups.c                           | 117 +++-
 kernel/bpf/pads.c                             |  65 ++-
 kernel/bpf/verifier.c                         | 167 ++++--
 .../bpf/progs/verifier_arena_stack.c          |   4 +-
 .../selftests/bpf/progs/verifier_barrier.c    |  15 +-
 .../selftests/bpf/progs/verifier_budget.c     | 550 +-----------------
 .../selftests/bpf/progs/verifier_passes.c     |  14 +-
 .../selftests/bpf/progs/verifier_unwind.c     |  10 +-
 9 files changed, 383 insertions(+), 592 deletions(-)
include/linux/bpf_verifier.h +28 -5
index d40bd855c539..893125e651d8 100644
@@ -452,6 +452,8 @@ static inline u64 bpf_xreg(u32 frameno, u32 xregno)
 enum bpf_site_kind {
 	BPF_SITE_GUARD,		/* a may_goto that the verifier adds before the insn */
 	BPF_SITE_RECURSION,	/* the stack check at the first insn of a recursive subprog */
+	/* a call without unwind_goto whose callee left with unwind_exit */
+	BPF_SITE_CALL,
 };
 
 /* The classes of resources that a landing pad releases */
@@ -476,6 +478,7 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_NOT_ALWAYS_HELD,
 	BPF_CONFLICT_NO_PLACE,
 	BPF_CONFLICT_ORDER_DIFFERS,
+	BPF_CONFLICT_CANNOT_UNWIND,
 };
 
 /*
@@ -514,6 +517,9 @@ struct bpf_pad_ent {
 	struct bpf_pad_place cand[BPF_PAD_MAX_ARGS][BPF_PAD_MAX_CANDS];
 };
 
+#define bpf_pad_for_each_callee(plan, s)						\
+	for (u32 __n = 0; __n < (plan)->nr_callees && ((s) = (plan)->callee[__n], true); __n++)
+
 /*
  * The plan of a site: what a frame holds when it leaves there, and so what the landing pad
  * releases. bpf_pad_visit() records each state whose frame leaves at the site. One landing pad
@@ -527,6 +533,9 @@ struct bpf_pad_plan {
 	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
 	u8 nr_ents;
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
+	/* the subprogs that came back to the call with unwind_exit, in ascending order */
+	u32 *callee;
+	u32 nr_callees;
 	/* the pad starts that many insns after the last insn of the subprog, once it is emitted */
 	u32 pad;
 };
@@ -665,6 +674,17 @@ struct bpf_equations {
 	u32 clean_sym_cnt;	/* after the last bpf_equations_clean() */
 };
 
+/* 'unwound' of struct bpf_verifier_state: how the callee left when it did not return */
+enum {
+	/*
+	 * With unwind_exit. The next insn is an unwind_goto, or the verifier adds one before it,
+	 * see check_unwound_arrival().
+	 */
+	BPF_UNWOUND = 1,
+	/* The same out of a callback. The next insn is the call of its helper once more. */
+	BPF_UNWOUND_CB,
+};
+
 struct bpf_verifier_state {
 	struct bpf_equations equations;
 	/* call stack tracking */
@@ -697,8 +717,7 @@ struct bpf_verifier_state {
 	);
 	u32 curframe;
 	bool in_sleepable;
-	/* The callee left with unwind_exit. Next insn is unwind_goto. */
-	bool unwound;
+	u8 unwound;	/* BPF_UNWOUND or BPF_UNWOUND_CB: the callee did not return */
 	/*
 	 * A function that is verified on its own changed packet data. Its callers
 	 * and their packet pointers are not in the state, see bpf_flow_return().
@@ -1312,10 +1331,13 @@ struct bpf_subprog_info {
 	bool loads_pkt_end: 1;
 	/* a call of it was verified on its own: its insns are not in insns_total of the caller */
 	bool on_its_own: 1;
-	/* it can leave with unwind_exit: it has one, or unwind_goto follows every call of it */
+	/*
+	 * It can leave with unwind_exit: the verifier adds the unwind_goto that its calls lack. Not
+	 * if a helper calls it, see subprog_cannot_unwind().
+	 */
 	bool bail_unwinds: 1;
-	/* some call of it is not followed by unwind_goto */
-	bool plain_call: 1;
+	/* it has an unwind_exit, or a state left it with unwind_exit in this pass */
+	bool did_unwind: 1;
 	u8 code_stack_args;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
 	u16 max_out_stack_arg_cnt;
@@ -1991,6 +2013,7 @@ int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
 struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_site_kind kind);
 struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx,
 				      enum bpf_site_kind kind);
+int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee);
 void 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_pad_plan **plans, bool save);
kernel/bpf/fixups.c +104 -13

169 lines not on this page · raw message

kernel/bpf/pads.c +63 -2

119 lines not on this page · raw message

kernel/bpf/verifier.c +123 -44

321 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_arena_stack.c +3 -1
index b90127d1f36b..6d188a19206f 100644
@@ -230,6 +230,7 @@ __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;"
@@ -244,7 +245,8 @@ __naked void recursion(void)
 	: __imm_addr(first_r12),
 	  __imm_addr(last_r12),
 	  __imm_insn(adj, ADJ(32)),
-	  __imm_insn(mov, MOV(BPF_REG_1))
+	  __imm_insn(mov, MOV(BPF_REG_1)),
+	  __imm_insn(unwind_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0))
 	: __clobber_all);
 }
 
tools/testing/selftests/bpf/progs/verifier_barrier.c +13 -2
index aaef593976ec..b012235a76a4 100644
@@ -181,7 +181,8 @@ static __naked __noinline __used int recurse(void)
 
 SEC("tc")
 __description("barrier: a speculative state holds more in a recursion")
-__success SPECULATES
+__failure __msg("loop at insn 12 acquires more than it releases")
+SPECULATES
 __failure_unpriv __msg_unpriv("recursive recurse() is allowed only to CAP_PERFMON")
 __naked void recursion(void)
 {
@@ -210,9 +211,19 @@ static __naked __noinline __used int recurse_in_frames(void)
 	"exit;" ::: __clobber_all);
 }
 
+/*
+ * This prog loads on a kernel where the check of a recursion returns 0 to the caller, which goes on
+ * and leaves the section. Here the check unwinds, and no landing pad serves the call in the prog.
+ * The function leaves the section of its caller and enters one of its own. When its first check
+ * fails the prog is in the section that it entered. When a deeper one does the pad of the function
+ * has left the only section there is. A pad is a fixed number of calls, and no store of the prog
+ * can count what its callee leaves: a hidden slot follows the insns of its own frame.
+ * Without CAP_PERFMON a recursion is refused.
+ */
 SEC("tc")
 __description("barrier: at the call of a recursion in the frames of the callers")
-__success SPECULATES
+__failure __msg("landing pad of call at 2: conflict: the number of sections differs")
+SPECULATES
 __failure_unpriv __msg_unpriv("recursive recurse_in_frames() is allowed only to CAP_PERFMON")
 __naked void recursion_in_frames(void)
 {
tools/testing/selftests/bpf/progs/verifier_budget.c +31 -519

638 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_passes.c +10 -4
index 8938135698b4..cc95688120e5 100644
@@ -1097,7 +1097,7 @@ static __noinline struct pair *throw_if_null(struct pair *p, long depth)
 SEC("tc")
 __description("calls: the function tests a reference of the caller for NULL")
 __arch_x86_64
-__failure __msg("invalid mem access 'scalar'") __not_msg("verifier bug")
+__failure __msg("conflict: the frame cannot unwind") __not_msg("verifier bug")
 int callee_tests_null(struct __sk_buff *skb)
 {
 	struct pair *n = bpf_obj_new(typeof(*n)), *copy;
@@ -1536,10 +1536,16 @@ __naked void ctx_moves(void)
 	EXIT_AT_9);
 }
 
-/* The verifier can't tell that the loop ends. It adds may_goto, which leaves with r7 = 0. */
+/*
+ * The verifier can't tell that the loop ends. It adds may_goto, which unwinds the function: no
+ * path continues with r7 = 0. Where a subprog cannot unwind may_goto leaves the loop.
+ */
 SEC("tc")
-__description("failing_path: the path continues where may_goto leaves an infinite loop")
-__failure __msg("R7 invalid mem access 'scalar'")
+__description("failing_path: no path continues where may_goto ends an infinite loop")
+__arch_x86_64
+__arch_arm64
+__load_if_JITed()
+__success
 __naked void exit_of_infinite_loop(void)
 {
 	ASM(VALUE_IN_R9
tools/testing/selftests/bpf/progs/verifier_unwind.c +8 -2
index 668e1d1b94b4..6be56387a825 100644
@@ -668,12 +668,18 @@ __naked int shared_pad(void)
 	);
 }
 
+/* The verifier adds it, and a landing pad that ends the prog with TC_ACT_SHOT */
 SEC("tc")
 __description("unwind: no unwind_goto after a call of a global subprog")
 __arch_x86_64
 __arch_arm64
 __load_if_JITed()
-__failure __msg("no unwind_goto after the call of global_returns()")
+__success __retval(7)
+__xlated("0: call pc+4")
+__xlated("1: unwind_goto pc+1")
+__xlated("2: exit")
+__xlated("3: r0 = 2")
+__xlated("4: exit")
 __naked int global_no_unwind_goto(void)
 {
 	asm volatile (
@@ -688,7 +694,7 @@ __description("unwind: no unwind_goto after a call of a static subprog")
 __arch_x86_64
 __arch_arm64
 __load_if_JITed()
-__failure __msg("unwind_exit, but no unwind_goto after the call at insn 1")
+__success __retval(2)
 __naked int static_no_unwind_goto(void)
 {
 	asm volatile (
Signature · 1 line
2.53.1-Meta
author maintainer
#16 lore raw

PATCH 16/73 bpf: Let the kernel cancel a program in a global subprog

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a global subprog can leave with unwind_exit only if the program gave it one. In any other global subprog the kernel cannot cancel the program. A may_goto that the verifier adds to one of its loops leaves the loop, and the program is rejected when the global subprog calls a subprog that can be cancelled. This loads as a static subprog and is rejected as a global one:

  __weak long wait(void)
  {
          do { p = bpf_map_lookup_elem(&map, &key); } while (!p);
          return *p;
  }

The difference is the order of verification. The callers of a global subprog are verified without it, and before it. To add an unwind_goto and a landing pad at a call, the verifier has to know that the subprog can leave with unwind_exit before it verifies the caller.

Let a global subprog leave with unwind_exit like a static one, and tell its callers by starting the pass again:

the pass callers: wait() returns
wait(): cancelled at may_goto -> wait() is marked,
and so is each subprog that calls a marked one without unwind_goto
starts again callers: wait() returns
wait() comes back with unwind_exit -> unwind_goto, landing pad

The second outcome of the call is what callers have today for a global subprog that has unwind_exit in the program.

Two points need care:

- The mark (did_unwind) goes to the next pass only if the program can still be cancelled in the subprog when the pass ends. The first pass takes the edge of may_goto in every loop without a bound, also in a loop that turns out to have a trip count and gets no may_goto.
- A chain of global subprogs costs one restart, not one per subprog, because all callers are marked at once.

What changes for programs that load today: when a loop has run too long in a global subprog that the program calls, the program ends, as it does in a static subprog. Until now the subprog left its loop.

---
 include/linux/bpf_verifier.h |  7 ++-
 kernel/bpf/fixups.c          |  7 +--
 kernel/bpf/pads.c            |  1 +
 kernel/bpf/verifier.c        | 84 ++++++++++++++++++++++++++++++++----
 4 files changed, 87 insertions(+), 12 deletions(-)
include/linux/bpf_verifier.h +6 -1
index 893125e651d8..b2cd2f42b951 100644
@@ -1336,7 +1336,10 @@ struct bpf_subprog_info {
 	 * if a helper calls it, see subprog_cannot_unwind().
 	 */
 	bool bail_unwinds: 1;
-	/* it has an unwind_exit, or a state left it with unwind_exit in this pass */
+	/*
+	 * It has an unwind_exit, or a state left it with unwind_exit in this pass, or is expected
+	 * to, see mark_unwind_above(). For a global subprog the bit goes to the next pass.
+	 */
 	bool did_unwind: 1;
 	u8 code_stack_args;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
@@ -1530,6 +1533,7 @@ 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() */
+	bool pads_late;			/* a global subprog unwinds: see settle_late_unwinds() */
 	bool calls_joined;		/* see flow_may_add_instance() */
 	bool extra_values;		/* a state can have constants that no run has */
 	bool new_linear_xreg;		/* see bpf_same_insns_unproven() */
@@ -2005,6 +2009,7 @@ int bpf_flow_edge_unproven(struct bpf_verifier_env *env, struct bpf_verifier_sta
 int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		    const struct bpf_verifier_state *exit, int call_idx);
 int bpf_insert_sites(struct bpf_verifier_env *env);
+void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env);
 bool bpf_insn_is_iter_next(struct bpf_verifier_env *env, struct bpf_insn *insn);
 bool bpf_insn_leaves_loop(struct bpf_verifier_env *env, int h, int n);
 int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
kernel/bpf/fixups.c +4 -3
index 0614a48b90e5..9e4e4a239ed9 100644
@@ -644,9 +644,10 @@ static bool site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_p
 /*
  * 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 unwind_exit: those that are
- * left at a site. A call is a site if it calls one of them.
+ * left at a site. A call is a site if it calls one of them. The main pass asks the same when a
+ * global subprog unwinds, see settle_late_unwinds().
  */
-static void mark_subprogs_that_unwind(struct bpf_verifier_env *env)
+void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env)
 {
 	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	const struct bpf_pad_plan *plan;
@@ -793,7 +794,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 		err = -ENOMEM;
 		goto out;
 	}
-	mark_subprogs_that_unwind(env);
+	bpf_mark_subprogs_that_unwind(env);
 	for (s = 0; s < env->subprog_cnt && !err; s++) {
 		sub = &env->subprog_info[s];
 		cnt = collect_pads(env, s, new, pad_aux, &pads);
kernel/bpf/pads.c +1 -0
index 1e97448f989f..bd6d1b2cd642 100644
@@ -205,6 +205,7 @@ void bpf_pads_new_round(struct bpf_verifier_env *env)
 {
 	int i;
 
+	env->pads_late = false;
 	for (i = 0; i < env->prog->len; i++)
 		bpf_pad_plans_free(&env->insn_aux_data[i]);
 }
kernel/bpf/verifier.c +76 -8

140 lines not on this page · raw message

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

PATCH 17/73 bpf: Release references in landing pads

In reply to Kumar Kartikeya Dwivedi

Currently no landing pad releases a reference: a pointer that a helper or a kfunc returned and that the program has to release. In a frame that holds one, a may_goto of the verifier still leaves the loop.

Teach landing pads to release a reference. For a frame that keeps a task from bpf_task_from_pid() in R6:

pad: r1 = r6

       call bpf_task_release
       r0 = 0; exit

No frame that holds a reference gets such a pad yet. A later patch turns that on, once pads also release iterators and dynptrs and test a pointer for NULL.

The pad calls:

- bpf_sk_release() for a socket from bpf_sk_lookup_tcp(), bpf_sk_lookup_udp(), bpf_skc_lookup_tcp() or a map lookup, also after a helper has cast it;
- bpf_ringbuf_discard() for a record from bpf_ringbuf_reserve();
- bpf_obj_drop() or bpf_percpu_obj_drop() for an object of the program;
- for a kernel object from a kfunc or bpf_kptr_xchg(), or a __ref argument of struct_ops, the kfunc that the new btf_find_release_kfunc() finds for its type.

btf_find_release_kfunc() uses a rule that the verifier already has: a program may release a reference to struct T with any kfunc that is KF_RELEASE and takes a struct T *, whichever kfunc acquired it. It returns the first kfunc that the program may call, that has the prototype void (*)(struct T *), and that has no flag beside KF_RELEASE, KF_SLEEPABLE and KF_SPINLOCK_SAFE. No subsystem has to register anything. Of the 16 types that have such a kfunc today, only struct cpumask has two, and both are empty functions.

A pad also serves states that were pruned or joined on the way. So the choice depends only on what the verifier compares between states: the type of the pointer, and whether the reference came with a __ref argument. It does not compare the insn that acquired the reference. That insn is used only for what the type does not say: which helper made a socket or a record, and where the BTF of a module is in fd_array.

The pointer has a location, as the address of a lock has. A copy, a pointer to a node in the object and a cast socket are locations too. So are R0-R5, but only for the first argument of the first call of the pad, which clobbers them. That now holds for a lock and for the irq flags of a caller as well. A pad releases pointers last, after locks, irq flags and sections, because few functions may be called under a lock and a release may sleep.

Three cases need care:

- The locks of the callers are still held when the pad releases pointers. Under a bpf_spin_lock or a resilient lock the pad calls only what the program could call there, a kfunc that is KF_SPINLOCK_SAFE, which no release is today. It does free an object of the program there, unless the object has a list head, an rb root or a referenced kptr. Without them the free only gives the memory back.
- The pad may free an object under the lock of a caller, who may have a non-owning reference to it. So non-owning references are invalidated when a frame that releases something is cancelled. A function that is verified separately records that at its exit (invalidated_non_owning), and a caller that holds something has the function verified again in its own frames, as for changed_pkt_data.
- A cancelled frame also releases a reference that a subprog acquired and returned to it.

The verifier cannot generate a pad when:

- the pointer may be NULL, only some of the states hold it, or no location holds it in all states. Later patches lift these;
- a location has pointers of two types, as after a bpf_kptr_xchg() that returns two types;
- nothing releases the pointer, as for what bpf_xdp_ct_alloc() returns, or a kfunc of a module releases it and the insn that acquired the pointer does not say where the BTF of the module is;
- the object has NMI unsafe fields and the program may run in NMI context, or it is a per-cpu object of a type with special fields, which bpf_percpu_obj_drop() does not free;
- a caller holds a lock under which the pad may not release the pointer.

---
 include/linux/bpf_verifier.h |  18 +-
 include/linux/btf.h          |   6 +
 kernel/bpf/btf.c             |  43 ++++
 kernel/bpf/fixups.c          |   2 +-
 kernel/bpf/pads.c            | 381 +++++++++++++++++++++++++++++++++--
 kernel/bpf/verifier.c        |  39 ++--
 6 files changed, 457 insertions(+), 32 deletions(-)
include/linux/bpf_verifier.h +15 -3
index b2cd2f42b951..f658a8aeeae0 100644
@@ -377,8 +377,9 @@ struct bpf_reference_state {
 	 * instruction creates the reference multiple times (eg, via CALL).
 	 */
 	int id;
-	/* Instruction where the allocation of this reference occurred. This
-	 * is used purely to inform the user of a reference leak.
+	/*
+	 * Instruction where the allocation of this reference occurred. It is reported with a
+	 * reference leak, and it tells a landing pad which function releases the reference.
 	 */
 	int insn_idx;
 	u32 diag_id;	/* finds the acquire in the report of a leak, it is not renumbered */
@@ -467,6 +468,7 @@ enum bpf_pad_class {
 	BPF_PAD_RES_LOCK,	/* bpf_res_spin_lock() */
 	BPF_PAD_RES_LOCK_IRQ,	/* bpf_res_spin_lock_irqsave(): two of refs[], one release */
 	BPF_PAD_SPIN_LOCK,	/* bpf_spin_lock() */
+	BPF_PAD_REF,		/* a pointer that a helper or a kfunc returned, REF_TYPE_PTR */
 };
 
 /* Why the verifier cannot generate one landing pad for all states that reach a site */
@@ -479,6 +481,7 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_NO_PLACE,
 	BPF_CONFLICT_ORDER_DIFFERS,
 	BPF_CONFLICT_CANNOT_UNWIND,
+	BPF_CONFLICT_CALLER_SAVED,
 };
 
 /*
@@ -497,6 +500,7 @@ enum bpf_place_loc {
 	BPF_PLACE_REG,		/* a register. R10: the pointer is an address in the stack */
 	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 */
 };
 
 /* A location: where a landing pad finds the pointer that a release takes */
@@ -511,6 +515,7 @@ struct bpf_pad_ent {
 	u32 origin;		/* the lowest 'origin' of the references that it stands for */
 	int ref;		/* its index in refs[] of the state that is being recorded, or -1 */
 	struct bpf_insn release; /* the call that releases it */
+	u32 obj_type;		/* the BTF id of the type, if it is an object of the program */
 	u8 class;		/* enum bpf_pad_class */
 	/* per argument of the call: the locations that all states share. The pad uses the first. */
 	u8 nr_cands[BPF_PAD_MAX_ARGS];
@@ -723,7 +728,11 @@ struct bpf_verifier_state {
 	 * and their packet pointers are not in the state, see bpf_flow_return().
 	 */
 	bool changed_pkt_data;
-	u8 unused;	/* the join_key has no holes */
+	/*
+	 * The same for non-owning references: the function invalidated them while a lock stayed
+	 * held, which may be a lock of its caller.
+	 */
+	bool invalidated_non_owning;
 	);
 	/* Not zero in a function that is verified on its own, see bpf_flow_call() */
 	u32 instance_id;
@@ -2031,6 +2040,7 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan);
 int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
+bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan);
 void bpf_pads_log(struct bpf_verifier_env *env);
 
 int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *dst_state,
@@ -2361,6 +2371,8 @@ static inline int bpf_head_guard_target(const struct bpf_verifier_env *env, int
 }
 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
 int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog);
+bool bpf_prog_may_run_in_nmi(const struct bpf_verifier_env *env);
+bool bpf_obj_free_runs_dtor(const struct btf *btf, u32 btf_id);
 
 /* The first field that ends behind 'off'. The fields are sorted and do not overlap. */
 static inline u32 btf_record_first_field(const struct btf_record *rec, s64 off)
include/linux/btf.h +6 -0
index 7bb3cc973c1f..6014282feacb 100644
@@ -623,6 +623,7 @@ struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog);
 u32 *btf_kfunc_flags(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog);
 int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag);
 bool btf_kfunc_is_allowed(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog);
+s32 btf_find_release_kfunc(const struct btf *btf, u32 btf_id, const struct bpf_prog *prog);
 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
 				const struct bpf_prog *prog);
 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
@@ -723,6 +724,11 @@ static inline s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
 {
 	return -ENOENT;
 }
+static inline s32 btf_find_release_kfunc(const struct btf *btf, u32 btf_id,
+					 const struct bpf_prog *prog)
+{
+	return -ENOENT;
+}
 static inline int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors,
 					      u32 add_cnt, struct module *owner)
 {
kernel/bpf/btf.c +43 -0

49 lines not on this page · raw message

kernel/bpf/fixups.c +1 -1
index 9e4e4a239ed9..25c0b0552b4d 100644
@@ -699,7 +699,7 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 			if (!plan_has_pad(env, i, plan))
 				continue;
 			n = emit_pad(env, s, plan, new, new_aux);
-			for (pad = 0; pad < cnt; pad += len) {
+			for (pad = bpf_pad_can_be_shared(plan) ? 0 : cnt; pad < cnt; pad += len) {
 				for (len = 1; buf[pad + len - 1].code != (BPF_JMP | BPF_EXIT);
 				     len++)
 					;
kernel/bpf/pads.c +365 -16

550 lines not on this page · raw message

kernel/bpf/verifier.c +27 -12
index 6a3c539ebead..1419f5e3fe2d 100644
@@ -11223,6 +11223,9 @@ static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
 			mark_reg_invalid(env, reg);
 		}
 	}));
+	/* Verified separately, the lock that is still held may be a caller's: tell the caller. */
+	if (env->cur_state->instance_id && env->cur_state->active_locks)
+		env->cur_state->invalidated_non_owning = true;
 }
 
 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)
@@ -11898,9 +11901,11 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 	/*
 	 * Keep only what the function held all the time. The state at its exit looks the same if
 	 * the function released a lock and acquired it again. Else verify the function in the
-	 * instance of the caller.
+	 * instance of the caller. The caller has non-owning references only under a lock, which
+	 * is one of what it holds.
 	 */
-	if (callee->entry_refs < nheld || callee->entry_rcu_locks < caller->active_rcu_locks ||
+	if (callee->entry_refs < nheld || (exit->invalidated_non_owning && nheld) ||
+	    callee->entry_rcu_locks < caller->active_rcu_locks ||
 	    callee->entry_preempt_locks < caller->active_preempt_locks) {
 		if (exit->speculative)
 			return -EACCES;
@@ -16004,7 +16009,7 @@ static int check_return_code(struct bpf_verifier_env *env, int regno, const char
  * destructors of a list head and of an rb root take the bpf_spin_lock in the object, and the
  * destructor of a kptr releases another object. No other field runs code when it is freed.
  */
-static bool obj_free_runs_dtor(const struct btf *btf, u32 btf_id)
+bool bpf_obj_free_runs_dtor(const struct btf *btf, u32 btf_id)
 {
 	const struct btf_struct_meta *meta = btf_find_struct_meta(btf, btf_id);
 
@@ -16016,7 +16021,6 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			    int *insn_idx_p)
 {
 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable, nmi_prog;
-	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
 	struct bpf_reg_state *regs = cur_regs(env), unwound_r0;
 	const char *func_name, *ptr_type_name;
 	const struct btf_type *t, *ptr_type;
@@ -16133,10 +16137,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	if (err)
 		return err;
 
-	nmi_prog = is_tracing_prog_type(prog_type) ||
-		   /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
-		   (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
-		    && !env->prog->sleepable);
+	nmi_prog = bpf_prog_may_run_in_nmi(env);
 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
 	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && nmi_prog) {
 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
@@ -16179,7 +16180,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		 * the lock in the node, and bpf_spin_locks of a cpu share one word for irq flags.
 		 */
 		if (bpf_subprog_unwinds(&env->subprog_info[meta.subprogno]) &&
-		    obj_free_runs_dtor(meta.arg_btf, meta.arg_btf_id)) {
+		    bpf_obj_free_runs_dtor(meta.arg_btf, meta.arg_btf_id)) {
 			verbose(env,
 				"%s with a comparator that unwinds cannot be used on types that take a lock when freed\n",
 				func_name);
@@ -21845,14 +21846,16 @@ static int release_frame_resources(struct bpf_verifier_env *env)
 {
 	struct bpf_verifier_state *st = env->cur_state;
 	struct bpf_func_state *frame = cur_func(env);
-	u32 locks = st->active_locks;
+	u32 refs = st->acquired_refs;
 	struct bpf_reference_state *ref;
 	int id, err;
 
 	while (st->acquired_refs > frame->entry_refs) {
 		ref = &st->refs[st->acquired_refs - 1];
 		id = ref->id;
-		if (ref->type == REF_TYPE_IRQ)
+		if (ref->type == REF_TYPE_PTR)
+			err = release_reference(env, ref->id);
+		else if (ref->type == REF_TYPE_IRQ)
 			err = release_irq_state(env, ref->id);
 		else
 			err = release_lock_state(env, ref->type, ref->id, ref->ptr);
@@ -21860,7 +21863,8 @@ static int release_frame_resources(struct bpf_verifier_env *env)
 			return -EFAULT;
 		unmark_stack_obj(env, id);
 	}
-	if (st->active_locks != locks)
+	/* A lock is gone, or an object was freed under the lock of a caller who may point to it. */
+	if (st->acquired_refs != refs)
 		invalidate_non_owning_refs(env);
 	st->active_rcu_locks = frame->entry_rcu_locks;
 	st->active_preempt_locks = frame->entry_preempt_locks;
@@ -22762,6 +22766,17 @@ static bool is_tracing_prog_type(enum bpf_prog_type type)
 	}
 }
 
+/* A program that may run in NMI context must not free an object with NMI unsafe fields. */
+bool bpf_prog_may_run_in_nmi(const struct bpf_verifier_env *env)
+{
+	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
+
+	return is_tracing_prog_type(prog_type) ||
+	       /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
+	       (prog_type == BPF_PROG_TYPE_TRACING &&
+		env->prog->expected_attach_type != BPF_TRACE_ITER && !env->prog->sleepable);
+}
+
 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
 {
 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
Signature · 1 line
2.53.1-Meta
author maintainer
#18 lore raw

PATCH 18/73 bpf: Release iterators and dynptrs in landing pads

In reply to Kumar Kartikeya Dwivedi

Currently no landing pad releases an open-coded iterator, or a dynptr that has to be released: the dynptr of a ring buffer or of a file. To the verifier both are references, but their release takes the address of the object in the stack. Release them where they are, as irq flags are released. For the iterator of a bpf_for_each(scx_dsq, ...) loop:

pad: r1 = r10

       r1 += -48
       call bpf_iter_scx_dsq_destroy
       r0 = 0; exit

The release function follows from what the verifier compares between
states: bpf_iter_<type>_destroy() for the type of an iterator, and bpf_ringbuf_discard_dynptr() or bpf_dynptr_file_discard() for the kind of a dynptr. The location is R10 plus an offset, or a pointer to the object when a caller has it.

The order of a pad gets two rules. An iterator that RCU protects is destroyed first, because irq flags or a section may be all that protects it. All other iterators and the dynptrs are released with the pointers, and a dynptr before the pointer that it was made from.

Three cases need care:

- An iterator that RCU protects is destroyed under the locks of the frame, where only a kfunc that is KF_SPINLOCK_SAFE may be called. No such destructor has the flag today, so the verifier cannot generate a pad for a frame that holds such an iterator and a lock.
- The pad may be the only caller of the destructor, and then no other check looks at the iterator. So the pad destroys an iterator only if bpf_iter_slots_valid_init() accepts it. That is the check of the argument of the destructor, split out of is_iter_reg_valid_init().
- For an iterator type of a module, the insn that acquired the iterator has to be a kfunc call of the same BTF, which gives the index of the BTF in fd_array. Otherwise the verifier cannot generate the pad.

Nothing changes for programs yet: a frame that holds a reference still gets no landing pad.

---
 include/linux/bpf_verifier.h |   6 ++
 kernel/bpf/pads.c            | 179 +++++++++++++++++++++++++++--------
 kernel/bpf/verifier.c        |  40 +++++---
 3 files changed, 173 insertions(+), 52 deletions(-)
include/linux/bpf_verifier.h +6 -0
index f658a8aeeae0..dc4694dc55f9 100644
@@ -469,6 +469,9 @@ enum bpf_pad_class {
 	BPF_PAD_RES_LOCK_IRQ,	/* bpf_res_spin_lock_irqsave(): two of refs[], one release */
 	BPF_PAD_SPIN_LOCK,	/* bpf_spin_lock() */
 	BPF_PAD_REF,		/* a pointer that a helper or a kfunc returned, REF_TYPE_PTR */
+	/* Objects in the stack, which are REF_TYPE_PTR too */
+	BPF_PAD_ITER,		/* bpf_iter_<type>_new() */
+	BPF_PAD_DYNPTR,		/* bpf_ringbuf_reserve_dynptr(), bpf_dynptr_from_file() */
 };
 
 /* Why the verifier cannot generate one landing pad for all states that reach a site */
@@ -517,6 +520,7 @@ struct bpf_pad_ent {
 	struct bpf_insn release; /* the call that releases it */
 	u32 obj_type;		/* the BTF id of the type, if it is an object of the program */
 	u8 class;		/* enum bpf_pad_class */
+	bool rcu;		/* an iterator that RCU protects: it is destroyed first */
 	/* 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];
@@ -2373,6 +2377,8 @@ bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
 int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog);
 bool bpf_prog_may_run_in_nmi(const struct bpf_verifier_env *env);
 bool bpf_obj_free_runs_dtor(const struct btf *btf, u32 btf_id);
+int bpf_iter_slots_valid_init(const struct bpf_func_state *state, int spi, const struct btf *btf,
+			      u32 btf_id, int nr_slots);
 
 /* The first field that ends behind 'off'. The fields are sorted and do not overlap. */
 static inline u32 btf_record_first_field(const struct btf_record *rec, s64 off)
kernel/bpf/pads.c +139 -40

308 lines not on this page · raw message

kernel/bpf/verifier.c +28 -12
index 1419f5e3fe2d..7549ddd3968c 100644
@@ -1143,15 +1143,11 @@ static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
 	return true;
 }
 
-static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
-				   struct btf *btf, u32 btf_id, int nr_slots)
+/* Returns 0 if the @nr_slots stack slots of @state from @spi down hold an iterator of @btf_id. */
+int bpf_iter_slots_valid_init(const struct bpf_func_state *state, int spi, const struct btf *btf,
+			      u32 btf_id, int nr_slots)
 {
-	struct bpf_func_state *state = bpf_func(env, reg);
-	int spi, i, j;
-
-	spi = iter_get_spi(env, reg, nr_slots);
-	if (spi < 0)
-		return -EINVAL;
+	int i, j;
 
 	for (i = 0; i < nr_slots; i++) {
 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
@@ -1175,6 +1171,16 @@ static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_s
 	return 0;
 }
 
+static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
+				   struct btf *btf, u32 btf_id, int nr_slots)
+{
+	int spi = iter_get_spi(env, reg, nr_slots);
+
+	if (spi < 0)
+		return -EINVAL;
+	return bpf_iter_slots_valid_init(bpf_func(env, reg), spi, btf, btf_id, nr_slots);
+}
+
 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
 static int release_irq_state(struct bpf_verifier_env *env, int id);
 
@@ -21820,17 +21826,27 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 	return err;
 }
 
-/* Irq flags, @id, are released. A caller may have the object: it is none any more. */
+/*
+ * A landing pad releases the irq flags or the iterator with @id. The object can be in the stack of
+ * a caller, so invalidate its stack slots in every frame.
+ */
 static void unmark_stack_obj(struct bpf_verifier_env *env, int id)
 {
-	u32 mask = 1 << STACK_IRQ_FLAG;
+	u32 mask = (1 << STACK_IRQ_FLAG) | (1 << STACK_ITER);
 	struct bpf_stack_state *slot;
 	struct bpf_func_state *frame;
 	struct bpf_reg_state *reg;
+	int nr;
 
 	bpf_for_each_reg_in_vstate_mask(env->cur_state, frame, reg, slot, mask, ({
-		if (slot && reg->id == id) {
-			bpf_mark_reg_not_init(env, reg);
+		/* a lock in a global variable has no id, nor have the other slots of an iterator */
+		if (!slot || !id || reg->id != id)
+			continue;
+		nr = 1;
+		if (slot->slot_type[0] == STACK_ITER)
+			nr = btf_type_by_id(reg->iter.btf, reg->iter.btf_id)->size / BPF_REG_SIZE;
+		for (; nr; nr--, slot--) {
+			bpf_mark_reg_not_init(env, &slot->spilled_ptr);
 			memset(slot->slot_type, STACK_INVALID, sizeof(slot->slot_type));
 		}
 	}));
Signature · 1 line
2.53.1-Meta
author maintainer
#19 lore raw

PATCH 19/73 bpf: Check pointers for NULL in landing pads

In reply to Kumar Kartikeya Dwivedi

Currently all states at a site have to hold the same resources, because only the program counter tells a landing pad what its frame holds. So the verifier cannot generate a pad where one path holds a resource and another does not:

  t = NULL;                                pad: r1 = r6
  if (pid)                                      if r1 == 0 goto +1
          t = bpf_task_from_pid(pid);           call bpf_task_release
  v = wait();     /* can be cancelled */        r0 = 0
  if (t)                                        exit
          bpf_task_release(t);

The program tests the pointer to tell whether it holds the reference. Let the landing pad do the same, as on the right. The location can be a stack slot too: rustc keeps an Option of a type with a destructor there.

A release is tested when its location is 0 in all states that do not hold the resource. If no location is, the verifier still cannot generate the pad ("a resource is held on some paths only"). A later patch lifts this. The test works for a pointer and for a lock in a map value. The address of an object in the stack tells nothing, so all states still have to hold irq flags, an iterator or a dynptr.

Three cases need care:

- A pointer that the program has not compared with NULL yet at the site takes the same test.
- The pad tests before it subtracts the constant offset of the location.
- The test reads 64 bits, and after 'w6 = 0' the upper half of R6 is zero only if the program reads it (zext_dst). So a register is a location only if its upper half is live at the site (live_hi32_before).

The states at a site no longer hold the same resources, so the order of the releases is settled when all states have been there (order_ents()). A pad releases the iterators that RCU protects first, then locks and irq flags in the reverse of the order in which a state took them, then the sections, then all other objects and pointers. The verifier cannot generate a pad only if no order suits all states, for example when two states took two locks in two orders.

A frame that holds a reference still gets no landing pad. For locks the test and the order apply from now on.

---
 include/linux/bpf_verifier.h |  21 ++-
 kernel/bpf/liveness.c        |   1 +
 kernel/bpf/pads.c            | 289 ++++++++++++++++++++++++++++-------
 3 files changed, 253 insertions(+), 58 deletions(-)
include/linux/bpf_verifier.h +18 -3
index dc4694dc55f9..5c34ace286df 100644
@@ -488,13 +488,13 @@ enum bpf_pad_conflict {
 };
 
 /*
- * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument and the
- * call. The 3 are the insns that leave the frame.
+ * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument, a test and
+ * the call. The 3 are the insns that leave the frame.
  */
 #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 + 1) + \
+#define BPF_PAD_MAX_INSNS	(BPF_PAD_MAX_ENTS * (2 * BPF_PAD_MAX_ARGS + 2) + \
 				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 3)
 #define BPF_PAD_MAX_CANDS	6
 
@@ -509,10 +509,18 @@ enum bpf_place_loc {
 /* A location: where a landing pad finds the pointer that a release takes */
 struct bpf_pad_place {
 	u8 loc;			/* enum bpf_place_loc */
+	bool maybe_null:1;	/* a state that holds the resource has not tested the pointer yet */
+	bool null:1;		/* it is 0 in all states that do not hold the resource */
 	s16 at;			/* number of the register | offset from R10 | index in used_maps */
 	s32 delta;		/* the location has the pointer plus 'delta' */
 };
 
+/* The registers and the stack slots of a frame that are 0 */
+struct bpf_pad_nulls {
+	u16 regs;
+	DECLARE_BITMAP(slots, MAX_BPF_STACK_SLOTS);
+};
+
 /* 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 */
@@ -521,6 +529,7 @@ struct bpf_pad_ent {
 	u32 obj_type;		/* the BTF id of the type, if it is an object of the program */
 	u8 class;		/* enum bpf_pad_class */
 	bool rcu;		/* an iterator that RCU protects: it is destroyed first */
+	bool always;		/* all states hold it */
 	/* 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];
@@ -541,7 +550,11 @@ struct bpf_pad_plan {
 	bool visited;
 	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
 	u8 nr_ents;
+	bool ordered;			/* see order_ents() */
 	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];
+	struct bpf_pad_nulls nulls;	/* in all states so far */
 	/* the subprogs that came back to the call with unwind_exit, in ascending order */
 	u32 *callee;
 	u32 nr_callees;
@@ -1158,6 +1171,8 @@ struct bpf_insn_aux_data {
 	u8 iv_operand;		/* the operand of the jump that tests the iv, + 1 */
 	/* registers alive before this instruction. */
 	u16 live_regs_before;
+	/* those of them whose upper half is alive */
+	u16 live_hi32_before;
 	/*
 	 * Registers that it reads and writes. The arguments of a static function and of callx
 	 * are not in @use_regs. The bits above r10 are not valid.
kernel/bpf/liveness.c +1 -0
index 4d04d17603ae..28044f12e9c7 100644
@@ -2983,6 +2983,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
 		insn_aux[i].live_regs_before = mask_lo(in) | mask_hi(in);
 		insn_aux[i].use_regs = mask_lo(state[i].use) | mask_hi(state[i].use);
 		insn_aux[i].def_regs = mask_lo(state[i].def);
+		insn_aux[i].live_hi32_before = mask_hi(in);
 		/*
 		 * On architectures where 32-bit operations do not reset upper halves
 		 * of the registers, the verifier needs to zero extend a destination
kernel/bpf/pads.c +234 -55

450 lines not on this page · raw message

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

PATCH 20/73 bpf: Let the kernel cancel a frame that holds references

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a frame that holds a reference, an iterator or a dynptr gets no landing pad, although pads release all of them by now and test a pointer for NULL. frame_can_unwind() refuses a frame that acquired one (REF_TYPE_PTR), and a may_goto of the verifier leaves its loop.

Remove the refusal, for all three at once. With pads for plain references only, a loop that holds an iterator or a dynptr would have been rejected in between, and without the test for NULL a frame that holds a pointer on some paths only. '+' marks what the verifier adds:

         call bpf_task_from_pid
         r6 = r0
         ...
      1: ...
         call bpf_map_lookup_elem
  +      may_goto pad
         if r0 == 0 goto 1b
         ...

+ pad: r1 = r6
+ call bpf_task_release
+ r0 = 0; exit

What changes for programs that load today:

- In a frame that holds a reference, an iterator or a dynptr, the may_goto of the verifier left the loop and the program continued. Now the pad releases what the frame holds, and the program ends.
- Such a program is rejected when the verifier cannot generate the pad, for example when no register or stack slot holds the pointer on all paths. A later patch lifts that case.
- A caller that holds one of them at the call of a subprog in which the program can be cancelled gets a pad for the call. Until now it was rejected with "conflict: the frame cannot unwind".

added_edge of verifier_trip_count.c is removed: it held a reference so that may_goto took an edge out of the outer loop, and the frame is cancelled instead now.

---
 kernel/bpf/verifier.c                            |  6 ------
 .../bpf/progs/plain_c_rbtree_search_kptr.c       |  6 ------
 .../selftests/bpf/progs/verifier_budget.c        |  4 ++--
 .../selftests/bpf/progs/verifier_passes.c        | 10 ++++++++--
 .../selftests/bpf/progs/verifier_trip_count.c    | 16 ----------------
 5 files changed, 10 insertions(+), 32 deletions(-)
kernel/bpf/verifier.c +0 -6
index 7549ddd3968c..fc5934aa9d1d 100644
@@ -21682,8 +21682,6 @@ static bool frame_holds_resources(const struct bpf_verifier_state *st)
  * the callers hold, or the program is rejected. Where a caller has none the verifier emits it.
  *
  * False when it cannot:
- * - This frame acquired something itself, and there is no landing pad for that: the verifier
- *   emits none for references.
  * - The subprog cannot leave with unwind_exit, see bail_unwinds.
  * - A helper that calls a callback doesn't expect it to unwind.
  * Then the program goes on along a path that it has, like after may_goto of
@@ -21697,7 +21695,6 @@ static bool frame_can_unwind(struct bpf_verifier_env *env, const struct bpf_veri
 {
 	const struct bpf_func_state *frame = st->frame[st->curframe];
 	const struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
-	int i;
 
 	/* unwind_frame() needs an insn at which the state leaves the function. */
 	if (sub->exit_idx == U32_MAX)
@@ -21705,9 +21702,6 @@ static bool frame_can_unwind(struct bpf_verifier_env *env, const struct bpf_veri
 	/* A landing pad has no nospec barrier, so only a loader with CAP_PERFMON gets one. */
 	if (!bpf_may_unwind(env))
 		return false;
-	for (i = frame->entry_refs; i < st->acquired_refs; i++)
-		if (st->refs[i].type == REF_TYPE_PTR)
-			return false;
 	if (frame->in_callback_fn)
 		return false;
 	return frame_is_top(st) || sub->bail_unwinds || or_exit;
tools/testing/selftests/bpf/progs/plain_c_rbtree_search_kptr.c +0 -6
index 5808d873fedd..3f63979cf71b 100644
@@ -46,9 +46,6 @@ static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
 
 SEC("syscall")
 __success __retval(0)
-#ifndef __clang__
-__skip("GCC's layout: the may_goto that the verifier adds leaves the loop with a reference")
-#endif
 long rbtree_search_kptr(void *ctx)
 {
 	struct tree_node *tnode;
@@ -156,9 +153,6 @@ static bool less_r(struct bpf_rb_node *a, const struct bpf_rb_node *b)
 
 SEC("syscall")
 __success __retval(0)
-#ifndef __clang__
-__skip("GCC's layout: the may_goto that the verifier adds leaves the loop with a reference")
-#endif
 long rbtree_search_kptr_ref(void *ctx)
 {
 	struct tree_node_ref *tnode_r, *tnode_m;
tools/testing/selftests/bpf/progs/verifier_budget.c +2 -2
index d741cf8dbffa..a6e1cd22f35b 100644
@@ -809,13 +809,13 @@ __naked void loop_with_two_entries(void)
 
 /*
  * bpf_iter_num_next() stops the loop that the program leaves when there is nothing left.
- * This one goes on. The iterator is held, so the loop is left when it is out of budget.
+ * This one goes on. When it is out of budget the landing pad destroys the iterator.
  */
 SEC("socket")
 __description("budget: a loop that goes on when its iterator is drained")
 __arch_x86_64
 __arch_arm64
-__success __retval(1)
+__success __retval(0)
 __naked void loop_after_iter_is_drained(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/progs/verifier_passes.c +8 -2
index cc95688120e5..523931868e65 100644
@@ -1083,7 +1083,11 @@ int calls_hold_other_things(struct __sk_buff *skb)
 	return val;
 }
 
-/* a recursive function is verified on its own, also with an argument that can be NULL */
+/*
+ * a recursive function is verified on its own, also with an argument that can be NULL. When its
+ * check of the stack fails it is unwound, and the landing pad of the caller drops the object: it
+ * returns only with a pointer that it has tested.
+ */
 static __noinline struct pair *throw_if_null(struct pair *p, long depth)
 {
 	if (!p)
@@ -1097,7 +1101,9 @@ static __noinline struct pair *throw_if_null(struct pair *p, long depth)
 SEC("tc")
 __description("calls: the function tests a reference of the caller for NULL")
 __arch_x86_64
-__failure __msg("conflict: the frame cannot unwind") __not_msg("verifier bug")
+__load_if_JITed()
+__success __log_level(2) __not_msg("verifier bug")
+__msg("landing pad of call at {{[0-9]+}}: ref@{{[0-9]+}}({{[^)]+}}) if not 0 rcu=0 preempt=0")
 int callee_tests_null(struct __sk_buff *skb)
 {
 	struct pair *n = bpf_obj_new(typeof(*n)), *copy;
tools/testing/selftests/bpf/progs/verifier_trip_count.c +0 -16
index 70a2a549f115..23253770be58 100644
@@ -3685,22 +3685,6 @@ LINKED(natural_loop_is_secondary_entry, MAP_OOB,
 	LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 1; r3 += 1;")
 	"if r7 < 10 goto o_%=;")
 
-/*
- * No exit of the inner loop dominates its backedges: may_goto is added before its header. The prog
- * holds a reference, so may_goto goes to the exit of the outer loop: an edge that the verifier
- * adds. Every iteration of the outer loop restores r3. At the header of the inner one it is r7.
- */
-LINKED(added_edge, OUTSIDE,
-	"r1 = %[ringbuf] ll; r2 = 8; r3 = 0; call %[bpf_ringbuf_reserve]; if r0 == 0 goto out_%=;"
-	"*(u64 *)(r10 - 16) = r0; r3 = r8;"
-	"o_%=: r2 = r3; r3 = r7;"
-	"i_%=: r1 = *(u8 *)(r6 + 0); if r1 == 1 goto a_%=; if r1 == 2 goto b_%=; goto i_%=;"
-	"a_%=: goto i_%=;"
-	"b_%=: r3 = r2; r1 = *(u8 *)(r6 + 1); if r1 == 3 goto o_%=;"
-	"r4 = r6; if r8 > 63 goto r_%=; r4 += r3;"
-	"r_%=: *(u64 *)(r10 - 24) = r4; r1 = *(u64 *)(r10 - 16); r2 = 0;"
-	"call %[bpf_ringbuf_discard]; r1 = *(u64 *)(r10 - 24);")
-
 /*
  * r7 = ctx->data;
  * r8 = r7
Signature · 1 line
2.53.1-Meta
author maintainer
#21 lore raw

PATCH 21/73 bpf: Add unwind_goto after helpers with a callback

In reply to Kumar Kartikeya Dwivedi

Currently the kernel cannot cancel a program inside a callback of bpf_loop() or of another helper. A callback may leave with unwind_exit only if the program has an unwind_goto after the call of the helper, and the verifier treats a callback and what it calls as functions that cannot leave with unwind_exit. So a may_goto that it adds there leaves the loop.

Add an unwind_goto after the call of a helper that has an unwind label for its callback, with a landing pad, as after the call of a subprog. '+' marks what the verifier adds:

cb: caller:
call bpf_rcu_read_lock call bpf_loop
1: ... .-> + unwind_goto pad --.

  +      may_goto pad --------------.  |          ...               |
         if r0 == 0 goto 1b         |  |          exit              |
         ...                        |  |   + pad: r0 = 0 <----------'
  + pad: call bpf_rcu_read_unlock <-'  |   +      exit
  +      r0 = 0                        |

+ unwind_exit --> bpf_loop() ---'

The unwind_exit of the callback goes to the unwind label of bpf_loop(), and from there to the unwind_goto after the call. For the rules about which function can leave with unwind_exit, such a helper is like callx.

Three kinds of callback stay as they are:

- A subprog whose address goes only to a helper that keeps it for later (a timer, a work queue, call_rcu) is called by the kernel alone. Its landing pads end in exit.
- The callback of a helper without an unwind label cannot be cancelled, for example that of any helper outside x86-64 and arm64.
- bpf_rbtree_add() drops the node at its unwind label. It must not do that for a type with NMI unsafe fields in a program that may run in NMI context, nor for a type with a list head, an rb root or a referenced kptr. A comparator of such a type cannot be cancelled, and one that has unwind_exit or is recursive is rejected as before.

What changes for programs that load today:

- When a loop of a callback has run too long, the program ends. Before, may_goto left the loop and the callback continued.
- Only fentry can attach to a callback in which the program can be cancelled.
- A program without unwind_goto after the call of a helper whose callback has unwind_exit loads.

---
 include/linux/bpf.h                           |   1 +
 include/linux/bpf_verifier.h                  |   2 +-
 kernel/bpf/pads.c                             |   2 +
 kernel/bpf/verifier.c                         | 140 ++++++++++--------
 .../selftests/bpf/progs/verifier_unwind.c     |   4 +-
 5 files changed, 81 insertions(+), 68 deletions(-)
include/linux/bpf.h +1 -0
index 4f9c2bf64643..915034e8acc2 100644
@@ -182,6 +182,7 @@ struct bpf_map_ops {
 	int (*map_set_for_each_callback_args)(struct bpf_verifier_env *env,
 					      struct bpf_func_state *caller,
 					      struct bpf_func_state *callee);
+	/* It has an unwind label for callback_fn, which may unwind, see bpf_call_cb() */
 	long (*map_for_each_callback)(struct bpf_map *map,
 				     bpf_callback_t callback_fn,
 				     void *callback_ctx, u64 flags);
include/linux/bpf_verifier.h +1 -1
index 5c34ace286df..2853a463df52 100644
@@ -1361,7 +1361,7 @@ struct bpf_subprog_info {
 	bool on_its_own: 1;
 	/*
 	 * It can leave with unwind_exit: the verifier adds the unwind_goto that its calls lack. Not
-	 * if a helper calls it, see subprog_cannot_unwind().
+	 * if a helper without an unwind label calls it, see subprog_cannot_unwind().
 	 */
 	bool bail_unwinds: 1;
 	/*
kernel/bpf/pads.c +2 -0
index 6027e9cca9cc..4e3a7894af84 100644
@@ -65,6 +65,8 @@
  *    + pad:  r0 = 0 <-----------'          |     + pad: call bpf_rcu_read_unlock <-'
  *    +       unwind_exit ------------------'     +      r0 = 0; exit
  *
+ * A helper that calls a callback is a C frame between the callback and its caller. It passes a
+ * cancellation on from its unwind label to the unwind_goto after its own call, see bpf_call_cb().
  * The frame that the kernel called leaves with exit, and the program returns the value of the
  * cancellation: bpf_cancelled_retval(), which goes by the program type.
  */
kernel/bpf/verifier.c +75 -65

250 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_unwind.c +2 -2
index 6be56387a825..b4d7dfdc675b 100644
@@ -930,13 +930,13 @@ static unsigned long cb_unwinds(void)
 	);
 }
 
-/* bpf_loop() has a pad for it, so what's missing is the one after the call */
+/* bpf_loop() has a pad for it, and the verifier adds the one after the call */
 SEC("tc")
 __description("unwind: callback unwinds")
 __arch_x86_64
 __arch_arm64
 __load_if_JITed()
-__failure __msg("no unwind_goto after the call of bpf_loop()")
+__success __retval(2)
 __naked int callback_unwinds(void)
 {
 	asm volatile (
Signature · 1 line
2.53.1-Meta
author maintainer
#22 lore raw

PATCH 22/73 bpf: Let a may_goto that the verifier adds go to its landing pad only

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a may_goto that the verifier adds to a loop has two possible targets, and so has the stack check of a recursive subprog:

the kernel can cancel it cannot
the frame

  may_goto       landing pad              the exit of the loop
  stack check    landing pad              r0 = 0; exit

The right column is behaviour that the program does not have. The code after the loop runs as if the loop had ended, and the caller of the subprog continues with a result that nobody computed.

By now the kernel can cancel a frame in subprogs and in callbacks, so remove the right column. A may_goto of the program itself is not changed. A site in a frame that the kernel cannot cancel is rejected, and the log gives the reason:

- "the function has no exit": it has neither an exit insn nor a call of bpf_throw();
- "the program is loaded without CAP_PERFMON";
- "the JIT or the helper that calls the function cannot unwind it": a subprog or a callback where the JIT is off or has no unwind_exit, which only x86-64 and arm64 have, an offloaded program, or the callback of a helper without an unwind label.

What changes for programs that load today:

- A program with such a site is rejected. Before, the may_goto left the loop there, and the stack check returned 0 from the subprog.
- Without CAP_PERFMON a program has no trip counts, and a loop that nothing else stops got a may_goto of the verifier. Now the verifier walks such a loop trip by trip, which costs load time in proportion to the trips, and the program loads only if the loop ends that way.

One point needs care. Every edge of may_goto that a pass takes now cancels a frame, and the first pass takes more of them than the program has in the end, because it does not know the trip counts yet. So a missing pad counts only at a site that the program keeps (bpf_site_is_used()). During a pass it is an error only at a site that cannot disappear any more (site_is_certain()). At any other site the state just ends.

The second target goes away with its special cases. These are guard_to and bpf_head_guard_target(), for an edge that the control flow graph did not have, the 'r0 = 0; exit' of a subprog with its nospec barrier, and the guess of a path-sensitive run about the target.

---
 Documentation/bpf/verifier.rst                | 135 ++++++++++----
 include/linux/bpf_verifier.h                  |  39 +---
 kernel/bpf/const_fold.c                       |  11 +-
 kernel/bpf/failing_path.c                     |   8 +-
 kernel/bpf/fixups.c                           |  81 ++++----
 kernel/bpf/flow.c                             | 107 ++++-------
 kernel/bpf/liveness.c                         |  14 --
 kernel/bpf/pads.c                             |  40 +++-
 kernel/bpf/precision.c                        |   3 -
 kernel/bpf/verifier.c                         | 175 ++++++++----------
 .../bpf/progs/compute_live_registers.c        |   8 +-
 .../selftests/bpf/progs/plain_c_arena_htab.c  |   2 +
 .../bpf/progs/plain_c_arena_strsearch.c       |   2 +
 .../bpf/progs/plain_c_verifier_arena_large.c  |   2 +
 .../selftests/bpf/progs/verifier_barrier.c    |  73 ++------
 .../selftests/bpf/progs/verifier_budget.c     |  12 +-
 .../selftests/bpf/progs/verifier_loop_walk.c  |   2 +
 .../selftests/bpf/progs/verifier_passes.c     |   2 +-
 18 files changed, 333 insertions(+), 383 deletions(-)
Documentation/bpf/verifier.rst +101 -34
index 0bffb2b1476a..21c92b7e829a 100644
@@ -756,27 +756,18 @@ none of these holds                    the verifier adds ``may_goto``
 =====================================  =========================================
 
 *may_goto* is a jump that is taken when the program has looped too long. The
-verifier puts it before a jump that leaves the loop, or at the header. It
-checks the new edge like any other edge::
+verifier puts it before a jump that leaves the loop, or at the header. The new
+edge goes to a *landing pad* that the verifier generates after the last insn of
+the function::
 
   do {                          do {
           p = lookup();                 p = lookup();
-  } while (!p);                         may_goto leave;
+  } while (!p);                         may_goto pad;
   use(p);                       } while (!p);
                                 use(p);
-                                ...
-                                leave: return 0;
 
-Where does the edge go? The verifier takes the first line that is possible:
-
-- In the main function: ``return 0``, if nothing has to be released and 0 is a
-  valid result.
-- In another function: *unwind*, if nothing has to be released and each call has
-  an ``unwind_goto`` after it. The function leaves with ``unwind_exit``, and
-  ``unwind_goto`` jumps to the code of the caller that cleans up.
-- The exit of the loop. The code there has to be safe. From a header the edge
-  leaves the outer loops too. If the code there reads a register that is not
-  set, the function returns 0.
+When the jump is taken, the kernel cancels the program: the pad releases what
+the function holds, and ``use(p)`` does not run. See `Cancellation`_.
 
 A loop without an exit is an error.
 
@@ -911,7 +902,7 @@ recursion           the start of the function     a check at run time
 ==================  ============================  ==============================
 
 A recursive function starts with ``may_goto`` and a test of the free stack. If
-there is no room, it returns 0 or unwinds. The verifier checks that edge too.
+there is no room, the program is cancelled. The verifier checks that edge too.
 A recursion in frames is not joined. It has to end in ``MAX_CALL_FRAMES``.
 
 An async callback, for example of a timer, runs later. It starts as a new state
@@ -919,6 +910,79 @@ with an empty stack. ``callx`` is checked as a call of each function that the
 register can hold. ``bpf_throw()`` ends the program from any frame, so nothing
 can be held there.
 
+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, or the
+stack check of a recursive function fails. 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
+two insns, or a call whose callee can be cancelled. For each site the verifier
+generates a landing pad after the last insn of the function. The pad releases
+what the frame holds at the site and leaves the frame::
+
+  bpf_rcu_read_lock();                       call bpf_rcu_read_lock
+  do {                                    1: ...
+          p = bpf_map_lookup_elem(...);      call bpf_map_lookup_elem
+  } while (!p);                              may_goto pad
+  v = *p;                                    if r0 == 0 goto 1b
+  bpf_rcu_read_unlock();                     ...
+  return v;                                  exit
+                                        pad: call bpf_rcu_read_unlock
+                                             r0 = 0
+                                             exit
+
+When the time is up, ``may_goto`` jumps to the pad, and the program ends without
+getting to ``*p``.
+
+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
+``bpf_cancelled_retval()``: the one that refuses, drops or changes nothing,
+such as ``TC_ACT_SHOT`` for tc or ``-EPERM`` for an LSM hook that returns an
+errno. It is 0 in the listings here.
+
+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
+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.
+
+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 and a recursion reject the program.
+
+Landing pads
+------------
+
+A state that gets to a site leaves its frame there, see ``unwind_frame()``. The
+verifier does not check the insns of the landing pad. The pad is a fixed list
+of calls, so it has to be right for all states at its site. It makes at most 8
+releases, and it calls only what the program could call at the site, for
+example under a lock of a caller. For each release the pad has to know two
+things:
+
+- Where the pointer is that the release takes. The pad loads it from a
+  *location*: a register or a stack slot of the program that is live at the
+  site and holds the pointer in all states. For a task that the program keeps
+  in ``R6`` the pad is ``r1 = r6; call bpf_task_release``. After a call only
+  ``R6`` - ``R9`` and the stack are locations.
+- Whether the frame holds it. If all states at the site hold it, the site
+  tells. If some do not, the pad tests the location for NULL, as the program
+  does. The location has to be 0 in the states that do not hold it.
+
+If the verifier cannot generate one pad for all states at a site, that is an
+error of the pass, like an unproven insn: a later pass that keeps more states
+apart may not have it. If the error stays, the program is rejected, and the log
+says why::
+
+  landing pad of may_goto at 7: conflict: the number of sections differs
+
 After an error
 ==============
 
@@ -1071,7 +1135,7 @@ The run has the same checks as a pass, and other rules:
   insn.
 - If only the jump on the iv depends on the xregs that moved in a trip, and all
   other live xregs are the same, the path skips trips.
-- If a loop does not end, the path continues where ``may_goto`` leaves it.
+- If a loop does not end, the frame is cancelled at its ``may_goto``.
 
 The path can end only at an unproven insn of the last pass. This includes an
 insn that was unproven because of another one. An error at any other insn drops
@@ -1082,7 +1146,7 @@ is something new: after ADD_DEPS, after a partition helped, after the budget
 grew, and before the final reject. It does not start again when there is a
 failing path.
 
-Three guesses of the run can make a path that the program cannot take. If such
+Two guesses of the run can make a path that the program cannot take. If such
 a path cuts the budget, a valid program can be rejected. So a path of such a
 run, a *path with a guess*, goes to the log, but the budget is not cut. If a
 pass has a real error, the log has that error.
@@ -1124,19 +1188,6 @@ also for a ring index. The same function finds it::
 The next runs keep this answer. So it is also a guess if the run made a guess
 before it.
 
-The third guess is the target of ``may_goto``. All states have the same one::
-
-  large = x > 7;
-  while (...) {
-          if (large && x <= 7) lock();        only a join gets here
-          do { p = lookup(); } while (!p);    gets may_goto
-          *p
-  }
-
-With no lock the target is ``return 0``. The joined state gets to ``lock()``, so
-the pass selects the code after the loop. A path with no lock goes there too,
-and ``*p`` fails.
-
 The run accepts nothing: it drops states and skips trips. It is not the verdict
 either: a path has ranges too, and it can fail at an insn that a pass proves.
 
@@ -1276,13 +1327,18 @@ A barrier has to stop each edge that leads to the insn::
 
   fall-through, jump, call, return     barrier before the insn
   exit of a callback --> helper        barrier at the exit
-  may_goto --> r0 = 0; exit            barrier before r0 = 0
   call --> recursion in frames         barrier at the call
   return --> dead code                 goto -1 replaces the code
 
 A speculative state is joined only with speculative states, and it subsumes
 only speculative states.
 
+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`` and ``unwind_goto``. Without it no function can be
+cancelled, see `Cancellation`_: a loop that needs a ``may_goto`` of the
+verifier and a recursion are rejected.
+
 Some mechanisms depend on a capability. The last line is there because the cpu
 can go past the jump that a proof needs:
 
@@ -1292,14 +1348,15 @@ can go past the jump that a proof needs:
                                    full `Limits`_
 ``CAP_PERFMON``                    trip count, reads of stack that is not
                                    written, pointers as numbers, access to BTF
-                                   objects, arena, recursion
+                                   objects, arena, recursion, landing pads
 ``CAP_PERFMON`` or no mitigations  equations of pointers, equations that a join
                                    makes from constants, the end of infeasible
                                    states, skipped first trips, stack access
                                    with many offsets, pointers out of the object
 =================================  =============================================
 
-Without a trip count a loop gets ``may_goto``, or it is peeled.
+Without a trip count a loop gets ``may_goto``, which needs ``CAP_PERFMON`` as
+well, or it is peeled.
 
 Limits
 ======
@@ -1459,6 +1516,10 @@ Common errors
 ``loop at insn 2 never exits``
   The loop has no edge that leaves it.
 
+``landing pad of may_goto at 7: conflict: the number of sections differs``
+  The verifier cannot generate one landing pad for all states that get to the
+  site. The text after "conflict:" says why, see `Landing pads`_.
+
 ``BPF program is too complex``, ``the limit on cost or memory ended pass 6``
   The load is over a limit. If a pass had an error before, the log has that
   error, or a path with a guess. That path can be false.
@@ -1470,6 +1531,8 @@ Words
 barrier             the ``nospec`` insn, it stops speculative execution
 basic block         a run of insns without a jump into it or out of it
 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
 control_deps        xregs whose value flows to a jump that can skip an unproven
                     insn
@@ -1502,8 +1565,11 @@ iv                  induction variable: each trip adds a constant to it
 join                two states become one that has the values of both
 join point          an insn where states can meet
 join_key            what has no join: states with two join_keys never meet
+landing pad         code that the verifier generates for a site: it releases
+                    what the frame holds and leaves the frame
 leftover            all trips that are not peeled
 live                read later, before it is written
+location            a register or a stack slot that holds a pointer at a site
 may_goto            a jump that is taken when the program has looped too long
 on its own          a function is checked without the frames of its callers
 partition           keep more states apart in the next pass
@@ -1517,6 +1583,7 @@ proven              an insn whose check did not fail in a state of the pass
 prune               drop a state that another state subsumes
 refine              remove values that a jump excludes
 seed                an insn whose reads start the backward slice
+site                an insn at which the kernel can cancel the program
 snapshot            a copy of the fixups and bounds that a pass writes
 speculative         the cpu can have the state only after a wrong prediction
 spill               a store of a register to a stack slot
include/linux/bpf_verifier.h +9 -30
index 2853a463df52..f548d38d8708 100644
@@ -484,6 +484,8 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_NO_PLACE,
 	BPF_CONFLICT_ORDER_DIFFERS,
 	BPF_CONFLICT_CANNOT_UNWIND,
+	BPF_CONFLICT_NO_EXIT,
+	BPF_CONFLICT_NO_PERFMON,
 	BPF_CONFLICT_CALLER_SAVED,
 };
 
@@ -548,6 +550,7 @@ struct bpf_pad_plan {
 	u8 kind;			/* enum bpf_site_kind */
 	u8 conflict;			/* enum bpf_pad_conflict */
 	bool visited;
+	bool used;			/* the program keeps the site, see bpf_pads_mark_used() */
 	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
@@ -1008,8 +1011,6 @@ struct bpf_loop {
 	bool rt_bounded;
 	/* insns in the loop, nested loops included */
 	u32 nr_insns;
-	/* not rt_bounded: there are places for may_goto, see guard_to in bpf_insn_aux_data */
-	bool has_guards;
 
 	/* What one pass gives to the next pass */
 	struct_group_tagged(bpf_loop_precision, precision,
@@ -1111,7 +1112,6 @@ struct bpf_insn_aux_data {
 	u64 cast_arena:1; /* addr_space_cast of an address in arena */
 	u64 cast_mov:1; /* addr_space_cast of a pointer that is not in arena, it's a move */
 	u64 loop_guard:1; /* may_goto is added in front of this instruction */
-	u64 guard_unwinds:1; /* it leaves the subprog */
 	u64 speculative_first:1; /* a speculative state came to it first */
 	u64 call_recorded:1; /* see record_call_fixup() */
 	u64 pessimized:1; /* see bpf_partition_for_pessimized() */
@@ -1138,8 +1138,6 @@ struct bpf_insn_aux_data {
 	);
 
 	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
-	u32 guard_no_unwind:1; /* it cannot unwind from here, at least sometimes */
-	u32 guard_unset_reg:1; /* where it goes a register is read that is not set here */
 	u32 non_speculative_first:1; /* speculative states end here, their fixups did not fit */
 	u32 acquires:1; /* a reference or a lock */
 	u32 releases:1;
@@ -1147,7 +1145,6 @@ struct bpf_insn_aux_data {
 	/* below flags are initialized once */
 	u32 bb_end:1; /* last instruction of a basic block */
 	u32 guard_place:1; /* it is the place for may_goto if the loop needs one */
-	u32 guard_at_header:1; /* there is no better place than the header of the loop */
 	/* true if instruction is a call to a helper function that
 	 * accepts callback function as a parameter.
 	 */
@@ -1201,8 +1198,6 @@ struct bpf_insn_aux_data {
 	 * stop, -1 if none was found. It doesn't stop the loops around that one either.
 	 */
 	s32 not_stopped;
-	/* where may_goto in front of this instruction goes */
-	s32 guard_to;
 	/* additional information about the loop if this instruction is a loop header */
 	struct bpf_loop *loop;
 	/* the call of a callback, or the first insn of a recursive function */
@@ -1369,6 +1364,8 @@ struct bpf_subprog_info {
 	 * to, see mark_unwind_above(). For a global subprog the bit goes to the next pass.
 	 */
 	bool did_unwind: 1;
+	/* it did so at a site that the program keeps for sure, see site_is_certain() */
+	bool unwinds_for_sure: 1;
 	u8 code_stack_args;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
 	u16 max_out_stack_arg_cnt;
@@ -2018,7 +2015,7 @@ void bpf_flow_put_header_state(struct loop_stack_entry *entry);
 int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 		     int insn_idx, int prev_insn_idx, bool again);
 int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx, u64 *log_pos, u64 *diag_pos);
-int bpf_flow_needs_guard(struct bpf_verifier_env *env, struct bpf_loop *loop);
+void bpf_flow_needs_guard(struct bpf_verifier_env *env, struct bpf_loop *loop);
 int bpf_flow_call(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		  struct bpf_verifier_state *entry, int subprog, int call_idx);
 int bpf_flow_exit(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int exit_idx);
@@ -2026,6 +2023,7 @@ void bpf_flow_next_is_no_bound(struct bpf_verifier_env *env, int insn_idx, int h
 bool bpf_flow_loops_lost_bound(struct bpf_verifier_env *env);
 void bpf_flow_new_pass(struct bpf_verifier_env *env);
 void bpf_flow_drop_guards(struct bpf_verifier_env *env);
+bool bpf_flow_guard_is_guess(struct bpf_verifier_env *env, int idx);
 int bpf_flow_place_guards(struct bpf_verifier_env *env);
 /* verifier.c, for flow.c */
 int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
@@ -2038,6 +2036,7 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 		    const struct bpf_verifier_state *exit, int call_idx);
 int bpf_insert_sites(struct bpf_verifier_env *env);
 void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env);
+bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan);
 bool bpf_insn_is_iter_next(struct bpf_verifier_env *env, struct bpf_insn *insn);
 bool bpf_insn_leaves_loop(struct bpf_verifier_env *env, int h, int n);
 int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
@@ -2057,6 +2056,7 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 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);
 void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan);
+void bpf_pads_mark_used(struct bpf_verifier_env *env);
 int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
 bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan);
@@ -2367,27 +2367,6 @@ const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog);
 int bpf_jmp_offset(struct bpf_insn *insn);
 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
 
-/*
- * Where the program goes from may_goto and from the checks that the verifier adds:
- * - May_goto before a jump goes where the jump goes, with the registers and the stack
- *   as they are before the jump. bpf_insn_successors() has that edge.
- * - A subprog that is out of budget is left at once, see unwind_frame(). No insn of it follows.
- * - May_goto before the header of a loop goes to where the loops around it are left: from
- *   @idx to what is returned here, -1 if there is none. No such edge. The registers and the
- *   stack are what they are before @idx.
- *
- * The main pass looks at the states that go there. What is computed from the graph before
- * the main pass has to take these edges into account where the main pass relies on it:
- * - Against the direction of the edges, liveness: what is live at the target is live at @idx.
- * - In the direction of the edges, bpf_compute_const_regs() and compute_subprog_args(): what
- *   holds on all edges of the graph to the target doesn't hold on this one.
- */
-static inline int bpf_head_guard_target(const struct bpf_verifier_env *env, int idx)
-{
-	const struct bpf_insn_aux_data *aux = &env->insn_aux_data[idx];
-
-	return aux->guard_at_header ? aux->guard_to : -1;
-}
 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
 int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog);
 bool bpf_prog_may_run_in_nmi(const struct bpf_verifier_env *env);
kernel/bpf/const_fold.c +1 -10
index 1a7e521a4b92..1a84ba1d27bf 100644
@@ -253,7 +253,7 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 	struct const_arg_info ci_out[MAX_BPF_REG];
 	struct bpf_iarray *succ;
 	bool changed;
-	int i, r, t, err;
+	int i, r, err;
 
 	/* kvzalloc zeroes memory, so all entries start as CONST_ARG_UNVISITED (0) */
 	env->mem += insn_cnt * sizeof(*ci_in);
@@ -268,15 +268,6 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 		for (r = 0; r < MAX_BPF_REG; r++)
 			ci_in[start][r] = unknown;
 	}
-	/*
-	 * The program gets from the head of a loop to where the loop is left, once the loops are
-	 * known. That is not an edge of the graph.
-	 */
-	for (i = 0; i < insn_cnt; i++) {
-		t = bpf_head_guard_target(env, i);
-		for (r = 0; r < MAX_BPF_REG && t >= 0; r++)
-			ci_in[t][r] = unknown;
-	}
 
 redo:
 	err = bpf_add_cost_and_check(env, env->cfg.cur_postorder * 2ULL, BPF_COST_XREG);
kernel/bpf/failing_path.c +4 -4
index 26469e41f04a..3c7dfb3270f9 100644
@@ -67,10 +67,10 @@ static int compute_hops(struct bpf_verifier_env *env)
 				succ = bpf_insn_successors(env, n);
 				iarray_for_each(t, succ)
 					changed |= shorter_via(prec, n, t);
-				/* see check_loop_guard() and check_recursion_guard() */
-				if (aux->guard_place)
-					changed |= shorter_via(prec, n, aux->guard_to);
-				/* the function is left there, see unwind_frame() */
+				/*
+				 * A frame can leave its function here, see check_loop_guard(),
+				 * check_recursion_guard() and unwind_frame().
+				 */
 				if ((aux->guard_place || (sub[s].cycle && n == sub[s].start)) &&
 				    sub[s].exit_idx != U32_MAX)
 					changed |= shorter(&prec->hops_to_exit[n], 0);
kernel/bpf/fixups.c +44 -37

152 lines not on this page · raw message

kernel/bpf/flow.c +38 -69

206 lines not on this page · raw message

kernel/bpf/liveness.c +0 -14
index 28044f12e9c7..aac5f2860121 100644
@@ -422,7 +422,6 @@ static inline bool update_insn(struct bpf_verifier_env *env, struct func_instanc
 	unsigned long *may_read, *must_write, *live_before;
 	struct frame_masks *fm = instance->frames[frame];
 	u32 rel = relative_idx(instance, insn_idx);
-	int t = bpf_head_guard_target(env, insn_idx);
 	struct bpf_iarray *succ;
 	bool changed = false;
 	u32 s, w;
@@ -450,8 +449,6 @@ static inline bool update_insn(struct bpf_verifier_env *env, struct func_instanc
 	for (w = 0; w < fm->words; w++) {
 		unsigned long new_before = (new_after[w] & ~must_write[w]) | may_read[w];
 
-		if (t >= 0)
-			new_before |= rel_mask(fm, relative_idx(instance, t), before)[w];
 		if (new_before != live_before[w]) {
 			live_before[w] = new_before;
 			changed = true;
@@ -2188,12 +2185,6 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 		memcpy(at_out, at_in[i], sizeof(at_out));
 		memcpy(at_stack_out, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*at_stack_out));
 
-		ti = bpf_head_guard_target(env, idx) - start;
-		if (ti >= 0 && arg_track_join_all(env, idx, start + ti, at_in[ti],
-						  &at_stack_in[(size_t)ti * nslots],
-						  at_out, at_stack_out, nslots))
-			__set_bit(ti, changed);
-
 		arg_track_xfer(env, insn, idx, at_out, at_stack_out, nslots,
 			       at_stack_arg_entry, instance, callsites);
 		arg_track_log(env, insn, idx, at_in[i], &at_stack_in[(size_t)i * nslots], at_out,
@@ -2946,7 +2937,6 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
 			u32 new_out = 0;
 			u32 new_in = 0;
 			u32 use;
-			int t;
 
 			succ = bpf_insn_successors(env, insn_idx);
 			for (int s = 0; s < succ->cnt; ++s)
@@ -2963,10 +2953,6 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
 			if (bpf_is_callx(&insns[insn_idx]))
 				use |= callx_use;
 			new_in = (new_out & ~live->def) | use;
-			/* may_goto that is added at the head of a loop goes there */
-			t = bpf_head_guard_target(env, insn_idx);
-			if (t >= 0)
-				new_in |= state[t].in;
 			if (new_out != live->out || new_in != live->in) {
 				live->in = new_in;
 				live->out = new_out;
kernel/bpf/pads.c +32 -8
index 4e3a7894af84..464e26a67819 100644
@@ -26,8 +26,8 @@
  *      its frame holds to the record of the site (struct bpf_pad_plan). unwind_frame() in
  *      verifier.c does to the state what the pad will do, and the state continues in the caller,
  *      whose call is a site in turn.
- *   2. When a pass ends without an error, bpf_pads_settle() decides for each site whether one
- *      landing pad serves all states that reached it. If none does, that is an error of
+ *   2. When a pass ends without an error, bpf_pads_settle() decides for each site that the program
+ *      keeps whether one pad serves all states that reached it. If none does, that is an error of
  *      the pass, like an insn that the pass could not prove: a later pass that keeps more states
  *      apart may not have it, and if it stays, the program is rejected.
  *   3. After the main pass, bpf_insert_sites() in fixups.c emits the pads after the last insn of
@@ -1380,7 +1380,10 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		[BPF_CONFLICT_NOT_ALWAYS_HELD]	= "a resource is held on some paths only",
 		[BPF_CONFLICT_NO_PLACE]		= "no place has the handle on all paths",
 		[BPF_CONFLICT_ORDER_DIFFERS]	= "the order of the releases differs",
-		[BPF_CONFLICT_CANNOT_UNWIND]	= "the frame cannot unwind",
+		[BPF_CONFLICT_CANNOT_UNWIND]	=
+			"the JIT or the helper that calls the function cannot unwind it",
+		[BPF_CONFLICT_NO_EXIT]		= "the function has no exit",
+		[BPF_CONFLICT_NO_PERFMON]	= "the program is loaded without CAP_PERFMON",
 		[BPF_CONFLICT_CALLER_SAVED]	= "a handle is in R0-R5 only",
 	};
 	int j;
@@ -1401,10 +1404,28 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 	print_plan(env, insn_idx, plan);
 }
 
+/*
+ * Mark the records of the sites that the program keeps ('used'). The main pass cancels states at
+ * more sites than that: the first pass takes the edge of may_goto in every loop that nothing else
+ * stops, and a loop that turns out to have a trip count gets no may_goto. The states that were
+ * cancelled there went on to the callers and were recorded at the calls. Only the records that are
+ * marked here are settled, and what a state found at any other site does not count.
+ */
+void bpf_pads_mark_used(struct bpf_verifier_env *env)
+{
+	struct bpf_pad_plan *plan;
+	int i;
+
+	for (i = 0; i < env->prog->len; i++)
+		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
+			plan->used = bpf_site_is_used(env, i, plan);
+}
+
 /*
  * A pass that counts is over: all states have visited the plans. A state whose visit made a
- * conflict was unproven at the site, see unwind_frame(). A conflict that shows only now is an
- * error of the pass as well, and its site is an unproven insn for the next one, see
+ * conflict ended at the site, see unwind_frame(): as an unproven insn if the program has the site
+ * for sure. A conflict that shows only now, at a site that the program has, is an error of the
+ * pass as well, and its site is an unproven insn for the next one, see
  * bpf_find_unproven_after_pass().
  */
 int bpf_pads_settle(struct bpf_verifier_env *env)
@@ -1424,6 +1445,8 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 		if (env->insn_aux_data[i].pad_plans && bpf_must_abort())
 			return -EINTR;
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
+			if (!plan->used)
+				continue;
 			err = settle_plan(env, plan);
 			if (err < 0)
 				return err;
@@ -1443,12 +1466,12 @@ bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux)
 	const struct bpf_pad_plan *plan;
 
 	for (plan = aux->pad_plans; plan; plan = plan->next)
-		if (plan->conflict)
+		if (plan->used && plan->conflict)
 			return true;
 	return false;
 }
 
-/* The plans of the program */
+/* The plans of the sites that the program has */
 void bpf_pads_log(struct bpf_verifier_env *env)
 {
 	const struct bpf_pad_plan *plan;
@@ -1458,5 +1481,6 @@ void bpf_pads_log(struct bpf_verifier_env *env)
 		return;
 	for (i = 0; i < env->prog->len; i++)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
-			print_plan(env, i, plan);
+			if (plan->used)
+				print_plan(env, i, plan);
 }
kernel/bpf/precision.c +0 -3
index 042ae3ddef92..75e4e25ec7db 100644
@@ -932,9 +932,6 @@ int bpf_compute_deps(struct bpf_verifier_env *env, unsigned long *masks,
 					bitmap_or(in, in, mask_at(env, masks, s, t), bits);
 					held |= test_bit(t, prec->held_insns);
 				}
-				t = bpf_head_guard_target(env, idx);
-				if (t >= 0)
-					bitmap_or(in, in, mask_at(env, masks, s, t), bits);
 				changed |= compute_insn_deps(env, masks, ret, s, idx,
 							     test_bit(idx, seed_insns), in, held);
 				if (idx == prec->loop_carried_at) {
kernel/bpf/verifier.c +76 -99

291 lines not on this page · raw message

tools/testing/selftests/bpf/progs/compute_live_registers.c +2 -6
index f1a0c2187c6c..9a6580bca311 100644
@@ -316,15 +316,11 @@ __naked void gotol(void)
 }
 #endif
 
-/*
- * If the verifier had to add may_goto to this loop it would be at the head, insn 0, and go to
- * insn 3. What is live at 3 is live at 0.
- */
 SEC("socket")
 __log_level(2)
-__msg("0: .1........ (b7) r1 = 1")
+__msg("0: .......... (b7) r1 = 1")
 __msg("1: .1........ (e5) may_goto pc+1")
-__msg("2: .1........ (05) goto pc-3")
+__msg("2: .......... (05) goto pc-3")
 __msg("3: .1........ (bf) r0 = r1")
 __msg("4: 0......... (95) exit")
 __naked void may_goto(void)
tools/testing/selftests/bpf/progs/plain_c_arena_htab.c +2 -0
index 10a50b5058dd..7122815667e9 100644
@@ -184,6 +184,8 @@ char __arena arr1[100000];
 char arr2[1000];
 
 SEC("syscall")
+__arch_x86_64
+__arch_arm64
 __success __retval(0)
 #if !defined(__clang__) && defined(BPF_ARENA_FORCE_ASM)
 __skip("GCC calls htab_init(): a global function gets an arena pointer as a scalar")
tools/testing/selftests/bpf/progs/plain_c_arena_strsearch.c +2 -0
index f05cf023c4d2..ebec872aa9a1 100644
@@ -231,6 +231,8 @@ static const char __arena glob_tests[] =
 	"0" "*ab*cd*\0" "abcabcabcabcefg\0";
 
 SEC("syscall")
+__arch_x86_64
+__arch_arm64
 __success __retval(0) __skip_without_arena
 int arena_strsearch(void *ctx)
 {
tools/testing/selftests/bpf/progs/plain_c_verifier_arena_large.c +2 -0
index 4c5339edb06f..411e9afaa3f3 100644
@@ -54,6 +54,8 @@ __noinline int alloc_pages(int page_cnt, int pages_atonce, bool first_pass,
 }
 
 SEC("syscall")
+__arch_x86_64
+__arch_arm64
 __success __retval(0) __skip_without_arena
 int big_alloc2(void *ctx)
 {
tools/testing/selftests/bpf/progs/verifier_barrier.c +12 -61

96 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_budget.c +5 -7
index a6e1cd22f35b..7f6bb13b5d16 100644
@@ -7,10 +7,10 @@
 /*
  * The verifier adds may_goto to a loop that it cannot count and a check of
  * the stack to a recursive subprog. What the program does when it is out of budget:
- * - it unwinds, frame by frame, up to the main prog or an async callback, which end. The landing
- *   pads that the callers have in the program are verified. Where a caller has none the verifier
- *   adds unwind_goto after the call. What a frame holds takes a landing pad, which it emits.
- * - a frame for which there is no landing pad yet leaves the loop
+ * it unwinds, frame by frame, up to the main prog or an async callback, which end. The landing
+ * pads that the callers have in the program are verified. Where a caller has none the verifier
+ * adds unwind_goto after the call. What a frame holds takes a landing pad, which it emits.
+ * If no landing pad will do the program is rejected.
  *
  * It takes unwinding, per-cpu insns and timed may_goto in JIT. Some of the progs never end
  * on their own.
@@ -924,9 +924,7 @@ __naked void insn_of_dropped_round(void)
 
 /*
  * The loop at 3: spins. It has no jump that every trip goes through, so may_goto is at its head.
- * The first way out of it, from 2: to 1:, is the back edge of the loop at 1:, which
- * has no may_goto of its own: bpf_iter_num_next() stops it. From the head of 3: to 1: there is
- * no bpf_iter_num_next().
+ * The loop at 1: around it has no may_goto of its own: bpf_iter_num_next() stops it.
  */
 SEC("socket")
 __description("budget: may_goto at the head of a loop leaves the loops around it too")
tools/testing/selftests/bpf/progs/verifier_loop_walk.c +2 -0
index cd834d776d8a..0327597a902d 100644
@@ -287,6 +287,8 @@ static __naked __noinline __used int long_loop(void)
  */
 SEC("socket")
 __description("walk: no other try for a loop that is too long")
+__arch_x86_64
+__arch_arm64
 __success __log_level(4) __msg("processed {{[0-9][0-9]}} insns")
 __naked void walk_fails_once(void)
 {
tools/testing/selftests/bpf/progs/verifier_passes.c +1 -1
index 523931868e65..708e35fcceb4 100644
@@ -1544,7 +1544,7 @@ __naked void ctx_moves(void)
 
 /*
  * The verifier can't tell that the loop ends. It adds may_goto, which unwinds the function: no
- * path continues with r7 = 0. Where a subprog cannot unwind may_goto leaves the loop.
+ * path continues with r7 = 0.
  */
 SEC("tc")
 __description("failing_path: no path continues where may_goto ends an infinite loop")
Signature · 1 line
2.53.1-Meta
author maintainer
#23 lore raw

PATCH 23/73 bpf: Record why a callee is cancelled when its call gets no landing pad

In reply to Kumar Kartikeya Dwivedi

Currently, when the verifier cannot generate the landing pad of a call, only the call becomes an unproven insn, and the next pass keeps apart what the call reads. That does not help when the reason is in the callee. A function is verified once for several of its calls, and two calls that each give a loop a trip count can be joined into a state that gives it none:

  static long count(long step, long end)
  {
          long i = 0;
          do i += step; while (i != end);
          return i;

}

  count(1, 1000000);
  count(-1, -999993);

In the join, step is 1 or -1 and end is one of two numbers. Any pair is possible, so the loop gets a may_goto, the calls become sites, and a caller that holds more than a landing pad can release is rejected. Kept apart, neither call can be cancelled. But the calls do not say what to keep apart, because their arguments are constants, and every following pass ends with the same error.

Add bpf_pads_note_causes(). When a pass ends with an error, it starts from each call whose landing pad could not be generated. It walks the callees that were cancelled at that call, and the callees below them, and records two kinds of insns in these functions as causes of the error:

- The conditional jumps that leave a loop which has a may_goto of the verifier. What such a jump reads decides the trip count. The next pass keeps it apart, back to the arguments of the function, so each call of count() is verified with its own values. The jump can be in an inner loop, when the loop that has the may_goto has no exit of its own.
- The calls at which a callee was cancelled. Only the jumps that can skip such a call have a part in the error. So the next pass keeps apart what those jumps read, as it does for a call on the way to an unproven insn. This also covers a callee that fails the stack check of a recursion, which is not an insn that could be recorded.

All causes are recorded in one walk that visits each function once, and the walk is charged to the cost of the load.

---
 include/linux/bpf_verifier.h |   7 ++
 kernel/bpf/pads.c            | 152 +++++++++++++++++++++++++++++++++++
 kernel/bpf/precision.c       |  31 +++++++
 kernel/bpf/verifier.c        |  11 ++-
 4 files changed, 199 insertions(+), 2 deletions(-)
include/linux/bpf_verifier.h +7 -0
index f548d38d8708..76e5a2db3f06 100644
@@ -551,6 +551,7 @@ struct bpf_pad_plan {
 	u8 conflict;			/* enum bpf_pad_conflict */
 	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 */
 	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
@@ -1032,6 +1033,7 @@ struct bpf_loop {
 	bool partitioned;	/* the last partition was for this loop */
 	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
 	bool changed;		/* see flow_forget_loop() */
+	bool guard_is_cause;	/* scratch of bpf_pads_note_causes(): its exits are causes */
 	bool guarded;		/* states take the edges of may_goto */
 	bool was_infinite;	/* at the start of the last path-sensitive run */
 	bool infinite;		/* see failing_path_trip() */
@@ -1366,6 +1368,8 @@ struct bpf_subprog_info {
 	bool did_unwind: 1;
 	/* it did so at a site that the program keeps for sure, see site_is_certain() */
 	bool unwinds_for_sure: 1;
+	/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */
+	bool below_conflict: 1;
 	u8 code_stack_args;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
 	u16 max_out_stack_arg_cnt;
@@ -1948,6 +1952,8 @@ void bpf_note_unproven_insn(struct bpf_verifier_env *env,
 			    const struct bpf_verifier_state *st, u32 idx);
 bool bpf_insn_is_unproven(struct bpf_verifier_env *env);
 void bpf_note_fixups_differ(struct bpf_verifier_env *env);
+void bpf_note_unproven_cause(struct bpf_verifier_env *env, u32 idx);
+void bpf_note_controlled_cause(struct bpf_verifier_env *env, u32 idx);
 void bpf_find_unproven_after_pass(struct bpf_verifier_env *env);
 int bpf_partition_for_pessimized(struct bpf_verifier_env *env);
 void bpf_restore_precision(struct bpf_verifier_env *env);
@@ -2059,6 +2065,7 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 void bpf_pads_mark_used(struct bpf_verifier_env *env);
 int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
+void bpf_pads_note_causes(struct bpf_verifier_env *env);
 bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan);
 void bpf_pads_log(struct bpf_verifier_env *env);
 
kernel/bpf/pads.c +152 -0

158 lines not on this page · raw message

kernel/bpf/precision.c +31 -0
index 75e4e25ec7db..2576ba62da5d 100644
@@ -668,6 +668,37 @@ static void note_unproven_after_pass(struct bpf_verifier_env *env, u32 idx)
 	suspect_loops_of_insn(env, idx);
 }
 
+/*
+ * Record the insn at @idx as a cause of an error that shows at another insn, so that the next pass
+ * keeps apart what it reads. The insn keeps its own error mark only if a state failed there
+ * before. The caller makes sure that the pass is over.
+ */
+void bpf_note_unproven_cause(struct bpf_verifier_env *env, u32 idx)
+{
+	bool failed = test_bit(idx, env->precision->err_insns);
+
+	note_unproven_after_pass(env, idx);
+	if (failed)
+		__set_bit(idx, env->precision->err_insns);
+}
+
+/*
+ * Record the insn at @idx as a cause of an error that shows at another insn, where what the insn
+ * reads does not matter: a call whose callee is cancelled, an access that faults. Only the jumps
+ * that can skip the insn matter. The next pass keeps apart what they read, in the function and in
+ * its callers, as for a call on the way to an unproven insn, see find_calls_to_unproven().
+ */
+void bpf_note_controlled_cause(struct bpf_verifier_env *env, u32 idx)
+{
+	struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, idx);
+
+	if (!sub)
+		return;
+	__set_bit(idx, env->precision->this_pass.call_insns);
+	__set_bit(sub - env->subprog_info, env->precision->this_pass.unproven_funcs);
+	suspect_loops_of_insn(env, idx);
+}
+
 /* check_after_pass() or bpf_pads_settle() found an error. Which insns caused it? */
 void bpf_find_unproven_after_pass(struct bpf_verifier_env *env)
 {
kernel/bpf/verifier.c +9 -2
index 074a5fa4cf13..5636d74dbe0d 100644
@@ -21899,6 +21899,8 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	certain = site_is_certain(env, plan, insn_idx);
 	if (plan->conflict && certain) {
 		bpf_pad_log(env, insn_idx, plan);
+		/* for bpf_pads_note_causes() */
+		plan->failed = true;
 		err = -EINVAL;
 		goto unproven;
 	}
@@ -24136,15 +24138,20 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
 		verbose(env, "pass %u\n", env->pass);
 	bpf_precision_new_pass(env);
 	ret = check_funcs(env, initial);
+	/* Record why callees were cancelled, so that the next pass can keep their calls apart. */
+	if (ret && env->err)
+		bpf_pads_note_causes(env);
 	if (ret || pass_needs_restart(env))
 		return ret;
 	/* a state that never gets to a site makes no conflict there */
 	mark_used_sites(env, initial);
 	ret = check_after_pass(env) ?: bpf_pads_settle(env);
-	if (ret)
+	if (ret) {
 		bpf_find_unproven_after_pass(env);
-	else
+		bpf_pads_note_causes(env);
+	} else {
 		bpf_pads_log(env);
+	}
 	env->err = ret;
 	return ret;
 }
Signature · 1 line
2.53.1-Meta
author maintainer
#24 lore raw

PATCH 24/73 bpf: Record what each call acquires and releases

In reply to Kumar Kartikeya Dwivedi

Currently a landing pad releases what the states at its site say that the frame holds. Where only some of them hold a reference and no NULL test tells them apart, the program is rejected.

For those cases a function is going to get hidden slots: stack slots that the verifier adds to the frame. A store at each call that acquires fills a slot, a store at each call that releases clears it, and the landing pad releases what the slots hold. The verifier emits the stores after the main pass and trusts them, so they have to be right for every execution. The states at a site cannot say where the stores belong: the insn that acquired a reference is not compared when states are joined or pruned, so a state knows only one of the calls that could have acquired it.

Every execution that reaches an insn is covered by a state that the main pass processes at that insn. So record there, at each call, what the call acquires or releases and which register has the pointer (struct bpf_pad_note). Slots go by group: RCU sections, preempt sections, locks and irq flags, and references (pointers, iterators and dynptrs). Where the states at a call disagree, or no store could follow, the function cannot have slots for the group. Nothing reads the records yet.

---
 include/linux/bpf_verifier.h |  51 +++++-
 kernel/bpf/fixups.c          |   2 +
 kernel/bpf/pads.c            | 315 +++++++++++++++++++++++++++++++++--
 kernel/bpf/verifier.c        |  73 ++++++--
 4 files changed, 406 insertions(+), 35 deletions(-)
include/linux/bpf_verifier.h +48 -3
index 76e5a2db3f06..cbfaba7e7628 100644
@@ -566,6 +566,39 @@ struct bpf_pad_plan {
 	u32 pad;
 };
 
+/* The groups of classes. A function has hidden slots for all of a group or for none of it. */
+enum bpf_pad_group {
+	BPF_PAD_GROUP_RCU,	/* BPF_PAD_RCU */
+	BPF_PAD_GROUP_PREEMPT,	/* BPF_PAD_PREEMPT */
+	BPF_PAD_GROUP_LOCKS,	/* locks and irq flags, which are released in order */
+	BPF_PAD_GROUP_REFS,	/* REF_TYPE_PTR: pointers, iterators, dynptrs */
+	BPF_PAD_NR_GROUPS,
+};
+
+/*
+ * What the main pass records at an insn for the hidden slots of its function: what the insn
+ * acquires or releases, and which register has the pointer. It has to hold for all states that
+ * reach the insn, or the function gets no slots for the group.
+ */
+struct bpf_pad_note {
+	/* The insn acquires a resource, or it calls a subprog that returns with one */
+	bool acquires;
+	u8 src;			/* the register that is stored in the slot */
+	u8 held;		/* the most that a frame holds of the group at the insn */
+	struct bpf_pad_ent ent;	/* how a pad releases a slot of the insn, without the offset */
+	/* The insn releases a resource that the frame acquired */
+	bool releases;
+	u8 group;		/* enum bpf_pad_group */
+	u8 reg;			/* the register that has the pointer plus 'delta' */
+	s16 delta;
+};
+
+/* 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;
+	struct bpf_pad_note *note;
+};
+
 struct loop_stack_entry {
 	struct bpf_loop *loop;
 	struct bpf_header_state *header_state;	/* see failing_path_trip() */
@@ -1137,6 +1170,8 @@ struct bpf_insn_aux_data {
 	u64 non_arena_load:1;
 	u64 indirect_target:1; /* if it is an indirect jump target */
 	u64 non_stack_access:1; /* instruction can access non-stack memory */
+	/* a subprog returned here without a pointer to release, and its R0 may not be 0 */
+	u64 call_brings_nothing:1;
 	);
 
 	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
@@ -1204,8 +1239,9 @@ struct bpf_insn_aux_data {
 	struct bpf_loop *loop;
 	/* the call of a callback, or the first insn of a recursive function */
 	struct bpf_loop *callback_loop, *recursion_loop;
-	/* the plans of the sites at this insn that the pass has reached */
+	/* the plans of the sites at this insn that the pass has reached, and its notes */
 	struct bpf_pad_plan *pad_plans;
+	struct bpf_pad_note *pad_note;
 };
 
 /*
@@ -1370,6 +1406,8 @@ struct bpf_subprog_info {
 	bool unwinds_for_sure: 1;
 	/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */
 	bool below_conflict: 1;
+	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
+	u8 no_slots: 4;
 	u8 code_stack_args;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
 	u16 max_out_stack_arg_cnt;
@@ -1563,6 +1601,7 @@ struct bpf_verifier_env {
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_needs_guard() */
 	bool pads_late;			/* a global subprog unwinds: see settle_late_unwinds() */
+	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 */
 	bool new_linear_xreg;		/* see bpf_same_insns_unproven() */
@@ -2052,10 +2091,16 @@ struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_
 struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx,
 				      enum bpf_site_kind kind);
 int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee);
+void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group);
+void bpf_pad_note_acquire(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
+void bpf_pad_note_release(struct bpf_verifier_env *env, int idx);
+void bpf_pad_note_section(struct bpf_verifier_env *env, enum bpf_pad_class class, bool enter);
+void bpf_pad_note_return(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			 const struct bpf_func_state *caller, int call_idx, bool plain);
 void 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_pad_plan **plans, bool save);
-void bpf_pads_free_moved(struct bpf_pad_plan **plans, u32 cnt);
+void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, bool save);
+void bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt);
 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 +2 -0
index 97a885c077ee..ad9b63289d83 100644
@@ -1000,6 +1000,8 @@ void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
 		free_loop(aux_data[i].recursion_loop);
 		aux_data[i].loop = aux_data[i].callback_loop = aux_data[i].recursion_loop = NULL;
 		bpf_pad_plans_free(&aux_data[i]);
+		kfree(aux_data[i].pad_note);
+		aux_data[i].pad_note = NULL;
 	}
 }
 
kernel/bpf/pads.c +299 -16

349 lines not on this page · raw message

kernel/bpf/verifier.c +57 -16

251 lines not on this page · raw message

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

PATCH 25/73 bpf: Add hidden stack slots for landing pads

In reply to Kumar Kartikeya Dwivedi

Currently a program is rejected when neither the program counter nor a NULL test tells a landing pad whether its frame holds a resource:

  t = bpf_task_from_pid(pid);
  own = !!t;
  if (!t)
          t = bpf_get_current_task_btf();
  v = wait(t);                    /* can be cancelled */
  if (own)
          bpf_task_release(t);

At the call of wait(), t points to a task on both paths, and only the program knows what 'own' means. (With clang this shape takes asm.)

Add hidden slots. A hidden slot is a stack slot that the verifier adds below the stack of a function, where no access of the program gets. Stores that the verifier emits on the normal path record in the slot what the frame holds, and the landing pad releases what it finds there. '+' marks what the verifier adds, and ax is BPF_REG_AX:

+ *(u64 *)(r10 - 8) = 0 entry
call bpf_task_from_pid
+ *(u64 *)(r10 - 8) = r0 acquire
...
call wait
+ unwind_goto pad
...
r1 = r6
+ ax = *(u64 *)(r10 - 8); if ax != r1 goto +1 release
+ *(u64 *)(r10 - 8) = 0
call bpf_task_release
...
+ pad: r1 = *(u64 *)(r10 - 8); if r1 == 0 goto +1
+ call bpf_task_release
+ r0 = 0; exit

Each call that acquires has a slot of its own. The slot takes the pointer that the release takes: R0 as it is, or the address of the lock, irq flags, iterator or dynptr. A section has no pointer, and its slot takes 1. A release finds its slot by comparing at run time, because nothing says at load time which call acquired the pointer. The stores follow from what the main pass recorded at each call, never from the states at a site, so joins and pruning stay as they are.

Hidden slots are the fallback. A function gets them for a group of resources only if one of its sites cannot do without them: a resource is held on some paths only and no NULL test tells, a pointer is in R0-R5 only and an earlier call of the pad clobbers it, or the number of sections differs between paths. All pads of the function then release that group through the slots alone. A program that needs no slot gets no store and no byte of stack, so nothing changes for programs that load today.

For each group that has slots, a function pays at run time one store per 8 bytes of slots at its entry, one to four insns at a call that acquires, and four or five insns per slot of the group at a release. On the stack it pays 8 bytes per slot, 16 for bpf_res_spin_lock_irqsave(), and the spills of bpf_fastcall stay in the frame.

Three cases need care:

- A call in a loop can run again while the frame holds what it acquired before. It has one slot more than the frame holds of the group when it gets there, and takes 4k - 1 insns to fill the first free one of k.
- A store after a call follows the unwind_goto, so a frame that is cancelled in the call does not run it.
- Where a release takes the pointer plus an offset, the search for the slot adds the offset in R0, which the call clobbers anyway. The offset is a constant of the program, and a JIT that blinds constants does so for an insn on R0 but not for one on AX.

A site that needs slots still rejects the program when the stack has no room for them, or when the function cannot have slots for the group:

- A callee releases what the frame holds, leaves a section of it, or returns with something to release that is not one pointer in R0.
- The frame holds two locks or sets of irq flags at once. Slots do not record the order of release.
- The reference is a __ref argument of struct_ops, a socket from bpf_map_lookup_elem(), a dynptr that is cloned, or was made from another reference.

---
 include/linux/bpf_verifier.h                  |  30 +-
 kernel/bpf/fixups.c                           |  70 +++-
 kernel/bpf/pads.c                             | 370 +++++++++++++++++-
 kernel/bpf/verifier.c                         |  60 ++-
 .../selftests/bpf/progs/verifier_budget.c     |   2 +-
 .../selftests/bpf/progs/verifier_passes.c     |  13 +-
 6 files changed, 525 insertions(+), 20 deletions(-)
include/linux/bpf_verifier.h +28 -2
index cbfaba7e7628..7027734c315e 100644
@@ -499,6 +499,12 @@ enum bpf_pad_conflict {
 #define BPF_PAD_MAX_INSNS	(BPF_PAD_MAX_ENTS * (2 * BPF_PAD_MAX_ARGS + 2) + \
 				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 3)
 #define BPF_PAD_MAX_CANDS	6
+/*
+ * 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. And the
+ * call.
+ */
+#define BPF_PAD_MAX_SLOT_INSNS	(BPF_PAD_MAX_ENTS * 9 + 1)
 
 /* The kinds of location */
 enum bpf_place_loc {
@@ -553,6 +559,7 @@ struct bpf_pad_plan {
 	bool used;			/* the program keeps the site, see bpf_pads_mark_used() */
 	bool failed;			/* a state made the conflict an error of the pass */
 	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
+	u8 sections_differ;		/* bit per class: the states differ in the number */
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
@@ -577,8 +584,8 @@ enum bpf_pad_group {
 
 /*
  * What the main pass records at an insn for the hidden slots of its function: what the insn
- * acquires or releases, and which register has the pointer. It has to hold for all states that
- * reach the insn, or the function gets no slots for the group.
+ * acquires or releases, and which register has the pointer. The stores are emitted from it, so it
+ * has to hold for all states that reach the insn, or the function gets no slots for the group.
  */
 struct bpf_pad_note {
 	/* The insn acquires a resource, or it calls a subprog that returns with one */
@@ -586,6 +593,8 @@ struct bpf_pad_note {
 	u8 src;			/* the register that is stored in the slot */
 	u8 held;		/* the most that a frame holds of the group at the insn */
 	struct bpf_pad_ent ent;	/* how a pad releases a slot of the insn, without the offset */
+	u8 nr_slots;		/* see subprog_take_slots() */
+	s16 off;		/* the first one, from R10. The others are below it. */
 	/* The insn releases a resource that the frame acquired */
 	bool releases;
 	u8 group;		/* enum bpf_pad_group */
@@ -1408,6 +1417,10 @@ struct bpf_subprog_info {
 	bool below_conflict: 1;
 	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
 	u8 no_slots: 4;
+	/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */
+	u8 slots: 4;
+	/* its hidden slots take that many words of 8 bytes below its stack */
+	u8 hidden_words;
 	u8 code_stack_args;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
 	u16 max_out_stack_arg_cnt;
@@ -1423,6 +1436,12 @@ static inline bool bpf_subprog_unwinds(const struct bpf_subprog_info *sub)
 	return sub->can_unwind || (sub->recursive && sub->bail_unwinds);
 }
 
+/* The stack depth of @sub with its hidden slots */
+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;
+}
+
 static inline u16 bpf_in_stack_arg_cnt(const struct bpf_subprog_info *sub)
 {
 	if (sub->stack_args_from_code)
@@ -2112,6 +2131,13 @@ int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
 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_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 *note,
+			struct bpf_insn *buf);
 void bpf_pads_log(struct bpf_verifier_env *env);
 
 int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *dst_state,
kernel/bpf/fixups.c +66 -4

90 lines not on this page · raw message

kernel/bpf/pads.c +365 -5

426 lines not on this page · raw message

kernel/bpf/verifier.c +58 -2

73 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_budget.c +1 -1
index 7f6bb13b5d16..ddf5f9168c53 100644
@@ -1083,7 +1083,7 @@ SEC("socket")
 __description("budget: a subprog is in a section on some paths")
 __arch_x86_64
 __arch_arm64
-__failure __msg("landing pad of may_goto at {{[0-9]+}}: conflict: the number of sections differs")
+__success __retval(42)
 __naked void unwinds_then_cannot(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/progs/verifier_passes.c +7 -6
index 708e35fcceb4..8b6db6898570 100644
@@ -1842,10 +1842,10 @@ __naked void spilled_iv_is_no_guess(void)
 
 /*
  * With @bound 7 no execution disables preemption. The joined state does, and then the landing
- * pad of may_goto of the loop at 3 has two numbers of sections to leave: a conflict. A pass
- * that keeps r6 apart has none.
+ * pad of may_goto of the loop at 3 has two numbers of sections to leave: it takes them from
+ * hidden slots. A pass that keeps r6 apart has one number.
  * With @bound 8 an execution with r6 == 8 disables preemption, once for each trip of the loop
- * at 2, so the conflict is real.
+ * at 2, and never enables it: the error is real.
  */
 #define GUARD_OF_THE_JOIN(bound)					\
 	asm volatile (							\
@@ -1891,7 +1891,7 @@ __naked void guess_takes_target_of_join(void)
 SEC("tc")
 __description("failing_path: a real state is in a section at may_goto")
 __failure
-__msg("landing pad of may_goto at {{[0-9]+}}: conflict: the number of sections differs")
+__msg("BPF_EXIT instruction in main prog cannot be used inside bpf_preempt_disable-ed region")
 __not_msg("this path has a guess")
 __naked void guess_takes_real_target(void)
 {
@@ -1900,8 +1900,9 @@ __naked void guess_takes_real_target(void)
 
 SEC("tc")
 __description("failing_path: level 2 has the path-sensitive run and the next pass")
-__failure __log_level(2) __msg("path-sensitive run after pass 0") __msg("pass 1")
-__msg("landing pad of may_goto at {{[0-9]+}}: conflict: the number of sections differs")
+__failure __log_level(2) __msg("path-sensitive run after pass 0")
+__msg("BPF_EXIT instruction in main prog cannot be used inside bpf_preempt_disable-ed region")
+__msg("pass 1")
 __naked void guess_in_level_2(void)
 {
 	GUARD_OF_THE_JOIN(8);
Signature · 1 line
2.53.1-Meta
author maintainer
#26 lore raw

PATCH 26/73 bpf: Use hidden slots for a pointer that has no location at a site

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Hidden slots help where a landing pad cannot tell whether a pointer is held. Currently they do not help where the pad cannot find the pointer, because no register or stack slot of the frame holds it at the site:

t = bpf_task_from_pid(1); /* and a NULL check */
t = wait(t); /* can be cancelled, returns t */
bpf_task_release(t);

When the program takes t from R0 after the call, t is in R1 alone at the call. If the kernel cancels the program in wait(), the landing pad after the call has to release t, but the call has clobbered R1-R5. The program is rejected. (With clang this shape takes a wait() that the compiler does not look into, or asm. Otherwise clang keeps t in R6 over the call.)

A hidden slot does not depend on where the program keeps the pointer. So let a pointer without a location ask for hidden slots as well. '+' marks what the verifier adds, and ax is BPF_REG_AX:

+ *(u64 *)(r10 - 8) = 0 entry
call bpf_task_from_pid
+ *(u64 *)(r10 - 8) = r0 acquire
...
r1 = r0
call wait t is in r1 alone
+ unwind_goto pad
r1 = r0
+ ax = *(u64 *)(r10 - 8); if ax != r1 goto +1 release
+ *(u64 *)(r10 - 8) = 0
call bpf_task_release
...
+ pad: r1 = *(u64 *)(r10 - 8); if r1 == 0 goto +1
+ call bpf_task_release
+ r0 = 2; exit TC_ACT_SHOT (tc)

A function gets hidden slots for this only if none of its insns acquires an iterator or a dynptr, see acquires_stack_obj(). The hidden slot of such an object holds its address in the stack of the program, and the landing pad destroys what is at that address. To the verifier an iterator and a dynptr are references like a pointer, so a state that holds a task without a location may stand for a state that holds an iterator at fp-8, which the program may have overwritten since. In a function that acquires neither, such a reference is always a pointer, and its slot holds it.

A function that cannot have hidden slots for references is still rejected.

---
 include/linux/bpf_verifier.h |  1 +
 kernel/bpf/pads.c            | 56 +++++++++++++++++++++++++++++-------
 2 files changed, 47 insertions(+), 10 deletions(-)
include/linux/bpf_verifier.h +1 -0
index 7027734c315e..ae407b6a14ab 100644
@@ -560,6 +560,7 @@ struct bpf_pad_plan {
 	bool failed;			/* a state made the conflict an error of the pass */
 	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
 	u8 sections_differ;		/* bit per class: the states differ in the number */
+	u8 no_place;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
kernel/bpf/pads.c +46 -10

125 lines not on this page · raw message

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

PATCH 27/73 bpf: Restore the sections of the call when a frame is cancelled

In reply to Kumar Kartikeya Dwivedi

Currently a callee that leaves a section of its caller makes the caller hold one section less, also when the callee is cancelled right after:

static void refill(void) /* called with preemption disabled */
{

          while (!idle) ;         /* loop 1 */
          bpf_preempt_enable();   /* drop the lock of the caller */
          while (!ready) ;        /* loop 2 */
          bpf_preempt_disable();  /* take it again */

}

If the kernel cancels refill() in loop 1, the caller is still in its section. In loop 2 it is in none. The pad of the call would have to enable preemption in the first case only, and no hidden slot of the caller can follow what a callee does, so the program is rejected.

Record in each frame how many RCU and preempt sections the state was in when the frame was called, and let the landing pad bring the frame back to that. The pad still leaves the sections that the frame entered, and now enters again the sections of its callers that the frame left: the pad of loop 2 calls bpf_preempt_disable(). A pad reads nothing under a section, so only the count has to be right. The caller is then in the sections of its call wherever the callee was cancelled. A recursive function that leaves the section of its caller loads again as well.

Three cases need care:

- A release may sleep, so the pad enters sections after all of its releases. A frame can also be back in a section of its caller while it holds an iterator whose destructor may sleep. The pad then leaves that section too before the release and enters it again afterwards. Such a release is rejected when the pad cannot do that: the program is not sleepable, a caller holds a lock or irq flags, the frame has never left the section, or it holds the object on some paths only.
- A pointer that no location holds is released through its hidden slot, and the state at the site does not say what releases it. If the pad cannot sleep there (no_place_atomic), none of its releases may sleep.
- A section also protects the RCU pointers of the callers. While the pad releases the pointers, the sections that the frame left are not entered yet. If nothing protects RCU pointers at that point, the main pass no longer trusts the RCU pointers of any frame.

Two cases stay rejected. A function gets no hidden slots for its sections once a callee has left one of them. And a callee that has left a section of its caller on some paths to a site only gets no landing pad there.

---
 include/linux/bpf_verifier.h                  |  17 +-
 kernel/bpf/pads.c                             | 152 ++++++++++++++++--
 kernel/bpf/verifier.c                         |  36 ++++-
 .../selftests/bpf/progs/verifier_barrier.c    |  13 +-
 4 files changed, 186 insertions(+), 32 deletions(-)
include/linux/bpf_verifier.h +16 -1
index ae407b6a14ab..d101bda70824 100644
@@ -558,8 +558,20 @@ 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 */
-	u8 sections[BPF_PAD_NR_SECTIONS]; /* how many of each class the frame has entered */
+	/*
+	 * 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.
+	 */
+	s8 sections[BPF_PAD_NR_SECTIONS];
 	u8 sections_differ;		/* bit per class: the states differ in the number */
+	/*
+	 * A release of the pad may sleep while the frame is in that many sections of its callers.
+	 * The pad leaves them too before it releases pointers, and enters them again afterwards.
+	 */
+	u8 outside[BPF_PAD_NR_SECTIONS];
+	/* a state that set 'no_place' was where the pad cannot sleep, see pad_can_sleep() */
+	bool no_place_atomic;
+	/* enum bpf_pad_conflict: no location has a pointer. No error if a hidden slot has it. */
 	u8 no_place;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
@@ -665,6 +677,9 @@ struct bpf_func_state {
 	u32 entry_refs;
 	u32 entry_rcu_locks;
 	u32 entry_preempt_locks;
+	/* the sections of the state when the frame was called. A landing pad restores them. */
+	u32 call_rcu_locks;
+	u32 call_preempt_locks;
 	struct bpf_retval_range callback_ret_range;
 	bool in_callback_fn;
 	bool in_async_callback_fn;
kernel/bpf/pads.c +136 -16

263 lines not on this page · raw message

kernel/bpf/verifier.c +28 -8
index d168f7b6e677..7681782ef66c 100644
@@ -11452,6 +11452,8 @@ static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int calls
 	callee->entry_refs = state->acquired_refs;
 	callee->entry_rcu_locks = state->active_rcu_locks;
 	callee->entry_preempt_locks = state->active_preempt_locks;
+	callee->call_rcu_locks = state->active_rcu_locks;
+	callee->call_preempt_locks = state->active_preempt_locks;
 	err = set_callee_state_cb(env, caller, callee, callsite);
 	if (err)
 		goto err_out;
@@ -11897,6 +11899,8 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
 	callee->entry_refs = entry.acquired_refs;
 	callee->entry_rcu_locks = entry.active_rcu_locks;
 	callee->entry_preempt_locks = entry.active_preempt_locks;
+	callee->call_rcu_locks = entry.active_rcu_locks;
+	callee->call_preempt_locks = entry.active_preempt_locks;
 
 	account_current_path(env);
 	env->subprog_info[subprog].on_its_own = true;
@@ -21762,14 +21766,17 @@ static bool frame_is_top(const struct bpf_verifier_state *st)
 	       frame->in_exception_callback_fn;
 }
 
-/* The current frame of @st holds resources that it acquired since its entry */
+/*
+ * The current frame of @st holds resources that it acquired since its entry, or it is in other
+ * sections than it was called in: more of them, or fewer, where it has left one of a caller
+ */
 static bool frame_holds_resources(const struct bpf_verifier_state *st)
 {
 	const struct bpf_func_state *frame = st->frame[st->curframe];
 
 	return st->acquired_refs != frame->entry_refs ||
-	       st->active_rcu_locks != frame->entry_rcu_locks ||
-	       st->active_preempt_locks != frame->entry_preempt_locks;
+	       st->active_rcu_locks != frame->call_rcu_locks ||
+	       st->active_preempt_locks != frame->call_preempt_locks;
 }
 
 /*
@@ -21889,12 +21896,13 @@ static void unmark_stack_obj(struct bpf_verifier_env *env, int id)
  * its entry. Do to the current state what the calls of the pad do to it, with the functions that
  * such a call of the program ends up in, and unmark_stack_obj(). The callers may have pointers that
  * are good as long as a lock or a section is held.
+ * @plan: the plan of the site that the state has visited.
  */
-static int release_frame_resources(struct bpf_verifier_env *env)
+static int release_frame_resources(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
 	struct bpf_verifier_state *st = env->cur_state;
 	struct bpf_func_state *frame = cur_func(env);
-	u32 refs = st->acquired_refs;
+	u32 rcu, preempt, refs = st->acquired_refs;
 	struct bpf_reference_state *ref;
 	int id, err;
 
@@ -21917,10 +21925,22 @@ static int release_frame_resources(struct bpf_verifier_env *env)
 	/* A lock is gone, or an object was freed under the lock of a caller who may point to it. */
 	if (st->acquired_refs != refs)
 		invalidate_non_owning_refs(env);
-	st->active_rcu_locks = frame->entry_rcu_locks;
-	st->active_preempt_locks = frame->entry_preempt_locks;
+	/*
+	 * When the pad releases the pointers, it has left the sections of the frame, and those of
+	 * the callers too if a release may sleep ('outside'). It enters the sections of the call
+	 * again only afterwards. If nothing protects RCU pointers in between, they are invalidated.
+	 */
+	rcu = min(st->active_rcu_locks, frame->call_rcu_locks);
+	preempt = min(st->active_preempt_locks, frame->call_preempt_locks);
+	rcu -= min(rcu, plan->outside[BPF_PAD_RCU]);
+	preempt -= min(preempt, plan->outside[BPF_PAD_PREEMPT]);
+	st->active_rcu_locks = rcu;
+	st->active_preempt_locks = preempt;
 	if (!in_rcu_cs(env))
 		invalidate_rcu_protected_refs(env);
+	/* After the pad the caller is in the sections of its call, wherever the callee left. */
+	st->active_rcu_locks = frame->call_rcu_locks;
+	st->active_preempt_locks = frame->call_preempt_locks;
 	return 0;
 }
 
@@ -21998,7 +22018,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	if (plan->conflict)
 		goto out;
 
-	err = release_frame_resources(env);
+	err = release_frame_resources(env, plan);
 	if (err)
 		goto out;
 	bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0],
tools/testing/selftests/bpf/progs/verifier_barrier.c +6 -7
index 302dccd68de9..cb6ae13141ae 100644
@@ -162,17 +162,16 @@ static __naked __noinline __used int recurse_in_frames(void)
 }
 
 /*
- * This prog loads on a kernel where the check of a recursion returns 0 to the caller, which goes on
- * and leaves the section. Here the check unwinds, and no landing pad serves the call in the prog.
- * The function leaves the section of its caller and enters one of its own. When its first check
- * fails the prog is in the section that it entered. When a deeper one does the pad of the function
- * has left the only section there is. A pad is a fixed number of calls, and no store of the prog
- * can count what its callee leaves: a hidden slot follows the insns of its own frame.
+ * The function leaves the section of its caller and enters one of its own. Here the check of the
+ * recursion unwinds. A frame is unwound with the sections of its call, so the prog is in one
+ * section at its call whichever check fails: the first one, when nothing has left the section, or
+ * a deeper one, when the frame in between is in as many sections as it was called in and its pad
+ * has no call. The pad of the prog leaves that one section.
  * Without CAP_PERFMON there is no pad, and no way out of a recursion that is too deep.
  */
 SEC("tc")
 __description("a recursion needs CAP_PERFMON")
-__failure __msg("landing pad of call at 2: conflict: the number of sections differs")
+__success
 SPECULATES
 __failure_unpriv
 __msg_unpriv("landing pad of recursion check at 6: conflict: the program is loaded without CAP_PERFMON")
Signature · 1 line
2.53.1-Meta
author maintainer
#28 lore raw

PATCH 28/73 bpf: Let hidden slots follow what a subprog does for its caller

In reply to Kumar Kartikeya Dwivedi

Currently the stores that keep hidden slots up to date stand next to the insn that acquires or releases. A function gets no slots for a group of resources once a subprog that it calls returns with something other than one pointer in R0, leaves a section of the function or releases a lock of it. So a lock that is taken and dropped through two functions works only where the program counter of the caller tells what is held:

/* returns 0 with irq flags saved and preemption disabled, or -EBUSY */ static int lock(struct lock *l, unsigned long *flags);

  if (flag && lock(l, &flags))
          return 0;
  work(l);                        /* can be cancelled */
  if (flag)
          unlock(l, &flags);

At the call of work() the frame is in the section and has the flags saved on some paths only, and the program is rejected. This is the lock of bpfjailer where the compiler does not inline it.

Let the call stand for what the subprog does, as the call of a kfunc does. The stores are in the caller, after the call, and only a normal return reaches them:

- The subprog returns in one section more: the slot takes 1.
- It returns with irq flags that it saved where an argument of the call
points: the slot takes that address. The argument register is dead after the call, so the address waits in one more hidden word of the function, the pending word, which a store before the call fills.
- It returns with these on some returns only: the stores are under a test of R0. The lower half of R0 has to be 0 on all returns of one kind and not 0 on all others.
- It has left a section that the frame entered, or released the lock or the irq flags that the frame held: the slot is cleared.

The call of lock() becomes this, where '+' marks what the verifier adds:

+ *(u64 *)(r10 - 32) = r2 r2 is &flags: the pending word
call lock
+ if w0 != 0 goto +1
+ *(u64 *)(r10 - 16) = 1 the slot of the section
+ if w0 != 0 goto +2
+ r1 = *(u64 *)(r10 - 32)
+ *(u64 *)(r10 - 24) = r1 the slot of the irq flags

lock() itself can need a slot for the same flags. Its landing pad restores them through their address, which lock() gets in an argument, and the compiler keeps the argument no longer than the function reads it. If lock() can be cancelled after the save, no register or stack slot has the address there. Let such flags ask for hidden slots for the locks of the function, as a pointer that no location holds asks for the slots for
references: the slot of the call that saved the flags has the address. The flags are still in the stack of the caller when the pad runs, because states are joined only if the same stack slots hold irq flags.

Two cases need care:

- A subprog that is cancelled does not get to the stores after its call. Its own landing pad has undone what it acquired and the sections that it left, but not the release of a lock or irq flags of the caller: the slot still has the address. So a frame that has released such a thing for a caller is marked (took_locks), as is every frame between the two. Where a marked frame is cancelled, or returns to a helper or to an unwind_goto, the caller gets no slots for its locks.
- Which argument had the address of the irq flags is asked of the state that returns from the subprog. The subprog has stopped reading its arguments by then, and a state that had something else in that register could have been pruned on the way. So what R1-R5 had at the call, as far as they point to the stack, is part of the join key of the callee.

These cases still rule out slots, and the program is rejected where a landing pad needs them:

- a subprog that returns with a lock other than irq flags, with two pointers or with an iterator,
- a subprog whose R0 does not tell what it returns with, or that releases for its caller on some returns only,
- a subprog that releases a pointer of its caller,
- a function that leaves a section of its caller and needs slots for its own sections.

---
 include/linux/bpf_verifier.h |  78 +++-
 kernel/bpf/fixups.c          |   6 +-
 kernel/bpf/pads.c            | 676 ++++++++++++++++++++++++++++++-----
 kernel/bpf/verifier.c        |  11 +-
 4 files changed, 659 insertions(+), 112 deletions(-)
include/linux/bpf_verifier.h +69 -9
index d101bda70824..b4b19cc605df 100644
@@ -501,10 +501,10 @@ enum bpf_pad_conflict {
 #define BPF_PAD_MAX_CANDS	6
 /*
  * 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. And the
- * call.
+ * BPF_PAD_MAX_ENTS slots, five that compare and clear it and four that find a free one. Three per
+ * group after the call of a subprog, a test of R0 and two for the pending word. And the call.
  */
-#define BPF_PAD_MAX_SLOT_INSNS	(BPF_PAD_MAX_ENTS * 9 + 1)
+#define BPF_PAD_MAX_SLOT_INSNS	(BPF_PAD_MAX_ENTS * 9 + 3 * BPF_PAD_NR_GROUPS + 1)
 
 /* The kinds of location */
 enum bpf_place_loc {
@@ -573,6 +573,7 @@ struct bpf_pad_plan {
 	bool no_place_atomic;
 	/* 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 */
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
@@ -584,6 +585,7 @@ struct bpf_pad_plan {
 	u32 nr_callees;
 	/* the pad starts that many insns after the last insn of the subprog, once it is emitted */
 	u32 pad;
+	u32 bytes;			/* its part of env->mem, see charge_plan() */
 };
 
 /* The groups of classes. A function has hidden slots for all of a group or for none of it. */
@@ -595,12 +597,44 @@ enum bpf_pad_group {
 	BPF_PAD_NR_GROUPS,
 };
 
+/* What the lower half of R0 is on a return of a subprog, see bpf_pad_note_return() */
+enum {
+	BPF_RET_ZERO	= BIT(0),
+	BPF_RET_NONZERO	= BIT(1),
+	BPF_RET_UNKNOWN	= BIT(2),
+};
+
+/* When a store after the call of a subprog runs, see bpf_pad_note_return() */
+enum bpf_pad_cond {
+	BPF_PAD_ALWAYS,
+	BPF_PAD_IF_ZERO,	/* the lower half of R0 is 0 */
+	BPF_PAD_IF_NONZERO,
+};
+
 /*
  * What the main pass records at an insn for the hidden slots of its function: what the insn
  * acquires or releases, and which register has the pointer. The stores are emitted from it, so it
  * has to hold for all states that reach the insn, or the function gets no slots for the group.
+ * The call of a subprog acquires what the subprog returns with, see bpf_pad_note_return().
  */
 struct bpf_pad_note {
+	/* the call of a subprog has one note for each group that the subprog returns with */
+	struct bpf_pad_note *next;
+	/*
+	 * The insn calls a subprog that returns with the resource, and the slot is filled after
+	 * the call. For irq flags, 'src' is the argument that had their address at the call.
+	 */
+	bool by_callee;
+	u8 cond;		/* enum bpf_pad_cond for that store, see subprog_take_slots() */
+	/*
+	 * In the first note of the call of a subprog, by group: BPF_RET_* of the returns with and
+	 * without something of the group, and whether the subprog had released what the frame
+	 * held of the group on some return (takes) and had not on some return (keeps).
+	 */
+	u8 hold_r0[BPF_PAD_NR_GROUPS];
+	u8 nohold_r0[BPF_PAD_NR_GROUPS];
+	u8 takes;
+	u8 keeps;
 	/* The insn acquires a resource, or it calls a subprog that returns with one */
 	bool acquires;
 	u8 src;			/* the register that is stored in the slot */
@@ -654,6 +688,13 @@ static inline bool bpf_trip_is_saved(const struct loop_stack_entry *entry)
 /* state of the program:
  * type of all registers and stack info
  */
+/* What an argument register had when a frame was called. All 0 if it is no such pointer. */
+struct bpf_pad_arg {
+	s16 off;
+	u8 frame;
+	bool stack;	/* a pointer to the stack of 'frame', at the constant offset 'off' */
+};
+
 struct bpf_func_state {
 	struct bpf_reg_state regs[MAX_BPF_REG];
 	/* equal in states that have a join, see bpf_same_join_key() */
@@ -691,6 +732,18 @@ struct bpf_func_state {
 	bool in_rcu_callback_fn;
 	/* parent_id of the args that are gone when this frame returns */
 	u32 frame_id;
+	/*
+	 * 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,
+	 * the function of frame f gets no hidden slots for locks, see took_lock_of_caller().
+	 */
+	u32 took_locks;
+	/*
+	 * What R1-R5 had at the call of the frame, see bpf_pad_note_args(). irq_arg() finds here
+	 * which argument had the address of irq flags that the frame returns with. The registers
+	 * are dead by then and would not be compared, so this is in the join key.
+	 */
+	struct bpf_pad_arg call_args[MAX_BPF_FUNC_REG_ARGS];
 	);
 	bool no_stack_arg_load;
 	/*
@@ -1366,6 +1419,11 @@ struct bpf_subprog_info {
 	u16 stack_extra;
 	u16 arena_stack_depth; /* size of the frame in the stack in arena */
 	u32 cycle; /* the first subprog of its cycle of the call graph, 0 if it is on none */
+	/*
+	 * The pending word: the address of irq flags waits there over the call of a subprog that
+	 * saves them, see bpf_pad_note_return(). An offset from R10, 0: none.
+	 */
+	s16 pend_off;
 	u32 insns_total;
 	u32 insns_self;
 	/* offsets in range [stack_depth .. fastcall_stack_off)
@@ -1435,7 +1493,7 @@ struct bpf_subprog_info {
 	u8 no_slots: 4;
 	/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */
 	u8 slots: 4;
-	/* its hidden slots take that many words of 8 bytes below its stack */
+	/* its hidden slots and words take that many words of 8 bytes below its stack */
 	u8 hidden_words;
 	u8 code_stack_args;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
@@ -1452,7 +1510,7 @@ static inline bool bpf_subprog_unwinds(const struct bpf_subprog_info *sub)
 	return sub->can_unwind || (sub->recursive && sub->bail_unwinds);
 }
 
-/* The stack depth of @sub with its hidden slots */
+/* 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)
 {
 	return round_up(sub->stack_depth, BPF_REG_SIZE) + sub->hidden_words * BPF_REG_SIZE;
@@ -2129,13 +2187,15 @@ int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee);
 void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group);
 void bpf_pad_note_acquire(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
 void bpf_pad_note_release(struct bpf_verifier_env *env, int idx);
+void bpf_pad_note_args(struct bpf_func_state *callee, const struct bpf_func_state *caller);
+size_t bpf_pad_note_free(struct bpf_pad_note *note);
 void bpf_pad_note_section(struct bpf_verifier_env *env, enum bpf_pad_class class, bool enter);
 void bpf_pad_note_return(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			 const struct bpf_func_state *caller, int call_idx, bool plain);
-void bpf_pad_plans_free(struct bpf_insn_aux_data *aux);
+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);
-void bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt);
+size_t bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt);
 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);
@@ -2152,8 +2212,8 @@ int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad
 int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, 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 *note,
-			struct bpf_insn *buf);
+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_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *dst_state,
kernel/bpf/fixups.c +3 -3
index 46ff571ef76e..b3a7f739bde1 100644
@@ -808,7 +808,7 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
 			/* the stores after a call follow the program's unwind_goto */
 			call = i - 1 - (i > sub->start && bpf_is_unwind_goto(insn - 1));
 			if (call >= (int)sub->start && !bpf_is_unwind_goto(insn))
-				n += bpf_pad_insns_after(sub, aux[call].pad_note, &buf[n]);
+				n += bpf_pad_insns_after(sub, notes, nr, aux[call].pad_note, &buf[n]);
 			err = n ? bpf_patch_list_append(env, i - 1, buf, n) : 0;
 			if (err)
 				return err;
@@ -1061,8 +1061,8 @@ void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
 		free_loop(aux_data[i].callback_loop);
 		free_loop(aux_data[i].recursion_loop);
 		aux_data[i].loop = aux_data[i].callback_loop = aux_data[i].recursion_loop = NULL;
-		bpf_pad_plans_free(&aux_data[i]);
-		kfree(aux_data[i].pad_note);
+		env->mem -= bpf_pad_plans_free(&aux_data[i]);
+		env->mem -= bpf_pad_note_free(aux_data[i].pad_note);
 		aux_data[i].pad_note = NULL;
 	}
 }
kernel/bpf/pads.c +580 -96

963 lines not on this page · raw message

kernel/bpf/verifier.c +7 -4
index 7681782ef66c..34238772cc7a 100644
@@ -11454,6 +11454,7 @@ static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int calls
 	callee->entry_preempt_locks = state->active_preempt_locks;
 	callee->call_rcu_locks = state->active_rcu_locks;
 	callee->call_preempt_locks = state->active_preempt_locks;
+	bpf_pad_note_args(callee, caller);
 	err = set_callee_state_cb(env, caller, callee, callsite);
 	if (err)
 		goto err_out;
@@ -11901,6 +11902,7 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
 	callee->entry_preempt_locks = entry.active_preempt_locks;
 	callee->call_rcu_locks = entry.active_rcu_locks;
 	callee->call_preempt_locks = entry.active_preempt_locks;
+	bpf_pad_note_args(callee, NULL);
 
 	account_current_path(env);
 	env->subprog_info[subprog].on_its_own = true;
@@ -21767,14 +21769,15 @@ static bool frame_is_top(const struct bpf_verifier_state *st)
 }
 
 /*
- * The current frame of @st holds resources that it acquired since its entry, or it is in other
- * sections than it was called in: more of them, or fewer, where it has left one of a caller
+ * Does the current frame of @st hold what it acquired since its entry, or is it in other sections
+ * than it was called in? A frame that released a lock of a caller (took_locks) counts too: the
+ * hidden slots of the caller have to learn that, see bpf_pad_visit().
  */
 static bool frame_holds_resources(const struct bpf_verifier_state *st)
 {
 	const struct bpf_func_state *frame = st->frame[st->curframe];
 
-	return st->acquired_refs != frame->entry_refs ||
+	return st->acquired_refs != frame->entry_refs || frame->took_locks ||
 	       st->active_rcu_locks != frame->call_rcu_locks ||
 	       st->active_preempt_locks != frame->call_preempt_locks;
 }
@@ -24116,7 +24119,7 @@ static void free_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *sna
 {
 	if (!snapshot)
 		return;
-	bpf_pads_free_moved(snapshot->pads, env->prog->len);
+	env->mem -= bpf_pads_free_moved(snapshot->pads, env->prog->len);
 	kvfree(snapshot);
 }
 
Signature · 1 line
2.53.1-Meta
author maintainer
#29 lore raw

PATCH 29/73 bpf: Let a callee hold a reference that its call hands over

In reply to Kumar Kartikeya Dwivedi

Currently a reference that a function passes to a static subprog stays with the frame of the caller, and a landing pad releases what its own frame holds. A caller that passes a pointer to a subprog which releases it keeps no copy:

  static void consume(struct task_struct *t)
  {
          while (!ready)
                  ;
          bpf_task_release(t);
  }

  t = bpf_task_from_pid(1);       /* and a NULL check */
  consume(t);

When the loop is out of time, the landing pad of the call has to release t, and no register or stack slot of the caller has t any more. A hidden slot of the caller cannot have it either, because no store of the caller follows the release in consume(). If consume() can be cancelled after its release as well, the pad of the call cannot even tell whether t is still held. Either way the program is rejected, and no pass that keeps more apart changes that.

The subprog has the pointer until it releases it, and each of its sites has a landing pad of its own. So let the call hand the reference over: the callee owns it from its entry, as long as the call lasts. The landing pads of the callee release it, and if the callee returns with it, the caller holds it again. Nothing is added at run time. The pad of the loop above is

pad: r1 = r6

        call bpf_task_release
        r0 = 0
        unwind_exit

and the pad of the call releases nothing. In the main pass, hand_over_refs() moves the reference to the frame of the callee, and such a call is verified in the frames of its caller.

A hand-over can cost a location: a caller that keeps the pointer for the path on which the callee does not release it has one today, and the callee may have none. A program that loads without a hand-over has to load as it did, with the same landing pads. So a hand-over is tried only where the program would be rejected:

- The main pass records which functions release a reference that their caller holds and passed to them in an argument register.
- When a pass fails at the landing pad of a call because no location holds a pointer, or because nothing tells whether a reference is held, the callees of that call that release an argument ask for it.
- When the load would end in a reject, each function that asked owns its argument from the next pass on, see hand_over_more(), and the passes continue.

A call does not hand over a pointer that can be NULL, an iterator or a dynptr, a reference that was made from another one or that another one was made from, or an argument on the stack. It hands nothing over to a recursive subprog or to a callback.

These cases are still rejected:

- The callee has no location for the pointer at one of its sites, or gets to a site with the reference on some paths only.
- The callee or one of its callers needs hidden slots for references. No store follows a reference from one frame to another, so where a call hands over, no function on the stack gets such slots.
- The landing pad of the callee would release under a lock of the caller what the program could not release there.
- The callee leaves with an unwind_exit of the program while it holds the reference. The caller holds it again and has no location for it.

---
 Documentation/bpf/verifier.rst |  72 ++++++++++++++++-
 include/linux/bpf_verifier.h   |  18 +++++
 kernel/bpf/join.c              |   4 +
 kernel/bpf/pads.c              | 143 +++++++++++++++++++++++++++++++--
 kernel/bpf/verifier.c          | 107 ++++++++++++++++++++++--
 5 files changed, 330 insertions(+), 14 deletions(-)
Documentation/bpf/verifier.rst +70 -2
index 21c92b7e829a..03bf363b3d30 100644
@@ -848,8 +848,9 @@ static, in frames   at each call, with the       the state at the exit
 A function that is checked *on its own* has a state without the frames of its
 callers. A static function is checked *in frames* if it can change what its
 callers see: it gets a pointer to the stack, tests a pointer for the caller,
-moves packet data, or releases what the caller holds. A callback is always in
-frames. See ``func_is_on_its_own()``. If only the exit state shows such a
+moves packet data, releases what the caller holds, or owns a reference that its
+call hands over, see `Calls that release for the caller`_. A callback is always
+in frames. See ``func_is_on_its_own()``. If only the exit state shows such a
 change, the call is checked again in frames. An error can ask for frames too,
 see IN_FRAMES in `Partition`_.
 
@@ -976,6 +977,16 @@ things:
   tells. If some do not, the pad tests the location for NULL, as the program
   does. The location has to be 0 in the states that do not hold it.
 
+Where a site has no such location or no such test, the function gets *hidden
+slots*: stack slots that the verifier adds below the stack of the function,
+where no access of the program gets. A store after each call that acquires
+fills a slot, a store at each call that releases clears it, and the landing
+pads of the function release what they find in the slots. These stores are on
+the normal path, so hidden slots are the fallback, and a function gets them
+only for the kind of resource that needs them: RCU sections, preempt sections,
+locks and irq flags, or references. Where no store can follow what happens to a
+resource, the function cannot have slots for that kind.
+
 If the verifier cannot generate one pad for all states at a site, that is an
 error of the pass, like an unproven insn: a later pass that keeps more states
 apart may not have it. If the error stays, the program is rejected, and the log
@@ -983,6 +994,49 @@ says why::
 
   landing pad of may_goto at 7: conflict: the number of sections differs
 
+Calls that release for the caller
+---------------------------------
+
+A static function can release a reference of its caller, and the caller keeps
+no copy of the pointer. When the kernel cancels the program in the callee, the
+landing pad of the call has no location for the pointer. A hidden slot of the
+caller does not help, because no store of the caller follows the release.
+
+The call can *hand* the reference *over*: the callee owns it from its entry, as
+long as the call lasts. The landing pads of the callee release it, and if the
+callee returns with it, the caller holds it again, see ``hand_over_refs()``::
+
+  t = bpf_task_from_pid(pid);           consume:
+  consume(t);                              r6 = r1
+                                        1: ...
+  static void consume(...)                 may_goto pad
+  {                                        if r0 == 0 goto 1b
+          do { ... } while (!p);           r1 = r6
+          bpf_task_release(t);             call bpf_task_release
+  }                                        exit
+                                      pad: r1 = r6
+                                           call bpf_task_release
+                                           r0 = 0
+                                           unwind_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
+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.
+
+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
+the caller what the program could not release there, or if the callee leaves
+with ``unwind_exit`` while it owns the reference.
+
+Where a call hands over, the caller and the functions above it get no hidden
+slots for references: a slot of the caller would keep the pointer that the
+callee releases. The callee gets none either.
+
+A hand-over is tried only where the program would be rejected without it, see
+`All passes`_.
+
 After an error
 ==============
 
@@ -1222,6 +1276,16 @@ The last answer is no in three cases:
 - No partition adds something.
 - The budget is used up.
 
+One more step comes before the REJECT, see ``hand_over_more()``. If the last
+pass with an error failed at a landing pad because of a reference that a callee
+releases for its caller, the passes continue with the limit of the load, and
+calls hand over what that pass asks for.
+
+`Calls that release for the caller`_ explains the hand-over. This is no
+partition: it changes which function releases a reference. So it comes last,
+and a program that loads without it loads as before, with the same landing
+pads.
+
 A pass that is over the limit of the load ends it too. The next chapter explains
 "pessimized".
 
@@ -1551,10 +1615,14 @@ gap                 a value of a join that is in neither state
 good pass           a pass without errors
 guess               a choice that can be wrong and cannot accept an unsafe
                     program
+hand over           a call gives a reference of the caller to the callee, which
+                    owns it as long as the call lasts
 header              the insn where each trip of a loop starts
 held                references, locks, dynptrs, iterators, irq flags
 helped              after a partition the first unproven insn of the last pass
                     has no error, and no old error came back
+hidden slot         a stack slot that the verifier adds to a function, it
+                    records what the frame holds for the landing pads
 id                  the name of a set of xregs that hold copies of one pointer
 imprecise           a state of the pass possibly has values that no path has
 in frames           a function is checked with the frames of its callers
include/linux/bpf_verifier.h +18 -0
index b4b19cc605df..a7ea1433f323 100644
@@ -746,6 +746,11 @@ struct bpf_func_state {
 	struct bpf_pad_arg call_args[MAX_BPF_FUNC_REG_ARGS];
 	);
 	bool no_stack_arg_load;
+	/*
+	 * Per argument register: 1 + the index in refs[] of a reference of the caller that the
+	 * call can hand over, see bpf_pad_handed_ref(). 0 if none. Not compared between states.
+	 */
+	u8 arg_refs[MAX_BPF_FUNC_REG_ARGS];
 	/*
 	 * Unique diagnostic identity for this function invocation. Frame depth is
 	 * reused after returns, while this ID is preserved across state clones.
@@ -1493,6 +1498,16 @@ struct bpf_subprog_info {
 	u8 no_slots: 4;
 	/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */
 	u8 slots: 4;
+	/*
+	 * Bits by argument register, R1 first, see bpf_pad_handed_ref().
+	 * releases_args: it, or a function below it, released a reference that its caller held and
+	 * passed in the register, in some pass so far.
+	 * asks_args: of those, the arguments that the last pass with an error wants handed over.
+	 * owns_args: its call hands the reference over, in every pass from now on.
+	 */
+	u8 releases_args;
+	u8 asks_args;
+	u8 owns_args;
 	/* its hidden slots and words take that many words of 8 bytes below its stack */
 	u8 hidden_words;
 	u8 code_stack_args;
@@ -2188,6 +2203,8 @@ void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group);
 void bpf_pad_note_acquire(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
 void bpf_pad_note_release(struct bpf_verifier_env *env, int idx);
 void bpf_pad_note_args(struct bpf_func_state *callee, const struct bpf_func_state *caller);
+int bpf_pad_handed_ref(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+		       const struct bpf_func_state *caller, int subprog, int regno);
 size_t bpf_pad_note_free(struct bpf_pad_note *note);
 void bpf_pad_note_section(struct bpf_verifier_env *env, enum bpf_pad_class class, bool enter);
 void bpf_pad_note_return(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
@@ -2202,6 +2219,7 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 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);
 void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan);
+void bpf_pad_log_handed_over(struct bpf_verifier_env *env, int subprog, u8 args);
 void bpf_pads_mark_used(struct bpf_verifier_env *env);
 int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
kernel/bpf/join.c +4 -0
index caaf711570a4..c6c250231aca 100644
@@ -218,6 +218,10 @@ static void join_func(struct join *j, struct bpf_func_state *dst, struct bpf_fun
 			 bpf_stack_arg(dst, src, i) ? bpf_stack_arg(src, dst, i) : NULL);
 	dst->no_stack_arg_load |= src->no_stack_arg_load;
 	dst->callback_depth = min(dst->callback_depth, src->callback_depth);
+	/* an argument keeps its reference only if both states agree on it, see hand_over_refs() */
+	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
+		if (dst->arg_refs[i] != src->arg_refs[i])
+			dst->arg_refs[i] = 0;
 }
 
 /*
kernel/bpf/pads.c +138 -5

205 lines not on this page · raw message

kernel/bpf/verifier.c +100 -7

166 lines not on this page · raw message

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

PATCH 30/73 bpf: Let a call clear the hidden slot of what its callee releases

In reply to Kumar Kartikeya Dwivedi

Currently a function gets no hidden slots for references once a static subprog that it calls releases one of them, because no store of the caller follows the release. A hand-over does not help where the caller needs the slot at a site of its own:

        t = bpf_task_from_pid(pid);
        put = put_if(t, x);             /* releases t on some returns */
        do { ... } while (!p);
        if (!put)
                bpf_task_release(t);

At the loop only 'put' says whether the frame still holds t, and the program is rejected.

Let the call stand for the release, as it does for a lock that a callee unlocks. The argument register waits in the pending word of the function over the call. After the call the slot that has the same pointer is cleared, if R0 says that the callee released:

        *(u64 *)(r10 - 16) = r1
        call put_if
        if w0 == 0 goto 1f
        r1 = *(u64 *)(r10 - 16)
        ax = *(u64 *)(r10 - 8)
        if ax != r1 goto 1f
        *(u64 *)(r10 - 8) = 0
     1:

A callee that releases on some returns only has to tell by R0: its lower half is 0 on all returns of one kind and not 0 on all others. The insn that releases gets no stores in the callee.

These are stores on the normal path, which a hand-over does not need, so they come last. Where the passes would end in a reject, try_more() goes through three steps, each when the one before it has nothing more to give:

1. Calls hand over what the last pass with an error asks for, as before.
2. Calls clear hidden slots. Once that is on, it stays on for the load.
3. What was handed over is taken back, once. A callee that owns a reference can be what stands in the way, for example where its landing pad would release under a lock of the caller. The caller then releases out of its hidden slot, and calls hand over again what the following passes ask for.

Steps 2 and 3 are tried only if a callee released a reference that its call had in a register, and the last pass with an error failed at a landing pad that has no location for a reference, cannot tell whether it is held, or can call nothing that releases it. Any other program is rejected as before.

Each step starts a round of passes. A round starts from what is kept apart and ends as soon as the program loads, so a step costs at most about as many passes as the round before it took. A program whose calls hand over again after the take-back pays those rounds a second time.

The caller still gets no slots for references, and is rejected where a landing pad needs them, if:

- the callee does not return to the store after the call: it is cancelled after the release, by itself or in a function that it calls, it leaves with unwind_exit, or a callback is between the caller and the release,
- the call did not have the pointer in one of R1-R5 at offset 0, or the reference is one that a call does not hand over either, such as a pointer that can be NULL,
- R0 does not tell whether the callee released,
- one call releases two references, or also saves irq flags for the
caller: a function has one pending word.

Two more cases need care:

- The frame of the callee records which reference each argument had and which one it has released. That is not part of the join key. The verifier may merge two states that differ in it. A caller that would need the store after such a call then gets no hidden slots for references.
- When the verifier checks a function separately from its callers, a reference released by the function belongs to no frame, and the function gets no slots for its own references in that pass. Only a function that is verified in the frames of its callers on every call releases for its caller and has such slots.

---
 Documentation/bpf/verifier.rst |  61 +++++++--
 include/linux/bpf_verifier.h   |  46 ++++++-
 kernel/bpf/join.c              |   3 +
 kernel/bpf/pads.c              | 229 ++++++++++++++++++++++++++-------
 kernel/bpf/states.c            |   6 +-
 kernel/bpf/verifier.c          |  75 +++++++++--
 6 files changed, 349 insertions(+), 71 deletions(-)
Documentation/bpf/verifier.rst +51 -10
index 03bf363b3d30..d2ea1b4c2a61 100644
@@ -1034,7 +1034,39 @@ Where a call hands over, the caller and the functions above it get no hidden
 slots for references: a slot of the caller would keep the pointer that the
 callee releases. The callee gets none either.
 
-A hand-over is tried only where the program would be rejected without it, see
+A hand-over does not help where the caller needs a hidden slot at a site of its
+own. There the call clears the slot for the callee::
+
+  t = bpf_task_from_pid(pid);           *(u64 *)(r10 - 16) = r1
+  put = put_if(t, x);                   call put_if
+  do { ... } while (!p);                if w0 == 0 goto 1f
+  if (!put)                             r1 = *(u64 *)(r10 - 16)
+          bpf_task_release(t);          ax = *(u64 *)(r10 - 8)
+                                        if ax != r1 goto 1f
+                                        *(u64 *)(r10 - 8) = 0
+                                     1: ...
+
+At the loop only ``put`` says whether the frame still holds ``t``. The argument
+register waits in a hidden word of the caller over the call. After the call the
+slot that has the same pointer is cleared, if ``R0`` says that the callee
+released. A callee that releases on some returns only has to tell by ``R0``:
+its lower half is 0 on all returns of one kind and not 0 on all others.
+
+The caller gets no slots for references, and the program is rejected where a
+landing pad needs them, in these cases:
+
+- The callee does not return to the stores after the call: it is cancelled
+  after the release, by itself or in a function that it calls, it leaves with
+  ``unwind_exit``, or a callback is between the caller and the release.
+- The pointer was not in one of ``R1`` - ``R5`` at offset 0, or the call would
+  not hand the reference over either.
+- ``R0`` does not tell whether the callee released, or the returns of the
+  callee release what was in different registers.
+- One call releases two references, or also saves irq flags for its caller.
+- The verifier merged two states of the callee that differ in what they
+  released or in what the arguments held.
+
+Both are tried only where the program would be rejected without them, see
 `All passes`_.
 
 After an error
@@ -1276,15 +1308,24 @@ The last answer is no in three cases:
 - No partition adds something.
 - The budget is used up.
 
-One more step comes before the REJECT, see ``hand_over_more()``. If the last
-pass with an error failed at a landing pad because of a reference that a callee
-releases for its caller, the passes continue with the limit of the load, and
-calls hand over what that pass asks for.
-
-`Calls that release for the caller`_ explains the hand-over. This is no
-partition: it changes which function releases a reference. So it comes last,
-and a program that loads without it loads as before, with the same landing
-pads.
+One more step comes before the REJECT, see ``try_more()``. If the last pass with
+an error failed at a landing pad because of a reference that a callee releases
+for its caller, the passes continue with the limit of the load. There are three
+steps, each when the one before it has nothing more to give:
+
+1. Calls hand over what the last pass with an error asks for.
+2. Calls clear hidden slots. These are stores on the normal path, so they come
+   after the hand-over.
+3. What was handed over is taken back, once: a callee that owns a reference can
+   be what stands in the way. Calls then hand over again what the passes ask
+   for.
+
+`Calls that release for the caller`_ explains the hand-over and the slots. This
+is no partition: it changes which function releases a reference. So it comes
+last, and a program that loads without it loads as before, with the same
+landing pads. Each step starts a round of passes, which costs at most about as
+many passes as the round before it took. A program whose calls hand over again
+after step 3 pays those rounds a second time.
 
 A pass that is over the limit of the load ends it too. The next chapter explains
 "pessimized".
include/linux/bpf_verifier.h +44 -2

82 lines not on this page · raw message

kernel/bpf/join.c +3 -0
index c6c250231aca..d07019e9e764 100644
@@ -222,6 +222,8 @@ static void join_func(struct join *j, struct bpf_func_state *dst, struct bpf_fun
 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
 		if (dst->arg_refs[i] != src->arg_refs[i])
 			dst->arg_refs[i] = 0;
+	dst->args_off |= src->args_off;
+	dst->took_arg = dst->took_arg ?: src->took_arg;
 }
 
 /*
@@ -239,6 +241,7 @@ int bpf_states_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst
 	env->pkt_pair_cnt = 0;
 	env->imprecise |= !env->err;
 	dst->suspect_loops |= src->suspect_loops;
+	bpf_pad_states_meet(env, dst, src);
 	bpf_equations_pre_join(env, dst, src, leftover_loop, leftover_loop && widen);
 	for (j.fr = 0; j.fr <= dst->curframe; j.fr++)
 		join_func(&j, dst->frame[j.fr], src->frame[j.fr],
kernel/bpf/pads.c +185 -44

356 lines not on this page · raw message

kernel/bpf/states.c +5 -1
index d80262956446..18f82546fa09 100644
@@ -667,5 +667,9 @@ bool bpf_state_subsumes(struct bpf_verifier_env *env, const struct bpf_verifier_
 				       bpf_frame_insn_idx(old, i)))
 			return false;
 
-	return bpf_equations_subsume(env, old, cur);
+	if (!bpf_equations_subsume(env, old, cur))
+		return false;
+	/* @old may stand for @cur from here on, see bpf_pad_states_meet() */
+	bpf_pad_states_meet(env, old, cur);
+	return true;
 }
kernel/bpf/verifier.c +61 -14

105 lines not on this page · raw message

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

PATCH 31/73 bpf: Give a callee a hidden slot for the reference that it is handed

In reply to Kumar Kartikeya Dwivedi

Currently a function that owns a reference which its call hands over gets no hidden slots for references, because no insn of the function fills a slot with the pointer. So a callee is rejected when it can be cancelled where its paths with and without the reference meet, or where no register or stack slot has the pointer:

        static int consume(struct task_struct *t, bool put)
        {
                if (put)
                        bpf_task_release(t);
                do { ... } while (!p);
                return put;
        }

Give such a function one more slot, which its entry fills from the argument register. Its release clears the slot like any other, and its landing pads release through the slots:

        consume:
                *(u64 *)(r10 - 8) = r1
                ...
        pad:    r1 = *(u64 *)(r10 - 8)
                if r1 == 0 goto 1f
                call bpf_task_release
             1: ...

The store at the entry runs however the function is entered. So the function still gets no slots for references, and is rejected where it needs them, if it is entered anywhere with nothing to hand over:

- by a call that passes a pointer which the caller does not hold,
- by a call that is verified separately from its callers,
- as a callback or as an exception callback.

A hand-over is no longer free at run time for such a callee. It stores each argument that it owns at its entry, and its release of one clears the slot. A callee that needs no hidden slots pays nothing, as before.

The caller and the frames above it get no slots for references, as before:
a slot of the caller would keep the pointer that the callee releases. If the callee passes the pointer on to a function that releases it, that call clears the slot which the entry filled, like any other slot of its caller.

---
 Documentation/bpf/verifier.rst |  6 ++-
 include/linux/bpf_verifier.h   |  7 +++
 kernel/bpf/pads.c              | 92 +++++++++++++++++++++++++++-------
 kernel/bpf/verifier.c          | 77 +++++++++++++++-------------
 4 files changed, 129 insertions(+), 53 deletions(-)
Documentation/bpf/verifier.rst +5 -1
index d2ea1b4c2a61..447df36c380b 100644
@@ -1032,7 +1032,11 @@ with ``unwind_exit`` while it owns the reference.
 
 Where a call hands over, the caller and the functions above it get no hidden
 slots for references: a slot of the caller would keep the pointer that the
-callee releases. The callee gets none either.
+callee releases. The callee can have them. Its entry then stores the argument
+register in one more slot, however the function is entered. So the callee gets
+no such slots if it is entered anywhere with nothing to hand over: as a
+callback, by a call that is checked on its own, or with a pointer that the
+caller does not hold.
 
 A hand-over does not help where the caller needs a hidden slot at a site of its
 own. There the call clears the slot for the callee::
include/linux/bpf_verifier.h +7 -0
index 0f68e01ce036..79b0d5f7d4fa 100644
@@ -658,6 +658,11 @@ struct bpf_pad_note {
 	u8 keep_r0: 2;
 	/* The insn releases a reference of a caller of the frame, see took_ref_of_caller() */
 	u8 for_caller: 1;
+	/*
+	 * A note of the first insn of a function: its call hands over the reference in R'src', and
+	 * a store at the first insn fills the slot, see bpf_pad_note_entry()
+	 */
+	u8 entry: 1;
 };
 
 /* The plans and the notes of an insn in the snapshot of a pass, see bpf_pads_move() */
@@ -2241,6 +2246,8 @@ int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee);
 void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group);
 void bpf_pad_note_acquire(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
 void bpf_pad_note_release(struct bpf_verifier_env *env, int idx);
+void bpf_pad_note_entry(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			int regno, int idx);
 bool bpf_pad_reg_is_handle(const struct bpf_reg_state *reg, const struct bpf_reference_state *ref);
 void bpf_pad_states_meet(struct bpf_verifier_env *env, const struct bpf_verifier_state *a,
 			 const struct bpf_verifier_state *b);
kernel/bpf/pads.c +75 -17

157 lines not on this page · raw message

kernel/bpf/verifier.c +42 -35

131 lines not on this page · raw message

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

PATCH 32/73 bpf: Give unwind_goto a 32 bit offset and prepare it for arena accesses

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a program that faults in an access to arena continues: the fault handler skips the access. The kernel is going to cancel the program there instead. An access to arena will get an unwind_goto after it, like a call, and a fault will go to the landing pad that the unwind_goto names. Nothing emits unwind_goto after an access yet. Three things have to change first.

unwind_goto has 16 bits for its offset. A landing pad stands after the last insn of its function, so it can be more than 32767 insns away. The patch list then relaxes unwind_goto like any conditional jump:

today with this change
call foo call foo
unwind_goto +1 ---. unwind_goto pad
goto +1 | r6 = r0
gotol pad <-------'
r6 = r0

unwind_goto itself is no code, only an exception table entry. 'goto +1' is code that runs each time the call returns, and after an access to arena it would run at each access. Add a second form of the insn: BPF_JMP32 | BPF_JCOND with BPF_UNWIND_GOTO in src_reg and the offset in imm, as in gotol. The unwind_goto that the verifier adds has this form, and bpf_jmp_offset() returns the offset of either form. A program cannot use the new form: the verifier rejects it with "unknown opcode e6". The unwind_goto of a program keeps its 16 bits.

The pass that zero extends 32 bit results appends insns to the insn that writes the result, such as 'w0 = w0' after a cmpxchg. They would stand between an access and its unwind_goto. A JIT keys the exception table entry of unwind_goto at the end of the native code of the insn before it, so a fault in the access would not find the entry, and the access would be skipped. Put the appended insns after unwind_goto. The landing pad does not need them: an access that faults has not written the register.

jit_subprogs() counts the exception table entries of unwind_goto, but it runs only for a program with subprogs. An access to arena needs no callee, and a program of one function would fail to load. Count unwind_goto in bpf_convert_ctx_accesses() as well.

---
 arch/arm64/net/bpf_jit_comp.c |  5 +++--
 arch/x86/net/bpf_jit_comp.c   |  6 ++++--
 include/linux/bpf_verifier.h  |  1 -
 include/linux/filter.h        | 14 +++++++++++++-
 kernel/bpf/core.c             |  4 ++--
 kernel/bpf/disasm.c           |  4 ++++
 kernel/bpf/fixups.c           | 28 +++++++++++++++++++++++-----
 kernel/bpf/liveness.c         |  9 ---------
 8 files changed, 49 insertions(+), 22 deletions(-)
arch/arm64/net/bpf_jit_comp.c +3 -2
index fe41871e3d1c..00667ce5303c 100644
@@ -1768,7 +1768,7 @@ static int build_landings(struct jit_ctx *ctx)
 		}
 		k++;
 		emit(A64_MOV(1, bpf2a64[BPF_REG_0], A64_R(0)), ctx);
-		jmp_offset = ctx->offset[i + 1 + insn->off] - ctx->idx;
+		jmp_offset = ctx->offset[i + 1 + bpf_jmp_offset(insn)] - ctx->idx;
 		check_imm26(jmp_offset);
 		emit(A64_B(jmp_offset), ctx);
 	}
@@ -2455,9 +2455,10 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		break;
 	/* unwind_goto. The verifier expanded may_goto. */
 	case BPF_JMP | BPF_JCOND:
+	case BPF_JMP32 | BPF_JCOND:
 	{
 		int ret_addr = ctx->idx - 1;
-		int target = ctx->offset[i + 1 + off];
+		int target = ctx->offset[i + 1 + bpf_jmp_offset(insn)];
 
 		/*
 		 * 'bl foo; mov x8, x0' is in front. After the call of a subprog
arch/x86/net/bpf_jit_comp.c +4 -2
index 4a934bab9c79..4d4dd004df20 100644
@@ -3491,9 +3491,11 @@ 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:
 			if (!after_call_len) {
 				err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
-							 addrs[i - 1], addrs[i + insn->off]);
+							 addrs[i - 1],
+							 addrs[i + bpf_jmp_offset(insn)]);
 				if (err)
 					return err;
 				break;
@@ -3515,7 +3517,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			EMIT2(0xEB, after_call_len + 5);
 			memcpy(prog, after_call, after_call_len);
 			prog += after_call_len;
-			EMIT1_off32(0xE9, addrs[i + insn->off] -
+			EMIT1_off32(0xE9, addrs[i + bpf_jmp_offset(insn)] -
 					  (addrs[i - 1] + 2 + after_call_len + 5));
 			break;
 
include/linux/bpf_verifier.h +0 -1
index 79b0d5f7d4fa..f03ecb8fe288 100644
@@ -2585,7 +2585,6 @@ 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);
 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog);
-int bpf_jmp_offset(struct bpf_insn *insn);
 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
 
 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
include/linux/filter.h +13 -1
index 5e30a4e70660..5e71c55f3307 100644
@@ -295,9 +295,21 @@ static inline bool insn_is_mov_percpu_addr(const struct bpf_insn *insn)
 		.off   = 0,					\
 		.imm   = 1 })
 
+/* gotol, and unwind_goto that the verifier adds, have 32 bits for the offset */
+static inline bool bpf_jmp_offset_is_imm(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_JMP32 | BPF_JA) || insn->code == (BPF_JMP32 | BPF_JCOND);
+}
+
+static inline int bpf_jmp_offset(const struct bpf_insn *insn)
+{
+	return bpf_jmp_offset_is_imm(insn) ? insn->imm : insn->off;
+}
+
 static inline bool bpf_is_unwind_goto(const struct bpf_insn *insn)
 {
-	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_UNWIND_GOTO;
+	return (insn->code == (BPF_JMP | BPF_JCOND) || insn->code == (BPF_JMP32 | BPF_JCOND)) &&
+	       insn->src_reg == BPF_UNWIND_GOTO;
 }
 
 static inline bool bpf_is_unwind_exit(const struct bpf_insn *insn)
kernel/bpf/core.c +2 -2
index 87262e4d4c0c..737db347de97 100644
@@ -399,8 +399,8 @@ static bool insn_get_rel(const struct bpf_insn *insn, s64 *rel, bool *is_imm)
 	    code == (BPF_JMP | BPF_TAIL_CALL) || code == (BPF_JMP | BPF_JA | BPF_X))
 		return false;
 
-	*is_imm = code == (BPF_JMP32 | BPF_JA);
-	*rel = *is_imm ? insn->imm : insn->off;
+	*is_imm = bpf_jmp_offset_is_imm(insn);
+	*rel = bpf_jmp_offset(insn);
 	return true;
 }
 
kernel/bpf/disasm.c +4 -0
index 2e377a7ea262..43aa0656a588 100644
@@ -404,6 +404,10 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 			   insn->src_reg == BPF_UNWIND_GOTO) {
 			verbose(cbs->private_data, "(%02x) unwind_goto pc%+d",
 				insn->code, insn->off);
+		} else if (insn->code == (BPF_JMP32 | BPF_JCOND) &&
+			   insn->src_reg == BPF_UNWIND_GOTO) {
+			verbose(cbs->private_data, "(%02x) unwind_goto pc%+d",
+				insn->code, insn->imm);
 		} else if (insn->code == (BPF_JMP32 | BPF_JA)) {
 			verbose(cbs->private_data, "(%02x) gotol pc%+d",
 				insn->code, insn->imm);
kernel/bpf/fixups.c +23 -5
index b3a7f739bde1..89a6bd52ef35 100644
@@ -738,10 +738,13 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
  * between a call and its unwind_goto, and jumps to the insn that follows the call go past it.
  * The pads are in the program: a call that has may_goto before it would need two jumps of one
  * patch, see bpf_patch_list_jump(). @added: how many insns the pads after each subprog have.
+ *
+ * unwind_goto is no code, the jumps that take a conditional jump to a target that is too far for
+ * 16 bits would be, see patch_image_relax(). So it has 32 bits for the offset.
  */
 static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 {
-	struct bpf_insn unwind_goto = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);
+	struct bpf_insn unwind_goto = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	struct bpf_patch_list *pl = &env->patch_list;
 	const struct bpf_subprog_info *sub;
@@ -1095,7 +1098,7 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 	int i;
 
 	for (i = 0; i < insn_cnt; i++, insn++) {
-		unwinds = bpf_is_unwind_goto(insn) && aux_data[i + 1 + insn->off].seen;
+		unwinds = bpf_is_unwind_goto(insn) && aux_data[i + 1 + bpf_jmp_offset(insn)].seen;
 		calls = (bpf_pseudo_call(insn) || bpf_is_callx(insn)) && aux_data[i].seen;
 		/*
 		 * The callee never exits. Its unwind_exit needs unwind_goto all the same.
@@ -1428,7 +1431,7 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
 	struct bpf_insn *zext_patch = env->insn_buf;
 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	int i, patch_len, len = env->prog->len;
+	int i, err, patch_len, len = env->prog->len;
 	struct bpf_insn *insns = env->prog->insnsi;
 	bool rnd_hi32;
 
@@ -1503,6 +1506,16 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
 		patch = zext_patch;
 		patch_len = 2;
 apply_patch_buffer:
+		/*
+		 * Nothing stands between an insn and its unwind_goto. On the way to the
+		 * landing pad the insn has not written the register.
+		 */
+		if (bpf_is_unwind_goto(&insns[i + 1])) {
+			err = bpf_patch_list_insert(env, i + 2, patch + 1, patch_len - 1);
+			if (err)
+				return err;
+			continue;
+		}
 		patch = bpf_patch_list_add(env, i, patch, patch_len);
 		if (IS_ERR(patch))
 			return PTR_ERR(patch);
@@ -1673,6 +1686,10 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
 			env->prog->aux->num_exentries++;
 			continue;
+		} else if (bpf_is_unwind_goto(insn)) {
+			/* jit_subprogs() counts them too, but only for a prog with subprogs */
+			env->prog->aux->num_exentries++;
+			continue;
 		} else if (insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW) &&
 			   insn->imm == BPF_LOAD_ACQ &&
 			   env->insn_aux_data[i].arena_member) {
@@ -3508,9 +3525,10 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	int reg_loop_ctx = BPF_REG_8;
 	struct bpf_insn *unwind_goto = &env->prog->insnsi[position + 1];
 	bool has_unwind_goto = bpf_is_unwind_goto(unwind_goto);
+	int pad_off = bpf_jmp_offset(unwind_goto);
 	bool pad = has_unwind_goto &&
 		   bpf_subprog_unwinds(&env->subprog_info[callback_subprogno]) &&
-		   env->insn_aux_data[position + 2 + unwind_goto->off].seen;
+		   env->insn_aux_data[position + 2 + pad_off].seen;
 
 	struct bpf_insn *insn_buf = env->insn_buf;
 	struct bpf_insn *last;
@@ -3582,7 +3600,7 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	 */
 	if (pad)
 		bpf_patch_list_jump(&env->patch_list, last - (cnt - 1 - 6),
-				    position + 2 + unwind_goto->off, 0);
+				    position + 2 + pad_off, 0);
 	/* The unwind_goto after the call of bpf_loop follows no call anymore. */
 	if (has_unwind_goto)
 		*unwind_goto = BPF_JMP_A(0);
kernel/bpf/liveness.c +0 -9
index aac5f2860121..a7120ecb0e80 100644
@@ -322,15 +322,6 @@ static int mark_stack_mask(struct func_instance *instance, u32 frame, u32 insn_i
 	return 0;
 }
 
-int bpf_jmp_offset(struct bpf_insn *insn)
-{
-	u8 code = insn->code;
-
-	if (code == (BPF_JMP32 | BPF_JA))
-		return insn->imm;
-	return insn->off;
-}
-
 __diag_push();
 __diag_ignore_all("-Woverride-init", "Allow field initialization overrides for opcode_info_tbl");
 
Signature · 1 line
2.53.1-Meta
author maintainer
#33 lore raw

PATCH 33/73 bpf, x86: Go to the landing pad when an access to arena faults

In reply to Kumar Kartikeya Dwivedi

Currently ex_handler_bpf() skips an access to arena that faults. It reports the fault to the stream of the program, clears the destination register of a load and resumes after the access. Add what the x86-64 JIT and the fault handler need to cancel the program there instead. The verifier does not add unwind_goto after an access yet, so no program changes.

An access to arena already has an exception table entry, which tells the handler how to skip it. unwind_goto after the access is a second entry and no code. Its key is the last byte of the native code of the access, E - 1, as after a call it is the return address minus one:

      r1 = *(u64 *)(r7 + 8)    mov rdi, [r13 + r12 + 8]   <- S
      unwind_goto pad          no code                    <- E
    the table entry of the access     { S, E - S, rdi, r13, 8 }
    the table entry of unwind_goto    { E - 1, pad - E }

At a fault ex_handler_bpf() calls the new bpf_arena_fault(), which reports the fault as before and returns where the program continues. If E - 1 has an entry of unwind_goto, that is the landing pad: R0-R9 stay as they are, and the report ends with ". The program is unwound". Otherwise it is E, and the access is skipped as today.

bpf_arena_fault() looks the entry up with the new bpf_fault_unwind_target(). bpf_unwind_target() does not fit, because it warns when it finds no entry, and after an access a missing entry is no bug. The generic version returns E, so arm64 keeps skipping until its JIT gets the same.

Two cases need care:

- The landing pad has to get the registers as they were before the access. An access is one native insn, which writes nothing when it faults. A fetching AND, OR or XOR is the exception. It is a cmpxchg loop that keeps R0 in r10 (BPF_REG_AX) while rax serves the cmpxchg, and its last insn puts R0 back. Today the handler resumes at that insn. Now both table entries of the loop give its end as E, and a new bit in them, R0_IN_AX, tells the handler to copy r10 to rax itself.
- After a call the JIT may emit a landing for unwind_goto, which redoes what follows the native call. After an access there is nothing to redo, so unwind_goto is the exception table entry alone.

---
 arch/arm64/net/bpf_jit_comp.c |  2 +-
 arch/x86/net/bpf_jit_comp.c   | 97 +++++++++++++++++++++--------------
 include/linux/bpf.h           |  8 +--
 include/linux/filter.h        |  1 +
 kernel/bpf/arena.c            | 25 ++++++---
 kernel/bpf/core.c             | 10 ++++
 6 files changed, 92 insertions(+), 51 deletions(-)
arch/arm64/net/bpf_jit_comp.c +1 -1
index 00667ce5303c..d1bf402bc42b 100644
@@ -1595,7 +1595,7 @@ bool ex_handler_bpf(const struct exception_table_entry *ex,
 
 	if (is_arena) {
 		addr = regs->regs[arena_reg] + off;
-		bpf_prog_report_arena_violation(is_write, addr, regs->pc);
+		bpf_arena_fault(is_write, addr, regs->pc, regs->pc + AARCH64_INSN_SIZE);
 	}
 
 	if (dst_reg != DONT_CLEAR)
arch/x86/net/bpf_jit_comp.c +58 -39

210 lines not on this page · raw message

include/linux/bpf.h +5 -3
index 915034e8acc2..f7ac105d9dd3 100644
@@ -3511,7 +3511,8 @@ void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
 		     enum bpf_dynptr_type type, u32 offset, u32 size);
 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);
-void bpf_prog_report_arena_violation(bool write, unsigned long addr, unsigned long fault_ip);
+unsigned long bpf_arena_fault(bool write, unsigned long addr, unsigned long fault_ip,
+			      unsigned long end);
 
 static __always_inline u32
 bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
@@ -3856,9 +3857,10 @@ static inline void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
 {
 }
 
-static inline void bpf_prog_report_arena_violation(bool write, unsigned long addr,
-						   unsigned long fault_ip)
+static inline unsigned long bpf_arena_fault(bool write, unsigned long addr,
+					    unsigned long fault_ip, unsigned long end)
 {
+	return end;
 }
 #endif /* CONFIG_BPF_SYSCALL */
 
include/linux/filter.h +1 -0
index 5e71c55f3307..3ce4609af05f 100644
@@ -1412,6 +1412,7 @@ bool bpf_jit_supports_kfunc_ret_reg_pair(void);
 bool bpf_jit_supports_unwind(void);
 bool bpf_jit_supports_hmul(void);
 u64 bpf_unwind_target(u64 ret_addr);
+u64 bpf_fault_unwind_target(u64 end);
 bool bpf_jit_supports_stack_args(void);
 bool bpf_jit_supports_arena_args(void);
 bool bpf_jit_supports_far_kfunc_call(void);
kernel/bpf/arena.c +17 -8
index 1c118f3da5a4..2890c65ad26a 100644
@@ -1399,7 +1399,8 @@ static int __init kfunc_init(void)
 late_initcall(kfunc_init);
 
 static void __bpf_prog_report_arena_violation(struct bpf_prog *prog, bool write,
-					      unsigned long addr, unsigned long fault_ip)
+					      unsigned long addr, unsigned long fault_ip,
+					      bool unwound)
 {
 	struct bpf_stream_stage ss;
 	u64 user_vm_start;
@@ -1411,8 +1412,9 @@ static void __bpf_prog_report_arena_violation(struct bpf_prog *prog, bool write,
 	addr += clear_lo32(user_vm_start);
 
 	bpf_stream_stage(ss, prog, BPF_STDERR, ({
-		bpf_stream_printk(ss, "ERROR: Arena %s access at unmapped address 0x%lx\n",
-				  write ? "WRITE" : "READ", addr);
+		bpf_stream_printk(ss, "ERROR: Arena %s access at unmapped address 0x%lx%s\n",
+				  write ? "WRITE" : "READ", addr,
+				  unwound ? ". The program is unwound" : "");
 		bpf_stream_dump_stack(ss);
 	}));
 }
@@ -1450,7 +1452,7 @@ bool bpf_arena_handle_page_fault(unsigned long addr, bool is_write, unsigned lon
 
 	if (prog && prog->aux->arena == arena)
 		__bpf_prog_report_arena_violation(prog, is_write,
-						  page_addr - kbase, fault_ip);
+						  page_addr - kbase, fault_ip, false);
 	else if (__ratelimit(&rs))
 		printk_deferred(KERN_ERR "BPF arena %u: %s fault at offset 0x%lx, IP %pS\n",
 				arena->map.id, is_write ? "WRITE" : "READ",
@@ -1461,8 +1463,15 @@ bool bpf_arena_handle_page_fault(unsigned long addr, bool is_write, unsigned lon
 	return handled;
 }
 
-void bpf_prog_report_arena_violation(bool write, unsigned long addr, unsigned long fault_ip)
+/*
+ * JITed code faulted at @fault_ip, in an access to arena at @addr. The code of the BPF insn ends at
+ * @end. Report it. Returns where the program goes on: at the landing pad when unwind_goto follows
+ * the insn, else at @end: the access is skipped.
+ */
+unsigned long bpf_arena_fault(bool write, unsigned long addr, unsigned long fault_ip,
+			      unsigned long end)
 {
+	unsigned long pad = bpf_fault_unwind_target(end);
 	struct bpf_prog *prog;
 
 	/*
@@ -1473,7 +1482,7 @@ void bpf_prog_report_arena_violation(bool write, unsigned long addr, unsigned lo
 	rcu_read_lock();
 	prog = bpf_prog_ksym_find(fault_ip);
 	rcu_read_unlock();
-	if (!prog)
-		return;
-	__bpf_prog_report_arena_violation(prog, write, addr, fault_ip);
+	if (prog)
+		__bpf_prog_report_arena_violation(prog, write, addr, fault_ip, pad != end);
+	return pad;
 }
kernel/bpf/core.c +10 -0
index 737db347de97..0f7199c5c1b8 100644
@@ -3845,6 +3845,16 @@ u64 __weak bpf_unwind_target(u64 ret_addr)
 	return ret_addr;
 }
 
+/*
+ * Where the program continues after a fault in an access to arena whose native code ends at @end:
+ * at the target of the unwind_goto after the access, or at @end, which skips the access. A JIT
+ * that cancels the program at a fault overrides this.
+ */
+u64 __weak bpf_fault_unwind_target(u64 end)
+{
+	return end;
+}
+
 /*
  * How this arch places a by-value kfunc argument, or NULL for one that has
  * not opted in and so only takes an argument of a single eightbyte, which
Signature · 1 line
2.53.1-Meta
author maintainer
#34 lore raw

PATCH 34/73 bpf, arm64: Go to the landing pad when an access to arena faults

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently the arm64 fault handler skips an access to arena that faults, whether unwind_goto follows the access or not. Do what the x86-64 JIT
does: unwind_goto after an access is an exception table entry and no code, and ex_handler_bpf() looks for it at the last byte of the native code of the access, E - 1:

r1 = *(u64 *)(r7 + 8) add x11, x28, #8
ldr x0, [x11, w20, uxtw] <- S
unwind_goto pad no code <- E

the table entry of unwind_goto { E - 1, pad - E }

with that entry pc = pad R0-R9 stay as they are
without it x0 = 0; pc = E the access is skipped, as today

E is S + 4. In every form of an access the native insn that can fault is the last one, and the insns before it write only temporaries. So the landing pad gets R0-R9 and the stack as they were before the access. LL/SC atomics are refused in arena.

The key is not where it is after a call. After a call it is the return address of 'bl' minus one, and 'mov x8, x0' follows 'bl', so the key is one insn back from the end of the code. After an access it is the last byte of the code.

The arm64 bpf_fault_unwind_target() does not warn when it finds no entry:
that only means that no unwind_goto follows the access. The verifier adds none yet, so no program changes.

---
 arch/arm64/net/bpf_jit_comp.c | 35 +++++++++++++++++++++++++++++------
 1 file changed, 29 insertions(+), 6 deletions(-)
arch/arm64/net/bpf_jit_comp.c +29 -6
index d1bf402bc42b..730f9d95bca1 100644
@@ -1591,17 +1591,21 @@ bool ex_handler_bpf(const struct exception_table_entry *ex,
 	int arena_reg = FIELD_GET(BPF_FIXUP_ARENA_REG_MASK, ex->fixup);
 	bool is_arena = !!(ex->fixup & BPF_ARENA_ACCESS);
 	bool is_write = !!(ex->fixup & BPF_ARENA_WRITE);
+	unsigned long end = regs->pc + AARCH64_INSN_SIZE, pad = end;
 	unsigned long addr;
 
 	if (is_arena) {
 		addr = regs->regs[arena_reg] + off;
-		bpf_arena_fault(is_write, addr, regs->pc, regs->pc + AARCH64_INSN_SIZE);
+		pad = bpf_arena_fault(is_write, addr, regs->pc, end);
 	}
 
-	if (dst_reg != DONT_CLEAR)
+	/*
+	 * Without a landing pad, skip the faulting instruction. A landing pad
+	 * gets the registers as they were before the access.
+	 */
+	if (pad == end && dst_reg != DONT_CLEAR)
 		regs->regs[dst_reg] = 0;
-	/* Skip the faulting instruction */
-	regs->pc += AARCH64_INSN_SIZE;
+	regs->pc = pad;
 
 	return true;
 }
@@ -1708,10 +1712,14 @@ static bool unwind_goto_after_helper(const struct bpf_insn *insn)
 /*
  * There is no branch for unwind_goto, only an extable entry
  *   { .insn = ret_addr - 1, .fixup = target - ret_addr }
- * where ret_addr is the return address of the call in front of it, and target
- * the pad, or the way into it. unwind_exit adds .fixup to its LR.
+ * where ret_addr is the return address of the call in front of it. unwind_exit
+ * adds .fixup to its LR.
  * 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.
+ * target is the insn that unwind_goto goes to, or its landing after the call of
+ * 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().
  */
 static int add_unwind_exentry(struct jit_ctx *ctx, int ret_addr, int target)
 {
@@ -1810,6 +1818,18 @@ u64 bpf_unwind_target(u64 ret_addr)
 	return ret_addr;
 }
 
+/*
+ * 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
+ * @end when none follows it. A missing entry is not a bug here.
+ */
+u64 bpf_fault_unwind_target(u64 end)
+{
+	const struct exception_table_entry *e = search_bpf_extables(end - 1);
+
+	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)
 {
@@ -2471,6 +2491,9 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		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) {
+			/* 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);
 		if (ret)
Signature · 1 line
2.53.1-Meta
author maintainer
#35 lore raw

PATCH 35/73 bpf: Let a register be the location of a lock in a global variable

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a landing pad knows one location for a lock in a global
variable: the address of the variable, a constant. That fails where one insn takes one of several such locks:

    lock = qa_q_lock(fifo->idx);    /* &qa_q_lock0 .. &qa_q_lock4 */
    if (!lock || qmap_spin_lock(lock))
            return;
    taskc->fifo = fifo;             /* arena */
    ..
    bpf_res_spin_unlock(lock);

scx_qmap has five such locks and one call that takes one of them. Five states reach a site under the lock, each with another constant, and each lock is held on some paths only. A constant is never NULL, so no test in the landing pad tells which lock is held. The function gets hidden slots then, which are stores on the normal path.

The program keeps the address for its own unlock, in R6-R9 or on the stack. Let that register or stack slot be a location too, as it is for a lock in a map value. All five states have it in common, so the landing pad is 'r1 = r7; call bpf_res_spin_unlock' and needs no test.

The constant stays the first candidate, so where one lock is held on all paths the landing pad is unchanged. Where a lock is held on some paths only, a register that is 0 on the other paths now tells the landing pad whether the lock is held, and no hidden slot is needed.

An access to arena like the store above is about to become a site.

---
 kernel/bpf/pads.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/bpf/pads.c +6 -2
index 985369fbb57c..60de6a42c756 100644
@@ -713,8 +713,9 @@ static int find_lock_cands(struct bpf_verifier_env *env, const struct bpf_verifi
 			   int insn_idx, const struct bpf_reference_state *ref,
 			   struct bpf_pad_place *cand)
 {
+	struct bpf_pad_place kept[BPF_PAD_MAX_CANDS];
 	const struct bpf_map *map;
-	int i, off, nr = 0;
+	int i, off, nr = 0, nr_kept;
 	u64 addr;
 
 	/* a lock in a global variable has no id: the only value of an array, a constant address */
@@ -727,7 +728,10 @@ static int find_lock_cands(struct bpf_verifier_env *env, const struct bpf_verifi
 		cand[nr++] = (struct bpf_pad_place){ .loc = BPF_PLACE_MAP_VALUE, .at = i,
 						     .delta = -off };
 	}
-	return ref->id ? find_cands(env, st, insn_idx, ref, NULL, cand) : nr;
+	/* one insn may take one of several such locks: the program keeps the address to unlock */
+	nr_kept = min(find_cands(env, st, insn_idx, ref, NULL, kept), BPF_PAD_MAX_CANDS - nr);
+	memcpy(&cand[nr], kept, nr_kept * sizeof(*cand));
+	return nr + nr_kept;
 }
 
 /*
Signature · 1 line
2.53.1-Meta
author maintainer
#36 lore raw

PATCH 36/73 bpf: Cancel a program at a fault in arena

In reply to Kumar Kartikeya Dwivedi

Currently a program that faults in an access to arena continues. The fault is reported to the stream of the program, a load reads 0, and the program then uses a value that it never read. sched_ext schedulers keep the first pages of their arena unmapped so that a NULL pointer faults, and an LSM program may decide from the value.

Cancel the program there, like one whose loop is out of time. Make an access to arena a site: the verifier adds unwind_goto after it, as after a call, and the fault handlers of x86-64 and arm64 go to the landing pad. '+' marks what the verifier adds:

    t = bpf_task_from_pid(pid);              r6 = r0
    v = node->val;      /* no page */        r1 = *(u64 *)(r7 + 8)
    bpf_task_release(t);              +      unwind_goto pad

...
+ pad: r1 = r6
+ call bpf_task_release
+ r0 = 0; exit

A load, a store and an atomic insn through a pointer to arena are sites, and so is an access to a stack in arena. The landing pad is generated for the state before the insn, because the fault comes before the insn writes anything.

No program is rejected because the verifier cannot generate a landing pad for an access. Such an access is skipped when it faults, as today:

at the access a fault
the frame holds nothing, or one landing pad
serves all states that reach the access cancels the program
the verifier cannot generate a landing pad is skipped
a frame that cannot be cancelled reaches it is skipped
the JIT is not that of x86-64 or arm64 is skipped

A site that can be skipped gets no hidden slots, because they are stores on the normal path. A call above such accesses is a site too. If the verifier cannot generate its landing pad and the functions below the call are cancelled at accesses to arena only, the program loads and those accesses are skipped. If one of them can also be cancelled at a site that cannot be skipped, like a may_goto of the verifier, the missing landing pad is an error as before, see bpf_pad_must_unwind().

What changes for programs that load today:

- A program ends at its first fault for which it has a landing pad, with the value of its program type.
- Only fentry can attach to a subprog that can unwind. In a program with an arena that is most subprogs now.
- A program with an unwind_goto of its own after a call can be rejected. A fault below the call now arrives at the program's landing pad, which has to release what the caller holds. A Rust build of scx_cosmos, not in the tree, is rejected that way with "Unreleased reference".

Where no state holds anything at an access, check_arena_site() records nothing per state, and the access gets a landing pad that releases nothing. unwind_frame() looks the record of the site up for release_frame_resources(), which accepts that there is none. One cancelled copy of the state serves a stretch of insns without a call or a store to the stack of a caller, because only those change what the caller gets.

A frame that has left a section of its caller is brought back to the sections of its call at a fault too. The head comment of pads.c shows it with grow(), which drops the lock of its caller, faults in arena and takes the lock again in its landing pad.

The verifier repeats a pass when a state reaches an access with something held after others passed it with nothing held. The landing pad has to test a pointer that is NULL on the earlier paths, so the repeated pass records every state. If what is held is not a pointer, no test can tell, and the access is skipped. A pass is also repeated after skip_faults() marked the functions below a call, so that their accesses are skipped from the start.

After an access nothing warns when the exception table entry of unwind_goto is missing: the fault is skipped. So add bpf_check_unwind_gotos(), which checks the final insns. Every unwind_goto has to follow a call or an access to arena, and every call or access that got one has to have it still. A failure is a verifier bug and fails the load.

Tests that look at what a skipped access leaves put the access into nine RCU sections, see arena_skipped.h. A landing pad leaves at most eight.

---
 include/linux/bpf_verifier.h                  |  26 ++-
 kernel/bpf/fixups.c                           |  87 ++++++-
 kernel/bpf/join.c                             |   6 +
 kernel/bpf/pads.c                             | 141 ++++++++++--
 kernel/bpf/precision.c                        |   2 +-
 kernel/bpf/verifier.c                         | 214 +++++++++++++++---
 .../testing/selftests/bpf/prog_tests/stream.c |   3 +-
 .../selftests/bpf/progs/arena_atomics.c       |   3 +
 .../selftests/bpf/progs/arena_skipped.h       |  11 +
 .../selftests/bpf/progs/jit_insns_arena.c     |  20 +-
 .../bpf/progs/pro_epilogue_arena_stack.c      |   2 +
 tools/testing/selftests/bpf/progs/stream.c    |  14 +-
 .../selftests/bpf/progs/verifier_arena.c      |  35 +--
 .../bpf/progs/verifier_arena_large.c          |  17 +-
 .../bpf/progs/verifier_arena_stack.c          |   3 +
 .../selftests/bpf/progs/verifier_ldsx.c       |  12 +-
 .../selftests/bpf/progs/verifier_zext.c       |   1 +
 17 files changed, 495 insertions(+), 102 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/progs/arena_skipped.h
include/linux/bpf_verifier.h +25 -1
index f03ecb8fe288..0b3e9dcd6aef 100644
@@ -455,6 +455,7 @@ enum bpf_site_kind {
 	BPF_SITE_RECURSION,	/* the stack check at the first insn of a recursive subprog */
 	/* a call without unwind_goto whose callee left with unwind_exit */
 	BPF_SITE_CALL,
+	BPF_SITE_FAULT,		/* an access to arena that faults */
 };
 
 /* The classes of resources that a landing pad releases */
@@ -479,6 +480,7 @@ enum bpf_pad_conflict {
 	BPF_NO_CONFLICT,
 	BPF_CONFLICT_SECTIONS_DIFFER,
 	BPF_CONFLICT_TOO_MUCH,
+	BPF_CONFLICT_SLOTS_FULL,	/* the function has more hidden slots than a pad releases */
 	BPF_CONFLICT_NO_RELEASE,
 	BPF_CONFLICT_NOT_ALWAYS_HELD,
 	BPF_CONFLICT_NO_PLACE,
@@ -762,6 +764,11 @@ struct bpf_func_state {
 	struct bpf_pad_arg call_args[MAX_BPF_FUNC_REG_ARGS];
 	);
 	bool no_stack_arg_load;
+	/*
+	 * A copy of the state was cancelled at an access to arena, and the frame has made no call
+	 * and no store to the stack of a caller since, see check_arena_site()
+	 */
+	bool fault_edge;
 	/*
 	 * Per argument register: 1 + the index in refs[] of a reference of the caller that the
 	 * call can hand over, see bpf_pad_handed_ref(). 0 if none. Not compared between states.
@@ -1278,12 +1285,17 @@ struct bpf_insn_aux_data {
 	u64 non_stack_access:1; /* instruction can access non-stack memory */
 	/* a subprog returned here without a pointer to release, and its R0 may not be 0 */
 	u64 call_brings_nothing:1;
+	/* An access to arena, see check_arena_site() */
+	u64 fault_skips:1; /* a fault is skipped: no pad, or the frame cannot be cancelled */
+	u64 fault_empty:1; /* in this pass a state that holds nothing passed without a record */
+	u64 unwind_goto_follows:1; /* the verifier added an unwind_goto after the insn */
 	);
 
 	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
 	u32 non_speculative_first:1; /* speculative states end here, their fixups did not fit */
 	u32 acquires:1; /* a reference or a lock */
 	u32 releases:1;
+	u32 fault_full:1; /* an access to arena: its plan records every state */
 
 	/* below flags are initialized once */
 	u32 bb_end:1; /* last instruction of a basic block */
@@ -1509,11 +1521,18 @@ struct bpf_subprog_info {
 	 * if a helper without an unwind label calls it, see subprog_cannot_unwind().
 	 */
 	bool bail_unwinds: 1;
+	/* bail_unwinds as it was before the first pass, see check_funcs() */
+	bool bail_unwinds_at_first: 1;
 	/*
 	 * It has an unwind_exit, or a state left it with unwind_exit in this pass, or is expected
 	 * to, see mark_unwind_above(). For a global subprog the bit goes to the next pass.
 	 */
 	bool did_unwind: 1;
+	/*
+	 * It did so at a site with no other way out, see bpf_pads_must_unwind(). A fault in arena
+	 * has one: the access is skipped.
+	 */
+	bool must_unwind: 1;
 	/* it did so at a site that the program keeps for sure, see site_is_certain() */
 	bool unwinds_for_sure: 1;
 	/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */
@@ -1728,6 +1747,7 @@ 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 fallthrough_first;		/* see find_failing_path() */
 	bool run_has_guess;		/* see run_path_sensitive() */
 	u32 failing_path_budget_shift;	/* see func_failing_path_budget() */
@@ -1753,6 +1773,7 @@ struct bpf_verifier_env {
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_needs_guard() */
 	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() */
 	bool calls_joined;		/* see flow_may_add_instance() */
 	bool extra_values;		/* a state can have constants that no run has */
@@ -2269,9 +2290,11 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 		  struct bpf_insn *buf, struct bpf_insn_aux_data *aux);
 void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan);
 void bpf_pad_log_handed_over(struct bpf_verifier_env *env, int subprog, u8 args);
+bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan);
+void bpf_pads_must_unwind(struct bpf_verifier_env *env);
 void bpf_pads_mark_used(struct bpf_verifier_env *env);
 int bpf_pads_settle(struct bpf_verifier_env *env);
-bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux);
+bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_data *aux);
 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);
@@ -2897,6 +2920,7 @@ int bpf_insert_arena_stack(struct bpf_verifier_env *env);
 int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union bpf_attr *attr);
 int bpf_convert_ctx_accesses(struct bpf_verifier_env *env);
 int bpf_jit_subprogs(struct bpf_verifier_env *env);
+int bpf_check_unwind_gotos(struct bpf_verifier_env *env);
 int bpf_fixup_call_args(struct bpf_verifier_env *env);
 int bpf_do_misc_fixups(struct bpf_verifier_env *env);
 int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);
kernel/bpf/fixups.c +77 -10

140 lines not on this page · raw message

kernel/bpf/join.c +6 -0
index d07019e9e764..0d88c3477652 100644
@@ -248,6 +248,12 @@ int bpf_states_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst
 			  env->insn_aux_data[bpf_frame_insn_idx(dst, j.fr)].live_regs_before);
 	bpf_equations_post_join(env, dst, src);
 	dst->max_held_cnt = max(dst->max_held_cnt, src->max_held_cnt);
+	/*
+	 * The joined state has frames of callers that no cancelled copy had, so the next access to
+	 * arena cancels a copy of it again, see check_arena_site().
+	 */
+	dst->frame[dst->curframe]->fault_edge &= src->frame[src->curframe]->fault_edge &&
+						 !dst->curframe;
 	/* no equation is found over a limit */
 	if (env->test_reg_invariants && !bpf_state_subsumes(env, dst, src) &&
 	    verifier_bug_if(!bpf_check_limits(env), env, "join at %d", dst->insn_idx))
kernel/bpf/pads.c +125 -16

247 lines not on this page · raw message

kernel/bpf/precision.c +1 -1
index 2576ba62da5d..feaab0485bdb 100644
@@ -709,7 +709,7 @@ void bpf_find_unproven_after_pass(struct bpf_verifier_env *env)
 	for (i = 0; i < env->subprog_cnt; i++)
 		note_unproven_after_pass(env, env->subprog_info[i].deepest_insn);
 	for (i = 0; i < env->prog->len; i++, insn++, aux++) {
-		if (aux->pessimized || bpf_pads_conflict(aux)) {
+		if (aux->pessimized || bpf_pads_conflict(env, aux)) {
 			note_unproven_after_pass(env, i);
 		} else if (aux->seen && (bpf_calls_function(env, i) || is_stack_arg_st(insn) ||
 					 is_stack_arg_stx(insn))) {
kernel/bpf/verifier.c +178 -36

356 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/stream.c +2 -1
index ae400dcfbf24..b1ad2dfe432f 100644
@@ -623,7 +623,8 @@ static void test_address(struct bpf_program *prog, unsigned long *fault_addr_p)
 
 	ret = bpf_prog_test_run_opts(prog_fd, &opts);
 	ASSERT_OK(ret, "ret");
-	ASSERT_OK(opts.retval, "retval");
+	/* the fault ends the prog: what the kernel unwinds does not return 0 to user space */
+	ASSERT_EQ((int)opts.retval, -ECANCELED, "retval");
 
 	sprintf(fault_addr, "0x%lx", *fault_addr_p);
 
tools/testing/selftests/bpf/progs/arena_atomics.c +3 -0
index 2a9664f54399..c12f7e6894e9 100644
@@ -8,6 +8,7 @@
 #include <bpf_arena_common.h>
 #include "../../../include/linux/filter.h"
 #include "bpf_misc.h"
+#include "arena_skipped.h"
 
 struct {
 	__uint(type, BPF_MAP_TYPE_ARENA);
@@ -298,6 +299,7 @@ int uaf(const void *ctx)
 	uaf_r0_after_src_r0 = 1;
 	uaf_reread = 1;
 
+	skip_faults();
 	page32 = (__u32 __arena *)page;
 	uaf_sink += __sync_fetch_and_add(page32, 1);
 	uaf_recovery_fails -= 1;
@@ -417,6 +419,7 @@ int uaf(const void *ctx)
 	: : [page]"r"(page64),
 	    __imm_addr(uaf_reread)
 	: "r1", "r2", "r3", "memory");
+	unwind_faults();
 #endif
 
 	return 0;
tools/testing/selftests/bpf/progs/arena_skipped.h new file +11 -0
new file mode 100644
index 000000000000..8b0a265ec6aa
@@ -0,0 +1,11 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#pragma once
+
+extern void bpf_rcu_read_lock(void) __ksym;
+extern void bpf_rcu_read_unlock(void) __ksym;
+
+/* A fault in the arena ends the prog. In nine RCU sections it is skipped: a pad leaves eight. */
+#define __nine(x) ({ x; x; x; x; x; x; x; x; x; })
+#define skip_faults()	__nine(bpf_rcu_read_lock())
+#define unwind_faults()	__nine(bpf_rcu_read_unlock())
+#define skipped(expr)	({ long __v; skip_faults(); __v = (expr); unwind_faults(); __v; })
tools/testing/selftests/bpf/progs/jit_insns_arena.c +15 -5
index 8f71d907ee57..b3dbe53eb2f0 100644
@@ -149,13 +149,25 @@ int cast_to_user(void *ctx)
 	return res != 0;
 }
 
+/*
+ * What a prog returns whose last insn is a load behind the pages of the arena:
+ * where the JIT can unwind, the fault ends the prog with the value of an
+ * unwound prog of its type, -ECANCELED. Elsewhere the load is skipped and
+ * reads 0.
+ */
+#if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64)
+#define LAST_LOAD_FAULTS	-125
+#else
+#define LAST_LOAD_FAULTS	0
+#endif
+
 /*
  * Every form of the arena address computation: offsets the add, the sub, the
  * shifted add and a move take, the end of the second 4K page, the narrow sizes
  * and immediate stores, each checked through r2 at the same address.
  */
 SEC("syscall")
-__success __retval(0)
+__success __retval(LAST_LOAD_FAULTS)
 __naked void arena_offsets(void)
 {
 	asm volatile ("					\
@@ -331,11 +343,9 @@ __naked void arena_offsets(void)
 	r1 = *(u32 *)(r2 + 0);				\
 	w1 ^= -1;					\
 	r9 |= r1;					\
-	r1 = *(u64 *)(r7 + 0x2000);			\
-	r9 |= r1;					\
-	r0 = 0;						\
-	if r9 == 0 goto 9f;				\
 	r0 = 1;						\
+	if r9 != 0 goto 9f;				\
+	r0 = *(u64 *)(r7 + 0x2000);			\
 9:	exit;						\
 "	:
 	: __imm_addr(arena)
tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c +2 -0
index 40fbcc004608..e901282c53a3 100644
@@ -82,6 +82,8 @@ __xlated("w12 += 16")
 __xlated("*(u64 *)(r12 -8) = 10")
 __xlated("...")
 __xlated("call pc+")
+/* a fault in the stack of the subprog unwinds */
+__xlated("unwind_goto pc+")
 /* give the stack back, then the epilogue */
 __xlated("w12 += -16")
 __xlated("if w12 & 0x10 goto pc+5")
tools/testing/selftests/bpf/progs/stream.c +8 -6
index 8c49a130150b..949c1b2fa6c0 100644
@@ -37,6 +37,8 @@ struct {
 
 #define ENOSPC 28
 #define E2BIG 7
+/* what a syscall prog returns when the kernel unwinds it */
+#define ECANCELED 125
 #define _STR "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 #define _X64 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 /* 1024 bytes: truncated by bstr_printf, must return -E2BIG. */
@@ -170,7 +172,7 @@ int stream_oversize(void *ctx)
 SEC("syscall")
 __arch_x86_64
 __arch_arm64
-__success __retval(0)
+__success __retval(-ECANCELED)
 __stderr("ERROR: Arena WRITE access at unmapped address 0x{{.*}}")
 __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}")
 __stderr("Call trace:\n"
@@ -196,7 +198,7 @@ int stream_arena_write_fault(void *ctx)
 SEC("syscall")
 __arch_x86_64
 __arch_arm64
-__success __retval(0)
+__success __retval(-ECANCELED)
 __stderr("ERROR: Arena READ access at unmapped address 0x{{.*}}")
 __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}")
 __stderr("Call trace:\n"
@@ -221,7 +223,7 @@ int stream_arena_read_fault(void *ctx)
 SEC("syscall")
 __arch_x86_64
 __arch_arm64
-__success __retval(0)
+__success __retval(-ECANCELED)
 __stderr("ERROR: Arena READ access at unmapped address 0x{{.*}}")
 __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}")
 __stderr("Call trace:\n"
@@ -257,7 +259,7 @@ int stream_arena_load_acquire_fault(void *ctx)
 SEC("syscall")
 __arch_x86_64
 __arch_arm64
-__success __retval(0)
+__success __retval(-ECANCELED)
 __stderr("ERROR: Arena WRITE access at unmapped address 0x{{.*}}")
 __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}")
 __stderr("Call trace:\n"
@@ -299,7 +301,7 @@ int stream_arena_xchg_fault(void *ctx)
 SEC("syscall")
 __arch_x86_64
 __arch_arm64
-__success __retval(0)
+__success __retval(-ECANCELED)
 __stderr("ERROR: Arena WRITE access at unmapped address 0x{{.*}}")
 __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}")
 __stderr("Call trace:\n"
@@ -351,7 +353,7 @@ static __noinline void subprog(void)
 SEC("syscall")
 __arch_x86_64
 __arch_arm64
-__success __retval(0)
+__success __retval(-ECANCELED)
 __stderr("ERROR: Arena WRITE access at unmapped address 0x{{.*}}")
 __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}")
 __stderr("Call trace:\n"
tools/testing/selftests/bpf/progs/verifier_arena.c +18 -17
index 99856ee10795..e46ce213c34d 100644
@@ -9,6 +9,7 @@
 #include "bpf_misc.h"
 #include "bpf_experimental.h"
 #include <bpf_arena_common.h>
+#include "arena_skipped.h"
 
 #define private(name) SEC(".bss." #name) __hidden __attribute__((aligned(8)))
 
@@ -80,7 +81,7 @@ int basic_alloc1(void *ctx)
 	bpf_arena_free_pages(&arena, (void __arena *)page2, 1);
 	if (*page1 != 1)
 		return 6;
-	if (*page2 != 0) /* use-after-free should return 0 */
+	if (skipped(*page2) != 0) /* use-after-free should return 0 */
 		return 7;
 	page3 = bpf_arena_alloc_pages(&arena, NULL, 1, NUMA_NO_NODE, 0);
 	if (!page3)
@@ -136,24 +137,24 @@ int basic_alloc2_nosleep(void *ctx)
 	page4 = page1 - __PAGE_SIZE;
 	*page1 = 1;
 	*page2 = 2;
-	*page3 = 3;
-	*page4 = 4;
+	skipped(*page3 = 3);
+	skipped(*page4 = 4);
 	if (*page1 != 1)
 		return 1;
 	if (*page2 != 2)
 		return 2;
-	if (*page3 != 0)
+	if (skipped(*page3) != 0)
 		return 3;
-	if (*page4 != 0)
+	if (skipped(*page4) != 0)
 		return 4;
 	bpf_arena_free_pages(&arena, (void __arena *)page1, 2);
-	if (*page1 != 0 && *page1 != 1)
+	if (skipped(*page1) != 0 && skipped(*page1) != 1)
 		return 5;
-	if (*page2 != 0 && *page2 != 2)
+	if (skipped(*page2) != 0 && skipped(*page2) != 2)
 		return 6;
-	if (*page3 != 0)
+	if (skipped(*page3) != 0)
 		return 7;
-	if (*page4 != 0)
+	if (skipped(*page4) != 0)
 		return 8;
 	return 0;
 }
@@ -173,24 +174,24 @@ int basic_alloc2(void *ctx)
 	page4 = page1 - __PAGE_SIZE;
 	*page1 = 1;
 	*page2 = 2;
-	*page3 = 3;
-	*page4 = 4;
+	skipped(*page3 = 3);
+	skipped(*page4 = 4);
 	if (*page1 != 1)
 		return 1;
 	if (*page2 != 2)
 		return 2;
-	if (*page3 != 0)
+	if (skipped(*page3) != 0)
 		return 3;
-	if (*page4 != 0)
+	if (skipped(*page4) != 0)
 		return 4;
 	bpf_arena_free_pages(&arena, (void __arena *)page1, 2);
-	if (*page1 != 0)
+	if (skipped(*page1) != 0)
 		return 5;
-	if (*page2 != 0)
+	if (skipped(*page2) != 0)
 		return 6;
-	if (*page3 != 0)
+	if (skipped(*page3) != 0)
 		return 7;
-	if (*page4 != 0)
+	if (skipped(*page4) != 0)
 		return 8;
 	return 0;
 }
tools/testing/selftests/bpf/progs/verifier_arena_large.c +9 -8
index 89f32a7772ac..73dc5ac69a82 100644
@@ -8,6 +8,7 @@
 #include "bpf_misc.h"
 #include "bpf_experimental.h"
 #include <bpf_arena_common.h>
+#include "arena_skipped.h"
 
 #define ARENA_SIZE (1ull << 32)
 #define LARGE_PAGE_CNT 1025
@@ -61,7 +62,7 @@ int big_alloc1(void *ctx)
 	bpf_arena_free_pages(&arena, (void __arena *)page1, 1);
 	if (*page2 != 2)
 		return 6;
-	if (*page1 != 0) /* use-after-free should return 0 */
+	if (skipped(*page1) != 0) /* use-after-free should return 0 */
 		return 7;
 	page3 = bpf_arena_alloc_pages(&arena, NULL, 1, NUMA_NO_NODE, 0);
 	if (!page3)
@@ -71,13 +72,13 @@ int big_alloc1(void *ctx)
 		return 9;
 	if (*page2 != 2)
 		return 10;
-	if (*(page1 + PAGE_SIZE) != 0)
+	if (skipped(*(page1 + PAGE_SIZE)) != 0)
 		return 11;
-	if (*(page1 - PAGE_SIZE) != 0)
+	if (skipped(*(page1 - PAGE_SIZE)) != 0)
 		return 12;
-	if (*(page2 + PAGE_SIZE) != 0)
+	if (skipped(*(page2 + PAGE_SIZE)) != 0)
 		return 13;
-	if (*(page2 - PAGE_SIZE) != 0)
+	if (skipped(*(page2 - PAGE_SIZE)) != 0)
 		return 14;
 	return 0;
 }
@@ -102,7 +103,7 @@ int access_reserved(void *ctx)
 
 	/* Try to dirty reserved memory. */
 	for (i = 0; i < len && can_loop; i++)
-		*page = 0x5a;
+		skipped(*page = 0x5a);
 
 	for (i = 0; i < len && can_loop; i++) {
 		page = (volatile char __arena *)(base + i * PAGE_SIZE);
@@ -111,10 +112,10 @@ int access_reserved(void *ctx)
 		 * Error out in case either the write went through,
 		 * or the address has random garbage.
 		 */
-		if (*page == 0x5a)
+		if (skipped(*page) == 0x5a)
 			return 2 + 2 * i;
 
-		if (*page)
+		if (skipped(*page))
 			return 2 + 2 * i + 1;
 	}
 	return 0;
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +3 -0
index 6d188a19206f..c7d613669c38 100644
@@ -47,6 +47,7 @@ SEC("syscall")
 __description("arena stack: load and store")
 __success __retval(12)
 __xlated("r0 = *(u64 *)(r12 -16)")
+__xlated("unwind_goto pc+")
 __xlated("r2 = *(u64 *)(r12 -8)")
 __naked void load_store(void)
 {
@@ -919,6 +920,8 @@ __success __retval(60)
 __load_if_JITed()
 /* the end of the main program, the first insn of loops_far_from_r12_cb() */
 __xlated("r0 = r6")
+__xlated("...")
+__xlated("r0 = r6")
 __xlated("exit")
 __xlated("r3 = r2")
 __xlated("...")
tools/testing/selftests/bpf/progs/verifier_ldsx.c +11 -1
index 232082428cb9..acf4f0471e4c 100644
@@ -325,9 +325,19 @@ __naked void arena_ldsx_disasm(void *ctx)
 	);
 }
 
+/*
+ * The store faults. Where the JIT can unwind that ends the prog, with the value of an unwound prog
+ * of its type, -ECANCELED. Elsewhere the store is skipped, and the load that follows reads 0.
+ */
+#if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64)
+#define ARENA_FAULT_RETVAL	-125
+#else
+#define ARENA_FAULT_RETVAL	0
+#endif
+
 SEC("syscall")
 __description("Arena LDSX Exception")
-__success __retval(0)
+__success __retval(ARENA_FAULT_RETVAL)
 __arch_x86_64
 __arch_arm64
 __arch_riscv64
tools/testing/selftests/bpf/progs/verifier_zext.c +1 -0
index 9fce1dd8ef7b..fc8594542845 100644
@@ -361,6 +361,7 @@ __naked void arena_ptr(void)
 SEC("socket")
 __success
 __xlated("probe r0 = atomic_cmpxchg((u32 *)(r1 +0), r0, r2)")
+__xlated("unwind_goto pc+")
 __xlated("w0 = w0")
 __naked void zext_arena_cmpxchg32(void)
 {
Signature · 1 line
2.53.1-Meta
author maintainer
#37 lore raw

PATCH 37/73 bpf: Share one landing pad among accesses to arena where nothing is held

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently every access to arena that can cancel the program has an unwind_goto after it: an insn and a second exception table entry, 20 bytes per access. At most accesses the frame holds nothing, and within a function their landing pads are the same, 'r0 = 0; exit' in the main program. In code compiled from Rust that is nearly all accesses, and one program can have more than ten thousand. Their unwind_gotos are about a fifth of what such a program takes in insns, native code and exception table.

The access has an exception table entry of its own already. Put a bit into it, UNWINDS, in place of the unwind_goto:

           r1 = *(u64 *)(r7 + 8)   entry of the access { .., UNWINDS }
    -      unwind_goto pad         entry of unwind_goto
           ...
      pad: r0 = 0
           exit

At a fault bpf_arena_fault() takes the first line that applies:

    the entry of the access has UNWINDS     go to prog->aux->fault_pad
    unwind_goto follows the access          go to its landing pad
    neither                                 skip the access

An access at which something is held keeps its unwind_goto.

The verifier marks each access at which nothing is held and records one landing pad per function for all of them, 'fault_pad'. It is the landing pad of the first such access. Two things need care:

- Later rewrites have to keep both right. The mark stays on the access when a patch adds insns after it, and fault_pad is remapped like the target of a jump.
- The fault handler needs fault_pad as an address. The x86-64 and arm64 JITs compute it from the start of the image and not from bpf_func, which is after the CFI preamble. The offsets of insns count from the image.

---
 arch/arm64/net/bpf_jit_comp.c                 | 34 ++++++++-----
 arch/x86/net/bpf_jit_comp.c                   | 48 ++++++++++++-------
 include/linux/bpf.h                           | 10 +++-
 include/linux/bpf_verifier.h                  |  3 ++
 kernel/bpf/arena.c                            | 13 +++--
 kernel/bpf/core.c                             | 18 +++++++
 kernel/bpf/fixups.c                           | 40 ++++++++++++----
 .../bpf/progs/verifier_arena_stack.c          |  1 -
 .../selftests/bpf/progs/verifier_zext.c       |  1 -
 9 files changed, 120 insertions(+), 48 deletions(-)
arch/arm64/net/bpf_jit_comp.c +23 -11
index 730f9d95bca1..5e4e08a65ea3 100644
@@ -1559,11 +1559,11 @@ static void build_epilogue(struct jit_ctx *ctx, bool was_classic, bool unwind)
  *
  * Bit layout of `fixup` (32-bit):
  *
- * +-----------+--------+-------------+-----------+-----------+----------+
- * |   31-27   | 26-23  |      22     |     21    |   20-16   |   15-0   |
- * |           |        |             |           |           |          |
- * | FIXUP_REG | Unused | ARENA_WRITE | ARENA_ACC | ARENA_REG |  OFFSET  |
- * +-----------+--------+-------------+-----------+-----------+----------+
+ * +-----------+--------+---------+-------------+-----------+-----------+----------+
+ * |   31-27   | 26-24  |    23   |      22     |     21    |   20-16   |   15-0   |
+ * |           |        |         |             |           |           |          |
+ * | FIXUP_REG | Unused | UNWINDS | ARENA_WRITE | ARENA_ACC | ARENA_REG |  OFFSET  |
+ * +-----------+--------+---------+-------------+-----------+-----------+----------+
  *
  * - OFFSET (16 bits): Offset used to compute address for Load/Store instruction.
  * - ARENA_REG (5 bits): Register that is used to calculate the address for load/store when
@@ -1572,6 +1572,9 @@ static void build_epilogue(struct jit_ctx *ctx, bool was_classic, bool unwind)
  * - ARENA_WRITE (1 bit): This bit is set when the faulting instruction wrote to the arena region.
  *                        It is independent of FIXUP_REG, since a read-modify-write both writes to
  *                        memory and reads the old value into a register.
+ * - UNWINDS (1 bit): The frame holds nothing at the insn, and no unwind_goto follows it. The
+ *                    handler goes to prog->aux->fault_pad, the landing pad that all such
+ *                    accesses of the function share.
  * - FIXUP_REG (5 bits): Destination register for the load instruction (cleared on fault) or set to
  *                       DONT_CLEAR if the instruction does not read into a register.
  */
@@ -1580,6 +1583,7 @@ static void build_epilogue(struct jit_ctx *ctx, bool was_classic, bool unwind)
 #define BPF_FIXUP_ARENA_REG_MASK   GENMASK(20, 16)
 #define BPF_ARENA_ACCESS           BIT(21)
 #define BPF_ARENA_WRITE            BIT(22)
+#define BPF_ARENA_UNWINDS          BIT(23)
 #define BPF_FIXUP_REG_MASK	GENMASK(31, 27)
 #define DONT_CLEAR 5 /* Unused ARM64 register from BPF's POV */
 
@@ -1596,7 +1600,8 @@ bool ex_handler_bpf(const struct exception_table_entry *ex,
 
 	if (is_arena) {
 		addr = regs->regs[arena_reg] + off;
-		pad = bpf_arena_fault(is_write, addr, regs->pc, end);
+		pad = bpf_arena_fault(is_write, addr, regs->pc, end,
+				      ex->fixup & BPF_ARENA_UNWINDS);
 	}
 
 	/*
@@ -1611,7 +1616,8 @@ bool ex_handler_bpf(const struct exception_table_entry *ex,
 }
 
 /* For accesses to BTF pointers, add an entry to the exception table */
-static int add_exception_handler(const struct bpf_insn *insn,
+static int add_exception_handler(const struct bpf_verifier_env *env,
+				 const struct bpf_insn *insn,
 				 struct jit_ctx *ctx,
 				 int dst_reg)
 {
@@ -1678,6 +1684,8 @@ static int add_exception_handler(const struct bpf_insn *insn,
 		ex->fixup |= BPF_ARENA_ACCESS;
 		if (is_write)
 			ex->fixup |= BPF_ARENA_WRITE;
+		if (bpf_insn_fault_unwinds(env, ctx->prog, insn - ctx->prog->insnsi))
+			ex->fixup |= BPF_ARENA_UNWINDS;
 		/*
 		 * insn->src_reg/dst_reg holds the address in the arena region with upper 32-bits
 		 * being zero because of a preceding addr_space_cast(r<n>, 0x0, 0x1) instruction.
@@ -2583,7 +2591,7 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		else
 			emit_ldst(code, dst, src, off_adj, tmp, ctx);
 
-		ret = add_exception_handler(insn, ctx, dst);
+		ret = add_exception_handler(env, insn, ctx, dst);
 		if (ret)
 			return ret;
 		break;
@@ -2620,7 +2628,7 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		else
 			emit_ldst(code, imm ? tmp : A64_ZR, dst, off, tmp2, ctx);
 
-		ret = add_exception_handler(insn, ctx, DONT_CLEAR);
+		ret = add_exception_handler(env, insn, ctx, DONT_CLEAR);
 		if (ret)
 			return ret;
 		break;
@@ -2644,7 +2652,7 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 		else
 			emit_ldst(code, src, dst, off, tmp, ctx);
 
-		ret = add_exception_handler(insn, ctx, DONT_CLEAR);
+		ret = add_exception_handler(env, insn, ctx, DONT_CLEAR);
 		if (ret)
 			return ret;
 		break;
@@ -2675,7 +2683,7 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 			 */
 			int load_reg = bpf_atomic_load_reg(insn);
 
-			ret = add_exception_handler(insn, ctx, load_reg < 0 ?
+			ret = add_exception_handler(env, insn, ctx, load_reg < 0 ?
 						    DONT_CLEAR : bpf2a64[load_reg]);
 			if (ret)
 				return ret;
@@ -2997,6 +3005,10 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	}
 
 	prog->bpf_func = (void *)ctx.ro_image + cfi_get_offset();
+	/* offset[] counts from the image, not from bpf_func */
+	if (bpf_prog_fault_pad(env, prog))
+		prog->aux->fault_pad =
+			(unsigned long)&ctx.ro_image[ctx.offset[bpf_prog_fault_pad(env, prog)]];
 	prog->jited = 1;
 	prog->jited_len = prog_size - cfi_get_offset();
 
arch/x86/net/bpf_jit_comp.c +30 -18

103 lines not on this page · raw message

include/linux/bpf.h +8 -2
index f7ac105d9dd3..e981d486a337 100644
@@ -1734,6 +1734,9 @@ void bpf_jit_uncharge_modmem(u32 size);
 bool bpf_prog_has_trampoline(const struct bpf_prog *prog);
 bool bpf_insn_is_indirect_target(const struct bpf_verifier_env *env, const struct bpf_prog *prog,
 				 int insn_idx);
+bool bpf_insn_fault_unwinds(const struct bpf_verifier_env *env, const struct bpf_prog *prog,
+			    int insn_idx);
+int bpf_prog_fault_pad(const struct bpf_verifier_env *env, const struct bpf_prog *prog);
 u16 bpf_out_stack_arg_cnt(const struct bpf_verifier_env *env, const struct bpf_prog *prog);
 #else
 static inline int bpf_trampoline_link_prog(struct bpf_tramp_node *node,
@@ -2046,6 +2049,8 @@ struct bpf_prog_aux {
 	struct module *mod;
 	u32 num_exentries;
 	struct exception_table_entry *extable;
+	/* the address of the landing pad that releases nothing, see bpf_arena_fault() */
+	unsigned long fault_pad;
 	union {
 		struct work_struct work;
 		struct rcu_head	rcu;
@@ -3512,7 +3517,7 @@ void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);
 unsigned long bpf_arena_fault(bool write, unsigned long addr, unsigned long fault_ip,
-			      unsigned long end);
+			      unsigned long end, bool unwinds);
 
 static __always_inline u32
 bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
@@ -3858,7 +3863,8 @@ static inline void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
 }
 
 static inline unsigned long bpf_arena_fault(bool write, unsigned long addr,
-					    unsigned long fault_ip, unsigned long end)
+					    unsigned long fault_ip, unsigned long end,
+					    bool unwinds)
 {
 	return end;
 }
include/linux/bpf_verifier.h +3 -0
index 0b3e9dcd6aef..3d699dd1045f 100644
@@ -1288,6 +1288,7 @@ struct bpf_insn_aux_data {
 	/* An access to arena, see check_arena_site() */
 	u64 fault_skips:1; /* a fault is skipped: no pad, or the frame cannot be cancelled */
 	u64 fault_empty:1; /* in this pass a state that holds nothing passed without a record */
+	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 */
 	);
 
@@ -1559,6 +1560,8 @@ struct bpf_subprog_info {
 	/* its hidden slots and words take that many words of 8 bytes below its stack */
 	u8 hidden_words;
 	u8 code_stack_args;
+	/* the pad that releases nothing, for all accesses to arena with 'fault_unwinds'. 0: none */
+	u32 fault_pad;
 	u16 stack_arg_cnt; /* incoming + max outgoing */
 	u16 max_out_stack_arg_cnt;
 };
kernel/bpf/arena.c +8 -5
index 2890c65ad26a..ebe4ac74f219 100644
@@ -1464,14 +1464,15 @@ bool bpf_arena_handle_page_fault(unsigned long addr, bool is_write, unsigned lon
 }
 
 /*
- * JITed code faulted at @fault_ip, in an access to arena at @addr. The code of the BPF insn ends at
- * @end. Report it. Returns where the program goes on: at the landing pad when unwind_goto follows
- * the insn, else at @end: the access is skipped.
+ * JITed code faulted at @fault_ip in an access to arena at @addr. Report the fault and return where
+ * the program continues: at prog->aux->fault_pad if @unwinds, else at the landing pad of the
+ * unwind_goto after the access. Without either, the access is skipped and the program continues at
+ * @end, where the code of the insn ends.
  */
 unsigned long bpf_arena_fault(bool write, unsigned long addr, unsigned long fault_ip,
-			      unsigned long end)
+			      unsigned long end, bool unwinds)
 {
-	unsigned long pad = bpf_fault_unwind_target(end);
+	unsigned long pad = unwinds ? end : bpf_fault_unwind_target(end);
 	struct bpf_prog *prog;
 
 	/*
@@ -1482,6 +1483,8 @@ unsigned long bpf_arena_fault(bool write, unsigned long addr, unsigned long faul
 	rcu_read_lock();
 	prog = bpf_prog_ksym_find(fault_ip);
 	rcu_read_unlock();
+	if (prog && unwinds)
+		pad = prog->aux->fault_pad;
 	if (prog)
 		__bpf_prog_report_arena_violation(prog, write, addr, fault_ip, pad != end);
 	return pad;
kernel/bpf/core.c +18 -0
index 0f7199c5c1b8..3582cde3cfe3 100644
@@ -2010,6 +2010,24 @@ bool bpf_insn_is_indirect_target(const struct bpf_verifier_env *env, const struc
 	return env->insn_aux_data[insn_idx].indirect_target;
 }
 
+/* Does a fault in the access to arena at @insn_idx of @prog lead to bpf_prog_fault_pad()? */
+bool bpf_insn_fault_unwinds(const struct bpf_verifier_env *env, const struct bpf_prog *prog,
+			    int insn_idx)
+{
+	if (!env)
+		return false;
+	insn_idx += prog->aux->subprog_start;
+	return env->insn_aux_data[insn_idx].fault_unwinds;
+}
+
+/* The first insn of the landing pad of @prog that releases nothing, or 0 if it has none */
+int bpf_prog_fault_pad(const struct bpf_verifier_env *env, const struct bpf_prog *prog)
+{
+	u32 pad = env ? env->subprog_info[prog->aux->func_idx].fault_pad : 0;
+
+	return pad ? pad - prog->aux->subprog_start : 0;
+}
+
 u16 bpf_out_stack_arg_cnt(const struct bpf_verifier_env *env, const struct bpf_prog *prog)
 {
 	const struct bpf_subprog_info *sub;
kernel/bpf/fixups.c +30 -10
index 8e007e4fad99..75ad6f567e14 100644
@@ -292,6 +292,8 @@ static void patch_list_adj_aux(struct bpf_prog *prog, struct bpf_insn_patch *p,
 		if (i >= p->target && !memcmp(&patch[i], orig, sizeof(*orig))) {
 			slot[i].non_stack_access = last->non_stack_access;
 			last->non_stack_access = false;
+			slot[i].fault_unwinds = last->fault_unwinds;
+			last->fault_unwinds = false;
 		} else if (bpf_is_mem_insn(&patch[i])) {
 			slot[i].non_stack_access = true;
 		}
@@ -484,6 +486,10 @@ static void patch_list_remap_subprogs(struct bpf_verifier_env *env,
 	/* NOTE: fake 'exit' subprog should be updated as well. */
 	for (i = 0; i <= env->subprog_cnt; i++) {
 		info[i].start = bpf_patch_image_remap(img, img->new_off, info[i].start);
+		/* a fault jumps to fault_pad, so remap it like the target of a jump */
+		if (info[i].fault_pad)
+			info[i].fault_pad = bpf_patch_image_remap(img, img->new_tgt,
+								  info[i].fault_pad);
 		if (img->new_linfo)
 			info[i].linfo_idx =
 				img->new_linfo[min(info[i].linfo_idx, img->nr_linfo)];
@@ -703,14 +709,22 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	int last = env->subprog_info[s + 1].start - 1, cnt = 0, i, n, pad, len;
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	struct bpf_insn *buf = *pads, *insn;
-	struct bpf_pad_plan *plan;
+	struct bpf_pad_plan *plan, *shared = NULL;
 
 	for (i = env->subprog_info[s].start; i <= last; i++) {
 		if (aux[i].loop_guard && !unvisited_plan(env, i, BPF_SITE_GUARD))
 			return -ENOMEM;
-		/* nothing is held there: the same */
-		if (aux[i].fault_empty && !unvisited_plan(env, i, BPF_SITE_FAULT))
-			return -ENOMEM;
+		/*
+		 * Nothing is held there: the same. There are many such accesses. They get no insn,
+		 * a bit in the entry that they have in the exception table tells, and the pad of
+		 * the first one serves all of the function, see bpf_arena_fault().
+		 */
+		aux[i].fault_unwinds = aux[i].fault_empty && !aux[i].fault_skips;
+		if (aux[i].fault_unwinds && !shared) {
+			shared = unvisited_plan(env, i, BPF_SITE_FAULT);
+			if (!shared)
+				return -ENOMEM;
+		}
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
 			if (!plan_has_pad(env, i, plan))
 				continue;
@@ -747,7 +761,7 @@ static const struct bpf_pad_plan *unwind_goto_plan(struct bpf_verifier_env *env,
 	const struct bpf_pad_plan *plan;
 
 	plan = bpf_pad_plan(aux, BPF_SITE_CALL) ?: bpf_pad_plan(aux, BPF_SITE_FAULT);
-	return plan && bpf_site_is_used(env, i, plan) ? plan : NULL;
+	return plan && bpf_site_is_used(env, i, plan) && !aux->fault_unwinds ? plan : NULL;
 }
 
 /*
@@ -928,11 +942,16 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 	aux = env->insn_aux_data;
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
-		for (i = sub->start; added[s] && i < sub[1].start - added[s]; i++)
-			for (plan = aux[i].pad_plans; plan; plan = plan->next)
-				if (plan_has_pad(env, i, plan))
-					emit_pad(env, s, plan, new,
-						 &aux[sub[1].start - added[s] + plan->pad]);
+		for (i = sub->start; added[s] && i < sub[1].start - added[s]; i++) {
+			for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+				if (!plan_has_pad(env, i, plan))
+					continue;
+				cnt = sub[1].start - added[s] + plan->pad;
+				emit_pad(env, s, plan, new, &aux[cnt]);
+				if (plan->kind == BPF_SITE_FAULT && aux[i].fault_unwinds)
+					sub->fault_pad = cnt;
+			}
+		}
 	}
 	err = insert_slot_stores(env, new, added);
 	err = err ?: insert_unwind_gotos(env, added);
@@ -2198,6 +2217,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 	prog->aux->ksym.fp_start = func[0]->aux->ksym.fp_start;
 	prog->aux->ksym.fp_end = func[0]->aux->ksym.fp_end;
 	prog->aux->ksym.fp_ret = func[0]->aux->ksym.fp_ret;
+	prog->aux->fault_pad = func[0]->aux->fault_pad;
 	prog->aux->func = func;
 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
 	prog->aux->real_func_cnt = env->subprog_cnt;
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +0 -1
index c7d613669c38..63697cbd5a92 100644
@@ -47,7 +47,6 @@ SEC("syscall")
 __description("arena stack: load and store")
 __success __retval(12)
 __xlated("r0 = *(u64 *)(r12 -16)")
-__xlated("unwind_goto pc+")
 __xlated("r2 = *(u64 *)(r12 -8)")
 __naked void load_store(void)
 {
tools/testing/selftests/bpf/progs/verifier_zext.c +0 -1
index fc8594542845..9fce1dd8ef7b 100644
@@ -361,7 +361,6 @@ __naked void arena_ptr(void)
 SEC("socket")
 __success
 __xlated("probe r0 = atomic_cmpxchg((u32 *)(r1 +0), r0, r2)")
-__xlated("unwind_goto pc+")
 __xlated("w0 = w0")
 __naked void zext_arena_cmpxchg32(void)
 {
Signature · 1 line
2.53.1-Meta
author maintainer
#38 lore raw

PATCH 38/73 bpf: Keep R0, R6-R9 and the stack live at a call of bpf_throw()

In reply to Kumar Kartikeya Dwivedi

Currently only the argument is live at a call of bpf_throw(), because no insn follows the call:

       call bpf_task_from_pid
       r6 = r0
       ...
       if r1 < 16 goto 1f
       r1 = 0
       call bpf_throw         <- r6 is dead
    1: ...

That stands in the way of a landing pad for bpf_throw(), which would have to release the task here. A landing pad takes the pointer that it releases from a location that is live at the site. The verifier does not track what is dead: states that differ only in a dead register are the same state to it. So R6 above is no location for the task.

Let liveness treat a call of bpf_throw() as a read of R0, R6-R9 and the stack of the frame. R0 holds what an acquiring call returned until the program moves it, and compilers keep pointers in R6-R9 and in the stack over calls. R1 is live as before: it is the argument.

R2-R5 stay dead, and a pointer that is only there at a throw needs a hidden slot. If they were live at a throw, whatever a caller left in them would count as an argument of every function that can reach a throw from its first insn. Where that is a pointer to the stack, a recursion that loads today would be rejected with "recursive depth() passes a pointer to the stack to depth()".

The frames of the callers are not affected: a landing pad at a call reads what is live after the call.

bpf_throw() is the first insn that has no successor and reads the stack, so remove the early return of update_insn() for such an insn.

A program with bpf_throw() or bpf_assert() can take longer to load: more is live between the first insn of a function and a throw, so fewer states are equal there. Nothing reads the newly live registers and slots yet, because bpf_throw() still walks the stack.

---
 kernel/bpf/liveness.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)
kernel/bpf/liveness.c +14 -3
index a7120ecb0e80..93f8d1686496 100644
@@ -418,9 +418,6 @@ static inline bool update_insn(struct bpf_verifier_env *env, struct func_instanc
 	u32 s, w;
 
 	succ = bpf_insn_successors(env, insn_idx);
-	if (succ->cnt == 0)
-		return false;
-
 	/* All instructions of one frame array share the same mask width */
 	for (s = 0; s < succ->cnt; ++s) {
 		unsigned long *succ_live;
@@ -1873,6 +1870,13 @@ static int record_call_access(struct bpf_verifier_env *env,
 	struct bpf_call_summary cs;
 	int r, err, callee, arg_slot_cnt = 5;
 
+	/*
+	 * The landing pad of a call of bpf_throw() reads the stack slots that hold what the frame
+	 * releases, so every slot of the frame is live at the call.
+	 */
+	if (bpf_is_throw_kfunc(insn))
+		return mark_stack_read_all(env, instance, instance->depth, insn_idx, true);
+
 	if (bpf_pseudo_call(insn)) {
 		/*
 		 * analyze_subprog() handles static callees. For global callees,
@@ -2821,6 +2825,13 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env,
 			 */
 			if (bpf_is_sync_callback_calling_insn(insn) && bpf_is_unwind_goto(insn + 1))
 				use |= r0;
+			/*
+			 * The landing pad of bpf_throw() may take a pointer from R0 or R6-R9, so
+			 * they are live at the call. R2-R5 stay dead: live, they would count as
+			 * arguments of every function that can reach a throw from its first insn.
+			 */
+			if (bpf_is_throw_kfunc(insn))
+				use |= r0 | mask_widen(GENMASK(BPF_REG_9, BPF_REG_6));
 			break;
 		default:
 			def = 0;
Signature · 1 line
2.53.1-Meta
author maintainer
#39 lore raw

PATCH 39/73 bpf: Refuse freplace on a function that can unwind

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently an extension can replace a global function that can unwind:

__weak int policy(int nice) the caller:

  {                                          call policy
          while (!ready)                     unwind_goto pad
                  ;                          ...
          return 0;

}

The verifier adds a may_goto to the loop, so the kernel can cancel the program in policy(), and each caller gets unwind_goto and a landing pad after its call for that. An extension is a program of its own. When it is cancelled, it ends in its main program and returns: it never unwinds into the program that it extends. With an extension in place of policy(), a cancellation inside the extension would end the extension only. The caller would continue after the call, past the landing pad that it has for this case.

Refuse to replace a function that can unwind. bpf_check_attach_target() already refuses fexit and fsession on such a function. Let the same check cover freplace, with the same message:

Only fentry can attach to policy, which can unwind

At this point of the series a function can unwind if it has unwind_exit, a may_goto of the verifier, a recursion check or an access to arena that cancels the program, or if it calls such a function and has no unwind_goto of its own after the call. In a program with an arena that is most functions.

The main program leaves with exit, so the check skipped it until now. Mark the main program when it has a site, and refuse freplace on it then. fexit and fsession stay allowed there.

An extension with a loop of its own loads and attaches as before. libxdp attaches XDP programs that way, to the placeholder functions of its dispatcher, which cannot unwind.

---
 include/linux/bpf_verifier.h                          |  6 +++++-
 kernel/bpf/fixups.c                                   |  6 ++++--
 kernel/bpf/verifier.c                                 | 11 +++++++----
 .../testing/selftests/bpf/prog_tests/unwind_attach.c  |  3 ++-
 4 files changed, 18 insertions(+), 8 deletions(-)
include/linux/bpf_verifier.h +5 -1
index 3d699dd1045f..91d8831de4e9 100644
@@ -1475,7 +1475,11 @@ struct bpf_subprog_info {
 	bool has_tail_call: 1;
 	bool might_throw: 1;
 	bool throws: 1; /* as the main pass found it, callx included */
-	bool can_unwind: 1; /* has unwind_exit */
+	/*
+	 * It has an unwind_exit, or a landing pad of it leaves with one, see
+	 * bpf_mark_subprogs_that_unwind(). Subprog 0 has the bit for such a site, for freplace.
+	 */
+	bool can_unwind: 1;
 	bool recursive: 1; /* on a cycle of the call graph */
 	bool in_recursion: 1; /* recursive, or a recursive subprog gets to it */
 	bool addr_taken: 1; /* callx calls nothing else */
kernel/bpf/fixups.c +4 -2
index 75ad6f567e14..a20830a628e7 100644
@@ -650,7 +650,8 @@ 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 unwind_exit: those that are
  * left at a site. A call is a site if it calls one of them. The main pass asks the same when a
- * global subprog unwinds, see settle_late_unwinds().
+ * 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().
  */
 void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env)
 {
@@ -664,7 +665,7 @@ void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env)
 		changed = false;
 		for (s = 0; s < env->subprog_cnt; s++) {
 			sub = &env->subprog_info[s];
-			if (sub->can_unwind || !sub->bail_unwinds)
+			if (sub->can_unwind || (s && !sub->bail_unwinds))
 				continue;
 			for (i = sub->start; i < sub[1].start && !sub->can_unwind; i++) {
 				sub->can_unwind = aux[i].loop_guard ||
@@ -903,6 +904,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 		goto out;
 	}
 	bpf_mark_subprogs_that_unwind(env);
+	env->prog->aux->can_unwind = env->subprog_info[0].can_unwind;
 	for (s = 0; s < env->subprog_cnt && !err; s++) {
 		sub = &env->subprog_info[s];
 		cnt = collect_pads(env, s, new, pad_aux, &pads);
kernel/bpf/verifier.c +7 -4
index 07fdc4fc7ebc..784810772b11 100644
@@ -25437,10 +25437,13 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
 				prog_extension ? "Extension" : "Tracing");
 			return -EINVAL;
 		}
-		/* unwind_exit of the main prog is exit */
-		tgt_can_unwind = subprog && aux->func && aux->func[subprog]->aux->can_unwind;
-		/* unwind_exit would return to the trampoline that called the target */
-		if (tgt_can_unwind && !prog_extension &&
+		tgt_can_unwind = aux->func ? aux->func[subprog]->aux->can_unwind : aux->can_unwind;
+		/*
+		 * unwind_exit or cancel_exit would return to the trampoline that called the target.
+		 * The main program leaves with exit. An extension ends in its own main program and
+		 * never unwinds into its caller, so it replaces no function that can unwind.
+		 */
+		if (tgt_can_unwind && (subprog || prog_extension) &&
 		    prog->expected_attach_type != BPF_TRACE_FENTRY) {
 			bpf_log(log, "Only fentry can attach to %s, which can unwind\n", tname);
 			return -EINVAL;
tools/testing/selftests/bpf/prog_tests/unwind_attach.c +2 -1
index 674c5272cf75..5ec96f478493 100644
@@ -103,8 +103,9 @@ void test_unwind_attach(void)
 	/* unwind_exit would return to the trampoline */
 	attach(tgt_fd, "global_unwinds", "fexit_unwind",
 	       "Only fentry can attach to global_unwinds", 0);
-	attach(tgt_fd, "global_unwinds", "freplace_returns", NULL, 9);
 	/* Nothing unwinds from an extension into the prog that it extends */
+	attach(tgt_fd, "global_unwinds", "freplace_returns",
+	       "Only fentry can attach to global_unwinds", 0);
 	attach(plain_fd, "global_never_unwinds", "freplace_unwinds",
 	       "unwind_exit in the main program of an extension", 0);
 	ASSERT_EQ(run(tgt_fd), 15, "retval");
Signature · 1 line
2.53.1-Meta
author maintainer
#40 lore raw

PATCH 40/73 bpf: Let landing pads pass on the value of unwind_exit

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently a generated landing pad drops what its callee left in R0. A pad of a subprog ends in 'r0 = 0; unwind_exit' and a pad of the main program in 'r0 = V; exit', where V is the value of the program type, bpf_cancelled_retval(). For bpf_throw(7) to go through landing pads, the 7 has to get from the frame that throws to the main program.

Let a landing pad after a call pass on the R0 that it is entered with. unwind_exit, the unwind labels of the helpers and the inlined bpf_loop() keep R0 already. The calls of a pad clobber R0, so the pad keeps the value in a hidden word of the frame, the value word. Like a hidden slot it lies below the stack of the function, where no access of the program reaches, and only the landing pads of the function write it:

today now

       call leaf                          call leaf
       unwind_goto pad                    unwind_goto pad
       ...                                ...

pad: call bpf_rcu_read_unlock pad: *(u64 *)(r10 - 8) = r0
r0 = 0 call bpf_rcu_read_unlock
unwind_exit r0 = *(u64 *)(r10 - 8)
unwind_exit

The first frame that is exited sets the value. A pad of a may_goto, a recursion check or a fault in arena loads V, also in a subprog, where it loaded 0. A program that unwinds with 'r0 = x; unwind_exit' sets x, and the verifier checks x at that insn like R0 at the exit of the main program. No value is checked in an async callback, whose return value nobody reads.

Only a program that calls bpf_throw() needs to return anything but V. In any other program x is not checked, and a pad after a call still drops it and ends in 'r0 = V'.

Three rejections are new:

- In every program, unwind_exit of a global subprog needs a scalar or a pointer to arena in R0, also in a function that returns void.
- In a program with bpf_throw(), a landing pad after a call must not be entered with a pointer in R0.
- In a program with bpf_throw(), the stack of a function needs room for the value word.

Liveness finds R0 dead after a call whose result the program does not use. So in a program with bpf_throw(), bpf_frame_live_regs() adds R0 for a state whose callee left with unwind_exit.

---
 include/linux/bpf_verifier.h | 41 +++++++++++++++++++++---
 kernel/bpf/const_fold.c      |  2 +-
 kernel/bpf/fixups.c          |  9 +++---
 kernel/bpf/helpers.c         |  2 +-
 kernel/bpf/join.c            |  2 +-
 kernel/bpf/pads.c            | 46 +++++++++++++++++++++++++--
 kernel/bpf/precision.c       |  2 +-
 kernel/bpf/states.c          | 13 +++-----
 kernel/bpf/verifier.c        | 61 +++++++++++++++++++++++++++---------
 9 files changed, 138 insertions(+), 40 deletions(-)
include/linux/bpf_verifier.h +36 -5
index 91d8831de4e9..e53a9f8618f6 100644
@@ -489,17 +489,19 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_NO_EXIT,
 	BPF_CONFLICT_NO_PERFMON,
 	BPF_CONFLICT_CALLER_SAVED,
+	BPF_CONFLICT_NO_VALUE,
+	BPF_CONFLICT_NO_ROOM,
 };
 
 /*
  * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument, a test and
- * the call. The 3 are the insns that leave the frame.
+ * the call. The 4 are one insn that saves the value and three that leave the frame.
  */
 #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 + 3)
+				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 4)
 #define BPF_PAD_MAX_CANDS	6
 /*
  * The most insns that keep hidden slots up to date at one call: nine for each of at most
@@ -1460,10 +1462,14 @@ struct bpf_subprog_info {
 	u16 stack_extra;
 	u16 arena_stack_depth; /* size of the frame in the stack in arena */
 	u32 cycle; /* the first subprog of its cycle of the call graph, 0 if it is on none */
+	/*
+	 * The hidden words of its frame, as offsets from R10. 0: it has none.
+	 * The value word: its landing pads keep the value there over their calls.
+	 */
+	s16 value_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().
-	 * An offset from R10, 0: none.
+	 * flags that the subprog saves or a pointer that it releases, see bpf_pad_note_return()
 	 */
 	s16 pend_off;
 	u32 insns_total;
@@ -1819,6 +1825,7 @@ struct bpf_verifier_env {
 	bool bypass_spec_v4;
 	/* a global function is verified for BPF_FUNC_CTX_NO_RCU_LOCK */
 	bool no_rcu_read_lock;
+	bool has_throw;			/* the program has a call of bpf_throw() */
 	bool signature;
 	u8 bug:1;			/* ends the load, see bpf_note_bug() */
 	u8 log_level:7;			/* of the user */
@@ -2267,6 +2274,16 @@ bool bpf_insn_leaves_loop(struct bpf_verifier_env *env, int h, int n);
 int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
 
 /* pads.c */
+
+/*
+ * Is the landing pad of a site of @kind entered with the value that the program is to return?
+ * Only in a program with bpf_throw(), after a call whose callee did not return.
+ */
+static inline bool bpf_site_has_value(const struct bpf_verifier_env *env, enum bpf_site_kind kind)
+{
+	return env->has_throw && kind == BPF_SITE_CALL;
+}
+
 struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_site_kind kind);
 struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx,
 				      enum bpf_site_kind kind);
@@ -2369,6 +2386,20 @@ static inline u32 bpf_frame_insn_idx(const struct bpf_verifier_state *st, u32 fr
 	       : st->frame[frame + 1]->callsite;
 }
 
+/*
+ * The registers of @frame that are live where @st is. A state whose callee did not return goes to
+ * a landing pad that is not in the program yet and that reads R0, see bpf_site_has_value().
+ */
+static inline u16 bpf_frame_live_regs(const struct bpf_verifier_env *env,
+				      const struct bpf_verifier_state *st, u32 frame)
+{
+	u16 live = env->insn_aux_data[bpf_frame_insn_idx(st, frame)].live_regs_before;
+
+	if (st->unwound && env->has_throw && frame == st->curframe)
+		live |= BIT(BPF_REG_0);
+	return live;
+}
+
 static inline bool bpf_is_spilled_reg(const struct bpf_stack_state *stack)
 {
 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
@@ -2618,7 +2649,7 @@ 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);
 
 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
-int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog);
+int bpf_cancelled_retval(struct bpf_verifier_env *env);
 bool bpf_prog_may_run_in_nmi(const struct bpf_verifier_env *env);
 bool bpf_obj_free_runs_dtor(const struct btf *btf, u32 btf_id);
 int bpf_iter_slots_valid_init(const struct bpf_func_state *state, int spi, const struct btf *btf,
kernel/bpf/const_fold.c +1 -1
index 1a84ba1d27bf..17d208f1ed0e 100644
@@ -306,7 +306,7 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 			 */
 			if (r == BPF_REG_0 && i + 1 < insn_cnt &&
 			    bpf_is_sync_callback_calling_insn(&insns[i]) &&
-			    bpf_is_unwind_goto(&insns[i + 1]))
+			    (bpf_is_unwind_goto(&insns[i + 1]) || env->has_throw))
 				continue;
 			switch (c->state) {
 			case CONST_ARG_CONST: {
kernel/bpf/fixups.c +4 -5
index a20830a628e7..233eca6e0df0 100644
@@ -597,7 +597,7 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
 {
 	int n = 0;
 
-	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env, s));
+	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env));
 	if (bpf_ret_reg_pair(env, s))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
 	buf[n++] = unwind_exit_insn(env, s);
@@ -1009,8 +1009,8 @@ static int emit_stack_check(struct bpf_insn *buf, int off)
  *	if (r10 is in the upper half of the kernel stack) goto body;
  *	bpf_prog_report_recursion();
  * bail:
- *	r0 = 0;
- *	exit;
+ *	r0 = bpf_cancelled_retval();
+ *	cancel_exit;			or exit, see emit_unwind_exit()
  * body:
  *
  * It is the stack as it is: whatever is there is counted, be it the callers of the prog in the
@@ -1022,8 +1022,7 @@ static int emit_stack_check(struct bpf_insn *buf, int off)
  * check_max_stack_depth() looked at together with that frame.
  *
  * A subprog that calls itself twice doesn't have to go deep to go on forever: hence may_goto.
- * Once the time slice of the invocation is over every call returns at once, and the frames
- * that are there come to an end.
+ * Once the time slice of the invocation is over the next call cancels the program.
  */
 int bpf_insert_recursion_checks(struct bpf_verifier_env *env)
 {
kernel/bpf/helpers.c +1 -1
index bc6f2a8da05e..1b55e9158332 100644
@@ -1275,7 +1275,7 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
 
 	key = map_key_from_value(map, value, &idx);
 
-	/* The verifier checked that return value is zero. */
+	/* The return value is ignored. It need not be 0 after unwind_exit or a cancellation. */
 	bpf_run_async_cb(prog, callback_fn, map, key, value);
 
 	this_cpu_write(hrtimer_running, NULL);
kernel/bpf/join.c +1 -1
index 0d88c3477652..466693fa0b80 100644
@@ -245,7 +245,7 @@ int bpf_states_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst
 	bpf_equations_pre_join(env, dst, src, leftover_loop, leftover_loop && widen);
 	for (j.fr = 0; j.fr <= dst->curframe; j.fr++)
 		join_func(&j, dst->frame[j.fr], src->frame[j.fr],
-			  env->insn_aux_data[bpf_frame_insn_idx(dst, j.fr)].live_regs_before);
+			  bpf_frame_live_regs(env, dst, j.fr));
 	bpf_equations_post_join(env, dst, src);
 	dst->max_held_cnt = max(dst->max_held_cnt, src->max_held_cnt);
 	/*
kernel/bpf/pads.c +43 -3

95 lines not on this page · raw message

kernel/bpf/precision.c +1 -1
index feaab0485bdb..776fb82b11ec 100644
@@ -177,7 +177,7 @@ u64 bpf_hash_live_types(struct bpf_verifier_env *env, const struct bpf_verifier_
 		aux = &env->insn_aux_data[bpf_frame_insn_idx(st, fr)];
 		bits = bpf_spi_to_xreg(bpf_stack_nr_slots(st->frame[fr]));
 		bitmap_zero(live, bits);
-		live[0] = aux->live_regs_before & XREG_REGS;
+		live[0] = bpf_frame_live_regs(env, st, fr) & XREG_REGS;
 		bpf_add_slots(live, aux->live_stack_before, bits);
 		bpf_add_cost(env, bitmap_weight(live, bits), BPF_COST_COPY);
 		for_each_set_bit(xregno, live, bits) {
kernel/bpf/states.c +4 -9
index 18f82546fa09..9201e3cbc448 100644
@@ -269,12 +269,8 @@ int bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_s
 	err = bpf_live_stack_query_init(env, st);
 	if (err)
 		return err;
-	for (i = 0; i <= st->curframe; i++) {
-		u32 ip = bpf_frame_insn_idx(st, i);
-		u16 live_regs = env->insn_aux_data[ip].live_regs_before;
-
-		__clean_func_state(env, st->frame[i], live_regs, i);
-	}
+	for (i = 0; i <= st->curframe; i++)
+		__clean_func_state(env, st->frame[i], bpf_frame_live_regs(env, st, i), i);
 	bpf_equations_clean(env, st);
 	return bpf_renumber_ids(env, st);
 }
@@ -626,9 +622,8 @@ static bool loop_stack_safe(struct bpf_func_state *old, struct bpf_func_state *c
  * the type in the current state is meaningful.
  */
 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
-			      struct bpf_func_state *cur, u32 insn_idx)
+			      struct bpf_func_state *cur, u16 live_regs)
 {
-	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
 	u16 i;
 
 	if (old->callback_depth > cur->callback_depth ||
@@ -664,7 +659,7 @@ bool bpf_state_subsumes(struct bpf_verifier_env *env, const struct bpf_verifier_
 
 	for (i = 0; i <= old->curframe; i++)
 		if (!func_states_equal(env, old->frame[i], cur->frame[i],
-				       bpf_frame_insn_idx(old, i)))
+				       bpf_frame_live_regs(env, old, i)))
 			return false;
 
 	if (!bpf_equations_subsume(env, old, cur))
kernel/bpf/verifier.c +47 -14

144 lines not on this page · raw message

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

PATCH 41/73 bpf: Keep a reference of the caller that a function finds NULL

In reply to Kumar Kartikeya Dwivedi

A function that is verified separately from its callers, as a recursive function is, has the references of its caller in its state but none of the caller's registers:

  static struct pair *throw_if_null(struct pair *p, long depth)
  {
          if (!p)
                  bpf_throw(0);
          if (depth)
                  throw_if_null(p, depth - 1);
          return p;
  }

Currently, when such a function finds a pointer of the caller to be NULL, the verifier drops the caller's reference from the state and verifies the call once more in the frames of the caller. With a recursion of unknown depth it runs out of frames, and the program is rejected. The function above loads today only because bpf_throw() ends its path in the verifier. Once bpf_throw() cancels the program through landing pads, a state comes back to the caller from the path with NULL.

Keep the reference instead, and mark it on the path with NULL, see found_null and ref_of_caller(). The verifier compares the mark, so such a state stays apart from the states that lack it. No register of the function holds the pointer after the test, so the function cannot release the reference. What follows depends on how the function is exited:

- If it is cancelled, the state goes to the caller with the reference held and without the mark. The landing pad of the caller tests the pointer for NULL before it releases it. The call is not verified a second time.
- If it returns, the caller may rely on what the function found. The call is verified once more in the frames of the caller, as before.

Two cases need care:

- A landing pad of the program after the call starts with the reference held and a pointer that can be NULL, also on the path on which the function found NULL. It has to test the pointer itself.
- The verifier still rejects a throw while a reference is held, so check_reference_leak() skips a reference that has the mark at a throw.

For programs that load today, a landing pad after a call whose callee is cancelled on the path with NULL now sees a pointer that can be NULL. Until now the call was verified once more with the pointer known to be NULL.

---
 include/linux/bpf_verifier.h |  9 ++++-
 kernel/bpf/verifier.c        | 71 ++++++++++++++++++++++++++++++------
 2 files changed, 67 insertions(+), 13 deletions(-)
include/linux/bpf_verifier.h +7 -2
index e53a9f8618f6..4582dddd5e28 100644
@@ -386,10 +386,15 @@ struct bpf_reference_state {
 	/* the insn that brought it into its frame: insn_idx, or a call that returned with it */
 	int origin;
 	union {
-		/* For REF_TYPE_PTR */
+		/* For REF_TYPE_PTR. Compared and hashed as 8 bytes, see same_refs(): no holes. */
 		struct {
 			int parent_id;
-			u32 ctx_arg;	/* it came with that __ref argument, the first is 1 */
+			u16 ctx_arg;	/* it came with that __ref argument, the first is 1 */
+			/*
+			 * A function that is verified separately found the pointer to be NULL,
+			 * and its caller holds the reference, see ref_of_caller()
+			 */
+			u16 found_null;
 		};
 		/* Use to keep track of the source object of a lock, to ensure
 		 * it matches on unlock.
kernel/bpf/verifier.c +60 -11

115 lines not on this page · raw message

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

PATCH 42/73 bpf: Make bpf_throw() cancel the program through landing pads

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

Currently bpf_throw() is a kfunc that walks the stack up to the main program and calls the exception callback, or a default one that returns the argument of bpf_throw(), the cookie. The main program is the exception boundary: it saves every callee-saved register in each invocation, and the callback takes over its frame and restores them. No frame on the way runs any code, so the verifier rejects a throw while the program holds anything, in a callback and under a bpf_spin_lock.

Make a call of bpf_throw() a site. The kfunc is never called: the verifier replaces the call by a jump to the landing pad, which releases what the frame holds and passes on the cookie as the value:

before now

       r6 = r0                        r6 = r0            <- a task
       if r7 < 16 goto +2             if r7 < 16 goto +2
       r1 = 0                         r1 = 0
       call bpf_throw                 gotol pad
       r1 = r6                        r1 = r6
       call bpf_task_release          call bpf_task_release
       ...                            ...
                                 pad: *(u64 *)(r10 - 8) = r1
                                      r1 = r6
                                      call bpf_task_release
                                      r0 = *(u64 *)(r10 - 8)
                                      exit

In a subprog the pad ends in unwind_exit, and the landing pads of the callers pass the value on. A sync callback is cancelled through the unwind label of its helper. An async callback exits, and the value is dropped. The main program, also that of an extension, returns the value. If it has an exception callback, it passes the value to the callback in R1 and returns what the callback returns.

Every landing pad of the main program calls the exception callback after its releases, like any global subprog, and the hidden subprog of the default callback is removed. So the callback also runs when the kernel cancels the program at a loop, a recursion or a fault in arena, with the value of the program type as its argument. That is intended: the callback is where a program chooses what it returns when it did not run to its end. It cannot resume the program, and what it returns is checked like R0 at the exit of the main program, as before. On an LSM hook the value of the program type is -EPERM, and a callback that returns 0 for it allows the operation.

Three cases need care:

- The callback itself can be cancelled. It is not called a second time, and the program returns the value of that cancellation. So the cookie of a throw in the callback, or in a function that it can reach, is checked like R0 at the exit of the main program. A program is rejected if the callback reaches a function only because a helper calls it through an address that was taken elsewhere.
- The call of the callback has an unwind_goto after it only where the callback can leave with unwind_exit. Without it the landing pad stays code that the interpreter and every JIT can run.
- bpf_throw() cannot return, so a program is rejected when the verifier cannot generate the landing pad of a throw. That includes a throw in the callback of a helper without an unwind label.

What changes for programs:

- A program can throw while it holds references, locks or irq flags, in an RCU or preempt section, in a callback and under a bpf_spin_lock.
- A caller keeps nothing over a call of a noreturn function that throws, so a pointer that it holds gets a hidden slot. Such a function stays rejected where its call is the last insn of a function, and where it is global, because it returns as far as the verifier knows.
- A program with bpf_throw() needs CAP_PERFMON, because a landing pad has no speculation barrier, and a JIT that has unwind_exit and unwind_goto. One that is loaded with CAP_BPF alone, or on s390x or powerpc64, is rejected now.
- An exception callback is also called when the kernel cancels the program. Because a landing pad calls it, it shares the stack limit with the main program and cannot use the stack in arena.
- freplace is refused on a function that can throw, on its callers and on a main program that can throw, as on any function that can unwind. fexit and fsession were refused on such a subprog already.
- A main program that can throw no longer saves every callee-saved register. Its landing pad ends in exit, so gen_epilogue() runs and a stack in arena is given back, which the stack walk did not do.

---
 Documentation/bpf/verifier.rst                |  29 ++-
 include/linux/bpf.h                           |   2 +-
 include/linux/bpf_verifier.h                  |  23 +-
 include/linux/filter.h                        |   8 +-
 kernel/bpf/failing_path.c                     |   3 +-
 kernel/bpf/fixups.c                           |  94 +++-----
 kernel/bpf/helpers.c                          |   2 +-
 kernel/bpf/pads.c                             |  18 +-
 kernel/bpf/verifier.c                         | 206 ++++++++----------
 tools/testing/selftests/bpf/DENYLIST.s390x    |   1 +
 .../testing/selftests/bpf/bpf_experimental.h  |  20 +-
 .../selftests/bpf/prog_tests/arena_stack.c    |   6 +-
 .../selftests/bpf/prog_tests/exceptions.c     |  34 +--
 .../selftests/bpf/prog_tests/unwind_attach.c  |   6 +-
 .../selftests/bpf/progs/arena_stack_throw.c   |   1 -
 .../selftests/bpf/progs/exceptions_fail.c     |  37 ++--
 .../selftests/bpf/progs/res_spin_lock_fail.c  |   2 +
 .../bpf/progs/verifier_arena_stack.c          |  33 +--
 .../selftests/bpf/progs/verifier_barrier.c    |  16 +-
 .../bpf/progs/verifier_jumps_ahead.c          |   2 +-
 .../selftests/bpf/progs/verifier_passes.c     |   3 +
 .../bpf/progs/verifier_private_stack.c        |  36 +--
 22 files changed, 249 insertions(+), 333 deletions(-)
Documentation/bpf/verifier.rst +17 -12
index 447df36c380b..ed72a57ed27b 100644
@@ -908,20 +908,20 @@ A recursion in frames is not joined. It has to end in ``MAX_CALL_FRAMES``.
 
 An async callback, for example of a timer, runs later. It starts as a new state
 with an empty stack. ``callx`` is checked as a call of each function that the
-register can hold. ``bpf_throw()`` ends the program from any frame, so nothing
-can be held there.
+register can hold. ``bpf_throw()`` cancels the program from any frame, see
+`Cancellation`_.
 
 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, or the
-stack check of a recursive function fails. 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`` 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.
 
 An insn at which the kernel can cancel the program is a *site*: one of these
-two insns, or a call whose callee can be cancelled. For each site the verifier
+four insns, or a call whose callee can be cancelled. For each site the verifier
 generates a landing pad after the last insn of the function. The pad releases
 what the frame holds at the site and leaves the frame::
 
@@ -943,7 +943,9 @@ 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
 ``bpf_cancelled_retval()``: the one that refuses, drops or changes nothing,
 such as ``TC_ACT_SHOT`` for tc or ``-EPERM`` for an LSM hook that returns an
-errno. It is 0 in the listings here.
+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
@@ -956,7 +958,10 @@ A function *cannot be cancelled* if it has neither ``exit`` nor a call of
 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 and a recursion reject the program.
+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.
 
 Landing pads
 ------------
@@ -1444,9 +1449,9 @@ only speculative states.
 
 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`` and ``unwind_goto``. Without it no function can be
-cancelled, see `Cancellation`_: a loop that needs a ``may_goto`` of the
-verifier and a recursion are rejected.
+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.
 
 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.h +1 -1
index e981d486a337..88dd179ff712 100644
@@ -1919,6 +1919,7 @@ struct bpf_prog_aux {
 	u32 id;
 	u32 func_cnt; /* used by non-func prog as the number of func progs */
 	u32 real_func_cnt; /* includes hidden progs, only used for JIT and freeing progs */
+	u32 exception_callback_subprog; /* index in func[], 0 if there is none */
 	u32 func_idx; /* 0 for non-func prog, the index in func array for func prog */
 	u32 attach_btf_id; /* in-kernel BTF type id to attach to */
 	u32 attach_st_ops_member_off;
@@ -1955,7 +1956,6 @@ struct bpf_prog_aux {
 	bool changes_pkt_data;
 	bool has_prologue;
 	bool might_sleep;
-	bool might_throw;
 	bool can_unwind;
 	/* frames of recursive subprogs can be on the stack when it is called */
 	bool in_recursion;
include/linux/bpf_verifier.h +14 -9
index 4582dddd5e28..46cb7baa46bc 100644
@@ -461,6 +461,7 @@ enum bpf_site_kind {
 	/* a call without unwind_goto whose callee left with unwind_exit */
 	BPF_SITE_CALL,
 	BPF_SITE_FAULT,		/* an access to arena that faults */
+	BPF_SITE_THROW,		/* a call of bpf_throw() */
 };
 
 /* The classes of resources that a landing pad releases */
@@ -500,13 +501,13 @@ enum bpf_pad_conflict {
 
 /*
  * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument, a test and
- * the call. The 4 are one insn that saves the value and three that leave the frame.
+ * the call. The 5 are one insn that saves the value and four that leave the frame.
  */
 #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 + 4)
+				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 5)
 #define BPF_PAD_MAX_CANDS	6
 /*
  * The most insns that keep hidden slots up to date at one call: nine for each of at most
@@ -1484,8 +1485,7 @@ struct bpf_subprog_info {
 	 */
 	s16 fastcall_stack_off;
 	bool has_tail_call: 1;
-	bool might_throw: 1;
-	bool throws: 1; /* as the main pass found it, callx included */
+	bool might_throw: 1; /* it calls bpf_throw(), or what it calls does, see may_not_return() */
 	/*
 	 * It has an unwind_exit, or a landing pad of it leaves with one, see
 	 * bpf_mark_subprogs_that_unwind(). Subprog 0 has the bit for such a site, for freplace.
@@ -1500,6 +1500,7 @@ struct bpf_subprog_info {
 	bool is_cb: 1;
 	bool is_async_cb: 1;
 	bool is_exception_cb: 1;
+	bool in_exception_cb: 1; /* it is the exception callback, or the callback can reach it */
 	/* bpf_loop() or bpf_for_each_map_elem() call it in a loop */
 	bool is_loop_cb: 1;
 	/* another helper or a kfunc calls it */
@@ -1799,7 +1800,6 @@ struct bpf_verifier_env {
 	bool seen_direct_write;
 	/* a register may point to the stack and is not PTR_TO_STACK, see bpf_reg_state::buf */
 	bool seen_stack_slice;
-	bool seen_exception;
 	bool sleepable_async_cb;
 	u32 id_gen;			/* used to generate unique reg IDs */
 	u32 max_stack_depth;		/* maximum combined stack depth */
@@ -1817,7 +1817,6 @@ struct bpf_verifier_env {
 	u32 used_map_cnt;		/* number of used maps */
 	u32 used_btf_cnt;		/* number of used BTF objects */
 	u32 insn_array_map_cnt;		/* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */
-	u32 hidden_subprog_cnt;		/* number of hidden subprogs */
 	int exception_callback_subprog;
 	bool allow_ptr_leaks;
 	/* Allow access to uninitialized stack memory. Writes with fixed offset are
@@ -2282,11 +2281,18 @@ int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
 
 /*
  * Is the landing pad of a site of @kind entered with the value that the program is to return?
- * Only in a program with bpf_throw(), after a call whose callee did not return.
+ * Only in a program with bpf_throw(): at the call of bpf_throw(), and after a call whose callee
+ * did not return.
  */
 static inline bool bpf_site_has_value(const struct bpf_verifier_env *env, enum bpf_site_kind kind)
 {
-	return env->has_throw && kind == BPF_SITE_CALL;
+	return env->has_throw && (kind == BPF_SITE_CALL || kind == BPF_SITE_THROW);
+}
+
+/* The register that has the value when the landing pad of a site of @kind is entered */
+static inline int bpf_site_value_reg(enum bpf_site_kind kind)
+{
+	return kind == BPF_SITE_THROW ? BPF_REG_1 : BPF_REG_0;
 }
 
 struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_site_kind kind);
@@ -2939,7 +2945,6 @@ static inline void bpf_free_kfunc_tab(struct bpf_kfunc_desc_tab *tab)
 }
 
 /* Functions exported from verifier.c, used by fixups.c */
-void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog);
 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env);
 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm);
 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset);
include/linux/filter.h +1 -7
index 3ce4609af05f..c2ebd258e275 100644
@@ -317,15 +317,9 @@ static inline bool bpf_is_unwind_exit(const struct bpf_insn *insn)
 	return insn->code == (BPF_JMP | BPF_EXIT) && insn->src_reg == BPF_UNWIND_EXIT;
 }
 
-/*
- * The caller of the main prog doesn't tell unwind_exit from exit.
- * An exception callback returns from the frame of the main prog. After freplace
- * or a tail call it returns to a prog that wasn't verified with the callback.
- */
+/* The caller of the main prog doesn't tell unwind_exit from exit */
 static inline bool bpf_prog_can_unwind(const struct bpf_prog *prog)
 {
-	if (prog->aux->exception_cb)
-		return false;
 	return bpf_is_subprog(prog);
 }
 
kernel/bpf/failing_path.c +2 -1
index 3c7dfb3270f9..1d5a5782835d 100644
@@ -71,7 +71,8 @@ static int compute_hops(struct bpf_verifier_env *env)
 				 * A frame can leave its function here, see check_loop_guard(),
 				 * check_recursion_guard() and unwind_frame().
 				 */
-				if ((aux->guard_place || (sub[s].cycle && n == sub[s].start)) &&
+				if ((aux->guard_place || (sub[s].cycle && n == sub[s].start) ||
+				     bpf_is_throw_kfunc(&env->prog->insnsi[n])) &&
 				    sub[s].exit_idx != U32_MAX)
 					changed |= shorter(&prec->hops_to_exit[n], 0);
 				if (!bpf_calls_function(env, n))
kernel/bpf/fixups.c +34 -60

182 lines not on this page · raw message

kernel/bpf/helpers.c +1 -1
index 1b55e9158332..d59b1d27324d 100644
@@ -5352,7 +5352,7 @@ BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
 #endif
 BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
 BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL)
-BTF_ID_FLAGS(func, bpf_throw)
+BTF_ID_FLAGS(func, bpf_throw, KF_SPINLOCK_SAFE)
 #ifdef CONFIG_BPF_EVENTS
 BTF_ID_FLAGS(func, bpf_send_signal_task, KF_PERFMON)
 #endif
kernel/bpf/pads.c +13 -5
index ba402a4e10e9..8f675995da71 100644
@@ -7,6 +7,7 @@
  *   - a may_goto that the verifier adds, when the time of the program is up (BPF_SITE_GUARD)
  *   - the stack check at the start of a recursive function (BPF_SITE_RECURSION)
  *   - an access to arena that faults (BPF_SITE_FAULT)
+ *   - a call of bpf_throw() (BPF_SITE_THROW)
  *   - a call whose callee was cancelled (BPF_SITE_CALL)
  * A LANDING PAD is code that the verifier generates for a site. It releases what the frame holds at
  * the site and leaves the frame. Here the loop gets a may_goto, which jumps to the pad when the
@@ -98,8 +99,8 @@
  * A helper that calls a callback is a C frame between the callback and its caller. It passes a
  * cancellation on from its unwind label to the unwind_goto after its own call, see bpf_call_cb().
  * The frame that the kernel called leaves with exit, and the program returns the value of the
- * cancellation: bpf_cancelled_retval(), which goes by the program type.
- * In a program with bpf_throw() the pad after a call passes on the R0 that it is
+ * cancellation: bpf_cancelled_retval(), which goes by the program type, or the argument of
+ * bpf_throw(). In a program with bpf_throw() the pad after a call passes on the R0 that it is
  * entered with, and keeps it over its calls in a hidden word, the value word.
  *
  * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
@@ -2286,10 +2287,14 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 		  struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
 {
 	int value_off = env->subprog_info[subprog].value_off;
+	int src = bpf_site_value_reg(plan->kind), dst = BPF_REG_0;
 	int class, i, n = 0;
 
+	/* the main program hands the value to the exception callback */
+	if (!subprog && env->exception_callback_subprog)
+		dst = BPF_REG_1;
 	if (plan_saves_value(env, plan))
-		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_0, value_off);
+		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, src, value_off);
 	n += release_ents(env, plan, PAD_TURN_RCU_ITERS, &buf[n], &aux[n]);
 	n += release_ents(env, plan, PAD_TURN_LOCKS, &buf[n], &aux[n]);
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
@@ -2301,9 +2306,11 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 		for (i = 0; i < pad_enters(plan, class); i++)
 			buf[n++] = enter_call(class);
 	if (plan_saves_value(env, plan))
-		buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_FP, value_off);
+		buf[n++] = BPF_LDX_MEM(BPF_DW, dst, BPF_REG_FP, value_off);
 	else if (!bpf_site_has_value(env, plan->kind))
-		buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env));
+		buf[n++] = BPF_MOV64_IMM(dst, bpf_cancelled_retval(env));
+	else if (src != dst)
+		buf[n++] = BPF_MOV64_REG(dst, src);
 	if (bpf_ret_reg_pair(env, subprog))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
 	return n;
@@ -3012,6 +3019,7 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		[BPF_SITE_RECURSION]		= "recursion check",
 		[BPF_SITE_CALL]			= "call",
 		[BPF_SITE_FAULT]		= "arena access",
+		[BPF_SITE_THROW]		= "bpf_throw",
 	};
 	static const char * const why[] = {
 		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
kernel/bpf/verifier.c +92 -114

480 lines not on this page · raw message

tools/testing/selftests/bpf/DENYLIST.s390x +1 -0
index f7e1e5f5511c..92786c6a9071 100644
@@ -1,5 +1,6 @@
 # TEMPORARY
 # Alphabetical order
+exceptions                               # JIT does not support unwinding                                              (bpf_throw)
 exe_ctx                                  # execution context check (e.g., hardirq, softirq, etc)
 get_stack_raw_tp                         # user_stack corrupted user stack                                             (no backchain userspace)
 stacktrace_build_id                      # compare_map_keys stackid_hmap vs. stackmap err -2 errno 2                   (?)
tools/testing/selftests/bpf/bpf_experimental.h +10 -10
index 2893bf06ff25..92ed34e8233f 100644
@@ -26,21 +26,21 @@ extern void bpf_iter_task_vma_destroy(struct bpf_iter_task_vma *it) __ksym;
 /* Description
  *	Throw a BPF exception from the program, immediately terminating its
  *	execution and unwinding the stack. The supplied 'cookie' parameter
- *	will be the return value of the program when an exception is thrown,
- *	and the default exception callback is used. Otherwise, if an exception
- *	callback is set using the '__exception_cb(callback)' declaration tag
- *	on the main program, the 'cookie' parameter will be the callback's only
- *	input argument.
+ *	will be the return value of the program when an exception is thrown.
+ *	Otherwise, if an exception callback is set using the
+ *	'__exception_cb(callback)' declaration tag on the main program, the
+ *	'cookie' parameter will be the callback's only input argument.
  *
- *	Thus, in case of default exception callback, 'cookie' is subjected to
+ *	Thus, without an exception callback, 'cookie' is subjected to
  *	constraints on the program's return value (as with R0 on exit).
  *	Otherwise, the return value of the marked exception callback will be
  *	subjected to the same checks.
+ *	A throw in an async callback ends that callback alone. A throw in the
+ *	exception callback ends the program with 'cookie', checked like R0.
  *
- *	Note that throwing an exception with lingering resources (locks,
- *	references, etc.) will lead to a verification error.
- *
- *	Note that callbacks *cannot* call this helper.
+ *	Each frame releases the resources that it holds (locks, references,
+ *	etc.) on the way, in a landing pad that the verifier emits. If it
+ *	cannot tell what a frame holds there is a verification error.
  * Returns
  *	Never.
  * Throws
tools/testing/selftests/bpf/prog_tests/arena_stack.c +3 -3
index 20950a8df3d8..d0d42b7a600f 100644
@@ -118,7 +118,7 @@ static void test_nesting(struct arena_stack *skel)
 	sched_setaffinity(0, sizeof(old), &old);
 }
 
-/* bpf_throw() doesn't return the stack. Programs run when all stacks of the cpu are taken. */
+/* The landing pad of bpf_throw() ends in an exit, which returns the stack */
 static void test_throw(struct arena_stack *skel)
 {
 	cpu_set_t old;
@@ -264,8 +264,8 @@ static void test_no_memory(void)
 }
 
 /*
- * bpf_throw() in a main program that has stack arguments. The exception callback restores the
- * registers of the caller.
+ * bpf_throw() in a main program that has stack arguments. The registers of the caller are as they
+ * were.
  */
 static void test_throw_stack_args(void)
 {
tools/testing/selftests/bpf/prog_tests/exceptions.c +17 -17
index fc36cd226fb1..b3997022bae7 100644
@@ -266,7 +266,7 @@ static void test_exceptions_success(void)
 		}), "", 0);
 
 	if (test__start_subtest("non-throwing fexit -> throwing subprog"))
-		/* non-throwing fexit -> throwing subprog : BAD */
+		/* non-throwing fexit -> throwing subprog : BAD (it unwinds past the trampoline) */
 		RUN_EXT(-EINVAL, true, ({
 			prog = eskel->progs.pfexit;
 			bpf_program__set_autoload(prog, true);
@@ -274,10 +274,10 @@ static void test_exceptions_success(void)
 				       bpf_program__fd(skel->progs.exception_throw_subprog),
 				       "throwing_subprog"), "set_attach_target"))
 				goto done;
-		}), "Only fentry can attach to throwing_subprog, which can throw", 0);
+		}), "Only fentry can attach to throwing_subprog", 0);
 
 	if (test__start_subtest("throwing fexit -> throwing subprog"))
-		/* throwing fexit -> throwing subprog : BAD */
+		/* throwing fexit -> throwing subprog : BAD (it unwinds past the trampoline) */
 		RUN_EXT(-EINVAL, true, ({
 			prog = eskel->progs.throwing_fexit;
 			bpf_program__set_autoload(prog, true);
@@ -285,7 +285,7 @@ static void test_exceptions_success(void)
 				       bpf_program__fd(skel->progs.exception_throw_subprog),
 				       "throwing_subprog"), "set_attach_target"))
 				goto done;
-		}), "Only fentry can attach to throwing_subprog, which can throw", 0);
+		}), "Only fentry can attach to throwing_subprog", 0);
 
 	/* fmod_ret not allowed for subprog - Check so we remember to handle its
 	 * throwing specification compatibility with target when supported.
@@ -333,7 +333,7 @@ static void test_exceptions_success(void)
 				       bpf_program__fd(skel->progs.exception_throw_subprog),
 				       "throwing_subprog"), "set_attach_target"))
 				goto done;
-		}), "Cannot replace static functions", 0);
+		}), "Only fentry can attach to throwing_subprog", 0);
 
 	if (test__start_subtest("non-throwing extension -> non-throwing subprog"))
 		/* non-throwing extension -> non-throwing global subprog : OK */
@@ -347,26 +347,26 @@ static void test_exceptions_success(void)
 		}), "", 0);
 
 	if (test__start_subtest("non-throwing extension -> throwing global subprog"))
-		/* non-throwing extension -> throwing global subprog : OK */
-		RUN_EXT(0, false, ({
+		/* non-throwing extension -> throwing global subprog : BAD (its callers have landing pads) */
+		RUN_EXT(-EINVAL, true, ({
 			prog = eskel->progs.extension;
 			bpf_program__set_autoload(prog, true);
 			if (!ASSERT_OK(bpf_program__set_attach_target(prog,
 				       bpf_program__fd(skel->progs.exception_throw_subprog),
 				       "throwing_global_subprog"), "set_attach_target"))
 				goto done;
-		}), "", 0);
+		}), "Only fentry can attach to throwing_global_subprog", 0);
 
 	if (test__start_subtest("throwing extension -> throwing global subprog"))
-		/* throwing extension -> throwing global subprog : OK */
-		RUN_EXT(0, false, ({
+		/* throwing extension -> throwing global subprog : BAD (its callers have landing pads) */
+		RUN_EXT(-EINVAL, true, ({
 			prog = eskel->progs.throwing_extension;
 			bpf_program__set_autoload(prog, true);
 			if (!ASSERT_OK(bpf_program__set_attach_target(prog,
 				       bpf_program__fd(skel->progs.exception_throw_subprog),
 				       "throwing_global_subprog"), "set_attach_target"))
 				goto done;
-		}), "", 0);
+		}), "Only fentry can attach to throwing_global_subprog", 0);
 
 	if (test__start_subtest("throwing extension -> non-throwing global subprog"))
 		/* throwing extension -> non-throwing global subprog : OK */
@@ -380,26 +380,26 @@ static void test_exceptions_success(void)
 		}), "", 0);
 
 	if (test__start_subtest("non-throwing extension -> main subprog"))
-		/* non-throwing extension -> main subprog : OK */
-		RUN_EXT(0, false, ({
+		/* non-throwing extension -> main subprog : BAD (it throws) */
+		RUN_EXT(-EINVAL, true, ({
 			prog = eskel->progs.extension;
 			bpf_program__set_autoload(prog, true);
 			if (!ASSERT_OK(bpf_program__set_attach_target(prog,
 				       bpf_program__fd(skel->progs.exception_throw_subprog),
 				       "exception_throw_subprog"), "set_attach_target"))
 				goto done;
-		}), "", 0);
+		}), "Only fentry can attach to exception_throw_subprog", 0);
 
 	if (test__start_subtest("throwing extension -> main subprog"))
-		/* throwing extension -> main subprog : OK */
-		RUN_EXT(0, false, ({
+		/* throwing extension -> main subprog : BAD (it throws) */
+		RUN_EXT(-EINVAL, true, ({
 			prog = eskel->progs.throwing_extension;
 			bpf_program__set_autoload(prog, true);
 			if (!ASSERT_OK(bpf_program__set_attach_target(prog,
 				       bpf_program__fd(skel->progs.exception_throw_subprog),
 				       "exception_throw_subprog"), "set_attach_target"))
 				goto done;
-		}), "", 0);
+		}), "Only fentry can attach to exception_throw_subprog", 0);
 
 done:
 	exceptions_ext__destroy(eskel);
tools/testing/selftests/bpf/prog_tests/unwind_attach.c +3 -3
index 5ec96f478493..6e3733aef105 100644
@@ -111,9 +111,9 @@ void test_unwind_attach(void)
 	ASSERT_EQ(run(tgt_fd), 15, "retval");
 
 	/*
-	 * An exception callback returns from the frame of the main prog. Here
-	 * that's a return to a call that unwind_goto follows. unwind_exit of
-	 * the callback has to be exit: the pad wasn't verified with it.
+	 * The pad of the main prog calls the exception callback and leaves with
+	 * exit. unwind_exit of the callback gets to that exit like its exit
+	 * does: nothing unwinds into the prog that is extended.
 	 */
 	shared_fd = bpf_program__fd(tgt->progs.shared_pad);
 	attach(shared_fd, "global_never_unwinds", "freplace_throws", NULL, 3);
tools/testing/selftests/bpf/progs/arena_stack_throw.c +0 -1
index ac14139fb901..82a1fdb05c76 100644
@@ -26,7 +26,6 @@ long never, throws, regs[4];
 
 /*
  * r6-r9 are in registers that a callee keeps. What the kfunc returns with is stored in regs[].
- * A program that can throw saves all such registers, so its own caller is not affected.
  */
 SEC("syscall")
 __naked int calls_kfunc(void)
tools/testing/selftests/bpf/progs/exceptions_fail.c +19 -18
index 22503cf62e9f..9481ee97767d 100644
@@ -106,12 +106,12 @@ int reject_exception_cb_type_5(struct __sk_buff *ctx)
 __noinline
 static int timer_cb(void *map, int *key, struct bpf_timer *timer)
 {
-	bpf_throw(0);
+	bpf_throw(1);
 	return 0;
 }
 
 SEC("?tc")
-__failure __msg("cannot be called from callback subprog")
+__success __retval(0)
 int reject_async_callback_throw(struct __sk_buff *ctx)
 {
 	struct hmap_elem *elem;
@@ -129,11 +129,12 @@ __noinline static int subprog_lock(struct __sk_buff *ctx)
 	bpf_spin_lock(&lock);
 	if (ctx->len)
 		bpf_throw(0);
+	bpf_spin_unlock(&lock);
 	return ret;
 }
 
 SEC("?tc")
-__failure __msg("function calls are not allowed while holding a lock")
+__success __retval(0)
 int reject_with_lock(void *ctx)
 {
 	bpf_spin_lock(&lock);
@@ -142,14 +143,14 @@ int reject_with_lock(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("function calls are not allowed while holding a lock")
+__success __retval(0)
 int reject_subprog_with_lock(void *ctx)
 {
 	return subprog_lock(ctx);
 }
 
 SEC("?tc")
-__failure __msg("bpf_throw cannot be used inside bpf_rcu_read_lock-ed region")
+__success __retval(0)
 int reject_with_rcu_read_lock(void *ctx)
 {
 	bpf_rcu_read_lock();
@@ -165,7 +166,7 @@ __noinline static int throwing_subprog(struct __sk_buff *ctx)
 }
 
 SEC("?tc")
-__failure __msg("bpf_throw cannot be used inside bpf_rcu_read_lock-ed region")
+__success __retval(0)
 int reject_subprog_with_rcu_read_lock(void *ctx)
 {
 	bpf_rcu_read_lock();
@@ -181,7 +182,7 @@ static bool rbless(struct bpf_rb_node *n1, const struct bpf_rb_node *n2)
 }
 
 SEC("?tc")
-__failure __msg("function calls are not allowed while holding a lock")
+__success __retval(0)
 int reject_with_rbtree_add_throw(void *ctx)
 {
 	struct foo *f;
@@ -196,7 +197,7 @@ int reject_with_rbtree_add_throw(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference")
+__success __retval(0)
 int reject_with_reference(void *ctx)
 {
 	struct foo *f;
@@ -216,7 +217,7 @@ __noinline int global_subprog_may_throw(struct __sk_buff *ctx)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference")
+__success __retval(0)
 int reject_global_subprog_throw_with_reference(struct __sk_buff *ctx)
 {
 	struct foo *f;
@@ -248,7 +249,7 @@ __noinline static int subprog_cb_ref(u32 i, void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference")
+__success __retval(0)
 int reject_with_cb_reference(void *ctx)
 {
 	struct foo *f;
@@ -262,7 +263,7 @@ int reject_with_cb_reference(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("cannot be called from callback")
+__success __retval(0)
 int reject_with_cb(void *ctx)
 {
 	bpf_loop(5, subprog_cb_ref, NULL, 0);
@@ -270,7 +271,7 @@ int reject_with_cb(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference")
+__success __retval(0)
 int reject_with_subprog_reference(void *ctx)
 {
 	return subprog_ref(ctx) + 1;
@@ -304,7 +305,7 @@ __noinline int global_func(struct __sk_buff *ctx)
 
 SEC("?tc")
 __exception_cb(throwing_exception_cb)
-__failure __msg("cannot be called from callback subprog")
+__success __retval(0)
 int reject_throwing_exception_cb(struct __sk_buff *ctx)
 {
 	return 0;
@@ -370,7 +371,7 @@ __noinline static int loop_cb2(u32 index, int *ctx)
 }
 
 SEC("?tc")
-__failure __msg("cannot be called from callback")
+__success __retval(0)
 int reject_exception_throw_cb(struct __sk_buff *ctx)
 {
 	bpf_loop(5, loop_cb1, NULL, 0);
@@ -378,7 +379,7 @@ int reject_exception_throw_cb(struct __sk_buff *ctx)
 }
 
 SEC("?tc")
-__failure __msg("cannot be called from callback")
+__success __retval(0)
 int reject_exception_throw_cb_diff(struct __sk_buff *ctx)
 {
 	if (ctx->protocol)
@@ -417,7 +418,7 @@ __noinline static int rcu_lock_then_throw(void)
 }
 
 SEC("?tc")
-__failure __msg("bpf_throw cannot be used inside bpf_rcu_read_lock-ed region")
+__success __retval(0)
 int reject_subprog_rcu_lock_throw(void *ctx)
 {
 	rcu_lock_then_throw();
@@ -425,7 +426,7 @@ int reject_subprog_rcu_lock_throw(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("bpf_throw cannot be used inside bpf_preempt_disable-ed region")
+__success __retval(0)
 int reject_subprog_throw_preempt_lock(void *ctx)
 {
 	bpf_preempt_disable();
@@ -435,7 +436,7 @@ int reject_subprog_throw_preempt_lock(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("bpf_throw cannot be used inside bpf_local_irq_save-ed region")
+__success __retval(0)
 int reject_subprog_throw_irq_lock(void *ctx)
 {
 	unsigned long flags;
tools/testing/selftests/bpf/progs/res_spin_lock_fail.c +2 -0
index 8fd591bd1f6c..2f180c99590b 100644
@@ -203,6 +203,8 @@ int res_spin_lock_bad_off(struct __sk_buff *ctx)
 }
 
 SEC("?tc")
+__arch_x86_64
+__arch_arm64
 __failure __msg("R1 doesn't have constant offset. bpf_res_spin_lock has to be at the constant offset")
 int res_spin_lock_var_off(struct __sk_buff *ctx)
 {
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +1 -32
index 63697cbd5a92..ca7bdbd7e1ce 100644
@@ -501,38 +501,7 @@ __naked void kfunc_stack_args(void)
 	: __clobber_all);
 }
 
-/*
- * bpf_throw() finds the registers that the main program saved from its stack pointer at the
- * call. x86 moves rsp for a kfunc that has stack arguments. bpf_throw() is not one of them.
- */
-SEC("syscall")
-__description("arena stack: no move of the stack pointer in front of bpf_throw()")
-__success
-__arch_x86_64
-__jited("	movq	%r9, {{.*}}(%rbp)")
-__jited("	callq	{{.*}}")
-__naked void throw_stack_args_jit(void)
-{
-	asm volatile (
-	".8byte %[adj];"
-	"r1 = 1;"
-	"r2 = 2;"
-	"r3 = 3;"
-	"r4 = 4;"
-	"r5 = 5;"
-	"*(u64 *)(r11 - 16) = 7;"
-	"*(u64 *)(r11 - 8) = 6;"
-	"call callee_7args;"
-	"r1 = r0;"
-	"call %[bpf_throw];"
-	"exit;"
-	:
-	: __imm(bpf_throw),
-	  __imm_insn(adj, ADJ(16))
-	: __clobber_all);
-}
-
-/* The caller of the program goes on with the registers that the exception callback restores */
+/* The landing pad leaves through the epilogue of the program, like any exit */
 SEC("syscall")
 __description("arena stack: the main program has stack arguments and throws")
 __success __retval(675)
tools/testing/selftests/bpf/progs/verifier_barrier.c +7 -9
index cb6ae13141ae..0982873ed0c5 100644
@@ -310,16 +310,14 @@ static __naked __noinline __used int throw_if_zero(void)
 	"exit;");
 }
 
-/* The code after the first call is dead. The load must not replace it. */
+/*
+ * The code after the first call is dead. bpf_throw() unwinds through the landing pad of the call,
+ * and a prog that is loaded without CAP_PERFMON gets none.
+ */
 SEC("tc")
-__description("barrier: after a call that never returns")
-__success SPECULATES __success_unpriv
-#ifdef SPEC_V1
-__xlated_unpriv("r1 = 0")
-__xlated_unpriv("call pc+")
-__xlated_unpriv("nospec")
-__xlated_unpriv("goto pc-2")
-#endif
+__description("bpf_throw() needs CAP_PERFMON")
+__success SPECULATES __failure_unpriv
+__msg_unpriv("CAP_PERFMON is required to unwind")
 __naked void never_returns(void)
 {
 	ASM(START
tools/testing/selftests/bpf/progs/verifier_jumps_ahead.c +1 -1
index 7fc4a3c2acdc..1d49346f1466 100644
@@ -541,7 +541,7 @@ void __kfunc_btf_root(void)
  * far ahead to keep 0 and 1 of the flag apart.
  */
 #define FLAG_AND_COOKIE(name, no, yes)			\
-__arch_x86_64 __arch_arm64 __arch_s390x			\
+__arch_x86_64 __arch_arm64				\
 __naked void name(void)					\
 {							\
 	asm volatile (					\
tools/testing/selftests/bpf/progs/verifier_passes.c +3 -0
index 8b6db6898570..d17254990744 100644
@@ -1087,6 +1087,9 @@ int calls_hold_other_things(struct __sk_buff *skb)
  * a recursive function is verified on its own, also with an argument that can be NULL. When its
  * check of the stack fails it is unwound, and the landing pad of the caller drops the object: it
  * returns only with a pointer that it has tested.
+ * bpf_throw() unwinds through the callers as well. On the path with NULL the function still has
+ * the reference of its caller, who tests the pointer: it stays on its own.
+ * The progs call kfuncs and are unwound, which takes a JIT: without one they are not loaded.
  */
 static __noinline struct pair *throw_if_null(struct pair *p, long depth)
 {
tools/testing/selftests/bpf/progs/verifier_private_stack.c +7 -29
index ed2a40475125..8f689ca69871 100644
@@ -308,21 +308,8 @@ SEC("fentry/bpf_fentry_test9")
 __description("Private stack, exception in main prog")
 __success __retval(0)
 __arch_x86_64
-__jited("	pushq	%r9")
-__jited("...")
-__jited("	callq")
-__jited("	popq	%r9")
+__jited("	movq	%rdi, -0x200(%r9)")
 __arch_arm64
-__jited("	stp	x29, x30, [sp, #-0x10]!")
-__jited("	mov	x29, sp")
-__jited("	stp	xzr, x26, [sp, #-0x10]!")
-__jited("	mov	x26, sp")
-__jited("...")
-__jited("	stp	x19, x20, [sp, #-0x10]!")
-__jited("	stp	x21, x22, [sp, #-0x10]!")
-__jited("	stp	x23, x24, [sp, #-0x10]!")
-__jited("	stp	x25, x26, [sp, #-0x10]!")
-__jited("	stp	x27, x28, [sp, #-0x10]!")
 __jited("	mov	x27, {{.*}}")
 __jited("	movk	x27, {{.*}}, lsl #16")
 __jited("	movk	x27, {{.*}}")
@@ -331,10 +318,6 @@ __jited("	add	x27, x27, x10")
 __jited("	add	x25, x27, {{.*}}")
 __jited("	mov	x0, #0x2a")
 __jited("	str	x0, [x27]")
-__jited("	mov	x0, #0x0")
-__jited("	bl	0x{{.*}}")
-__jited("	mov	x8, x0")
-__jited("	ldp	x27, x28, [sp], #0x10")
 int private_stack_exception_main_prog(void)
 {
 	asm volatile ("			\
@@ -362,7 +345,6 @@ __jited("...")
 __jited("	callq")
 __jited("	popq	%r9")
 __arch_arm64
-__jited("	stp	x27, x28, [sp, #-0x10]!")
 __jited("	mov	x27, {{.*}}")
 __jited("	movk	x27, {{.*}}, lsl #16")
 __jited("	movk	x27, {{.*}}")
@@ -371,9 +353,6 @@ __jited("	add	x27, x27, x10")
 __jited("	add	x25, x27, {{.*}}")
 __jited("	mov	x0, #0x2a")
 __jited("	str	x0, [x27]")
-__jited("	bl	0x{{.*}}")
-__jited("	mov	x8, x0")
-__jited("	ldp	x27, x28, [sp], #0x10")
 int private_stack_exception_sub_prog(void)
 {
 	asm volatile ("			\
@@ -387,8 +366,8 @@ int private_stack_exception_sub_prog(void)
 
 /*
  * Nothing attaches the two fentry progs above, so they are loaded, but never
- * run. BPF_PROG_TEST_RUN does run a raw_tp prog. The default exception callback
- * returns the cookie of bpf_throw().
+ * run. BPF_PROG_TEST_RUN does run a raw_tp prog. It returns the cookie of
+ * bpf_throw().
  */
 SEC("raw_tp")
 __description("Private stack, run, exception in main prog")
@@ -396,9 +375,8 @@ __success __retval(1)
 __arch_x86_64
 __jited("	movq	%rdi, -0x200(%r9)")
 __jited("	movl	$0x1, %edi")
-__jited("	pushq	%r9")
-__jited("...")
-__jited("	callq")
+__jited("	movq	%rdi, %rax")
+__jited("	leave")
 __naked void private_stack_run_exception_main_prog(void)
 {
 	asm volatile ("			\
@@ -461,7 +439,7 @@ __naked static void private_stack_subprog_throw(void)
 	: __clobber_all);
 }
 
-/* Only the frame of the main prog counts, and it has nothing pushed at the call */
+/* The frame that throws has a private stack, the one that it unwinds to has none */
 SEC("raw_tp")
 __description("Private stack, run, exception in subprog, no private stack in main prog")
 __success __retval(3)
@@ -472,7 +450,7 @@ __jited("func #1")
 __jited("...")
 __jited("	movq	%rdi, -0x200(%r9)")
 __jited("	movl	$0x3, %edi")
-__jited("	pushq	%r9")
+__jited("	movq	%rdi, %rax")
 __naked void no_private_stack_run_exception_sub_prog(void)
 {
 	asm volatile ("				\
Signature · 1 line
2.53.1-Meta
author maintainer
#43 lore raw

PATCH 43/73 bpf, x86: Remove the exception boundary

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

The x86-64 JIT still has the code of the exception boundary, which served the stack walk of bpf_throw(). A main program that could throw saved r12, rbx, r13, r14 and r15 in each invocation, used or not, so that the exception callback could restore them. The callback had a prologue of its own, which took over rsp and rbp of that frame.

A call of bpf_throw() is a jump to a landing pad now. Each frame leaves through its own epilogue, and a landing pad of the main program calls the exception callback like any subprog. Nothing sets exception_boundary and exception_cb of a program any more.

Remove the code that reads them, and the store to stack_arg_sp_adjust, which told bpf_throw() where the saved registers are.

The native code does not change: both bits are 0 already.

---
 arch/x86/net/bpf_jit_comp.c | 95 +++++++------------------------------
 1 file changed, 17 insertions(+), 78 deletions(-)
arch/x86/net/bpf_jit_comp.c +17 -78
index e91148abbfbb..aa0d760deeb5 100644
@@ -33,7 +33,6 @@ void __asan_load8(void *p);
 void __asan_store8(void *p);
 #endif
 
-static bool all_callee_regs_used[4] = {true, true, true, true};
 
 static u8 *emit_code(u8 *ptr, u32 bytes, unsigned int len)
 {
@@ -517,8 +516,7 @@ static void emit_prologue_tail_call(u8 **pprog, bool is_subprog)
  * while jumping to another program
  */
 static void emit_prologue(u8 **pprog, u8 *ip, u32 stack_depth, bool ebpf_from_cbpf,
-			  bool tail_call_reachable, bool is_subprog,
-			  bool is_exception_cb)
+			  bool tail_call_reachable, bool is_subprog)
 {
 	u8 *prog = *pprog;
 
@@ -541,22 +539,8 @@ static void emit_prologue(u8 **pprog, u8 *ip, u32 stack_depth, bool ebpf_from_cb
 			/* Keep the same instruction layout. */
 			emit_nops(&prog, 3);     /* nop3 */
 	}
-	/* Exception callback receives FP as third parameter */
-	if (is_exception_cb) {
-		EMIT3(0x48, 0x89, 0xF4); /* mov rsp, rsi */
-		EMIT3(0x48, 0x89, 0xD5); /* mov rbp, rdx */
-		/* The main frame must have exception_boundary as true, so we
-		 * first restore those callee-saved regs from stack, before
-		 * reusing the stack frame.
-		 */
-		pop_callee_regs(&prog, all_callee_regs_used);
-		pop_r12(&prog);
-		/* Reset the stack frame. */
-		EMIT3(0x48, 0x89, 0xEC); /* mov rsp, rbp */
-	} else {
-		EMIT1(0x55);             /* push rbp */
-		EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
-	}
+	EMIT1(0x55);             /* push rbp */
+	EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
 
 	/* X86_TAIL_CALL_OFFSET is here */
 	EMIT_ENDBR();
@@ -848,14 +832,9 @@ static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
 	/* Inc tail_call_cnt if the slot is populated. */
 	EMIT4(0x48, 0x83, 0x00, 0x01);            /* add qword ptr [rax], 1 */
 
-	if (bpf_prog->aux->exception_boundary) {
-		pop_callee_regs(&prog, all_callee_regs_used);
+	pop_callee_regs(&prog, callee_regs_used);
+	if (bpf_prog_uses_arena_insns(bpf_prog))
 		pop_r12(&prog);
-	} else {
-		pop_callee_regs(&prog, callee_regs_used);
-		if (bpf_prog_uses_arena_insns(bpf_prog))
-			pop_r12(&prog);
-	}
 
 	/* Pop tail_call_cnt_ptr. */
 	EMIT1(0x58);                              /* pop rax */
@@ -914,14 +893,9 @@ static void emit_bpf_tail_call_direct(struct bpf_prog *bpf_prog,
 	/* Inc tail_call_cnt if the slot is populated. */
 	EMIT4(0x48, 0x83, 0x00, 0x01);                /* add qword ptr [rax], 1 */
 
-	if (bpf_prog->aux->exception_boundary) {
-		pop_callee_regs(&prog, all_callee_regs_used);
+	pop_callee_regs(&prog, callee_regs_used);
+	if (bpf_prog_uses_arena_insns(bpf_prog))
 		pop_r12(&prog);
-	} else {
-		pop_callee_regs(&prog, callee_regs_used);
-		if (bpf_prog_uses_arena_insns(bpf_prog))
-			pop_r12(&prog);
-	}
 
 	/* Pop tail_call_cnt_ptr. */
 	EMIT1(0x58);                                  /* pop rax */
@@ -2528,40 +2502,22 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 	emit_prologue(&prog, image, stack_depth,
 		      bpf_prog_was_classic(bpf_prog), tail_call_reachable,
-		      bpf_is_subprog(bpf_prog), bpf_prog->aux->exception_cb);
+		      bpf_is_subprog(bpf_prog));
 
 	bpf_prog->aux->ksym.fp_start = prog - temp - cfi_get_offset();
 	bpf_prog->aux->ksym.fp_end = U32_MAX;
 
-	/* Exception callback will clobber callee regs for its own use, and
-	 * restore the original callee regs from main prog's stack frame.
-	 */
-	if (bpf_prog->aux->exception_boundary) {
-		/* We also need to save r12, which is not mapped to any BPF
-		 * register, as we throw after entry into the kernel, which may
-		 * overwrite r12.
-		 */
+	if (arena_vm_start)
 		push_r12(&prog);
-		push_callee_regs(&prog, all_callee_regs_used);
-	} else {
-		if (arena_vm_start)
-			push_r12(&prog);
-		push_callee_regs(&prog, callee_regs_used);
-	}
+	push_callee_regs(&prog, callee_regs_used);
 
 	/* Compute callee-saved register area size. */
 	callee_saved_size = 0;
-	if (bpf_prog->aux->exception_boundary || arena_vm_start)
+	if (arena_vm_start)
 		callee_saved_size += 8; /* r12 */
-	if (bpf_prog->aux->exception_boundary) {
-		callee_saved_size += 4 * 8; /* rbx, r13, r14, r15 */
-	} else {
-		int j;
-
-		for (j = 0; j < 4; j++)
-			if (callee_regs_used[j])
-				callee_saved_size += 8;
-	}
+	for (i = 0; i < 4; i++)
+		if (callee_regs_used[i])
+			callee_saved_size += 8;
 	/*
 	 * Base offset from rbp for translating BPF outgoing args 7+
 	 * to native offsets. BPF uses negative offsets from r11
@@ -2590,15 +2546,6 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 	outgoing_rsp = out_stack_arg_cnt > 1 ? (out_stack_arg_cnt - 1) * 8 : 0;
 	if (arena_sp)
 		outgoing_rsp = out_stack_arg_cnt * 8;
-	/*
-	 * bpf_throw() sees rsp of this frame as it is at a call. The callee-saved
-	 * regs are above the outgoing args, or above r9, which is pushed around
-	 * every call when the stack is private. With BPF_REG_ARENA_SP the slot
-	 * that keeps r9 over calls is between the two.
-	 */
-	if (bpf_prog->aux->exception_boundary)
-		bpf_prog->aux->stack_arg_sp_adjust = outgoing_rsp +
-						     (priv_frame_ptr || arena_sp_save ? 8 : 0);
 	emit_sub_rsp(&prog, outgoing_rsp);
 
 	if (arena_vm_start)
@@ -3437,10 +3384,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				if (err < 0)
 					return err;
 				ip += err;
-				/*
-				 * Other kfuncs leave rsp alone. bpf_throw() is one of
-				 * them, see stack_arg_sp_adjust.
-				 */
+				/* Other kfuncs leave rsp alone. */
 				arena_sp_args = arena_sp && kfunc_has_stack_args(fm);
 				if (arena_sp_args) {
 					u8 *start = prog;
@@ -3833,14 +3777,9 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			}
 			/* Deallocate outgoing args 7+ area and the slot of BPF_REG_ARENA_SP. */
 			emit_add_rsp(&prog, outgoing_rsp + (arena_sp_save ? 8 : 0));
-			if (bpf_prog->aux->exception_boundary) {
-				pop_callee_regs(&prog, all_callee_regs_used);
+			pop_callee_regs(&prog, callee_regs_used);
+			if (arena_vm_start)
 				pop_r12(&prog);
-			} else {
-				pop_callee_regs(&prog, callee_regs_used);
-				if (arena_vm_start)
-					pop_r12(&prog);
-			}
 			EMIT1(0xC9);         /* leave */
 			bpf_prog->aux->ksym.fp_ret = proglen + (prog - temp) - cfi_get_offset();
 
Signature · 1 line
2.53.1-Meta
author maintainer
#44 lore raw

PATCH 44/73 bpf, arm64: Remove the exception boundary

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

The arm64 JIT still has the code of the exception boundary, which served the stack walk of bpf_throw(). A main program that could throw saved x19-x28 in each invocation, used or not, so that the exception callback could restore them. The callback had a prologue of its own, which took over the frame of the main program. It also dropped the return address of bpf_throw() from the shadow call stack.

A call of bpf_throw() is a jump to a landing pad now. Each frame leaves through its own epilogue, and a landing pad of the main program calls the exception callback like any subprog. Nothing sets exception_boundary and exception_cb of a program any more.

Remove the code that reads them.

The native code does not change: both bits are 0 already.

---
 arch/arm64/net/bpf_jit_comp.c | 128 ++++++++++------------------------
 1 file changed, 37 insertions(+), 91 deletions(-)
arch/arm64/net/bpf_jit_comp.c +37 -91
index 5e4e08a65ea3..475a7ae2c356 100644
@@ -15,7 +15,6 @@
 #include <linux/filter.h>
 #include <linux/memory.h>
 #include <linux/printk.h>
-#include <linux/scs.h>
 #include <linux/slab.h>
 
 #include <asm/asm-extable.h>
@@ -862,64 +861,35 @@ static void push_callee_regs(struct jit_ctx *ctx)
 {
 	int reg1, reg2, i;
 
-	/*
-	 * Program acting as exception boundary should save all ARM64
-	 * Callee-saved registers as the exception callback needs to recover
-	 * all ARM64 Callee-saved registers in its epilogue.
-	 */
-	if (ctx->prog->aux->exception_boundary) {
-		emit(A64_PUSH(A64_R(19), A64_R(20), A64_SP), ctx);
-		emit(A64_PUSH(A64_R(21), A64_R(22), A64_SP), ctx);
-		emit(A64_PUSH(A64_R(23), A64_R(24), A64_SP), ctx);
-		emit(A64_PUSH(A64_R(25), A64_R(26), A64_SP), ctx);
-		emit(A64_PUSH(A64_R(27), A64_R(28), A64_SP), ctx);
-		ctx->fp_used = true;
-	} else {
-		find_used_callee_regs(ctx);
-		for (i = 0; i + 1 < ctx->nr_used_callee_reg; i += 2) {
-			reg1 = ctx->used_callee_reg[i];
-			reg2 = ctx->used_callee_reg[i + 1];
-			emit(A64_PUSH(reg1, reg2, A64_SP), ctx);
-		}
-		if (i < ctx->nr_used_callee_reg) {
-			reg1 = ctx->used_callee_reg[i];
-			/* keep SP 16-byte aligned */
-			emit(A64_PUSH(reg1, A64_ZR, A64_SP), ctx);
-		}
+	find_used_callee_regs(ctx);
+	for (i = 0; i + 1 < ctx->nr_used_callee_reg; i += 2) {
+		reg1 = ctx->used_callee_reg[i];
+		reg2 = ctx->used_callee_reg[i + 1];
+		emit(A64_PUSH(reg1, reg2, A64_SP), ctx);
+	}
+	if (i < ctx->nr_used_callee_reg) {
+		reg1 = ctx->used_callee_reg[i];
+		/* keep SP 16-byte aligned */
+		emit(A64_PUSH(reg1, A64_ZR, A64_SP), ctx);
 	}
 }
 
 /* Restore callee-saved registers */
 static void pop_callee_regs(struct jit_ctx *ctx)
 {
-	struct bpf_prog_aux *aux = ctx->prog->aux;
 	int reg1, reg2, i;
 
-	/*
-	 * Program acting as exception boundary pushes R23 and R24 in addition
-	 * to BPF callee-saved registers. Exception callback uses the boundary
-	 * program's stack frame, so recover these extra registers in the above
-	 * two cases.
-	 */
-	if (aux->exception_boundary || aux->exception_cb) {
-		emit(A64_POP(A64_R(27), A64_R(28), A64_SP), ctx);
-		emit(A64_POP(A64_R(25), A64_R(26), A64_SP), ctx);
-		emit(A64_POP(A64_R(23), A64_R(24), A64_SP), ctx);
-		emit(A64_POP(A64_R(21), A64_R(22), A64_SP), ctx);
-		emit(A64_POP(A64_R(19), A64_R(20), A64_SP), ctx);
-	} else {
-		i = ctx->nr_used_callee_reg - 1;
-		if (ctx->nr_used_callee_reg % 2 != 0) {
-			reg1 = ctx->used_callee_reg[i];
-			emit(A64_POP(reg1, A64_ZR, A64_SP), ctx);
-			i--;
-		}
-		while (i > 0) {
-			reg1 = ctx->used_callee_reg[i - 1];
-			reg2 = ctx->used_callee_reg[i];
-			emit(A64_POP(reg1, reg2, A64_SP), ctx);
-			i -= 2;
-		}
+	i = ctx->nr_used_callee_reg - 1;
+	if (ctx->nr_used_callee_reg % 2 != 0) {
+		reg1 = ctx->used_callee_reg[i];
+		emit(A64_POP(reg1, A64_ZR, A64_SP), ctx);
+		i--;
+	}
+	while (i > 0) {
+		reg1 = ctx->used_callee_reg[i - 1];
+		reg2 = ctx->used_callee_reg[i];
+		emit(A64_POP(reg1, reg2, A64_SP), ctx);
+		i -= 2;
 	}
 }
 
@@ -999,51 +969,27 @@ static int build_prologue(struct jit_ctx *ctx, bool ebpf_from_cbpf)
 	emit(A64_MOV(1, A64_R(9), A64_LR), ctx);
 	emit(A64_NOP, ctx);
 
-	if (!prog->aux->exception_cb) {
-		/* Sign lr */
-		if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
-			emit(A64_PACIASP, ctx);
+	/* Sign lr */
+	if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
+		emit(A64_PACIASP, ctx);
 
-		/* Save FP and LR registers to stay align with ARM64 AAPCS */
-		emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
-		emit(A64_MOV(1, A64_FP, A64_SP), ctx);
+	/* Save FP and LR registers to stay align with ARM64 AAPCS */
+	emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
+	emit(A64_MOV(1, A64_FP, A64_SP), ctx);
 
-		prepare_bpf_tail_call_cnt(ctx);
+	prepare_bpf_tail_call_cnt(ctx);
 
-		if (!ebpf_from_cbpf && is_main_prog) {
-			cur_offset = ctx->idx - idx0;
-			if (cur_offset != PROLOGUE_OFFSET) {
-				pr_err_once("PROLOGUE_OFFSET = %d, expected %d!\n",
-						cur_offset, PROLOGUE_OFFSET);
-				return -1;
-			}
-			/* BTI landing pad for the tail call, done with a BR */
-			emit_bti(A64_BTI_J, ctx);
+	if (!ebpf_from_cbpf && is_main_prog) {
+		cur_offset = ctx->idx - idx0;
+		if (cur_offset != PROLOGUE_OFFSET) {
+			pr_err_once("PROLOGUE_OFFSET = %d, expected %d!\n",
+					cur_offset, PROLOGUE_OFFSET);
+			return -1;
 		}
-		push_callee_regs(ctx);
-	} else {
-		/*
-		 * Exception callback receives FP of Main Program as third
-		 * parameter
-		 */
-		emit(A64_MOV(1, A64_FP, A64_R(2)), ctx);
-		/*
-		 * Main Program already pushed the frame record and the
-		 * callee-saved registers. The exception callback will not push
-		 * anything and re-use the main program's stack.
-		 *
-		 * 12 registers are on the stack
-		 */
-		emit(A64_SUB_I(1, A64_SP, A64_FP, 96), ctx);
-		/*
-		 * Pop the return address of bpf_throw() from the shadow call
-		 * stack. The frames of the JIT put nothing there.
-		 */
-		if (scs_is_enabled())
-			emit(A64_SUB_I(1, A64_R(18), A64_R(18), 8), ctx);
-		/* The callback may use its own BPF stack, set up fp for it. */
-		ctx->fp_used = true;
+		/* BTI landing pad for the tail call, done with a BR */
+		emit_bti(A64_BTI_J, ctx);
 	}
+	push_callee_regs(ctx);
 
 	/* Stack must be multiples of 16B */
 	ctx->stack_size = round_up(prog->aux->stack_depth, 16);
Signature · 1 line
2.53.1-Meta
author maintainer
#45 lore raw

PATCH 45/73 s390/bpf: Remove the exception boundary

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

The s390x JIT still has the code of the exception boundary, which served the stack walk of bpf_throw(). A main program that could throw saved %r6-%r15 in each invocation, used or not. The exception callback switched to the stack of that frame and restored them in its epilogue.

A call of bpf_throw() is a jump to a landing pad now, and landing pads need unwind_exit and unwind_goto in the JIT. The s390x JIT has neither, so the verifier rejects a program that calls bpf_throw() there with "JIT does not support unwinding" until the JIT has the two insns. Nothing sets exception_boundary and exception_cb of a program any more.

Remove the code that reads them: NVREGS, and the extra_regs argument of save_restore_regs(), which is 0 in all remaining calls.

arch_bpf_stack_walk() stays, because BPF streams print the stack with it.

---
 arch/s390/net/bpf_jit_comp.c | 38 +++++++++---------------------------
 1 file changed, 9 insertions(+), 29 deletions(-)
arch/s390/net/bpf_jit_comp.c +9 -29
index d6c3c4270a0b..5d3cfa3fe49e 100644
@@ -62,8 +62,6 @@ struct bpf_jit {
 #define SEEN_FUNC	BIT(2)		/* calls C functions */
 #define SEEN_STACK	(SEEN_FUNC | SEEN_MEM)
 
-#define NVREGS		0xffc0		/* %r6-%r15 */
-
 /*
  * s390 registers
  */
@@ -517,9 +515,8 @@ static int get_end(u16 seen_regs, int start)
  * Save and restore clobbered registers (6-15) on stack.
  * We save/restore registers in chunks with gap >= 2 registers.
  */
-static void save_restore_regs(struct bpf_jit *jit, int op, u16 extra_regs)
+static void save_restore_regs(struct bpf_jit *jit, int op)
 {
-	u16 seen_regs = jit->seen_regs | extra_regs;
 	const int last = 15, save_restore_size = 6;
 	int re = 6, rs;
 
@@ -533,10 +530,10 @@ static void save_restore_regs(struct bpf_jit *jit, int op, u16 extra_regs)
 	}
 
 	do {
-		rs = get_start(seen_regs, re);
+		rs = get_start(jit->seen_regs, re);
 		if (!rs)
 			break;
-		re = get_end(seen_regs, rs + 1);
+		re = get_end(jit->seen_regs, rs + 1);
 		if (op == REGS_SAVE)
 			save_regs(jit, rs, re);
 		else
@@ -633,21 +630,8 @@ static void bpf_jit_prologue(struct bpf_jit *jit, struct bpf_prog *fp)
 	}
 	/* Tail calls have to skip above initialization */
 	jit->tail_call_start = jit->prg - cfi_get_offset();
-	if (fp->aux->exception_cb) {
-		/*
-		 * Switch stack, the new address is in the 2nd parameter.
-		 *
-		 * Arrange the restoration of %r6-%r15 in the epilogue.
-		 * Do not restore them now, the prog does not need them.
-		 */
-		/* lgr %r15,%r3 */
-		EMIT4(0xb9040000, REG_15, REG_3);
-		jit->seen_regs |= NVREGS;
-	} else {
-		/* Save registers */
-		save_restore_regs(jit, REGS_SAVE,
-				  fp->aux->exception_boundary ? NVREGS : 0);
-	}
+	/* Save registers */
+	save_restore_regs(jit, REGS_SAVE);
 	/* Setup literal pool */
 	if (is_first_pass(jit) || (jit->seen & SEEN_LITERAL)) {
 		if (!is_first_pass(jit) &&
@@ -699,7 +683,7 @@ static void bpf_jit_epilogue(struct bpf_jit *jit)
 	/* Load exit code: lgr %r2,%b0 */
 	EMIT4(0xb9040000, REG_2, BPF_REG_0);
 	/* Restore registers */
-	save_restore_regs(jit, REGS_RESTORE, 0);
+	save_restore_regs(jit, REGS_RESTORE);
 	EMIT_JUMP_REG(14);
 
 	jit->prg = ALIGN(jit->prg, 8);
@@ -1973,7 +1957,7 @@ static noinline int bpf_jit_insn(struct bpf_jit *jit, struct bpf_prog *fp,
 		/*
 		 * Restore registers before calling function
 		 */
-		save_restore_regs(jit, REGS_RESTORE, 0);
+		save_restore_regs(jit, REGS_RESTORE);
 
 		/*
 		 * goto *(prog->bpf_func + tail_call_start);
@@ -3096,12 +3080,8 @@ void arch_bpf_stack_walk(bool (*consume_fn)(void *, u64, u64, u64),
 			break;
 		/*
 		 * addr is a return address and state.sp is the value of %r15
-		 * at this address. exception_cb needs %r15 at entry to the
-		 * function containing addr, so take the next state.sp.
-		 *
-		 * There is no bp, and the exception_cb prog does not need one
-		 * to perform a quasi-longjmp. The common code requires a
-		 * non-zero bp, so pass sp there as well.
+		 * at this address. Pass the next state.sp, which is %r15 at
+		 * entry to the function containing addr. There is no bp.
 		 */
 		if (prev_addr && !consume_fn(cookie, prev_addr, state.sp,
 					     state.sp))
Signature · 1 line
2.53.1-Meta
author maintainer
#46 lore raw

PATCH 46/73 powerpc64/bpf: Remove the exception boundary

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

The powerpc64 JIT still has the code of the exception boundary, which served the stack walk of bpf_throw(). A main program that could throw had a larger frame and saved r14-r25 in each invocation, on top of the registers that hold R6-R10. The exception callback took over that frame and restored them in its epilogue.

A call of bpf_throw() is a jump to a landing pad now, and landing pads need unwind_exit and unwind_goto in the JIT. The powerpc64 JIT has neither, so the verifier rejects a program that calls bpf_throw() there with "JIT does not support unwinding" until the JIT has the two insns. Nothing sets exception_boundary and exception_cb of a program any more.

Remove the code that reads them: the two flags of the codegen context, the larger frame with its save area for r14-r25, and the prologue and epilogue of the callback.

arch_bpf_stack_walk() stays, because BPF streams print the stack with it.

---
 arch/powerpc/net/bpf_jit.h        |   2 -
 arch/powerpc/net/bpf_jit_comp.c   |   2 -
 arch/powerpc/net/bpf_jit_comp64.c | 145 ++++--------------------------
 3 files changed, 19 insertions(+), 130 deletions(-)
arch/powerpc/net/bpf_jit.h +0 -2
index 4da8bde92e1e..f65c06039ac5 100644
@@ -183,8 +183,6 @@ struct codegen_context {
 	u64 arena_vm_start;
 	u64 user_vm_start;
 	bool is_subprog;
-	bool exception_boundary;
-	bool exception_cb;
 	void __percpu *priv_sp;
 	unsigned int priv_stack_size;
 };
arch/powerpc/net/bpf_jit_comp.c +0 -2
index c246709a15ce..b7147bb31ce3 100644
@@ -272,8 +272,6 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		cgctx.user_vm_start = bpf_arena_get_user_vm_start(fp->aux->arena);
 	}
 	cgctx.is_subprog = bpf_is_subprog(fp);
-	cgctx.exception_boundary = fp->aux->exception_boundary;
-	cgctx.exception_cb = fp->aux->exception_cb;
 	cgctx.priv_sp = priv_stack_ptr;
 	cgctx.priv_stack_size = 0;
 	if (priv_stack_ptr) {
arch/powerpc/net/bpf_jit_comp64.c +19 -126

241 lines not on this page · raw message

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

PATCH 47/73 bpf: Remove the stack walk of bpf_throw()

In reply to Kumar Kartikeya Dwivedi

From: Alexei Starovoitov <[email protected]>

bpf_throw() still has a body that walks the stack up to the main program and calls the exception callback there. No program calls the kfunc any
more: the verifier replaces each call of it by a jump to a landing pad. Programs and libbpf name the function, so it stays in BTF, with a WARN_ON_ONCE() for a body.

Remove what served the walk. For each piece, what it did and what replaces it:

bpf_stack_walker(), The walk from bpf_throw() up to the
struct bpf_throw_ctx main program. Each frame leaves
through its landing pad instead.
bpf_exception_cb The pointer through which bpf_throw()
called the exception callback. A landing pad of the main program calls the callback with a call insn.
exception_boundary, The bits that told a JIT to emit the
exception_cb exception boundary and the prologue of
the callback. Nothing sets or reads them any more.
stack_arg_sp_adjust Where bpf_throw() found the registers
that the main program saved on x86-64. Nothing sets or reads it any more.
real_func_cnt func_cnt plus the hidden subprog of the
default exception callback, which no longer exists. Its readers use func_cnt.
bpf_jit_supports_exceptions() "The stack can be walked from a kfunc
up to the main program." A program with bpf_throw() needs bpf_jit_supports_unwind() instead.

bpf_throw() was notrace, NOKPROBE_SYMBOL() and not instrumented by KASAN, because it did not return. It is an ordinary function now.

bpf_prog_has_invocation_budget() asked bpf_jit_supports_exceptions() too, because the report of a recursion that is out of stack walks the stack. So a recursive program was rejected where the stack cannot be walked, on x86-64 without ORC, with "JIT does not support recursive calls". Such a program loads there now. When its recursion is out of stack, arch_bpf_stack_walk() finds nothing and there is no report.

arch_bpf_stack_walk() stays: BPF streams and bpf_prog_find_from_stack() use it.

---
 arch/arm64/net/bpf_jit_comp.c   | 10 -------
 arch/powerpc/net/bpf_jit_comp.c |  5 ----
 arch/s390/net/bpf_jit_comp.c    |  9 ------
 arch/x86/net/bpf_jit_comp.c     |  9 ------
 include/linux/bpf.h             |  5 ----
 include/linux/filter.h          |  5 +---
 kernel/bpf/core.c               | 15 ++++------
 kernel/bpf/fixups.c             |  2 --
 kernel/bpf/helpers.c            | 53 +++++----------------------------
 kernel/bpf/syscall.c            |  4 +--
 scripts/gdb/linux/bpf.py        |  4 +--
 11 files changed, 17 insertions(+), 104 deletions(-)
arch/arm64/net/bpf_jit_comp.c +0 -10
index 475a7ae2c356..86f49bf96036 100644
@@ -4002,16 +4002,6 @@ u64 bpf_arch_uaddress_limit(void)
 	return 0;
 }
 
-bool bpf_jit_supports_exceptions(void)
-{
-	/* We unwind through both kernel frames starting from within bpf_throw
-	 * call and BPF frames. Therefore we require FP unwinder to be enabled
-	 * to walk kernel frames and reach BPF frames in the stack trace.
-	 * ARM64 kernel is always compiled with CONFIG_FRAME_POINTER=y
-	 */
-	return true;
-}
-
 bool bpf_jit_supports_arena(void)
 {
 	return true;
arch/powerpc/net/bpf_jit_comp.c +0 -5
index b7147bb31ce3..df44afc79378 100644
@@ -552,11 +552,6 @@ void bpf_jit_free(struct bpf_prog *fp)
 	bpf_prog_unlock_free(fp);
 }
 
-bool bpf_jit_supports_exceptions(void)
-{
-	return IS_ENABLED(CONFIG_PPC64);
-}
-
 bool bpf_jit_supports_subprog_tailcalls(void)
 {
 	return IS_ENABLED(CONFIG_PPC64);
arch/s390/net/bpf_jit_comp.c +0 -9
index 5d3cfa3fe49e..7f9e1c7b7b10 100644
@@ -3059,15 +3059,6 @@ bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
 	return true;
 }
 
-bool bpf_jit_supports_exceptions(void)
-{
-	/*
-	 * Exceptions require unwinding support, which is always available,
-	 * because the kernel is always built with backchain.
-	 */
-	return true;
-}
-
 void arch_bpf_stack_walk(bool (*consume_fn)(void *, u64, u64, u64),
 			 void *cookie)
 {
arch/x86/net/bpf_jit_comp.c +0 -9
index aa0d760deeb5..3a0143c4d212 100644
@@ -5141,15 +5141,6 @@ void bpf_jit_free(struct bpf_prog *prog)
 	bpf_prog_unlock_free(prog);
 }
 
-bool bpf_jit_supports_exceptions(void)
-{
-	/* We unwind through both kernel frames (starting from within bpf_throw
-	 * call) and BPF frames. Therefore we require ORC unwinder to be enabled
-	 * to walk kernel frames and reach BPF frames in the stack trace.
-	 */
-	return IS_ENABLED(CONFIG_UNWINDER_ORC);
-}
-
 bool bpf_jit_supports_private_stack(void)
 {
 	return true;
include/linux/bpf.h +0 -5
index 88dd179ff712..a8e9d12dbe80 100644
@@ -1918,7 +1918,6 @@ struct bpf_prog_aux {
 	u32 stack_depth;
 	u32 id;
 	u32 func_cnt; /* used by non-func prog as the number of func progs */
-	u32 real_func_cnt; /* includes hidden progs, only used for JIT and freeing progs */
 	u32 exception_callback_subprog; /* index in func[], 0 if there is none */
 	u32 func_idx; /* 0 for non-func prog, the index in func array for func prog */
 	u32 attach_btf_id; /* in-kernel BTF type id to attach to */
@@ -1949,8 +1948,6 @@ struct bpf_prog_aux {
 	bool func_proto_unreliable;
 	bool tail_call_reachable;
 	bool xdp_has_frags;
-	bool exception_cb;
-	bool exception_boundary;
 	bool jits_use_priv_stack;
 	bool priv_stack_requested;
 	bool changes_pkt_data;
@@ -2007,8 +2004,6 @@ struct bpf_prog_aux {
 	int cgroup_atype; /* enum cgroup_bpf_attach_type */
 	struct bpf_map *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE];
 	char name[BPF_OBJ_NAME_LEN];
-	u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64);
-	u16 stack_arg_sp_adjust;
 	u16 freplace_link_cnt; /* counts freplace links extending this prog */
 #ifdef CONFIG_SECURITY
 	void *security;
include/linux/filter.h +1 -4
index c2ebd258e275..05a0bf8689a4 100644
@@ -1410,7 +1410,6 @@ u64 bpf_fault_unwind_target(u64 end);
 bool bpf_jit_supports_stack_args(void);
 bool bpf_jit_supports_arena_args(void);
 bool bpf_jit_supports_far_kfunc_call(void);
-bool bpf_jit_supports_exceptions(void);
 bool bpf_jit_supports_ptr_xchg(void);
 bool bpf_jit_supports_arena(void);
 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena);
@@ -1427,13 +1426,11 @@ bool bpf_jit_supports_fsession(void);
  *    emit_stack_check() knows.
  *  - All may_goto of the prog share one time slice. That is the timed form, which only JITed
  *    progs get, see bpf_do_misc_fixups(). The other form counts in each frame.
- *  - A walk of the stack finds the prog when there is no room, to tell user space, see
- *    bpf_prog_report_recursion().
  */
 static inline bool bpf_prog_has_invocation_budget(const struct bpf_prog *prog)
 {
 	return (IS_ENABLED(CONFIG_X86_64) || IS_ENABLED(CONFIG_ARM64)) && prog->jit_requested &&
-	       bpf_jit_supports_timed_may_goto() && bpf_jit_supports_exceptions();
+	       bpf_jit_supports_timed_may_goto();
 }
 
 struct bpf_jit_arg_abi {
kernel/bpf/core.c +5 -10
index 3582cde3cfe3..52fbca734d13 100644
@@ -844,7 +844,7 @@ static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp)
 {
 	int i;
 
-	for (i = 0; i < fp->aux->real_func_cnt; i++)
+	for (i = 0; i < fp->aux->func_cnt; i++)
 		bpf_prog_kallsyms_del(fp->aux->func[i]);
 }
 
@@ -1636,7 +1636,7 @@ int bpf_jit_get_func_addr(const struct bpf_prog *prog,
 		if (!extra_pass)
 			addr = NULL;
 		else if (prog->aux->func &&
-			 imm >= 0 && imm < prog->aux->real_func_cnt)
+			 imm >= 0 && imm < prog->aux->func_cnt)
 			addr = (u8 *)prog->aux->func[imm]->bpf_func;
 		else
 			return -EINVAL;
@@ -3586,7 +3586,7 @@ static void bpf_prog_free_images(struct work_struct *work)
 	int i;
 
 	aux = container_of(to_rcu_work(work), struct bpf_prog_aux, rwork);
-	for (i = 0; i < aux->real_func_cnt; i++) {
+	for (i = 0; i < aux->func_cnt; i++) {
 		/* We can just unlink the subprog poke descriptor table as
 		 * it was originally linked to the main program and is also
 		 * released along with it.
@@ -3594,7 +3594,7 @@ static void bpf_prog_free_images(struct work_struct *work)
 		aux->func[i]->aux->poke_tab = NULL;
 		bpf_jit_free(aux->func[i]);
 	}
-	if (aux->real_func_cnt) {
+	if (aux->func_cnt) {
 		kvfree(aux->func);
 		bpf_prog_unlock_free(aux->prog);
 	} else {
@@ -3612,7 +3612,7 @@ static void bpf_prog_free_deferred(struct work_struct *work)
 	 * A prog that still runs when its last reference goes needs its symbols,
 	 * by which its exception table is found.  It has ended by now.
 	 */
-	ksyms = aux->real_func_cnt || !list_empty(&aux->ksym.lnode);
+	ksyms = aux->func_cnt || !list_empty(&aux->ksym.lnode);
 	bpf_prog_kallsyms_del_all(aux->prog);
 #ifdef CONFIG_BPF_SYSCALL
 	bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab);
@@ -4042,11 +4042,6 @@ int __weak bpf_arch_text_invalidate(void *dst, size_t len)
 	return -ENOTSUPP;
 }
 
-bool __weak bpf_jit_supports_exceptions(void)
-{
-	return false;
-}
-
 bool __weak bpf_jit_supports_private_stack(void)
 {
 	return false;
kernel/bpf/fixups.c +0 -2
index 91aba7d99290..97e147cc73ab 100644
@@ -2177,7 +2177,6 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 		 */
 		func[i]->aux->func = func;
 		func[i]->aux->func_cnt = env->subprog_cnt;
-		func[i]->aux->real_func_cnt = env->subprog_cnt;
 	}
 	for (i = 0; i < env->subprog_cnt; i++) {
 		old_bpf_func = func[i]->bpf_func;
@@ -2238,7 +2237,6 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 	prog->aux->fault_pad = func[0]->aux->fault_pad;
 	prog->aux->func = func;
 	prog->aux->func_cnt = env->subprog_cnt;
-	prog->aux->real_func_cnt = env->subprog_cnt;
 	prog->aux->exception_callback_subprog = env->exception_callback_subprog;
 	bpf_prog_jit_attempt_done(prog);
 	return 0;
kernel/bpf/helpers.c +7 -46

60 lines not on this page · raw message

kernel/bpf/syscall.c +2 -2
index 198438b95849..70112c2c1e40 100644
@@ -3216,7 +3216,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
 	 * period before we can tear down JIT memory since symbols
 	 * are already exposed under kallsyms.
 	 */
-	__bpf_prog_put_noref(prog, prog->aux->real_func_cnt);
+	__bpf_prog_put_noref(prog, prog->aux->func_cnt);
 	return err;
 
 free_prog:
@@ -5071,7 +5071,7 @@ static int bpf_prog_map_addrs(const struct bpf_prog *prog, struct maple_tree *mt
 /* the id of the subprog that starts at insn 'start' */
 static u32 bpf_prog_find_func(const struct bpf_prog *prog, u32 start)
 {
-	u32 l = 0, r = prog->aux->real_func_cnt, m;
+	u32 l = 0, r = prog->aux->func_cnt, m;
 
 	while (r - l > 1) {
 		m = (l + r) / 2;
scripts/gdb/linux/bpf.py +2 -2
index 1870534ef6f9..3a6d69d7ed5b 100644
@@ -88,8 +88,8 @@ def list_progs():
         # func[0] is the current prog.
         aux = prog["aux"]
         func = aux["func"]
-        real_func_cnt = int(aux["real_func_cnt"])
-        for i in range(1, real_func_cnt):
+        func_cnt = int(aux["func_cnt"])
+        for i in range(1, func_cnt):
             progs.append(func[i])
     return progs
 
Signature · 1 line
2.53.1-Meta
author maintainer
#48 lore raw

PATCH 48/73 bpf: Find at a site that a frame holds more than a landing pad releases

In reply to Kumar Kartikeya Dwivedi

A landing pad has at most eight releases apart from the sections that it leaves (BPF_PAD_MAX_ENTS). Each reference or lock that a frame holds needs one, and so does a pointer in a hidden slot. A frame that holds more gets no landing pad, wherever the pointers are.

Currently the verifier finds that late. When a state reaches a site, visit_refs() reports "too much is held" only if a reference that has a location would need a ninth release. A pointer without a location waits for the hidden slots, and whether those fit is decided when the pass is over. That is too late for a loop that acquires a reference in each trip and has no exit but a site:

    for (;;)
            p = bpf_ringbuf_reserve(&rb, 8, 0);

A leaked reference is normally found at an exit, and no state of this loop reaches one. Its states hold one more reference with each trip, and the program is rejected only when the budget of the passes is used up.

Count what the frame holds when a state reaches a site, before anything else. If it is more than a landing pad releases, the verifier cannot generate a pad for that state, and a path-sensitive run finds the error after a few trips:

landing pad of may_goto at 12: conflict: too much is held

A lock taken with bpf_res_spin_lock_irqsave() is two references and one release, so it counts once.

What visit_refs() reported until now is a different case. No single state holds too much, but the states that reach the site hold different things, and each needs a release. The log now says "the paths to the site hold more different things than a pad releases" for it.

A may_goto of the program is about to become a site, and a loop whose only exit is its may_goto is then such a loop.

---
 include/linux/bpf_verifier.h |  3 ++-
 kernel/bpf/pads.c            | 16 ++++++++++++++--
 2 files changed, 16 insertions(+), 3 deletions(-)
include/linux/bpf_verifier.h +2 -1
index 46cb7baa46bc..1d4860542c42 100644
@@ -485,7 +485,8 @@ enum bpf_pad_class {
 enum bpf_pad_conflict {
 	BPF_NO_CONFLICT,
 	BPF_CONFLICT_SECTIONS_DIFFER,
-	BPF_CONFLICT_TOO_MUCH,
+	BPF_CONFLICT_TOO_MUCH,		/* one state holds more than a pad releases */
+	BPF_CONFLICT_PLAN_FULL,		/* the states together hold more different things */
 	BPF_CONFLICT_SLOTS_FULL,	/* the function has more hidden slots than a pad releases */
 	BPF_CONFLICT_NO_RELEASE,
 	BPF_CONFLICT_NOT_ALWAYS_HELD,
kernel/bpf/pads.c +14 -2
index 8f675995da71..57cbeae78edb 100644
@@ -1236,12 +1236,21 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 	const struct bpf_reference_state *ref;
 	struct bpf_pad_ent new, *ent, *prev;
 	struct bpf_pad_nulls nulls;
-	int i, j, arg, pass, err;
+	int i, j, arg, pass, pos, err;
 
 	/* the pad of a call runs after it: its locations are what is live at the next insn */
 	insn_idx += plan->kind == BPF_SITE_CALL;
 	for (i = 0; i < plan->nr_ents; i++)
 		plan->ents[i].ref = -1;
+	/*
+	 * Each reference needs a release of its own, also a pointer without a location, which takes
+	 * a hidden slot. A loop that acquires in each trip and has no exit but this site is
+	 * rejected here: no state of it reaches an exit, where a leak is found.
+	 */
+	for (i = st->frame[st->curframe]->entry_refs, pos = 0; i < st->acquired_refs; i++)
+		pos += !i || st->refs[i - 1].type != REF_TYPE_RES_LOCK_IRQ;
+	if (pos > BPF_PAD_MAX_ENTS)
+		return BPF_CONFLICT_TOO_MUCH;
 	for (pass = 0; pass < 2; pass++) {
 		for (i = st->frame[st->curframe]->entry_refs; i < st->acquired_refs; i++) {
 			ref = &st->refs[i];
@@ -1269,8 +1278,9 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 			ent = match_ent(plan, &new, !pass);
 			if (!ent && !pass)
 				continue;
+			/* the states together need more releases than a pad has */
 			if (!ent && plan->nr_ents == BPF_PAD_MAX_ENTS)
-				return BPF_CONFLICT_TOO_MUCH;
+				return BPF_CONFLICT_PLAN_FULL;
 			if (!ent)
 				ent = add_ent(plan, &new, plan->nr_ents);
 			if (!ent)
@@ -3024,6 +3034,8 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	static const char * const why[] = {
 		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
 		[BPF_CONFLICT_TOO_MUCH]		= "too much is held",
+		[BPF_CONFLICT_PLAN_FULL]	=
+			"the paths to the site hold more different things than a pad releases",
 		[BPF_CONFLICT_SLOTS_FULL]	=
 			"the function has more hidden slots than a pad has entries",
 		[BPF_CONFLICT_NO_RELEASE]	= "the program can call nothing that releases a resource",
Signature · 1 line
2.53.1-Meta
author maintainer
#49 lore raw

PATCH 49/73 bpf: Cancel the program when the time of its own may_goto is up

In reply to Kumar Kartikeya Dwivedi

A may_goto of the program, which can_loop and cond_break expand to, is a jump that is taken when the time slice of the invocation is over:

    do {
            p = bpf_map_lookup_elem(&map, &key);
    } while (!p && can_loop);
    v = *p;

Currently the program continues at the target of the jump. Here it would continue with p == NULL, and the verifier rejects it for that. Where the verifier accepts the code at the target, the program continues with half of a result: a list that was not walked to its end, a lock that was not taken. No user of can_loop or cond_break in the selftests or in the scx schedulers is known to recover from that.

A may_goto of the verifier jumps to a landing pad, and the kernel cancels the program. Do the same for a may_goto of the program. The landing pads release what the frames hold, and the program returns the value of its program type.

What changes for programs that load today:

- The code at the target of the jump no longer runs after a time-out. arena_spin_lock() does not return -ETIMEDOUT: the program ends in the lock.
- A program is rejected if the verifier cannot generate a landing pad for a may_goto of the program, or for a call above it.
- A program that was rejected for the code at the target loads, like the loop above.
- A global function with such a loop can unwind, so an extension cannot replace it and fexit cannot attach to it.
- The time that is up stays up for the invocation, as before. After a function that cannot be cancelled has used it up, the next may_goto in a function that can be cancelled ends the program.

A may_goto of the program stays a plain jump in three cases:

- It is 'may_goto +0', or it jumps over nothing but insns like itself. The verifier removes such an insn.
- It is the form that counts trips, where no JIT runs the timed form. BPF_MAX_LOOPS trips are a bound of the loop, not a time that is up.
- Its function cannot be cancelled.

The third case is decided once for all frames of a function, because the verifier rewrites an insn in one way for all of them. The code marks such a function 'stuck'. It does so when a helper without an unwind label for its callback calls the function, and when a frame that cannot be cancelled calls it or reaches its may_goto. A frame of a marked function that has a caller in the program marks what it calls, and skip_faults() sets the same mark. A frame cannot be cancelled if its function has no exit insn, if the program is loaded without CAP_PERFMON, or if it has a caller in the program and the JIT has no unwind_exit.

Three things need care:

- The program can still continue after a time-out in a function that only bpf_loop() or bpf_for_each_map_elem() calls. The existing check at its start returns 1 if the time is up, the helper ends its loop, and the program continues until its next may_goto. The check is not a site. A comment at the check says why.
- retarget_may_gotos() makes the insn jump to its landing pad before dead code is removed. No state takes the jump, so its old target can be dead code. The insn would become 'goto +0', and nothing would stop the loop.
- The jump stays an edge of the control flow graph and of liveness. So a loop whose only exit is its may_goto is not a loop without an exit, and a register that the program reads only at the target is live at the insn, where a landing pad can use it.

In the main pass check_may_goto_site() makes the insn a site of a new kind, BPF_SITE_MAY_GOTO, and hidden slots serve it like a may_goto of the verifier. A function can be marked late in a pass, after a state was cancelled at its may_goto or a frame of it made a call. The verifier then repeats the pass with the mark set from its start. The mark is kept for every later pass. That is safe, because a marked function behaves as it does today. It is also needed: a pass that does not reach the call that sets the mark could reject a program that loads today.

Tests that relied on the jump now expect the value of the program type, use up the time in a function that cannot be cancelled, or give the loop a second exit.

---
 include/linux/bpf_verifier.h                  |  28 +-
 kernel/bpf/fixups.c                           |  83 ++++-
 kernel/bpf/pads.c                             | 154 +++++++-
 kernel/bpf/verifier.c                         | 189 +++++++++-
 .../selftests/bpf/prog_tests/may_goto_far.c   |  23 +-
 .../selftests/bpf/prog_tests/timed_may_goto.c |  89 ++++-
 .../selftests/bpf/progs/may_goto_priv_stack.c |   8 +-
 tools/testing/selftests/bpf/progs/stream.c    |   2 +-
 .../selftests/bpf/progs/timed_may_goto.c      | 332 +++++++++++++-----
 .../selftests/bpf/progs/timed_may_goto_ext.c  |  22 +-
 .../selftests/bpf/progs/timed_may_goto_user.c | 169 +++++++--
 .../bpf/progs/verifier_arena_stack.c          |  27 +-
 .../bpf/progs/verifier_bpf_fastcall.c         |  12 +-
 .../selftests/bpf/progs/verifier_equations.c  |   9 +-
 .../bpf/progs/verifier_iterating_callbacks.c  |  25 +-
 .../bpf/progs/verifier_linked_scalars.c       |   7 +-
 .../selftests/bpf/progs/verifier_may_goto_1.c |  17 +-
 .../selftests/bpf/progs/verifier_passes.c     |  26 +-
 .../selftests/bpf/progs/verifier_patch_list.c | 100 ++++--
 .../selftests/bpf/progs/verifier_stack_arg.c  |   8 +-
 20 files changed, 1082 insertions(+), 248 deletions(-)
include/linux/bpf_verifier.h +26 -2
index 1d4860542c42..e20df219d332 100644
@@ -462,6 +462,7 @@ enum bpf_site_kind {
 	BPF_SITE_CALL,
 	BPF_SITE_FAULT,		/* an access to arena that faults */
 	BPF_SITE_THROW,		/* a call of bpf_throw() */
+	BPF_SITE_MAY_GOTO,	/* a may_goto of the program, see check_may_goto_site() */
 };
 
 /* The classes of resources that a landing pad releases */
@@ -1310,6 +1311,8 @@ struct bpf_insn_aux_data {
 	/* below flags are initialized once */
 	u32 bb_end:1; /* last instruction of a basic block */
 	u32 guard_place:1; /* it is the place for may_goto if the loop needs one */
+	/* a may_goto that jumps over nothing but may_gotos: bpf_opt_remove_nops() removes it */
+	u32 may_goto_nop:1;
 	/* true if instruction is a call to a helper function that
 	 * accepts callback function as a parameter.
 	 */
@@ -1548,11 +1551,27 @@ struct bpf_subprog_info {
 	bool did_unwind: 1;
 	/*
 	 * It did so at a site with no other way out, see bpf_pads_must_unwind(). A fault in arena
-	 * has one: the access is skipped.
+	 * has one: the access is skipped. So has a may_goto of the program: in a stuck subprog it
+	 * jumps.
 	 */
 	bool must_unwind: 1;
-	/* it did so at a site that the program keeps for sure, see site_is_certain() */
+	/*
+	 * It did so at a site that the program keeps for sure, see site_is_certain(), and that is
+	 * no access to arena.
+	 */
 	bool unwinds_for_sure: 1;
+	/*
+	 * may_goto_unwinds: in this pass a frame of it was cancelled at a may_goto of the program.
+	 * stuck: it cannot be cancelled. In all its frames, in this pass and in every later one, a
+	 * may_goto of the program jumps, see stuck_frame_calls().
+	 */
+	bool may_goto_unwinds: 1;
+	bool stuck: 1;
+	/*
+	 * In this pass a frame of it made a call that did not mark the callee stuck. If the subprog
+	 * is marked stuck later, the pass is repeated, see stuck_frame_calls().
+	 */
+	bool made_calls: 1;
 	/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */
 	bool below_conflict: 1;
 	/*
@@ -1560,6 +1579,8 @@ struct bpf_subprog_info {
 	 * references the arguments of the call had, see bpf_pad_states_meet()
 	 */
 	bool arg_refs_differ: 1;
+	/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
+	u8 left_at;
 	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
 	u8 no_slots: 4;
 	/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */
@@ -2262,6 +2283,7 @@ void bpf_flow_new_pass(struct bpf_verifier_env *env);
 void bpf_flow_drop_guards(struct bpf_verifier_env *env);
 bool bpf_flow_guard_is_guess(struct bpf_verifier_env *env, int idx);
 int bpf_flow_place_guards(struct bpf_verifier_env *env);
+void bpf_mark_may_goto_nops(struct bpf_verifier_env *env);
 /* verifier.c, for flow.c */
 int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
 			bool *starts_leftover);
@@ -2326,6 +2348,8 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 		  struct bpf_insn *buf, struct bpf_insn_aux_data *aux);
 void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan);
 void bpf_pad_log_handed_over(struct bpf_verifier_env *env, int subprog, u8 args);
+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);
 bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan);
 void bpf_pads_must_unwind(struct bpf_verifier_env *env);
 void bpf_pads_mark_used(struct bpf_verifier_env *env);
kernel/bpf/fixups.c +79 -4

119 lines not on this page · raw message

kernel/bpf/pads.c +141 -13

253 lines not on this page · raw message

kernel/bpf/verifier.c +178 -11

298 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/may_goto_far.c +14 -9
index b6d262911a3e..201cda7cf34b 100644
@@ -18,7 +18,7 @@ static struct bpf_insn *fill(struct bpf_insn *insn, int cnt, int reg)
  * away:
  *
  *	r6 = r7 = 0, but not a constant for the verifier
- *	r8 = 2
+ *	r8 = 3
  *	r9 = 0
  *	r0 = r8		x FILL_CNT or 1
  * 1:	if r6 == r9 goto +1
@@ -31,16 +31,21 @@ static struct bpf_insn *fill(struct bpf_insn *insn, int cnt, int reg)
  * 3:	r0 = r8		x N when off is positive
  * 4:	exit
  *
- * The prog returns 0 when may_goto jumps to its target and 2 when
- * it lands in one of 'r0 = r8' areas. There are no constants between
- * may_goto and its target to keep the distance when constants are blinded.
+ * When may_goto expires the prog is unwound: the insn does not go to the
+ * target that the program gives it, but to a landing pad behind the last
+ * insn, which is far too. It is a tc prog: it returns 2, TC_ACT_SHOT, when
+ * may_goto jumps to the pad, 3 when it lands in one of the 'r0 = r8' areas,
+ * and 0, which r0 has in the loop, when it lands on an exit: the last one
+ * is one insn short of the pad. There are no constants between may_goto
+ * and its target to keep the distance when constants are blinded.
  *
  * With 'subprog' all of that is a subprog.
  */
 static void test_far(int off, bool subprog)
 {
-	LIBBPF_OPTS(bpf_prog_load_opts, opts, .prog_flags = BPF_F_SLEEPABLE);
-	LIBBPF_OPTS(bpf_test_run_opts, topts);
+	LIBBPF_OPTS(bpf_prog_load_opts, opts);
+	char pkt[64] = {};
+	LIBBPF_OPTS(bpf_test_run_opts, topts, .data_in = pkt, .data_size_in = sizeof(pkt));
 	int front = off < 0 ? 1 : FILL_CNT;
 	int mid = off < 0 ? -off - 5 : 1;
 	int back = off < 0 ? FILL_CNT : off - 1;
@@ -61,7 +66,7 @@ static void test_far(int off, bool subprog)
 	*insn++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_6, 63);
 	*insn++ = BPF_MOV64_REG(BPF_REG_7, BPF_REG_0);
 	*insn++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_7, 63);
-	*insn++ = BPF_MOV64_IMM(BPF_REG_8, 2);
+	*insn++ = BPF_MOV64_IMM(BPF_REG_8, 3);
 	*insn++ = BPF_MOV64_IMM(BPF_REG_9, 0);
 	insn = fill(insn, front, BPF_REG_8);
 	*insn++ = BPF_JMP_REG(BPF_JEQ, BPF_REG_6, BPF_REG_9, 1);
@@ -74,14 +79,14 @@ static void test_far(int off, bool subprog)
 	insn = fill(insn, back, BPF_REG_8);
 	*insn++ = BPF_EXIT_INSN();
 
-	fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", insns, insn - insns, &opts);
+	fd = bpf_prog_load(BPF_PROG_TYPE_SCHED_CLS, NULL, "GPL", insns, insn - insns, &opts);
 	free(insns);
 	if (!ASSERT_GE(fd, 0, "prog_load"))
 		return;
 
 	err = bpf_prog_test_run_opts(fd, &topts);
 	ASSERT_OK(err, "test_run");
-	ASSERT_EQ(topts.retval, 0, "retval");
+	ASSERT_EQ(topts.retval, 2, "retval");
 	close(fd);
 }
 
tools/testing/selftests/bpf/prog_tests/timed_may_goto.c +71 -18

140 lines not on this page · raw message

tools/testing/selftests/bpf/progs/may_goto_priv_stack.c +5 -3
index 5c2aa0aa5055..d842cf5c966d 100644
@@ -5,13 +5,15 @@
 #include "../../../include/linux/filter.h"
 #include "bpf_misc.h"
 
-/* r0-r5 after the loop and the number of iterations */
+/* r0-r5 in the last trip of the loop and the number of iterations */
 __u64 regs_64[7];
 __u64 regs_128[7];
 
 /*
  * fentry prog with 64 or more bytes of stack uses private stack.
  * Loop until may_goto expires. r0-r5 should stay zero.
+ * When may_goto expires the prog is unwound: what follows the loop does not run, so each trip
+ * stores the registers.
  */
 #define TIMED_MAY_GOTO_PRIV_STACK(size, func)				\
 SEC("fentry/" #func)							\
@@ -30,7 +32,6 @@ __naked void priv_stack_##size(void)					\
 "1:"									\
 	".8byte %[may_goto];"						\
 	"r6 += 1;"							\
-	"goto 1b;"							\
 	"*(u64 *)(r7 + 0) = r0;"					\
 	"*(u64 *)(r7 + 8) = r1;"					\
 	"*(u64 *)(r7 + 16) = r2;"					\
@@ -38,11 +39,12 @@ __naked void priv_stack_##size(void)					\
 	"*(u64 *)(r7 + 32) = r4;"					\
 	"*(u64 *)(r7 + 40) = r5;"					\
 	"*(u64 *)(r7 + 48) = r6;"					\
+	"goto 1b;"							\
 	"r0 = 0;"							\
 	"exit;"								\
 	:								\
 	: [regs]"i"(&regs_##size),					\
-	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 2, 0)) \
+	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 9, 0)) \
 	: __clobber_all);						\
 }
 
tools/testing/selftests/bpf/progs/stream.c +1 -1
index 949c1b2fa6c0..68c2c80d7edf 100644
@@ -74,7 +74,7 @@ __arch_arm64
 __arch_s390x
 __arch_riscv64
 __arch_loongarch
-__success __retval(0)
+__success __retval(-ECANCELED)
 __stderr("ERROR: Timeout detected for may_goto instruction")
 __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}")
 __stderr("Call trace:\n"
tools/testing/selftests/bpf/progs/timed_may_goto.c +247 -85

618 lines not on this page · raw message

tools/testing/selftests/bpf/progs/timed_may_goto_ext.c +20 -2
index 969ca58b6eed..d6cd5f370fd8 100644
@@ -15,9 +15,27 @@ static __noinline int spins(void)
 	return bpf_ktime_get_ns() - t0 > 100 * 1000 * 1000;
 }
 
-/* Each call of an extension prog is an invocation: one of its two calls spins. */
+/*
+ * Each call of an extension prog is an invocation, with its own time. When that is up the
+ * extension is unwound, to its own exit: the function that it replaces returns the value of an
+ * unwound prog of the type that it extends, and the caller goes on.
+ */
+static __noinline int counts_to_1000(void)
+{
+	int i, cnt = 0;
+
+	for (i = 0; i < 1000 && can_loop; i++)
+		cnt++;
+	return cnt;
+}
+
+/* The calls that had the time for a short loop before they used it up */
+int calls, counted_to_1000;
+
 SEC("freplace")
 int replacement(int i)
 {
-	return spins() + spins() + i;
+	calls++;
+	counted_to_1000 += counts_to_1000() == 1000;
+	return 10 + spins() + spins() + i;
 }
tools/testing/selftests/bpf/progs/timed_may_goto_user.c +136 -33

307 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_arena_stack.c +21 -6
index ca7bdbd7e1ce..5d22dfc6fdcb 100644
@@ -1032,7 +1032,11 @@ __naked void may_goto_keeps_r12(void)
 	: __clobber_all);
 }
 
-/* counts the calls and spins until the time of may_goto is up */
+/*
+ * Counts the calls, takes its time in a loop that has a trip count, and gets to one may_goto. The
+ * one that finds the time up is the last insn of its kind in the call: the callback returns, and
+ * nothing is unwound.
+ */
 static __naked __noinline __used long spin_cb(void)
 {
 	asm volatile (
@@ -1040,9 +1044,12 @@ static __naked __noinline __used long spin_cb(void)
 	"r3 = *(u64 *)(r2 + 0);"
 	"r3 += 1;"
 	"*(u64 *)(r2 + 0) = r3;"
+	"r4 = 1000;"
 "1:"
+	"r4 += -1;"
+	"if r4 != 0 goto 1b;"
 	".8byte %[may_goto];"
-	"goto 1b;"
+	"r4 = 1;"
 	"r0 = 0;"
 	"exit;"
 	:
@@ -1051,10 +1058,16 @@ static __naked __noinline __used long spin_cb(void)
 	: __clobber_all);
 }
 
+/*
+ * The call after the one that found the time up returns 1 in its first insns, before it takes a
+ * frame in the stack in arena: bpf_loop() ends, and the prog, which has no may_goto, goes on.
+ * The helper counts one call more than the callback, some calls ran, and the slot of the prog in
+ * the stack in arena is as it was: 20 + 1 + 100.
+ */
 SEC("syscall")
 __description("arena stack: bpf_loop() ends when the time of may_goto is up")
 __success __retval(121)
-/* the second call of the callback returns 1 before it takes a stack */
+/* a call of the callback when the time is up returns 1 before it takes a stack */
 __xlated("if r0 != 0x0 goto pc+2")
 __xlated("r0 = 1")
 __xlated("exit")
@@ -1075,10 +1088,12 @@ __naked void loop_ends_early(void)
 	"r3 += -8;"
 	"r4 = 0;"
 	"call %[bpf_loop];"
-	/* 2 calls, 1 of them ran */
-	"r0 *= 10;"
+	/* the last call did not run */
 	"r1 = *(u64 *)(r10 - 8);"
-	"r0 += r1;"
+	"r0 -= r1;"
+	"r0 *= 20;"
+	"if r1 == 0 goto +1;"
+	"r0 += 1;"
 	".8byte %[ldx];"	/* r1 = *(u64 *)(r12 - 8) */
 	"r0 += r1;"
 	"exit;"
tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c +10 -2
index 2120f4e71fb8..8a69d6b7874f 100644
@@ -949,7 +949,8 @@ __xlated("...")
 __xlated("10: r2 = ")
 __xlated("12: r2 = &(void __percpu *)(r2)")
 __xlated("13: r13 = *(u64 *)(r2 +0)")
-__xlated("14: if r13 == 0x0 goto pc+6")
+/* when the time is up may_goto goes to the landing pad of the prog */
+__xlated("14: if r13 == 0x0 goto pc+7")
 __xlated("15: r13 -= 1")
 __xlated("16: if r13 != 0x0 goto pc+2")
 __xlated("17: r13 = r2")
@@ -958,6 +959,9 @@ __xlated("19: *(u64 *)(r2 +0) = r13")
 /* may_goto expansion ends */
 __xlated("20: *(u64 *)(r10 -8) = r1")
 __xlated("21: exit")
+/* the landing pad */
+__xlated("22: r0 = 0")
+__xlated("23: exit")
 __success
 __naked void may_goto_interaction_x86_64(void)
 {
@@ -992,7 +996,8 @@ __xlated("7: call bpf_get_smp_processor_id")
 __xlated("8: r2 = ")
 __xlated("10: r2 = &(void __percpu *)(r2)")
 __xlated("11: r13 = *(u64 *)(r2 +0)")
-__xlated("12: if r13 == 0x0 goto pc+6")
+/* when the time is up may_goto goes to the landing pad of the prog */
+__xlated("12: if r13 == 0x0 goto pc+7")
 __xlated("13: r13 -= 1")
 __xlated("14: if r13 != 0x0 goto pc+2")
 __xlated("15: r13 = r2")
@@ -1001,6 +1006,9 @@ __xlated("17: *(u64 *)(r2 +0) = r13")
 /* may_goto expansion ends */
 __xlated("18: *(u64 *)(r10 -8) = r1")
 __xlated("19: exit")
+/* the landing pad */
+__xlated("20: r0 = 0")
+__xlated("21: exit")
 __success
 __naked void may_goto_interaction(void)
 {
tools/testing/selftests/bpf/progs/verifier_equations.c +7 -2
index 66786aae3664..21a30e6c9b3f 100644
@@ -821,12 +821,17 @@ ONE_TEST(cond_of_low_half_bad, BAD_WRITE, 8, COND_OF_LOW_HALF(-1))
 ONE_TEST(and_of_two_values, __success, 8, TWO_ANDS(7))
 ONE_TEST(and_of_two_values_bad, BAD_WRITE, 8, TWO_ANDS(255))
 
-/* The jump compares a number with itself. It gives no trip count. */
+/*
+ * The jump compares a number with itself. It gives no trip count. The loop is left when the clock
+ * says 0: the jump of may_goto ends the prog.
+ */
 ONE_TEST(jump_that_does_not_count,
 	 __failure __msg("invalid write to stack R8 off=0 size=1"), 8,
 	"r7 = 0; r8 = r10; r8 += -24; r9 = r10; r9 += -256;"
 "1:"	"r0 = 0;"
-"2:"	MAY_GOTO(2)
+"2:"	"call %[bpf_ktime_get_ns];"
+	"if r0 == 0 goto +3;"
+	MAY_GOTO(2)
 	"r9 += 1;"
 	"if r9 == r9 goto 2b;"
 	"*(u8 *)(r8 + 0) = r7;"
tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c +14 -11
index 1dfeb13b4382..c4a0c3f303b4 100644
@@ -590,19 +590,24 @@ int cond_break3(const void *ctx)
 	return loop();
 }
 
+/*
+ * A socket filter that is unwound returns 0. Where may_goto jumps, without a JIT, the prog goes
+ * on and returns 1.
+ */
 SEC("socket")
-__success __retval(1)
+__load_if_JITed()
+__success __retval(0)
 int cond_break4(const void *ctx)
 {
 	int cnt = zero;
 
 	for (;;) {
-		/* should eventually break out of the loop */
+		/* should eventually end the prog, and not break out of the loop */
 		cond_break;
 		cnt++;
 	}
-	/* if we looped a bit, it's a success */
-	return cnt > 1 ? 1 : 0;
+	/* if we looped a bit, it's 1 */
+	return cnt > 1 ? 1 : 2;
 }
 
 static __noinline int static_subprog(void)
@@ -618,24 +623,22 @@ static __noinline int static_subprog(void)
 }
 
 SEC("socket")
-__success __retval(1)
+__load_if_JITed()
+__success __retval(0)
 int cond_break5(const void *ctx)
 {
 	int cnt1 = zero, cnt2;
 
-	/*
-	 * There is one time slice for all may_goto of the prog. When it's used up a function that
-	 * is called after that makes no iteration. So this loop has an end.
-	 */
+	/* This loop has an end: it does not use up the time slice of the prog. */
 	for (; cnt1 < 100;) {
 		cond_break;
 		cnt1++;
 	}
 
+	/* The loop of the subprog does. The prog is unwound from there. */
 	cnt2 = static_subprog();
 
-	/* main and subprog have to loop a bit */
-	return cnt1 > 1 && cnt2 > 1 ? 1 : 0;
+	return cnt1 > 1 && cnt2 > 1 ? 1 : 2;
 }
 
 #define ARR2_SZ 1000
tools/testing/selftests/bpf/progs/verifier_linked_scalars.c +6 -1
index f61a07424834..4995b3116691 100644
@@ -812,7 +812,10 @@ LINK_TEST(and_cuts_in_the_middle, TOO_FAR,
 LINK_TEST(and_rounds_down_far, TOO_FAR,
 	  "r6 &= 0xff; r7 = r6; r7 &= 0xf0; if r7 > 7 goto 1f;")
 
-/* r7 is 4 * trip + 8, r8 is 8 * trip. The loop has no trip count, so the products wrap. */
+/*
+ * r7 is 4 * trip + 8, r8 is 8 * trip. The loop has no trip count, so the products wrap. It is
+ * left when the random number is 0: the jump of may_goto ends the prog.
+ */
 #define STRIDE_TEST(name, verdict, body)			\
 SEC("raw_tp")							\
 verdict								\
@@ -823,6 +826,8 @@ __naked void name(void)						\
 	"r8 = 0;"						\
 	"*(u64 *)(r10 - 8) = r8;"				\
 "2:"								\
+	"call %[bpf_get_prandom_u32];"				\
+	"if r0 == 0 goto +4;"					\
 	".8byte %[may_goto];"					\
 	"r7 += 4;"						\
 	"r8 += 8;"						\
tools/testing/selftests/bpf/progs/verifier_may_goto_1.c +12 -5
index 8d231fb2a317..f8861ad046ce 100644
@@ -94,11 +94,11 @@ __xlated("2: r0 = &(void __percpu *)(r0)")
 __xlated("3: *(u64 *)(r0 +0) = 65535")
 __xlated("4: *(u64 *)(r0 +8) = 0")
 __xlated("5: *(u64 *)(r0 +16) = 0")
-/* may_goto, r0 is dead */
+/* may_goto, r0 is dead. When the time is up it goes to the landing pad of the prog. */
 __xlated("6: r0 = ")
 __xlated("8: r0 = &(void __percpu *)(r0)")
 __xlated("9: r13 = *(u64 *)(r0 +0)")
-__xlated("10: if r13 == 0x0 goto pc+6")
+__xlated("10: if r13 == 0x0 goto pc+8")
 __xlated("11: r13 -= 1")
 __xlated("12: if r13 != 0x0 goto pc+2")
 __xlated("13: r13 = r0")
@@ -107,6 +107,9 @@ __xlated("15: *(u64 *)(r0 +0) = r13")
 __xlated("16: r0 = 1")
 __xlated("17: r0 = 2")
 __xlated("18: exit")
+/* the landing pad */
+__xlated("19: r0 = 0")
+__xlated("20: exit")
 __success
 __naked void may_goto_batch_2(void)
 {
@@ -125,6 +128,8 @@ __naked void may_goto_batch_2(void)
 /*
  * Use bpf_get_prandom_u32() to prevent DCE from removing the checks.
  * retval: 0=all ok, 1-6=R0-R5 clobbered.
+ * The loop makes more trips than may_goto counts before it reads the clock, and ends by its own
+ * count: a loop that waits for its time to be up ends the prog, and the checks never run.
  */
 SEC("syscall")
 __description("timed may_goto preserves R0-R5")
@@ -152,8 +157,11 @@ __naked void timed_may_goto_preserves_regs(void)
 	"r4 += r6;"
 	"r5 = 0x6666;"
 	"r5 += r6;"
+	"r7 = 70000;"
+"7:"
 	".8byte %[may_goto];"
-	".8byte %[loop];"
+	"r7 -= 1;"
+	"if r7 != 0 goto 7b;"
 	"r0 -= r6;"
 	"r1 -= r6;"
 	"r2 -= r6;"
@@ -176,8 +184,7 @@ __naked void timed_may_goto_preserves_regs(void)
 	"6: r0 = 6; exit;"
 	:
 	: __imm(bpf_get_prandom_u32),
-	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 1, 0)),
-	  __imm_insn(loop, BPF_RAW_INSN(BPF_JMP | BPF_JA, 0, 0, -2, 0))
+	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 2, 0))
 	: __clobber_all);
 }
 
tools/testing/selftests/bpf/progs/verifier_passes.c +21 -5
index d17254990744..48c59e7935e2 100644
@@ -823,8 +823,10 @@ __naked void thresholds_over_budget(void)
 	"r0 = *(u8 *)(r1 + 0);"
 	".rept 500;"
 	"r6 = 0;"
-"3:"	MAY_GOTO(10)
+"3:"	MAY_GOTO(11)
 	"call %[bpf_get_prandom_u32];"
+	/* the way to what follows the loop: the jump of may_goto ends the prog */
+	"if r0 == 2 goto 5f;"
 	"if r0 & 1 goto 4f;"
 	"if r6 >= 60000 goto 4f;"
 	"r6 += 1;"
@@ -834,7 +836,7 @@ __naked void thresholds_over_budget(void)
 	"r1 = 0;"
 	"call long_dead_code;"
 	"goto 3b;"
-	"r6 >>= 10;"
+"5:	r6 >>= 10;"
 	"r1 = r9;"
 	"r1 += r6;"
 	"r0 = *(u8 *)(r1 + 0);"
@@ -2577,13 +2579,21 @@ int leak_made_up_in_loop(struct __sk_buff *skb)
 	return 0;
 }
 
+/*
+ * The time of may_goto that is up ends the prog, and no state takes its jump. These loops have
+ * another way out, so that what follows them is verified.
+ */
+#define OR_BREAK	if (bpf_get_prandom_u32() & 1) break
+
 SEC("tc")
 __description("held: a loop acquires and does not release")
 __failure __msg("BPF_EXIT instruction in main prog cannot be used inside bpf_preempt_disable")
 int loop_only_acquires(void *unused)
 {
-	while (can_loop)
+	while (can_loop) {
+		OR_BREAK;
 		bpf_preempt_disable();
+	}
 	return 0;
 }
 
@@ -2591,6 +2601,7 @@ int loop_only_acquires(void *unused)
 	void *prev = NULL, *cur = NULL;					\
 									\
 	while (can_loop) {						\
+		OR_BREAK;						\
 		if (prev)						\
 			bpf_ringbuf_discard(prev, 0);			\
 		prev = cur;						\
@@ -2625,8 +2636,10 @@ int loop_drops_the_pointer(void *unused)
 {
 	void *cur = NULL;
 
-	while (can_loop)
+	while (can_loop) {
+		OR_BREAK;
 		cur = bpf_ringbuf_reserve(&rb, 8, 0);
+	}
 	if (cur)
 		bpf_ringbuf_discard(cur, 0);
 	return 0;
@@ -3120,7 +3133,10 @@ __naked void peel_does_not_starve(void)
 {
 	ASM(VALUE_IN_R9
 	"r6 = 0;"
-"1:"	MAY_GOTO(2)
+	/* the way to what follows the loop: the jump of may_goto ends the prog */
+"1:	call %[bpf_get_prandom_u32];"
+	"if r0 == 0 goto +3;"
+	MAY_GOTO(2)
 	"r6 += 1;"
 	"goto 1b;"
 	"call %[bpf_get_prandom_u32];"
tools/testing/selftests/bpf/progs/verifier_patch_list.c +67 -33

165 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_stack_arg.c +6 -2
index 16afc69af947..91357043fdf4 100644
@@ -982,9 +982,13 @@ static long spins_then_reads_8args(long a, long b, long c, long d, long e, long
 	);
 }
 
+/*
+ * The callee is unwound when the time is up: it does not get to the loads of its args, which
+ * are behind the jump of may_goto, and tc drops the packet.
+ */
 SEC("tc")
-__description("stack_arg: the time of may_goto is up, then the callee reads its args")
-__success __retval(876)
+__description("stack_arg: the time of may_goto is up, the callee with args in the stack is unwound")
+__success __retval(2)
 __naked void stack_arg_may_goto_timeout_in_callee(void)
 {
 	asm volatile (
Signature · 1 line
2.53.1-Meta
author maintainer
#50 lore raw

PATCH 50/73 bpf: Reject a program that has no landing pad for a fault in arena

In reply to Kumar Kartikeya Dwivedi

Currently a fault in arena cancels the program only where the verifier has a landing pad for the access. Where it has none, the access is skipped and the program continues. Here the states at the load are in different numbers of sections, so a fault in the load is skipped:

    bpf_rcu_read_lock();
    if (x)
            bpf_preempt_disable();
    v = node->val;                  /* no page at node */

So a program that loads does not tell which of its faults end it.

Remove this fallback. An access to arena becomes a site like any other, and hidden slots serve it. In the example the function gets a hidden slot for the section that only some paths enter, and the fault cancels the program. check_arena_site() marks a site without a landing pad as failed, as unwind_frame() does. So the verifier also lets calls clear hidden slots and takes a hand-over back before it rejects for an access to arena.

What changes for programs that load today:

- Every fault in arena in a function that can be cancelled ends the program.
- A program is rejected if the verifier cannot generate a landing pad, even with hidden slots, for an access to arena in such a function or for a call above the access. Until now it loaded and the access was skipped. An access in nine RCU sections is an example, because a landing pad leaves at most eight.

An access that faults is still skipped where the JIT has no unwind_exit, which is every JIT but those of x86-64 and arm64, and in a function that cannot be cancelled. That is the 'stuck' mark that makes a may_goto of the program a plain jump. It holds for all frames of a function, so an async callback that is marked skips the access also when the kernel calls it.

One case remains in which a call gets no landing pad and the program loads. A cancelled state comes back to a call whose frame cannot be cancelled, and the functions below the call were cancelled only at accesses to arena and at their own may_goto. bpf_pad_skip_faults(), which was skip_faults(), marks those functions and has the pass repeated.

As today, a fault does not cancel the caller across three boundaries: an extension ends at its own exit, the callee of a tail call that a subprog makes returns into that subprog, and what a kfunc or a helper touches in arena is not an access of the program.

---
 include/linux/bpf_verifier.h                  |  25 +--
 kernel/bpf/pads.c                             | 161 +++++++++++-------
 kernel/bpf/verifier.c                         | 161 +++++++-----------
 .../selftests/bpf/progs/arena_atomics.c       |  99 +++++++++--
 .../selftests/bpf/progs/arena_skipped.h       |  11 --
 .../selftests/bpf/progs/verifier_arena.c      |  43 +----
 .../bpf/progs/verifier_arena_large.c          |  54 +-----
 7 files changed, 272 insertions(+), 282 deletions(-)
 delete mode 100644 tools/testing/selftests/bpf/progs/arena_skipped.h
include/linux/bpf_verifier.h +15 -10
index e20df219d332..12b93e15f7a4 100644
@@ -1296,7 +1296,7 @@ struct bpf_insn_aux_data {
 	/* a subprog returned here without a pointer to release, and its R0 may not be 0 */
 	u64 call_brings_nothing:1;
 	/* An access to arena, see check_arena_site() */
-	u64 fault_skips:1; /* a fault is skipped: no pad, or the frame cannot be cancelled */
+	u64 fault_skips:1; /* a fault is skipped: its subprog cannot be cancelled */
 	u64 fault_empty:1; /* in this pass a state that holds nothing passed without a record */
 	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 */
@@ -1551,22 +1551,25 @@ struct bpf_subprog_info {
 	bool did_unwind: 1;
 	/*
 	 * It did so at a site with no other way out, see bpf_pads_must_unwind(). A fault in arena
-	 * has one: the access is skipped. So has a may_goto of the program: in a stuck subprog it
-	 * jumps.
+	 * and a may_goto of the program have one: in a stuck subprog the fault is skipped and the
+	 * may_goto jumps.
 	 */
 	bool must_unwind: 1;
-	/*
-	 * It did so at a site that the program keeps for sure, see site_is_certain(), and that is
-	 * no access to arena.
-	 */
+	/* it did so at a site that the program keeps for sure, see site_is_certain() */
 	bool unwinds_for_sure: 1;
 	/*
-	 * may_goto_unwinds: in this pass a frame of it was cancelled at a may_goto of the program.
+	 * soft_unwinds: in this pass a frame of it was cancelled at a may_goto of the program or at
+	 * an access to arena.
 	 * stuck: it cannot be cancelled. In all its frames, in this pass and in every later one, a
-	 * may_goto of the program jumps, see stuck_frame_calls().
+	 * may_goto of the program jumps and a fault in arena is skipped, see stuck_frame_calls().
 	 */
-	bool may_goto_unwinds: 1;
+	bool soft_unwinds: 1;
 	bool stuck: 1;
+	/*
+	 * 'pad_skip_gen' of the env when bpf_pad_skip_faults() walked the subprog and the subprogs
+	 * that were cancelled below it. While the two are equal, all of them are marked stuck.
+	 */
+	u32 skip_gen;
 	/*
 	 * In this pass a frame of it made a call that did not mark the callee stuck. If the subprog
 	 * is marked stuck later, the pass is repeated, see stuck_frame_calls().
@@ -1802,6 +1805,7 @@ struct bpf_verifier_env {
 	u64 pass_max_cost;		/* see bpf_undo_precision() */
 	bool aborted;			/* a thaw does not take it back */
 	bool no_mem;			/* a table cannot grow, see bpf_check_limits() */
+	u32 pad_skip_gen;		/* see 'skip_gen' of struct bpf_subprog_info */
 	/* What a pass writes. Each pass starts from the snapshot. */
 	struct_group_tagged(bpf_env_per_pass, per_pass,
 	int err;			/* the first error */
@@ -2353,6 +2357,7 @@ void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *su
 bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan);
 void bpf_pads_must_unwind(struct bpf_verifier_env *env);
 void bpf_pads_mark_used(struct bpf_verifier_env *env);
+int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan);
 int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_data *aux);
 void bpf_pads_note_causes(struct bpf_verifier_env *env);
kernel/bpf/pads.c +97 -64

289 lines not on this page · raw message

kernel/bpf/verifier.c +64 -97

271 lines not on this page · raw message

tools/testing/selftests/bpf/progs/arena_atomics.c +82 -17

131 lines not on this page · raw message

tools/testing/selftests/bpf/progs/arena_skipped.h deleted +0 -11
deleted file mode 100644
index 8b0a265ec6aa..000000000000
@@ -1,11 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0 */
-#pragma once
-
-extern void bpf_rcu_read_lock(void) __ksym;
-extern void bpf_rcu_read_unlock(void) __ksym;
-
-/* A fault in the arena ends the prog. In nine RCU sections it is skipped: a pad leaves eight. */
-#define __nine(x) ({ x; x; x; x; x; x; x; x; x; })
-#define skip_faults()	__nine(bpf_rcu_read_lock())
-#define unwind_faults()	__nine(bpf_rcu_read_unlock())
-#define skipped(expr)	({ long __v; skip_faults(); __v = (expr); unwind_faults(); __v; })
tools/testing/selftests/bpf/progs/verifier_arena.c +8 -35

93 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_arena_large.c +6 -48

73 lines not on this page · raw message

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

PATCH 51/73 bpf: Log why a call is a site and which functions cannot be cancelled

In reply to Kumar Kartikeya Dwivedi

A call is a site when a function below it can leave with unwind_exit. When the verifier cannot generate a landing pad for the call, the program is rejected. Currently the log names the call, but not what makes it a site. Print a line before the error that names the kinds of site at which the functions below the call are cancelled or unwind:

what the call at 12 calls is left at: may_goto of the program landing pad of call at 12: conflict: too much is held

The kinds are "may_goto" for one of the verifier, "recursion check", "arena access", "bpf_throw", "may_goto of the program" and "unwind_exit", separated by commas. They come from 'left_at' of the functions. The program's own unwind_exit is not a site, so 'left_at' gets a bit for it.

The verifier also decides two things about a function that change what it does at run time, and the log shows neither. A function that is marked as one that cannot be cancelled has may_gotos that jump and accesses to arena that are skipped. A function with hidden slots has stores and stack that the program did not ask for. Print one line for each such function at log level 2, after the landing pads. Each of these is one line of the log, and "cannot unwind" stands for "cannot be cancelled":

func#1 cannot unwind, the call at 23 has no landing pad for it: its may_goto jumps, its arena accesses are skipped
func#2 cannot unwind, func#1 calls it at 106 and cannot unwind: its may_goto jumps, its arena accesses are skipped
func#3 has hidden slots for: rcu refs

A line names the insn at which the function was marked, because the mark is kept for later passes and the pass that is loaded may not reach that insn. The insn is one of four:

- "the call at N has no landing pad for it": the call hands the function to a helper that has no unwind label for it.
- "func#M calls it at N and cannot unwind": the frame that calls cannot be cancelled, or its function is marked.
- "it came back to the call at N in func#M, which cannot unwind": a cancelled state came back from the function to a call in a frame that cannot be cancelled.
- "at N": a frame of the function that cannot be cancelled reached its own may_goto or access to arena.

bpf_subprog_set_stuck() now sets the mark in all places and records the first insn that did.

---
 include/linux/bpf_verifier.h |  27 +++++++-
 kernel/bpf/pads.c            | 120 +++++++++++++++++++++++++++++------
 kernel/bpf/verifier.c        |  16 +++--
 3 files changed, 138 insertions(+), 25 deletions(-)
include/linux/bpf_verifier.h +26 -1
index 12b93e15f7a4..a143c7685cc2 100644
@@ -501,6 +501,16 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_NO_ROOM,
 };
 
+/* How a subprog was found to be one that cannot be cancelled, see 'stuck' of bpf_subprog_info */
+enum bpf_stuck_by {
+	BPF_STUCK_NO_PAD = 1,	/* a call passes it to a helper that has no unwind label for it */
+	BPF_STUCK_CALLED,	/* a frame that cannot be cancelled calls it */
+	/* a frame of it that cannot be cancelled reached its own may_goto or access to arena */
+	BPF_STUCK_AT_SITE,
+	/* a cancelled state came back from it to a call in a frame that cannot be cancelled */
+	BPF_STUCK_CAME_BACK,
+};
+
 /*
  * 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 one insn that saves the value and four that leave the frame.
@@ -1565,6 +1575,9 @@ struct bpf_subprog_info {
 	 */
 	bool soft_unwinds: 1;
 	bool stuck: 1;
+	/* how it was found to be stuck, enum bpf_stuck_by, and at which insn. For the log. */
+	u8 stuck_by;
+	u32 stuck_insn;
 	/*
 	 * 'pad_skip_gen' of the env when bpf_pad_skip_faults() walked the subprog and the subprogs
 	 * that were cancelled below it. While the two are equal, all of them are marked stuck.
@@ -1617,6 +1630,17 @@ static inline bool bpf_subprog_unwinds(const struct bpf_subprog_info *sub)
 	return sub->can_unwind || (sub->recursive && sub->bail_unwinds);
 }
 
+/* Mark @sub as stuck. The log names the first insn that marked it, see bpf_pads_log(). */
+static inline void bpf_subprog_set_stuck(struct bpf_subprog_info *sub, enum bpf_stuck_by by,
+					 u32 insn_idx)
+{
+	if (sub->stuck)
+		return;
+	sub->stuck = true;
+	sub->stuck_by = by;
+	sub->stuck_insn = insn_idx;
+}
+
 /* 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)
 {
@@ -2357,7 +2381,8 @@ void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *su
 bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan);
 void bpf_pads_must_unwind(struct bpf_verifier_env *env);
 void bpf_pads_mark_used(struct bpf_verifier_env *env);
-int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan);
+int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			int insn_idx);
 int bpf_pads_settle(struct bpf_verifier_env *env);
 bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_data *aux);
 void bpf_pads_note_causes(struct bpf_verifier_env *env);
kernel/bpf/pads.c +102 -18

202 lines not on this page · raw message

kernel/bpf/verifier.c +10 -6
index 22da9e990f5f..7036baf1efe7 100644
@@ -3426,7 +3426,7 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 	/* If a state left @subprog or a frame of it made a call before, the pass is repeated. */
 	env->faults_late |= did_unwind || ((sub->soft_unwinds || sub->made_calls) && !sub->stuck);
 	sub->bail_unwinds = false;
-	sub->stuck = true;
+	bpf_subprog_set_stuck(sub, BPF_STUCK_NO_PAD, env->insn_idx);
 	return 0;
 }
 
@@ -22044,7 +22044,7 @@ static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog)
 	}
 	env->faults_late |= sub->soft_unwinds || sub->made_calls ||
 			    (sub->did_unwind && sub->bail_unwinds);
-	sub->stuck = true;
+	bpf_subprog_set_stuck(sub, BPF_STUCK_CALLED, env->insn_idx);
 }
 
 /* This insn is a site of @kind. Push a copy of the current state that leaves its frame here. */
@@ -22130,7 +22130,7 @@ static int check_may_goto_site(struct bpf_verifier_env *env)
 		return 0;
 	if (sub->stuck || frame_cannot_unwind(env, env->cur_state)) {
 		env->faults_late |= (sub->soft_unwinds || sub->made_calls) && !sub->stuck;
-		sub->stuck = true;
+		bpf_subprog_set_stuck(sub, BPF_STUCK_AT_SITE, env->insn_idx);
 		return 0;
 	}
 	sub->soft_unwinds = true;
@@ -22164,7 +22164,7 @@ static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_s
 		return 0;
 	if (sub->stuck || frame_cannot_unwind(env, st)) {
 		env->faults_late |= (sub->soft_unwinds || sub->made_calls) && !sub->stuck;
-		sub->stuck = true;
+		bpf_subprog_set_stuck(sub, BPF_STUCK_AT_SITE, env->insn_idx);
 		aux->fault_skips = true;
 		return 0;
 	}
@@ -22376,7 +22376,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		 * sites that can be skipped. Mark them 'stuck', which stuck_frame_calls() missed.
 		 */
 		if (stuck && kind == BPF_SITE_CALL && !bpf_pad_must_unwind(env, plan))
-			err = bpf_pad_skip_faults(env, plan);
+			err = bpf_pad_skip_faults(env, plan, insn_idx);
 		if (plan->conflict)
 			goto out;
 	}
@@ -24617,7 +24617,11 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 		 * 'stuck' is kept for every later run. A function with the mark behaves as it does
 		 * without cancellation, and a run that misses the call that sets it could fail.
 		 */
-		initial->subprogs[i].stuck |= env->subprog_info[i].stuck;
+		if (env->subprog_info[i].stuck && !initial->subprogs[i].stuck) {
+			initial->subprogs[i].stuck = true;
+			initial->subprogs[i].stuck_by = env->subprog_info[i].stuck_by;
+			initial->subprogs[i].stuck_insn = env->subprog_info[i].stuck_insn;
+		}
 		/* releases_args adds up. asks_args is that of the last pass with an error. */
 		initial->subprogs[i].releases_args |= env->subprog_info[i].releases_args;
 		initial->subprogs[i].asks_args = env->subprog_info[i].asks_args;
Signature · 1 line
2.53.1-Meta
author maintainer
#52 lore raw

PATCH 52/73 bpf: Add cancel_goto and cancel_exit, which only the verifier emits

In reply to Kumar Kartikeya Dwivedi

The landing pads of the verifier leave a function with unwind_exit, the insn that a program uses for its own unwinding in C++ or Rust. So when the kernel cancels a program inside a callee, the caller sees an ordinary unwind. If the caller has an unwind_goto of its own after the call, the cancellation lands in the program's landing pad, which is code like any other and can continue running:

call spins
unwind_goto +1
exit
r0 = 42 <- the program's landing pad
exit

The loop in spins() runs out of time, the kernel cancels the program in spins(), and the program returns 42. A cancelled program must not be able to continue, whether it ran out of time or stack, faulted in arena or called bpf_throw().

A call can now end in three ways: the callee returns, unwinds, or is cancelled, and the caller has to tell the last two apart. unwind_goto and unwind_exit tell a return from an unwind by where the callee returns to, without a register. Do the same for a cancellation, with a second pair of insns:

cancel_exit BPF_JMP | BPF_EXIT with BPF_CANCEL_EXIT in src_reg. Leaves
a frame like unwind_exit, but returns to the cancel_goto after the call, never to an unwind_goto.
cancel_goto BPF_JMP32 | BPF_JCOND with BPF_CANCEL_GOTO in src_reg, the
offset in imm. Follows a call, or the unwind_goto of a call, and jumps to the landing pad of the caller.

call spins
unwind_goto +2 <- spins() left with unwind_exit
cancel_goto pad <- spins() left with cancel_exit

Like unwind_goto, cancel_goto is not a jump that is taken. A JIT turns it into an exception table entry for the call, so neither insn costs anything when the callee returns.

A flag in a register, set before unwind_exit and tested after the call, does not work in place of the two insns. It is lost in a helper that calls a callback: bpf_loop() is a C frame between the callback and its caller, and what it leaves in a register is up to the compiler. It would also be a second insn that every later rewrite of an exit has to keep before it, where cancel_exit carries the meaning itself.

The passes that run after the main pass treat a cancel_goto like an unwind_goto, through bpf_is_pad_goto(): the hard wiring of dead branches keeps one whose target is alive, the zero extension of what a call returns goes after it, and it is counted for the exception table. bpf_check_unwind_gotos() reports a cancel_goto that follows neither a call nor the unwind_goto of a call as a verifier bug, and also a cancel_exit in the main program, which the kernel calls.

bpf_cancel_target() is for cancel_exit what bpf_unwind_target() is for unwind_exit. Add the weak default, which returns the address unchanged. A JIT that supports the two insns overrides it.

A program cannot contain either insn: both values of src_reg are above what the uapi defines, and check_jmp_fields() rejects them. Nothing emits them yet.

---
 include/linux/filter.h | 37 +++++++++++++++++++++++++++++++--
 kernel/bpf/core.c      |  9 +++++++++
 kernel/bpf/disasm.c    |  9 ++++++++-
 kernel/bpf/fixups.c    | 46 ++++++++++++++++++++++++++++++++----------
 kernel/bpf/verifier.c  |  2 ++
 5 files changed, 89 insertions(+), 14 deletions(-)
include/linux/filter.h +35 -2
index 05a0bf8689a4..74e61ef02285 100644
@@ -295,7 +295,23 @@ static inline bool insn_is_mov_percpu_addr(const struct bpf_insn *insn)
 		.off   = 0,					\
 		.imm   = 1 })
 
-/* gotol, and unwind_goto that the verifier adds, have 32 bits for the offset */
+/*
+ * The two insns of a cancellation. Only the verifier emits them, see kernel/bpf/pads.c. A program
+ * that has one is rejected, see check_jmp_fields().
+ *
+ * cancel_exit: BPF_JMP | BPF_EXIT with BPF_CANCEL_EXIT in src_reg. It leaves a frame like
+ * unwind_exit, but returns to the cancel_goto after the call and never to an unwind_goto, so that
+ * no landing pad of the program can catch a cancellation.
+ * cancel_goto: BPF_JMP32 | BPF_JCOND with BPF_CANCEL_GOTO in src_reg, the offset in imm. It
+ * follows a call, or the unwind_goto of a call.
+ */
+#define BPF_CANCEL_GOTO	2
+#define BPF_CANCEL_EXIT	2
+
+static_assert(BPF_CANCEL_GOTO > BPF_UNWIND_GOTO);
+static_assert(BPF_CANCEL_EXIT > BPF_UNWIND_EXIT);
+
+/* gotol, cancel_goto and an unwind_goto that the verifier adds have a 32 bit offset, in imm */
 static inline bool bpf_jmp_offset_is_imm(const struct bpf_insn *insn)
 {
 	return insn->code == (BPF_JMP32 | BPF_JA) || insn->code == (BPF_JMP32 | BPF_JCOND);
@@ -317,7 +333,23 @@ static inline bool bpf_is_unwind_exit(const struct bpf_insn *insn)
 	return insn->code == (BPF_JMP | BPF_EXIT) && insn->src_reg == BPF_UNWIND_EXIT;
 }
 
-/* The caller of the main prog doesn't tell unwind_exit from exit */
+static inline bool bpf_is_cancel_goto(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_JMP32 | BPF_JCOND) && insn->src_reg == BPF_CANCEL_GOTO;
+}
+
+static inline bool bpf_is_cancel_exit(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_JMP | BPF_EXIT) && insn->src_reg == BPF_CANCEL_EXIT;
+}
+
+/* unwind_goto or cancel_goto: no code, an exception table entry for the insn before it */
+static inline bool bpf_is_pad_goto(const struct bpf_insn *insn)
+{
+	return bpf_is_unwind_goto(insn) || bpf_is_cancel_goto(insn);
+}
+
+/* The caller of the main prog cannot tell unwind_exit or cancel_exit from exit */
 static inline bool bpf_prog_can_unwind(const struct bpf_prog *prog)
 {
 	return bpf_is_subprog(prog);
@@ -1406,6 +1438,7 @@ bool bpf_jit_supports_kfunc_ret_reg_pair(void);
 bool bpf_jit_supports_unwind(void);
 bool bpf_jit_supports_hmul(void);
 u64 bpf_unwind_target(u64 ret_addr);
+u64 bpf_cancel_target(u64 ret_addr);
 u64 bpf_fault_unwind_target(u64 end);
 bool bpf_jit_supports_stack_args(void);
 bool bpf_jit_supports_arena_args(void);
kernel/bpf/core.c +9 -0
index 52fbca734d13..25fd3213d000 100644
@@ -3863,6 +3863,15 @@ u64 __weak bpf_unwind_target(u64 ret_addr)
 	return ret_addr;
 }
 
+/*
+ * The same for cancel_exit and the cancel_goto after the call. Without a JIT that overrides this
+ * the verifier emits no cancel_exit.
+ */
+u64 __weak bpf_cancel_target(u64 ret_addr)
+{
+	return ret_addr;
+}
+
 /*
  * Where the program continues after a fault in an access to arena whose native code ends at @end:
  * at the target of the unwind_goto after the access, or at @end, which skips the access. A JIT
kernel/bpf/disasm.c +8 -1
index 43aa0656a588..8426c6c04610 100644
@@ -10,6 +10,8 @@
 /* Only defined by the non-UAPI linux/filter.h, which this file cannot use. */
 #define BPF_PROBE_ATOMIC 0xe0
 #define BPF_ATOMIC_LOCAL 0x1000
+#define BPF_CANCEL_GOTO 2
+#define BPF_CANCEL_EXIT 2
 
 #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
 static const char * const func_id_str[] = {
@@ -408,12 +410,17 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 			   insn->src_reg == BPF_UNWIND_GOTO) {
 			verbose(cbs->private_data, "(%02x) unwind_goto pc%+d",
 				insn->code, insn->imm);
+		} else if (insn->code == (BPF_JMP32 | BPF_JCOND) &&
+			   insn->src_reg == BPF_CANCEL_GOTO) {
+			verbose(cbs->private_data, "(%02x) cancel_goto pc%+d",
+				insn->code, insn->imm);
 		} else if (insn->code == (BPF_JMP32 | BPF_JA)) {
 			verbose(cbs->private_data, "(%02x) gotol pc%+d",
 				insn->code, insn->imm);
 		} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
 			verbose(cbs->private_data, "(%02x) %s", insn->code,
-				insn->src_reg == BPF_UNWIND_EXIT ? "unwind_exit" : "exit");
+				insn->src_reg == BPF_UNWIND_EXIT ? "unwind_exit" :
+				insn->src_reg == BPF_CANCEL_EXIT ? "cancel_exit" : "exit");
 		} else if (BPF_SRC(insn->code) == BPF_X) {
 			verbose(cbs->private_data,
 				"(%02x) if %c%d %s %c%d goto pc%+d",
kernel/bpf/fixups.c +35 -11

108 lines not on this page · raw message

kernel/bpf/verifier.c +2 -0
index 7036baf1efe7..ed73f660d5ce 100644
@@ -23652,6 +23652,7 @@ static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
 		}
 		return 0;
 	case BPF_EXIT:
+		/* Only the verifier emits cancel_exit, see BPF_CANCEL_EXIT. */
 		if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 ||
 		    insn->src_reg > BPF_UNWIND_EXIT || insn->dst_reg != BPF_REG_0 ||
 		    class == BPF_JMP32) {
@@ -23660,6 +23661,7 @@ static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
 		}
 		return 0;
 	case BPF_JCOND:
+		/* The same for cancel_goto and for the form of unwind_goto with a 32 bit offset. */
 		if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg > BPF_UNWIND_GOTO ||
 		    insn->dst_reg || insn->imm) {
 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
Signature · 1 line
2.53.1-Meta